drm/i915: assert_panel_unlocked() in chv_enable_pll()
[cascardo/linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include <drm/i915_drm.h>
38 #include "i915_drv.h"
39 #include "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 typedef struct {
122         int     min, max;
123 } intel_range_t;
124
125 typedef struct {
126         int     dot_limit;
127         int     p2_slow, p2_fast;
128 } intel_p2_t;
129
130 typedef struct intel_limit intel_limit_t;
131 struct intel_limit {
132         intel_range_t   dot, vco, n, m, m1, m2, p, p1;
133         intel_p2_t          p2;
134 };
135
136 /* returns HPLL frequency in kHz */
137 static int valleyview_get_vco(struct drm_i915_private *dev_priv)
138 {
139         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
140
141         /* Obtain SKU information */
142         mutex_lock(&dev_priv->sb_lock);
143         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
144                 CCK_FUSE_HPLL_FREQ_MASK;
145         mutex_unlock(&dev_priv->sb_lock);
146
147         return vco_freq[hpll_freq] * 1000;
148 }
149
150 static int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
151                                   const char *name, u32 reg)
152 {
153         u32 val;
154         int divider;
155
156         if (dev_priv->hpll_freq == 0)
157                 dev_priv->hpll_freq = valleyview_get_vco(dev_priv);
158
159         mutex_lock(&dev_priv->sb_lock);
160         val = vlv_cck_read(dev_priv, reg);
161         mutex_unlock(&dev_priv->sb_lock);
162
163         divider = val & CCK_FREQUENCY_VALUES;
164
165         WARN((val & CCK_FREQUENCY_STATUS) !=
166              (divider << CCK_FREQUENCY_STATUS_SHIFT),
167              "%s change in progress\n", name);
168
169         return DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, divider + 1);
170 }
171
172 static int
173 intel_pch_rawclk(struct drm_i915_private *dev_priv)
174 {
175         return (I915_READ(PCH_RAWCLK_FREQ) & RAWCLK_FREQ_MASK) * 1000;
176 }
177
178 static int
179 intel_vlv_hrawclk(struct drm_i915_private *dev_priv)
180 {
181         return vlv_get_cck_clock_hpll(dev_priv, "hrawclk",
182                                       CCK_DISPLAY_REF_CLOCK_CONTROL);
183 }
184
185 static int
186 intel_g4x_hrawclk(struct drm_i915_private *dev_priv)
187 {
188         uint32_t clkcfg;
189
190         /* hrawclock is 1/4 the FSB frequency */
191         clkcfg = I915_READ(CLKCFG);
192         switch (clkcfg & CLKCFG_FSB_MASK) {
193         case CLKCFG_FSB_400:
194                 return 100000;
195         case CLKCFG_FSB_533:
196                 return 133333;
197         case CLKCFG_FSB_667:
198                 return 166667;
199         case CLKCFG_FSB_800:
200                 return 200000;
201         case CLKCFG_FSB_1067:
202                 return 266667;
203         case CLKCFG_FSB_1333:
204                 return 333333;
205         /* these two are just a guess; one of them might be right */
206         case CLKCFG_FSB_1600:
207         case CLKCFG_FSB_1600_ALT:
208                 return 400000;
209         default:
210                 return 133333;
211         }
212 }
213
214 static void intel_update_rawclk(struct drm_i915_private *dev_priv)
215 {
216         if (HAS_PCH_SPLIT(dev_priv))
217                 dev_priv->rawclk_freq = intel_pch_rawclk(dev_priv);
218         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
219                 dev_priv->rawclk_freq = intel_vlv_hrawclk(dev_priv);
220         else if (IS_G4X(dev_priv) || IS_PINEVIEW(dev_priv))
221                 dev_priv->rawclk_freq = intel_g4x_hrawclk(dev_priv);
222         else
223                 return; /* no rawclk on other platforms, or no need to know it */
224
225         DRM_DEBUG_DRIVER("rawclk rate: %d kHz\n", dev_priv->rawclk_freq);
226 }
227
228 static void intel_update_czclk(struct drm_i915_private *dev_priv)
229 {
230         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
231                 return;
232
233         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
234                                                       CCK_CZ_CLOCK_CONTROL);
235
236         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
237 }
238
239 static inline u32 /* units of 100MHz */
240 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
241                     const struct intel_crtc_state *pipe_config)
242 {
243         if (HAS_DDI(dev_priv))
244                 return pipe_config->port_clock; /* SPLL */
245         else if (IS_GEN5(dev_priv))
246                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
247         else
248                 return 270000;
249 }
250
251 static const intel_limit_t intel_limits_i8xx_dac = {
252         .dot = { .min = 25000, .max = 350000 },
253         .vco = { .min = 908000, .max = 1512000 },
254         .n = { .min = 2, .max = 16 },
255         .m = { .min = 96, .max = 140 },
256         .m1 = { .min = 18, .max = 26 },
257         .m2 = { .min = 6, .max = 16 },
258         .p = { .min = 4, .max = 128 },
259         .p1 = { .min = 2, .max = 33 },
260         .p2 = { .dot_limit = 165000,
261                 .p2_slow = 4, .p2_fast = 2 },
262 };
263
264 static const intel_limit_t intel_limits_i8xx_dvo = {
265         .dot = { .min = 25000, .max = 350000 },
266         .vco = { .min = 908000, .max = 1512000 },
267         .n = { .min = 2, .max = 16 },
268         .m = { .min = 96, .max = 140 },
269         .m1 = { .min = 18, .max = 26 },
270         .m2 = { .min = 6, .max = 16 },
271         .p = { .min = 4, .max = 128 },
272         .p1 = { .min = 2, .max = 33 },
273         .p2 = { .dot_limit = 165000,
274                 .p2_slow = 4, .p2_fast = 4 },
275 };
276
277 static const intel_limit_t intel_limits_i8xx_lvds = {
278         .dot = { .min = 25000, .max = 350000 },
279         .vco = { .min = 908000, .max = 1512000 },
280         .n = { .min = 2, .max = 16 },
281         .m = { .min = 96, .max = 140 },
282         .m1 = { .min = 18, .max = 26 },
283         .m2 = { .min = 6, .max = 16 },
284         .p = { .min = 4, .max = 128 },
285         .p1 = { .min = 1, .max = 6 },
286         .p2 = { .dot_limit = 165000,
287                 .p2_slow = 14, .p2_fast = 7 },
288 };
289
290 static const intel_limit_t intel_limits_i9xx_sdvo = {
291         .dot = { .min = 20000, .max = 400000 },
292         .vco = { .min = 1400000, .max = 2800000 },
293         .n = { .min = 1, .max = 6 },
294         .m = { .min = 70, .max = 120 },
295         .m1 = { .min = 8, .max = 18 },
296         .m2 = { .min = 3, .max = 7 },
297         .p = { .min = 5, .max = 80 },
298         .p1 = { .min = 1, .max = 8 },
299         .p2 = { .dot_limit = 200000,
300                 .p2_slow = 10, .p2_fast = 5 },
301 };
302
303 static const intel_limit_t intel_limits_i9xx_lvds = {
304         .dot = { .min = 20000, .max = 400000 },
305         .vco = { .min = 1400000, .max = 2800000 },
306         .n = { .min = 1, .max = 6 },
307         .m = { .min = 70, .max = 120 },
308         .m1 = { .min = 8, .max = 18 },
309         .m2 = { .min = 3, .max = 7 },
310         .p = { .min = 7, .max = 98 },
311         .p1 = { .min = 1, .max = 8 },
312         .p2 = { .dot_limit = 112000,
313                 .p2_slow = 14, .p2_fast = 7 },
314 };
315
316
317 static const intel_limit_t intel_limits_g4x_sdvo = {
318         .dot = { .min = 25000, .max = 270000 },
319         .vco = { .min = 1750000, .max = 3500000},
320         .n = { .min = 1, .max = 4 },
321         .m = { .min = 104, .max = 138 },
322         .m1 = { .min = 17, .max = 23 },
323         .m2 = { .min = 5, .max = 11 },
324         .p = { .min = 10, .max = 30 },
325         .p1 = { .min = 1, .max = 3},
326         .p2 = { .dot_limit = 270000,
327                 .p2_slow = 10,
328                 .p2_fast = 10
329         },
330 };
331
332 static const intel_limit_t intel_limits_g4x_hdmi = {
333         .dot = { .min = 22000, .max = 400000 },
334         .vco = { .min = 1750000, .max = 3500000},
335         .n = { .min = 1, .max = 4 },
336         .m = { .min = 104, .max = 138 },
337         .m1 = { .min = 16, .max = 23 },
338         .m2 = { .min = 5, .max = 11 },
339         .p = { .min = 5, .max = 80 },
340         .p1 = { .min = 1, .max = 8},
341         .p2 = { .dot_limit = 165000,
342                 .p2_slow = 10, .p2_fast = 5 },
343 };
344
345 static const intel_limit_t intel_limits_g4x_single_channel_lvds = {
346         .dot = { .min = 20000, .max = 115000 },
347         .vco = { .min = 1750000, .max = 3500000 },
348         .n = { .min = 1, .max = 3 },
349         .m = { .min = 104, .max = 138 },
350         .m1 = { .min = 17, .max = 23 },
351         .m2 = { .min = 5, .max = 11 },
352         .p = { .min = 28, .max = 112 },
353         .p1 = { .min = 2, .max = 8 },
354         .p2 = { .dot_limit = 0,
355                 .p2_slow = 14, .p2_fast = 14
356         },
357 };
358
359 static const intel_limit_t intel_limits_g4x_dual_channel_lvds = {
360         .dot = { .min = 80000, .max = 224000 },
361         .vco = { .min = 1750000, .max = 3500000 },
362         .n = { .min = 1, .max = 3 },
363         .m = { .min = 104, .max = 138 },
364         .m1 = { .min = 17, .max = 23 },
365         .m2 = { .min = 5, .max = 11 },
366         .p = { .min = 14, .max = 42 },
367         .p1 = { .min = 2, .max = 6 },
368         .p2 = { .dot_limit = 0,
369                 .p2_slow = 7, .p2_fast = 7
370         },
371 };
372
373 static const intel_limit_t intel_limits_pineview_sdvo = {
374         .dot = { .min = 20000, .max = 400000},
375         .vco = { .min = 1700000, .max = 3500000 },
376         /* Pineview's Ncounter is a ring counter */
377         .n = { .min = 3, .max = 6 },
378         .m = { .min = 2, .max = 256 },
379         /* Pineview only has one combined m divider, which we treat as m2. */
380         .m1 = { .min = 0, .max = 0 },
381         .m2 = { .min = 0, .max = 254 },
382         .p = { .min = 5, .max = 80 },
383         .p1 = { .min = 1, .max = 8 },
384         .p2 = { .dot_limit = 200000,
385                 .p2_slow = 10, .p2_fast = 5 },
386 };
387
388 static const intel_limit_t intel_limits_pineview_lvds = {
389         .dot = { .min = 20000, .max = 400000 },
390         .vco = { .min = 1700000, .max = 3500000 },
391         .n = { .min = 3, .max = 6 },
392         .m = { .min = 2, .max = 256 },
393         .m1 = { .min = 0, .max = 0 },
394         .m2 = { .min = 0, .max = 254 },
395         .p = { .min = 7, .max = 112 },
396         .p1 = { .min = 1, .max = 8 },
397         .p2 = { .dot_limit = 112000,
398                 .p2_slow = 14, .p2_fast = 14 },
399 };
400
401 /* Ironlake / Sandybridge
402  *
403  * We calculate clock using (register_value + 2) for N/M1/M2, so here
404  * the range value for them is (actual_value - 2).
405  */
406 static const intel_limit_t intel_limits_ironlake_dac = {
407         .dot = { .min = 25000, .max = 350000 },
408         .vco = { .min = 1760000, .max = 3510000 },
409         .n = { .min = 1, .max = 5 },
410         .m = { .min = 79, .max = 127 },
411         .m1 = { .min = 12, .max = 22 },
412         .m2 = { .min = 5, .max = 9 },
413         .p = { .min = 5, .max = 80 },
414         .p1 = { .min = 1, .max = 8 },
415         .p2 = { .dot_limit = 225000,
416                 .p2_slow = 10, .p2_fast = 5 },
417 };
418
419 static const intel_limit_t intel_limits_ironlake_single_lvds = {
420         .dot = { .min = 25000, .max = 350000 },
421         .vco = { .min = 1760000, .max = 3510000 },
422         .n = { .min = 1, .max = 3 },
423         .m = { .min = 79, .max = 118 },
424         .m1 = { .min = 12, .max = 22 },
425         .m2 = { .min = 5, .max = 9 },
426         .p = { .min = 28, .max = 112 },
427         .p1 = { .min = 2, .max = 8 },
428         .p2 = { .dot_limit = 225000,
429                 .p2_slow = 14, .p2_fast = 14 },
430 };
431
432 static const intel_limit_t intel_limits_ironlake_dual_lvds = {
433         .dot = { .min = 25000, .max = 350000 },
434         .vco = { .min = 1760000, .max = 3510000 },
435         .n = { .min = 1, .max = 3 },
436         .m = { .min = 79, .max = 127 },
437         .m1 = { .min = 12, .max = 22 },
438         .m2 = { .min = 5, .max = 9 },
439         .p = { .min = 14, .max = 56 },
440         .p1 = { .min = 2, .max = 8 },
441         .p2 = { .dot_limit = 225000,
442                 .p2_slow = 7, .p2_fast = 7 },
443 };
444
445 /* LVDS 100mhz refclk limits. */
446 static const intel_limit_t intel_limits_ironlake_single_lvds_100m = {
447         .dot = { .min = 25000, .max = 350000 },
448         .vco = { .min = 1760000, .max = 3510000 },
449         .n = { .min = 1, .max = 2 },
450         .m = { .min = 79, .max = 126 },
451         .m1 = { .min = 12, .max = 22 },
452         .m2 = { .min = 5, .max = 9 },
453         .p = { .min = 28, .max = 112 },
454         .p1 = { .min = 2, .max = 8 },
455         .p2 = { .dot_limit = 225000,
456                 .p2_slow = 14, .p2_fast = 14 },
457 };
458
459 static const intel_limit_t intel_limits_ironlake_dual_lvds_100m = {
460         .dot = { .min = 25000, .max = 350000 },
461         .vco = { .min = 1760000, .max = 3510000 },
462         .n = { .min = 1, .max = 3 },
463         .m = { .min = 79, .max = 126 },
464         .m1 = { .min = 12, .max = 22 },
465         .m2 = { .min = 5, .max = 9 },
466         .p = { .min = 14, .max = 42 },
467         .p1 = { .min = 2, .max = 6 },
468         .p2 = { .dot_limit = 225000,
469                 .p2_slow = 7, .p2_fast = 7 },
470 };
471
472 static const intel_limit_t intel_limits_vlv = {
473          /*
474           * These are the data rate limits (measured in fast clocks)
475           * since those are the strictest limits we have. The fast
476           * clock and actual rate limits are more relaxed, so checking
477           * them would make no difference.
478           */
479         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
480         .vco = { .min = 4000000, .max = 6000000 },
481         .n = { .min = 1, .max = 7 },
482         .m1 = { .min = 2, .max = 3 },
483         .m2 = { .min = 11, .max = 156 },
484         .p1 = { .min = 2, .max = 3 },
485         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
486 };
487
488 static const intel_limit_t intel_limits_chv = {
489         /*
490          * These are the data rate limits (measured in fast clocks)
491          * since those are the strictest limits we have.  The fast
492          * clock and actual rate limits are more relaxed, so checking
493          * them would make no difference.
494          */
495         .dot = { .min = 25000 * 5, .max = 540000 * 5},
496         .vco = { .min = 4800000, .max = 6480000 },
497         .n = { .min = 1, .max = 1 },
498         .m1 = { .min = 2, .max = 2 },
499         .m2 = { .min = 24 << 22, .max = 175 << 22 },
500         .p1 = { .min = 2, .max = 4 },
501         .p2 = { .p2_slow = 1, .p2_fast = 14 },
502 };
503
504 static const intel_limit_t intel_limits_bxt = {
505         /* FIXME: find real dot limits */
506         .dot = { .min = 0, .max = INT_MAX },
507         .vco = { .min = 4800000, .max = 6700000 },
508         .n = { .min = 1, .max = 1 },
509         .m1 = { .min = 2, .max = 2 },
510         /* FIXME: find real m2 limits */
511         .m2 = { .min = 2 << 22, .max = 255 << 22 },
512         .p1 = { .min = 2, .max = 4 },
513         .p2 = { .p2_slow = 1, .p2_fast = 20 },
514 };
515
516 static bool
517 needs_modeset(struct drm_crtc_state *state)
518 {
519         return drm_atomic_crtc_needs_modeset(state);
520 }
521
522 /**
523  * Returns whether any output on the specified pipe is of the specified type
524  */
525 bool intel_pipe_has_type(struct intel_crtc *crtc, enum intel_output_type type)
526 {
527         struct drm_device *dev = crtc->base.dev;
528         struct intel_encoder *encoder;
529
530         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
531                 if (encoder->type == type)
532                         return true;
533
534         return false;
535 }
536
537 /**
538  * Returns whether any output on the specified pipe will have the specified
539  * type after a staged modeset is complete, i.e., the same as
540  * intel_pipe_has_type() but looking at encoder->new_crtc instead of
541  * encoder->crtc.
542  */
543 static bool intel_pipe_will_have_type(const struct intel_crtc_state *crtc_state,
544                                       int type)
545 {
546         struct drm_atomic_state *state = crtc_state->base.state;
547         struct drm_connector *connector;
548         struct drm_connector_state *connector_state;
549         struct intel_encoder *encoder;
550         int i, num_connectors = 0;
551
552         for_each_connector_in_state(state, connector, connector_state, i) {
553                 if (connector_state->crtc != crtc_state->base.crtc)
554                         continue;
555
556                 num_connectors++;
557
558                 encoder = to_intel_encoder(connector_state->best_encoder);
559                 if (encoder->type == type)
560                         return true;
561         }
562
563         WARN_ON(num_connectors == 0);
564
565         return false;
566 }
567
568 /*
569  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
570  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
571  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
572  * The helpers' return value is the rate of the clock that is fed to the
573  * display engine's pipe which can be the above fast dot clock rate or a
574  * divided-down version of it.
575  */
576 /* m1 is reserved as 0 in Pineview, n is a ring counter */
577 static int pnv_calc_dpll_params(int refclk, intel_clock_t *clock)
578 {
579         clock->m = clock->m2 + 2;
580         clock->p = clock->p1 * clock->p2;
581         if (WARN_ON(clock->n == 0 || clock->p == 0))
582                 return 0;
583         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
584         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
585
586         return clock->dot;
587 }
588
589 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
590 {
591         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
592 }
593
594 static int i9xx_calc_dpll_params(int refclk, intel_clock_t *clock)
595 {
596         clock->m = i9xx_dpll_compute_m(clock);
597         clock->p = clock->p1 * clock->p2;
598         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
599                 return 0;
600         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
601         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
602
603         return clock->dot;
604 }
605
606 static int vlv_calc_dpll_params(int refclk, intel_clock_t *clock)
607 {
608         clock->m = clock->m1 * clock->m2;
609         clock->p = clock->p1 * clock->p2;
610         if (WARN_ON(clock->n == 0 || clock->p == 0))
611                 return 0;
612         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
613         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
614
615         return clock->dot / 5;
616 }
617
618 int chv_calc_dpll_params(int refclk, intel_clock_t *clock)
619 {
620         clock->m = clock->m1 * clock->m2;
621         clock->p = clock->p1 * clock->p2;
622         if (WARN_ON(clock->n == 0 || clock->p == 0))
623                 return 0;
624         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
625                         clock->n << 22);
626         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
627
628         return clock->dot / 5;
629 }
630
631 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
632 /**
633  * Returns whether the given set of divisors are valid for a given refclk with
634  * the given connectors.
635  */
636
637 static bool intel_PLL_is_valid(struct drm_device *dev,
638                                const intel_limit_t *limit,
639                                const intel_clock_t *clock)
640 {
641         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
642                 INTELPllInvalid("n out of range\n");
643         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
644                 INTELPllInvalid("p1 out of range\n");
645         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
646                 INTELPllInvalid("m2 out of range\n");
647         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
648                 INTELPllInvalid("m1 out of range\n");
649
650         if (!IS_PINEVIEW(dev) && !IS_VALLEYVIEW(dev) &&
651             !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev))
652                 if (clock->m1 <= clock->m2)
653                         INTELPllInvalid("m1 <= m2\n");
654
655         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) && !IS_BROXTON(dev)) {
656                 if (clock->p < limit->p.min || limit->p.max < clock->p)
657                         INTELPllInvalid("p out of range\n");
658                 if (clock->m < limit->m.min || limit->m.max < clock->m)
659                         INTELPllInvalid("m out of range\n");
660         }
661
662         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
663                 INTELPllInvalid("vco out of range\n");
664         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
665          * connector, etc., rather than just a single range.
666          */
667         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
668                 INTELPllInvalid("dot out of range\n");
669
670         return true;
671 }
672
673 static int
674 i9xx_select_p2_div(const intel_limit_t *limit,
675                    const struct intel_crtc_state *crtc_state,
676                    int target)
677 {
678         struct drm_device *dev = crtc_state->base.crtc->dev;
679
680         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
681                 /*
682                  * For LVDS just rely on its current settings for dual-channel.
683                  * We haven't figured out how to reliably set up different
684                  * single/dual channel state, if we even can.
685                  */
686                 if (intel_is_dual_link_lvds(dev))
687                         return limit->p2.p2_fast;
688                 else
689                         return limit->p2.p2_slow;
690         } else {
691                 if (target < limit->p2.dot_limit)
692                         return limit->p2.p2_slow;
693                 else
694                         return limit->p2.p2_fast;
695         }
696 }
697
698 /*
699  * Returns a set of divisors for the desired target clock with the given
700  * refclk, or FALSE.  The returned values represent the clock equation:
701  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
702  *
703  * Target and reference clocks are specified in kHz.
704  *
705  * If match_clock is provided, then best_clock P divider must match the P
706  * divider from @match_clock used for LVDS downclocking.
707  */
708 static bool
709 i9xx_find_best_dpll(const intel_limit_t *limit,
710                     struct intel_crtc_state *crtc_state,
711                     int target, int refclk, intel_clock_t *match_clock,
712                     intel_clock_t *best_clock)
713 {
714         struct drm_device *dev = crtc_state->base.crtc->dev;
715         intel_clock_t clock;
716         int err = target;
717
718         memset(best_clock, 0, sizeof(*best_clock));
719
720         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
721
722         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
723              clock.m1++) {
724                 for (clock.m2 = limit->m2.min;
725                      clock.m2 <= limit->m2.max; clock.m2++) {
726                         if (clock.m2 >= clock.m1)
727                                 break;
728                         for (clock.n = limit->n.min;
729                              clock.n <= limit->n.max; clock.n++) {
730                                 for (clock.p1 = limit->p1.min;
731                                         clock.p1 <= limit->p1.max; clock.p1++) {
732                                         int this_err;
733
734                                         i9xx_calc_dpll_params(refclk, &clock);
735                                         if (!intel_PLL_is_valid(dev, limit,
736                                                                 &clock))
737                                                 continue;
738                                         if (match_clock &&
739                                             clock.p != match_clock->p)
740                                                 continue;
741
742                                         this_err = abs(clock.dot - target);
743                                         if (this_err < err) {
744                                                 *best_clock = clock;
745                                                 err = this_err;
746                                         }
747                                 }
748                         }
749                 }
750         }
751
752         return (err != target);
753 }
754
755 /*
756  * Returns a set of divisors for the desired target clock with the given
757  * refclk, or FALSE.  The returned values represent the clock equation:
758  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
759  *
760  * Target and reference clocks are specified in kHz.
761  *
762  * If match_clock is provided, then best_clock P divider must match the P
763  * divider from @match_clock used for LVDS downclocking.
764  */
765 static bool
766 pnv_find_best_dpll(const intel_limit_t *limit,
767                    struct intel_crtc_state *crtc_state,
768                    int target, int refclk, intel_clock_t *match_clock,
769                    intel_clock_t *best_clock)
770 {
771         struct drm_device *dev = crtc_state->base.crtc->dev;
772         intel_clock_t clock;
773         int err = target;
774
775         memset(best_clock, 0, sizeof(*best_clock));
776
777         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
778
779         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
780              clock.m1++) {
781                 for (clock.m2 = limit->m2.min;
782                      clock.m2 <= limit->m2.max; clock.m2++) {
783                         for (clock.n = limit->n.min;
784                              clock.n <= limit->n.max; clock.n++) {
785                                 for (clock.p1 = limit->p1.min;
786                                         clock.p1 <= limit->p1.max; clock.p1++) {
787                                         int this_err;
788
789                                         pnv_calc_dpll_params(refclk, &clock);
790                                         if (!intel_PLL_is_valid(dev, limit,
791                                                                 &clock))
792                                                 continue;
793                                         if (match_clock &&
794                                             clock.p != match_clock->p)
795                                                 continue;
796
797                                         this_err = abs(clock.dot - target);
798                                         if (this_err < err) {
799                                                 *best_clock = clock;
800                                                 err = this_err;
801                                         }
802                                 }
803                         }
804                 }
805         }
806
807         return (err != target);
808 }
809
810 /*
811  * Returns a set of divisors for the desired target clock with the given
812  * refclk, or FALSE.  The returned values represent the clock equation:
813  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
814  *
815  * Target and reference clocks are specified in kHz.
816  *
817  * If match_clock is provided, then best_clock P divider must match the P
818  * divider from @match_clock used for LVDS downclocking.
819  */
820 static bool
821 g4x_find_best_dpll(const intel_limit_t *limit,
822                    struct intel_crtc_state *crtc_state,
823                    int target, int refclk, intel_clock_t *match_clock,
824                    intel_clock_t *best_clock)
825 {
826         struct drm_device *dev = crtc_state->base.crtc->dev;
827         intel_clock_t clock;
828         int max_n;
829         bool found = false;
830         /* approximately equals target * 0.00585 */
831         int err_most = (target >> 8) + (target >> 9);
832
833         memset(best_clock, 0, sizeof(*best_clock));
834
835         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
836
837         max_n = limit->n.max;
838         /* based on hardware requirement, prefer smaller n to precision */
839         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
840                 /* based on hardware requirement, prefere larger m1,m2 */
841                 for (clock.m1 = limit->m1.max;
842                      clock.m1 >= limit->m1.min; clock.m1--) {
843                         for (clock.m2 = limit->m2.max;
844                              clock.m2 >= limit->m2.min; clock.m2--) {
845                                 for (clock.p1 = limit->p1.max;
846                                      clock.p1 >= limit->p1.min; clock.p1--) {
847                                         int this_err;
848
849                                         i9xx_calc_dpll_params(refclk, &clock);
850                                         if (!intel_PLL_is_valid(dev, limit,
851                                                                 &clock))
852                                                 continue;
853
854                                         this_err = abs(clock.dot - target);
855                                         if (this_err < err_most) {
856                                                 *best_clock = clock;
857                                                 err_most = this_err;
858                                                 max_n = clock.n;
859                                                 found = true;
860                                         }
861                                 }
862                         }
863                 }
864         }
865         return found;
866 }
867
868 /*
869  * Check if the calculated PLL configuration is more optimal compared to the
870  * best configuration and error found so far. Return the calculated error.
871  */
872 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
873                                const intel_clock_t *calculated_clock,
874                                const intel_clock_t *best_clock,
875                                unsigned int best_error_ppm,
876                                unsigned int *error_ppm)
877 {
878         /*
879          * For CHV ignore the error and consider only the P value.
880          * Prefer a bigger P value based on HW requirements.
881          */
882         if (IS_CHERRYVIEW(dev)) {
883                 *error_ppm = 0;
884
885                 return calculated_clock->p > best_clock->p;
886         }
887
888         if (WARN_ON_ONCE(!target_freq))
889                 return false;
890
891         *error_ppm = div_u64(1000000ULL *
892                                 abs(target_freq - calculated_clock->dot),
893                              target_freq);
894         /*
895          * Prefer a better P value over a better (smaller) error if the error
896          * is small. Ensure this preference for future configurations too by
897          * setting the error to 0.
898          */
899         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
900                 *error_ppm = 0;
901
902                 return true;
903         }
904
905         return *error_ppm + 10 < best_error_ppm;
906 }
907
908 /*
909  * Returns a set of divisors for the desired target clock with the given
910  * refclk, or FALSE.  The returned values represent the clock equation:
911  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
912  */
913 static bool
914 vlv_find_best_dpll(const intel_limit_t *limit,
915                    struct intel_crtc_state *crtc_state,
916                    int target, int refclk, intel_clock_t *match_clock,
917                    intel_clock_t *best_clock)
918 {
919         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
920         struct drm_device *dev = crtc->base.dev;
921         intel_clock_t clock;
922         unsigned int bestppm = 1000000;
923         /* min update 19.2 MHz */
924         int max_n = min(limit->n.max, refclk / 19200);
925         bool found = false;
926
927         target *= 5; /* fast clock */
928
929         memset(best_clock, 0, sizeof(*best_clock));
930
931         /* based on hardware requirement, prefer smaller n to precision */
932         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
933                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
934                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
935                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
936                                 clock.p = clock.p1 * clock.p2;
937                                 /* based on hardware requirement, prefer bigger m1,m2 values */
938                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
939                                         unsigned int ppm;
940
941                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
942                                                                      refclk * clock.m1);
943
944                                         vlv_calc_dpll_params(refclk, &clock);
945
946                                         if (!intel_PLL_is_valid(dev, limit,
947                                                                 &clock))
948                                                 continue;
949
950                                         if (!vlv_PLL_is_optimal(dev, target,
951                                                                 &clock,
952                                                                 best_clock,
953                                                                 bestppm, &ppm))
954                                                 continue;
955
956                                         *best_clock = clock;
957                                         bestppm = ppm;
958                                         found = true;
959                                 }
960                         }
961                 }
962         }
963
964         return found;
965 }
966
967 /*
968  * Returns a set of divisors for the desired target clock with the given
969  * refclk, or FALSE.  The returned values represent the clock equation:
970  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
971  */
972 static bool
973 chv_find_best_dpll(const intel_limit_t *limit,
974                    struct intel_crtc_state *crtc_state,
975                    int target, int refclk, intel_clock_t *match_clock,
976                    intel_clock_t *best_clock)
977 {
978         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
979         struct drm_device *dev = crtc->base.dev;
980         unsigned int best_error_ppm;
981         intel_clock_t clock;
982         uint64_t m2;
983         int found = false;
984
985         memset(best_clock, 0, sizeof(*best_clock));
986         best_error_ppm = 1000000;
987
988         /*
989          * Based on hardware doc, the n always set to 1, and m1 always
990          * set to 2.  If requires to support 200Mhz refclk, we need to
991          * revisit this because n may not 1 anymore.
992          */
993         clock.n = 1, clock.m1 = 2;
994         target *= 5;    /* fast clock */
995
996         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
997                 for (clock.p2 = limit->p2.p2_fast;
998                                 clock.p2 >= limit->p2.p2_slow;
999                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
1000                         unsigned int error_ppm;
1001
1002                         clock.p = clock.p1 * clock.p2;
1003
1004                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
1005                                         clock.n) << 22, refclk * clock.m1);
1006
1007                         if (m2 > INT_MAX/clock.m1)
1008                                 continue;
1009
1010                         clock.m2 = m2;
1011
1012                         chv_calc_dpll_params(refclk, &clock);
1013
1014                         if (!intel_PLL_is_valid(dev, limit, &clock))
1015                                 continue;
1016
1017                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
1018                                                 best_error_ppm, &error_ppm))
1019                                 continue;
1020
1021                         *best_clock = clock;
1022                         best_error_ppm = error_ppm;
1023                         found = true;
1024                 }
1025         }
1026
1027         return found;
1028 }
1029
1030 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1031                         intel_clock_t *best_clock)
1032 {
1033         int refclk = 100000;
1034         const intel_limit_t *limit = &intel_limits_bxt;
1035
1036         return chv_find_best_dpll(limit, crtc_state,
1037                                   target_clock, refclk, NULL, best_clock);
1038 }
1039
1040 bool intel_crtc_active(struct drm_crtc *crtc)
1041 {
1042         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1043
1044         /* Be paranoid as we can arrive here with only partial
1045          * state retrieved from the hardware during setup.
1046          *
1047          * We can ditch the adjusted_mode.crtc_clock check as soon
1048          * as Haswell has gained clock readout/fastboot support.
1049          *
1050          * We can ditch the crtc->primary->fb check as soon as we can
1051          * properly reconstruct framebuffers.
1052          *
1053          * FIXME: The intel_crtc->active here should be switched to
1054          * crtc->state->active once we have proper CRTC states wired up
1055          * for atomic.
1056          */
1057         return intel_crtc->active && crtc->primary->state->fb &&
1058                 intel_crtc->config->base.adjusted_mode.crtc_clock;
1059 }
1060
1061 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1062                                              enum pipe pipe)
1063 {
1064         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1065         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1066
1067         return intel_crtc->config->cpu_transcoder;
1068 }
1069
1070 static bool pipe_dsl_stopped(struct drm_device *dev, enum pipe pipe)
1071 {
1072         struct drm_i915_private *dev_priv = dev->dev_private;
1073         i915_reg_t reg = PIPEDSL(pipe);
1074         u32 line1, line2;
1075         u32 line_mask;
1076
1077         if (IS_GEN2(dev))
1078                 line_mask = DSL_LINEMASK_GEN2;
1079         else
1080                 line_mask = DSL_LINEMASK_GEN3;
1081
1082         line1 = I915_READ(reg) & line_mask;
1083         msleep(5);
1084         line2 = I915_READ(reg) & line_mask;
1085
1086         return line1 == line2;
1087 }
1088
1089 /*
1090  * intel_wait_for_pipe_off - wait for pipe to turn off
1091  * @crtc: crtc whose pipe to wait for
1092  *
1093  * After disabling a pipe, we can't wait for vblank in the usual way,
1094  * spinning on the vblank interrupt status bit, since we won't actually
1095  * see an interrupt when the pipe is disabled.
1096  *
1097  * On Gen4 and above:
1098  *   wait for the pipe register state bit to turn off
1099  *
1100  * Otherwise:
1101  *   wait for the display line value to settle (it usually
1102  *   ends up stopping at the start of the next frame).
1103  *
1104  */
1105 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1106 {
1107         struct drm_device *dev = crtc->base.dev;
1108         struct drm_i915_private *dev_priv = dev->dev_private;
1109         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1110         enum pipe pipe = crtc->pipe;
1111
1112         if (INTEL_INFO(dev)->gen >= 4) {
1113                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1114
1115                 /* Wait for the Pipe State to go off */
1116                 if (wait_for((I915_READ(reg) & I965_PIPECONF_ACTIVE) == 0,
1117                              100))
1118                         WARN(1, "pipe_off wait timed out\n");
1119         } else {
1120                 /* Wait for the display line to settle */
1121                 if (wait_for(pipe_dsl_stopped(dev, pipe), 100))
1122                         WARN(1, "pipe_off wait timed out\n");
1123         }
1124 }
1125
1126 /* Only for pre-ILK configs */
1127 void assert_pll(struct drm_i915_private *dev_priv,
1128                 enum pipe pipe, bool state)
1129 {
1130         u32 val;
1131         bool cur_state;
1132
1133         val = I915_READ(DPLL(pipe));
1134         cur_state = !!(val & DPLL_VCO_ENABLE);
1135         I915_STATE_WARN(cur_state != state,
1136              "PLL state assertion failure (expected %s, current %s)\n",
1137                         onoff(state), onoff(cur_state));
1138 }
1139
1140 /* XXX: the dsi pll is shared between MIPI DSI ports */
1141 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1142 {
1143         u32 val;
1144         bool cur_state;
1145
1146         mutex_lock(&dev_priv->sb_lock);
1147         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1148         mutex_unlock(&dev_priv->sb_lock);
1149
1150         cur_state = val & DSI_PLL_VCO_EN;
1151         I915_STATE_WARN(cur_state != state,
1152              "DSI PLL state assertion failure (expected %s, current %s)\n",
1153                         onoff(state), onoff(cur_state));
1154 }
1155
1156 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1157                           enum pipe pipe, bool state)
1158 {
1159         bool cur_state;
1160         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1161                                                                       pipe);
1162
1163         if (HAS_DDI(dev_priv->dev)) {
1164                 /* DDI does not have a specific FDI_TX register */
1165                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1166                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1167         } else {
1168                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1169                 cur_state = !!(val & FDI_TX_ENABLE);
1170         }
1171         I915_STATE_WARN(cur_state != state,
1172              "FDI TX state assertion failure (expected %s, current %s)\n",
1173                         onoff(state), onoff(cur_state));
1174 }
1175 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1176 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1177
1178 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1179                           enum pipe pipe, bool state)
1180 {
1181         u32 val;
1182         bool cur_state;
1183
1184         val = I915_READ(FDI_RX_CTL(pipe));
1185         cur_state = !!(val & FDI_RX_ENABLE);
1186         I915_STATE_WARN(cur_state != state,
1187              "FDI RX state assertion failure (expected %s, current %s)\n",
1188                         onoff(state), onoff(cur_state));
1189 }
1190 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1191 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1192
1193 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1194                                       enum pipe pipe)
1195 {
1196         u32 val;
1197
1198         /* ILK FDI PLL is always enabled */
1199         if (INTEL_INFO(dev_priv->dev)->gen == 5)
1200                 return;
1201
1202         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1203         if (HAS_DDI(dev_priv->dev))
1204                 return;
1205
1206         val = I915_READ(FDI_TX_CTL(pipe));
1207         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1208 }
1209
1210 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1211                        enum pipe pipe, bool state)
1212 {
1213         u32 val;
1214         bool cur_state;
1215
1216         val = I915_READ(FDI_RX_CTL(pipe));
1217         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1218         I915_STATE_WARN(cur_state != state,
1219              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1220                         onoff(state), onoff(cur_state));
1221 }
1222
1223 void assert_panel_unlocked(struct drm_i915_private *dev_priv,
1224                            enum pipe pipe)
1225 {
1226         struct drm_device *dev = dev_priv->dev;
1227         i915_reg_t pp_reg;
1228         u32 val;
1229         enum pipe panel_pipe = PIPE_A;
1230         bool locked = true;
1231
1232         if (WARN_ON(HAS_DDI(dev)))
1233                 return;
1234
1235         if (HAS_PCH_SPLIT(dev)) {
1236                 u32 port_sel;
1237
1238                 pp_reg = PCH_PP_CONTROL;
1239                 port_sel = I915_READ(PCH_PP_ON_DELAYS) & PANEL_PORT_SELECT_MASK;
1240
1241                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1242                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1243                         panel_pipe = PIPE_B;
1244                 /* XXX: else fix for eDP */
1245         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1246                 /* presumably write lock depends on pipe, not port select */
1247                 pp_reg = VLV_PIPE_PP_CONTROL(pipe);
1248                 panel_pipe = pipe;
1249         } else {
1250                 pp_reg = PP_CONTROL;
1251                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1252                         panel_pipe = PIPE_B;
1253         }
1254
1255         val = I915_READ(pp_reg);
1256         if (!(val & PANEL_POWER_ON) ||
1257             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1258                 locked = false;
1259
1260         I915_STATE_WARN(panel_pipe == pipe && locked,
1261              "panel assertion failure, pipe %c regs locked\n",
1262              pipe_name(pipe));
1263 }
1264
1265 static void assert_cursor(struct drm_i915_private *dev_priv,
1266                           enum pipe pipe, bool state)
1267 {
1268         struct drm_device *dev = dev_priv->dev;
1269         bool cur_state;
1270
1271         if (IS_845G(dev) || IS_I865G(dev))
1272                 cur_state = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
1273         else
1274                 cur_state = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
1275
1276         I915_STATE_WARN(cur_state != state,
1277              "cursor on pipe %c assertion failure (expected %s, current %s)\n",
1278                         pipe_name(pipe), onoff(state), onoff(cur_state));
1279 }
1280 #define assert_cursor_enabled(d, p) assert_cursor(d, p, true)
1281 #define assert_cursor_disabled(d, p) assert_cursor(d, p, false)
1282
1283 void assert_pipe(struct drm_i915_private *dev_priv,
1284                  enum pipe pipe, bool state)
1285 {
1286         bool cur_state;
1287         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1288                                                                       pipe);
1289         enum intel_display_power_domain power_domain;
1290
1291         /* if we need the pipe quirk it must be always on */
1292         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1293             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1294                 state = true;
1295
1296         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1297         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1298                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1299                 cur_state = !!(val & PIPECONF_ENABLE);
1300
1301                 intel_display_power_put(dev_priv, power_domain);
1302         } else {
1303                 cur_state = false;
1304         }
1305
1306         I915_STATE_WARN(cur_state != state,
1307              "pipe %c assertion failure (expected %s, current %s)\n",
1308                         pipe_name(pipe), onoff(state), onoff(cur_state));
1309 }
1310
1311 static void assert_plane(struct drm_i915_private *dev_priv,
1312                          enum plane plane, bool state)
1313 {
1314         u32 val;
1315         bool cur_state;
1316
1317         val = I915_READ(DSPCNTR(plane));
1318         cur_state = !!(val & DISPLAY_PLANE_ENABLE);
1319         I915_STATE_WARN(cur_state != state,
1320              "plane %c assertion failure (expected %s, current %s)\n",
1321                         plane_name(plane), onoff(state), onoff(cur_state));
1322 }
1323
1324 #define assert_plane_enabled(d, p) assert_plane(d, p, true)
1325 #define assert_plane_disabled(d, p) assert_plane(d, p, false)
1326
1327 static void assert_planes_disabled(struct drm_i915_private *dev_priv,
1328                                    enum pipe pipe)
1329 {
1330         struct drm_device *dev = dev_priv->dev;
1331         int i;
1332
1333         /* Primary planes are fixed to pipes on gen4+ */
1334         if (INTEL_INFO(dev)->gen >= 4) {
1335                 u32 val = I915_READ(DSPCNTR(pipe));
1336                 I915_STATE_WARN(val & DISPLAY_PLANE_ENABLE,
1337                      "plane %c assertion failure, should be disabled but not\n",
1338                      plane_name(pipe));
1339                 return;
1340         }
1341
1342         /* Need to check both planes against the pipe */
1343         for_each_pipe(dev_priv, i) {
1344                 u32 val = I915_READ(DSPCNTR(i));
1345                 enum pipe cur_pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
1346                         DISPPLANE_SEL_PIPE_SHIFT;
1347                 I915_STATE_WARN((val & DISPLAY_PLANE_ENABLE) && pipe == cur_pipe,
1348                      "plane %c assertion failure, should be off on pipe %c but is still active\n",
1349                      plane_name(i), pipe_name(pipe));
1350         }
1351 }
1352
1353 static void assert_sprites_disabled(struct drm_i915_private *dev_priv,
1354                                     enum pipe pipe)
1355 {
1356         struct drm_device *dev = dev_priv->dev;
1357         int sprite;
1358
1359         if (INTEL_INFO(dev)->gen >= 9) {
1360                 for_each_sprite(dev_priv, pipe, sprite) {
1361                         u32 val = I915_READ(PLANE_CTL(pipe, sprite));
1362                         I915_STATE_WARN(val & PLANE_CTL_ENABLE,
1363                              "plane %d assertion failure, should be off on pipe %c but is still active\n",
1364                              sprite, pipe_name(pipe));
1365                 }
1366         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
1367                 for_each_sprite(dev_priv, pipe, sprite) {
1368                         u32 val = I915_READ(SPCNTR(pipe, sprite));
1369                         I915_STATE_WARN(val & SP_ENABLE,
1370                              "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1371                              sprite_name(pipe, sprite), pipe_name(pipe));
1372                 }
1373         } else if (INTEL_INFO(dev)->gen >= 7) {
1374                 u32 val = I915_READ(SPRCTL(pipe));
1375                 I915_STATE_WARN(val & SPRITE_ENABLE,
1376                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1377                      plane_name(pipe), pipe_name(pipe));
1378         } else if (INTEL_INFO(dev)->gen >= 5) {
1379                 u32 val = I915_READ(DVSCNTR(pipe));
1380                 I915_STATE_WARN(val & DVS_ENABLE,
1381                      "sprite %c assertion failure, should be off on pipe %c but is still active\n",
1382                      plane_name(pipe), pipe_name(pipe));
1383         }
1384 }
1385
1386 static void assert_vblank_disabled(struct drm_crtc *crtc)
1387 {
1388         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1389                 drm_crtc_vblank_put(crtc);
1390 }
1391
1392 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1393                                     enum pipe pipe)
1394 {
1395         u32 val;
1396         bool enabled;
1397
1398         val = I915_READ(PCH_TRANSCONF(pipe));
1399         enabled = !!(val & TRANS_ENABLE);
1400         I915_STATE_WARN(enabled,
1401              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1402              pipe_name(pipe));
1403 }
1404
1405 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1406                             enum pipe pipe, u32 port_sel, u32 val)
1407 {
1408         if ((val & DP_PORT_EN) == 0)
1409                 return false;
1410
1411         if (HAS_PCH_CPT(dev_priv->dev)) {
1412                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1413                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1414                         return false;
1415         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1416                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1417                         return false;
1418         } else {
1419                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1420                         return false;
1421         }
1422         return true;
1423 }
1424
1425 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1426                               enum pipe pipe, u32 val)
1427 {
1428         if ((val & SDVO_ENABLE) == 0)
1429                 return false;
1430
1431         if (HAS_PCH_CPT(dev_priv->dev)) {
1432                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1433                         return false;
1434         } else if (IS_CHERRYVIEW(dev_priv->dev)) {
1435                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1436                         return false;
1437         } else {
1438                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1439                         return false;
1440         }
1441         return true;
1442 }
1443
1444 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1445                               enum pipe pipe, u32 val)
1446 {
1447         if ((val & LVDS_PORT_EN) == 0)
1448                 return false;
1449
1450         if (HAS_PCH_CPT(dev_priv->dev)) {
1451                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1452                         return false;
1453         } else {
1454                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1455                         return false;
1456         }
1457         return true;
1458 }
1459
1460 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1461                               enum pipe pipe, u32 val)
1462 {
1463         if ((val & ADPA_DAC_ENABLE) == 0)
1464                 return false;
1465         if (HAS_PCH_CPT(dev_priv->dev)) {
1466                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1467                         return false;
1468         } else {
1469                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1470                         return false;
1471         }
1472         return true;
1473 }
1474
1475 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1476                                    enum pipe pipe, i915_reg_t reg,
1477                                    u32 port_sel)
1478 {
1479         u32 val = I915_READ(reg);
1480         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1481              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1482              i915_mmio_reg_offset(reg), pipe_name(pipe));
1483
1484         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & DP_PORT_EN) == 0
1485              && (val & DP_PIPEB_SELECT),
1486              "IBX PCH dp port still using transcoder B\n");
1487 }
1488
1489 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1490                                      enum pipe pipe, i915_reg_t reg)
1491 {
1492         u32 val = I915_READ(reg);
1493         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1494              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1495              i915_mmio_reg_offset(reg), pipe_name(pipe));
1496
1497         I915_STATE_WARN(HAS_PCH_IBX(dev_priv->dev) && (val & SDVO_ENABLE) == 0
1498              && (val & SDVO_PIPE_B_SELECT),
1499              "IBX PCH hdmi port still using transcoder B\n");
1500 }
1501
1502 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1503                                       enum pipe pipe)
1504 {
1505         u32 val;
1506
1507         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1508         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1509         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1510
1511         val = I915_READ(PCH_ADPA);
1512         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1513              "PCH VGA enabled on transcoder %c, should be disabled\n",
1514              pipe_name(pipe));
1515
1516         val = I915_READ(PCH_LVDS);
1517         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1518              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1519              pipe_name(pipe));
1520
1521         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1522         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1523         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1524 }
1525
1526 static void vlv_enable_pll(struct intel_crtc *crtc,
1527                            const struct intel_crtc_state *pipe_config)
1528 {
1529         struct drm_device *dev = crtc->base.dev;
1530         struct drm_i915_private *dev_priv = dev->dev_private;
1531         enum pipe pipe = crtc->pipe;
1532         i915_reg_t reg = DPLL(pipe);
1533         u32 dpll = pipe_config->dpll_hw_state.dpll;
1534
1535         assert_pipe_disabled(dev_priv, pipe);
1536
1537         /* PLL is protected by panel, make sure we can write it */
1538         assert_panel_unlocked(dev_priv, pipe);
1539
1540         I915_WRITE(reg, dpll);
1541         POSTING_READ(reg);
1542         udelay(150);
1543
1544         if (wait_for(((I915_READ(reg) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1545                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1546
1547         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1548         POSTING_READ(DPLL_MD(pipe));
1549
1550         /* We do this three times for luck */
1551         I915_WRITE(reg, dpll);
1552         POSTING_READ(reg);
1553         udelay(150); /* wait for warmup */
1554         I915_WRITE(reg, dpll);
1555         POSTING_READ(reg);
1556         udelay(150); /* wait for warmup */
1557         I915_WRITE(reg, dpll);
1558         POSTING_READ(reg);
1559         udelay(150); /* wait for warmup */
1560 }
1561
1562 static void chv_enable_pll(struct intel_crtc *crtc,
1563                            const struct intel_crtc_state *pipe_config)
1564 {
1565         struct drm_device *dev = crtc->base.dev;
1566         struct drm_i915_private *dev_priv = dev->dev_private;
1567         enum pipe pipe = crtc->pipe;
1568         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1569         u32 tmp;
1570
1571         assert_pipe_disabled(dev_priv, pipe);
1572
1573         /* PLL is protected by panel, make sure we can write it */
1574         assert_panel_unlocked(dev_priv, pipe);
1575
1576         mutex_lock(&dev_priv->sb_lock);
1577
1578         /* Enable back the 10bit clock to display controller */
1579         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1580         tmp |= DPIO_DCLKP_EN;
1581         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1582
1583         mutex_unlock(&dev_priv->sb_lock);
1584
1585         /*
1586          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1587          */
1588         udelay(1);
1589
1590         /* Enable PLL */
1591         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1592
1593         /* Check PLL is locked */
1594         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1595                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1596
1597         if (pipe != PIPE_A) {
1598                 /*
1599                  * WaPixelRepeatModeFixForC0:chv
1600                  *
1601                  * DPLLCMD is AWOL. Use chicken bits to propagate
1602                  * the value from DPLLBMD to either pipe B or C.
1603                  */
1604                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1605                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1606                 I915_WRITE(CBR4_VLV, 0);
1607                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1608
1609                 /*
1610                  * DPLLB VGA mode also seems to cause problems.
1611                  * We should always have it disabled.
1612                  */
1613                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1614         } else {
1615                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1616                 POSTING_READ(DPLL_MD(pipe));
1617         }
1618 }
1619
1620 static int intel_num_dvo_pipes(struct drm_device *dev)
1621 {
1622         struct intel_crtc *crtc;
1623         int count = 0;
1624
1625         for_each_intel_crtc(dev, crtc)
1626                 count += crtc->base.state->active &&
1627                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1628
1629         return count;
1630 }
1631
1632 static void i9xx_enable_pll(struct intel_crtc *crtc)
1633 {
1634         struct drm_device *dev = crtc->base.dev;
1635         struct drm_i915_private *dev_priv = dev->dev_private;
1636         i915_reg_t reg = DPLL(crtc->pipe);
1637         u32 dpll = crtc->config->dpll_hw_state.dpll;
1638
1639         assert_pipe_disabled(dev_priv, crtc->pipe);
1640
1641         /* PLL is protected by panel, make sure we can write it */
1642         if (IS_MOBILE(dev) && !IS_I830(dev))
1643                 assert_panel_unlocked(dev_priv, crtc->pipe);
1644
1645         /* Enable DVO 2x clock on both PLLs if necessary */
1646         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1647                 /*
1648                  * It appears to be important that we don't enable this
1649                  * for the current pipe before otherwise configuring the
1650                  * PLL. No idea how this should be handled if multiple
1651                  * DVO outputs are enabled simultaneosly.
1652                  */
1653                 dpll |= DPLL_DVO_2X_MODE;
1654                 I915_WRITE(DPLL(!crtc->pipe),
1655                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1656         }
1657
1658         /*
1659          * Apparently we need to have VGA mode enabled prior to changing
1660          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1661          * dividers, even though the register value does change.
1662          */
1663         I915_WRITE(reg, 0);
1664
1665         I915_WRITE(reg, dpll);
1666
1667         /* Wait for the clocks to stabilize. */
1668         POSTING_READ(reg);
1669         udelay(150);
1670
1671         if (INTEL_INFO(dev)->gen >= 4) {
1672                 I915_WRITE(DPLL_MD(crtc->pipe),
1673                            crtc->config->dpll_hw_state.dpll_md);
1674         } else {
1675                 /* The pixel multiplier can only be updated once the
1676                  * DPLL is enabled and the clocks are stable.
1677                  *
1678                  * So write it again.
1679                  */
1680                 I915_WRITE(reg, dpll);
1681         }
1682
1683         /* We do this three times for luck */
1684         I915_WRITE(reg, dpll);
1685         POSTING_READ(reg);
1686         udelay(150); /* wait for warmup */
1687         I915_WRITE(reg, dpll);
1688         POSTING_READ(reg);
1689         udelay(150); /* wait for warmup */
1690         I915_WRITE(reg, dpll);
1691         POSTING_READ(reg);
1692         udelay(150); /* wait for warmup */
1693 }
1694
1695 /**
1696  * i9xx_disable_pll - disable a PLL
1697  * @dev_priv: i915 private structure
1698  * @pipe: pipe PLL to disable
1699  *
1700  * Disable the PLL for @pipe, making sure the pipe is off first.
1701  *
1702  * Note!  This is for pre-ILK only.
1703  */
1704 static void i9xx_disable_pll(struct intel_crtc *crtc)
1705 {
1706         struct drm_device *dev = crtc->base.dev;
1707         struct drm_i915_private *dev_priv = dev->dev_private;
1708         enum pipe pipe = crtc->pipe;
1709
1710         /* Disable DVO 2x clock on both PLLs if necessary */
1711         if (IS_I830(dev) &&
1712             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1713             !intel_num_dvo_pipes(dev)) {
1714                 I915_WRITE(DPLL(PIPE_B),
1715                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1716                 I915_WRITE(DPLL(PIPE_A),
1717                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1718         }
1719
1720         /* Don't disable pipe or pipe PLLs if needed */
1721         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1722             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1723                 return;
1724
1725         /* Make sure the pipe isn't still relying on us */
1726         assert_pipe_disabled(dev_priv, pipe);
1727
1728         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1729         POSTING_READ(DPLL(pipe));
1730 }
1731
1732 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1733 {
1734         u32 val;
1735
1736         /* Make sure the pipe isn't still relying on us */
1737         assert_pipe_disabled(dev_priv, pipe);
1738
1739         val = DPLL_INTEGRATED_REF_CLK_VLV |
1740                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1741         if (pipe != PIPE_A)
1742                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1743
1744         I915_WRITE(DPLL(pipe), val);
1745         POSTING_READ(DPLL(pipe));
1746 }
1747
1748 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1749 {
1750         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1751         u32 val;
1752
1753         /* Make sure the pipe isn't still relying on us */
1754         assert_pipe_disabled(dev_priv, pipe);
1755
1756         val = DPLL_SSC_REF_CLK_CHV |
1757                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1758         if (pipe != PIPE_A)
1759                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1760
1761         I915_WRITE(DPLL(pipe), val);
1762         POSTING_READ(DPLL(pipe));
1763
1764         mutex_lock(&dev_priv->sb_lock);
1765
1766         /* Disable 10bit clock to display controller */
1767         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1768         val &= ~DPIO_DCLKP_EN;
1769         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1770
1771         mutex_unlock(&dev_priv->sb_lock);
1772 }
1773
1774 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1775                          struct intel_digital_port *dport,
1776                          unsigned int expected_mask)
1777 {
1778         u32 port_mask;
1779         i915_reg_t dpll_reg;
1780
1781         switch (dport->port) {
1782         case PORT_B:
1783                 port_mask = DPLL_PORTB_READY_MASK;
1784                 dpll_reg = DPLL(0);
1785                 break;
1786         case PORT_C:
1787                 port_mask = DPLL_PORTC_READY_MASK;
1788                 dpll_reg = DPLL(0);
1789                 expected_mask <<= 4;
1790                 break;
1791         case PORT_D:
1792                 port_mask = DPLL_PORTD_READY_MASK;
1793                 dpll_reg = DPIO_PHY_STATUS;
1794                 break;
1795         default:
1796                 BUG();
1797         }
1798
1799         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1800                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1801                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1802 }
1803
1804 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1805                                            enum pipe pipe)
1806 {
1807         struct drm_device *dev = dev_priv->dev;
1808         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1809         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1810         i915_reg_t reg;
1811         uint32_t val, pipeconf_val;
1812
1813         /* Make sure PCH DPLL is enabled */
1814         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1815
1816         /* FDI must be feeding us bits for PCH ports */
1817         assert_fdi_tx_enabled(dev_priv, pipe);
1818         assert_fdi_rx_enabled(dev_priv, pipe);
1819
1820         if (HAS_PCH_CPT(dev)) {
1821                 /* Workaround: Set the timing override bit before enabling the
1822                  * pch transcoder. */
1823                 reg = TRANS_CHICKEN2(pipe);
1824                 val = I915_READ(reg);
1825                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1826                 I915_WRITE(reg, val);
1827         }
1828
1829         reg = PCH_TRANSCONF(pipe);
1830         val = I915_READ(reg);
1831         pipeconf_val = I915_READ(PIPECONF(pipe));
1832
1833         if (HAS_PCH_IBX(dev_priv->dev)) {
1834                 /*
1835                  * Make the BPC in transcoder be consistent with
1836                  * that in pipeconf reg. For HDMI we must use 8bpc
1837                  * here for both 8bpc and 12bpc.
1838                  */
1839                 val &= ~PIPECONF_BPC_MASK;
1840                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1841                         val |= PIPECONF_8BPC;
1842                 else
1843                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1844         }
1845
1846         val &= ~TRANS_INTERLACE_MASK;
1847         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1848                 if (HAS_PCH_IBX(dev_priv->dev) &&
1849                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1850                         val |= TRANS_LEGACY_INTERLACED_ILK;
1851                 else
1852                         val |= TRANS_INTERLACED;
1853         else
1854                 val |= TRANS_PROGRESSIVE;
1855
1856         I915_WRITE(reg, val | TRANS_ENABLE);
1857         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1858                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1859 }
1860
1861 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1862                                       enum transcoder cpu_transcoder)
1863 {
1864         u32 val, pipeconf_val;
1865
1866         /* FDI must be feeding us bits for PCH ports */
1867         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1868         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1869
1870         /* Workaround: set timing override bit. */
1871         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1872         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1873         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1874
1875         val = TRANS_ENABLE;
1876         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1877
1878         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1879             PIPECONF_INTERLACED_ILK)
1880                 val |= TRANS_INTERLACED;
1881         else
1882                 val |= TRANS_PROGRESSIVE;
1883
1884         I915_WRITE(LPT_TRANSCONF, val);
1885         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
1886                 DRM_ERROR("Failed to enable PCH transcoder\n");
1887 }
1888
1889 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1890                                             enum pipe pipe)
1891 {
1892         struct drm_device *dev = dev_priv->dev;
1893         i915_reg_t reg;
1894         uint32_t val;
1895
1896         /* FDI relies on the transcoder */
1897         assert_fdi_tx_disabled(dev_priv, pipe);
1898         assert_fdi_rx_disabled(dev_priv, pipe);
1899
1900         /* Ports must be off as well */
1901         assert_pch_ports_disabled(dev_priv, pipe);
1902
1903         reg = PCH_TRANSCONF(pipe);
1904         val = I915_READ(reg);
1905         val &= ~TRANS_ENABLE;
1906         I915_WRITE(reg, val);
1907         /* wait for PCH transcoder off, transcoder state */
1908         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1909                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1910
1911         if (HAS_PCH_CPT(dev)) {
1912                 /* Workaround: Clear the timing override chicken bit again. */
1913                 reg = TRANS_CHICKEN2(pipe);
1914                 val = I915_READ(reg);
1915                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1916                 I915_WRITE(reg, val);
1917         }
1918 }
1919
1920 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1921 {
1922         u32 val;
1923
1924         val = I915_READ(LPT_TRANSCONF);
1925         val &= ~TRANS_ENABLE;
1926         I915_WRITE(LPT_TRANSCONF, val);
1927         /* wait for PCH transcoder off, transcoder state */
1928         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
1929                 DRM_ERROR("Failed to disable PCH transcoder\n");
1930
1931         /* Workaround: clear timing override bit. */
1932         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1933         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1934         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1935 }
1936
1937 /**
1938  * intel_enable_pipe - enable a pipe, asserting requirements
1939  * @crtc: crtc responsible for the pipe
1940  *
1941  * Enable @crtc's pipe, making sure that various hardware specific requirements
1942  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1943  */
1944 static void intel_enable_pipe(struct intel_crtc *crtc)
1945 {
1946         struct drm_device *dev = crtc->base.dev;
1947         struct drm_i915_private *dev_priv = dev->dev_private;
1948         enum pipe pipe = crtc->pipe;
1949         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1950         enum pipe pch_transcoder;
1951         i915_reg_t reg;
1952         u32 val;
1953
1954         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1955
1956         assert_planes_disabled(dev_priv, pipe);
1957         assert_cursor_disabled(dev_priv, pipe);
1958         assert_sprites_disabled(dev_priv, pipe);
1959
1960         if (HAS_PCH_LPT(dev_priv->dev))
1961                 pch_transcoder = TRANSCODER_A;
1962         else
1963                 pch_transcoder = pipe;
1964
1965         /*
1966          * A pipe without a PLL won't actually be able to drive bits from
1967          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1968          * need the check.
1969          */
1970         if (HAS_GMCH_DISPLAY(dev_priv->dev))
1971                 if (crtc->config->has_dsi_encoder)
1972                         assert_dsi_pll_enabled(dev_priv);
1973                 else
1974                         assert_pll_enabled(dev_priv, pipe);
1975         else {
1976                 if (crtc->config->has_pch_encoder) {
1977                         /* if driving the PCH, we need FDI enabled */
1978                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
1979                         assert_fdi_tx_pll_enabled(dev_priv,
1980                                                   (enum pipe) cpu_transcoder);
1981                 }
1982                 /* FIXME: assert CPU port conditions for SNB+ */
1983         }
1984
1985         reg = PIPECONF(cpu_transcoder);
1986         val = I915_READ(reg);
1987         if (val & PIPECONF_ENABLE) {
1988                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1989                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
1990                 return;
1991         }
1992
1993         I915_WRITE(reg, val | PIPECONF_ENABLE);
1994         POSTING_READ(reg);
1995
1996         /*
1997          * Until the pipe starts DSL will read as 0, which would cause
1998          * an apparent vblank timestamp jump, which messes up also the
1999          * frame count when it's derived from the timestamps. So let's
2000          * wait for the pipe to start properly before we call
2001          * drm_crtc_vblank_on()
2002          */
2003         if (dev->max_vblank_count == 0 &&
2004             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
2005                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
2006 }
2007
2008 /**
2009  * intel_disable_pipe - disable a pipe, asserting requirements
2010  * @crtc: crtc whose pipes is to be disabled
2011  *
2012  * Disable the pipe of @crtc, making sure that various hardware
2013  * specific requirements are met, if applicable, e.g. plane
2014  * disabled, panel fitter off, etc.
2015  *
2016  * Will wait until the pipe has shut down before returning.
2017  */
2018 static void intel_disable_pipe(struct intel_crtc *crtc)
2019 {
2020         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2021         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2022         enum pipe pipe = crtc->pipe;
2023         i915_reg_t reg;
2024         u32 val;
2025
2026         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2027
2028         /*
2029          * Make sure planes won't keep trying to pump pixels to us,
2030          * or we might hang the display.
2031          */
2032         assert_planes_disabled(dev_priv, pipe);
2033         assert_cursor_disabled(dev_priv, pipe);
2034         assert_sprites_disabled(dev_priv, pipe);
2035
2036         reg = PIPECONF(cpu_transcoder);
2037         val = I915_READ(reg);
2038         if ((val & PIPECONF_ENABLE) == 0)
2039                 return;
2040
2041         /*
2042          * Double wide has implications for planes
2043          * so best keep it disabled when not needed.
2044          */
2045         if (crtc->config->double_wide)
2046                 val &= ~PIPECONF_DOUBLE_WIDE;
2047
2048         /* Don't disable pipe or pipe PLLs if needed */
2049         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2050             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2051                 val &= ~PIPECONF_ENABLE;
2052
2053         I915_WRITE(reg, val);
2054         if ((val & PIPECONF_ENABLE) == 0)
2055                 intel_wait_for_pipe_off(crtc);
2056 }
2057
2058 static bool need_vtd_wa(struct drm_device *dev)
2059 {
2060 #ifdef CONFIG_INTEL_IOMMU
2061         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2062                 return true;
2063 #endif
2064         return false;
2065 }
2066
2067 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2068 {
2069         return IS_GEN2(dev_priv) ? 2048 : 4096;
2070 }
2071
2072 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2073                                            uint64_t fb_modifier, unsigned int cpp)
2074 {
2075         switch (fb_modifier) {
2076         case DRM_FORMAT_MOD_NONE:
2077                 return cpp;
2078         case I915_FORMAT_MOD_X_TILED:
2079                 if (IS_GEN2(dev_priv))
2080                         return 128;
2081                 else
2082                         return 512;
2083         case I915_FORMAT_MOD_Y_TILED:
2084                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2085                         return 128;
2086                 else
2087                         return 512;
2088         case I915_FORMAT_MOD_Yf_TILED:
2089                 switch (cpp) {
2090                 case 1:
2091                         return 64;
2092                 case 2:
2093                 case 4:
2094                         return 128;
2095                 case 8:
2096                 case 16:
2097                         return 256;
2098                 default:
2099                         MISSING_CASE(cpp);
2100                         return cpp;
2101                 }
2102                 break;
2103         default:
2104                 MISSING_CASE(fb_modifier);
2105                 return cpp;
2106         }
2107 }
2108
2109 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2110                                uint64_t fb_modifier, unsigned int cpp)
2111 {
2112         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2113                 return 1;
2114         else
2115                 return intel_tile_size(dev_priv) /
2116                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2117 }
2118
2119 /* Return the tile dimensions in pixel units */
2120 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2121                             unsigned int *tile_width,
2122                             unsigned int *tile_height,
2123                             uint64_t fb_modifier,
2124                             unsigned int cpp)
2125 {
2126         unsigned int tile_width_bytes =
2127                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2128
2129         *tile_width = tile_width_bytes / cpp;
2130         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2131 }
2132
2133 unsigned int
2134 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2135                       uint32_t pixel_format, uint64_t fb_modifier)
2136 {
2137         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2138         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2139
2140         return ALIGN(height, tile_height);
2141 }
2142
2143 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2144 {
2145         unsigned int size = 0;
2146         int i;
2147
2148         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2149                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2150
2151         return size;
2152 }
2153
2154 static void
2155 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2156                         const struct drm_framebuffer *fb,
2157                         unsigned int rotation)
2158 {
2159         if (intel_rotation_90_or_270(rotation)) {
2160                 *view = i915_ggtt_view_rotated;
2161                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2162         } else {
2163                 *view = i915_ggtt_view_normal;
2164         }
2165 }
2166
2167 static void
2168 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2169                    struct drm_framebuffer *fb)
2170 {
2171         struct intel_rotation_info *info = &to_intel_framebuffer(fb)->rot_info;
2172         unsigned int tile_size, tile_width, tile_height, cpp;
2173
2174         tile_size = intel_tile_size(dev_priv);
2175
2176         cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2177         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2178                         fb->modifier[0], cpp);
2179
2180         info->plane[0].width = DIV_ROUND_UP(fb->pitches[0], tile_width * cpp);
2181         info->plane[0].height = DIV_ROUND_UP(fb->height, tile_height);
2182
2183         if (info->pixel_format == DRM_FORMAT_NV12) {
2184                 cpp = drm_format_plane_cpp(fb->pixel_format, 1);
2185                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2186                                 fb->modifier[1], cpp);
2187
2188                 info->uv_offset = fb->offsets[1];
2189                 info->plane[1].width = DIV_ROUND_UP(fb->pitches[1], tile_width * cpp);
2190                 info->plane[1].height = DIV_ROUND_UP(fb->height / 2, tile_height);
2191         }
2192 }
2193
2194 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2195 {
2196         if (INTEL_INFO(dev_priv)->gen >= 9)
2197                 return 256 * 1024;
2198         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2199                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2200                 return 128 * 1024;
2201         else if (INTEL_INFO(dev_priv)->gen >= 4)
2202                 return 4 * 1024;
2203         else
2204                 return 0;
2205 }
2206
2207 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2208                                          uint64_t fb_modifier)
2209 {
2210         switch (fb_modifier) {
2211         case DRM_FORMAT_MOD_NONE:
2212                 return intel_linear_alignment(dev_priv);
2213         case I915_FORMAT_MOD_X_TILED:
2214                 if (INTEL_INFO(dev_priv)->gen >= 9)
2215                         return 256 * 1024;
2216                 return 0;
2217         case I915_FORMAT_MOD_Y_TILED:
2218         case I915_FORMAT_MOD_Yf_TILED:
2219                 return 1 * 1024 * 1024;
2220         default:
2221                 MISSING_CASE(fb_modifier);
2222                 return 0;
2223         }
2224 }
2225
2226 int
2227 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2228                            unsigned int rotation)
2229 {
2230         struct drm_device *dev = fb->dev;
2231         struct drm_i915_private *dev_priv = dev->dev_private;
2232         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2233         struct i915_ggtt_view view;
2234         u32 alignment;
2235         int ret;
2236
2237         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2238
2239         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2240
2241         intel_fill_fb_ggtt_view(&view, fb, rotation);
2242
2243         /* Note that the w/a also requires 64 PTE of padding following the
2244          * bo. We currently fill all unused PTE with the shadow page and so
2245          * we should always have valid PTE following the scanout preventing
2246          * the VT-d warning.
2247          */
2248         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2249                 alignment = 256 * 1024;
2250
2251         /*
2252          * Global gtt pte registers are special registers which actually forward
2253          * writes to a chunk of system memory. Which means that there is no risk
2254          * that the register values disappear as soon as we call
2255          * intel_runtime_pm_put(), so it is correct to wrap only the
2256          * pin/unpin/fence and not more.
2257          */
2258         intel_runtime_pm_get(dev_priv);
2259
2260         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2261                                                    &view);
2262         if (ret)
2263                 goto err_pm;
2264
2265         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2266          * fence, whereas 965+ only requires a fence if using
2267          * framebuffer compression.  For simplicity, we always install
2268          * a fence as the cost is not that onerous.
2269          */
2270         if (view.type == I915_GGTT_VIEW_NORMAL) {
2271                 ret = i915_gem_object_get_fence(obj);
2272                 if (ret == -EDEADLK) {
2273                         /*
2274                          * -EDEADLK means there are no free fences
2275                          * no pending flips.
2276                          *
2277                          * This is propagated to atomic, but it uses
2278                          * -EDEADLK to force a locking recovery, so
2279                          * change the returned error to -EBUSY.
2280                          */
2281                         ret = -EBUSY;
2282                         goto err_unpin;
2283                 } else if (ret)
2284                         goto err_unpin;
2285
2286                 i915_gem_object_pin_fence(obj);
2287         }
2288
2289         intel_runtime_pm_put(dev_priv);
2290         return 0;
2291
2292 err_unpin:
2293         i915_gem_object_unpin_from_display_plane(obj, &view);
2294 err_pm:
2295         intel_runtime_pm_put(dev_priv);
2296         return ret;
2297 }
2298
2299 static void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2300 {
2301         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2302         struct i915_ggtt_view view;
2303
2304         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2305
2306         intel_fill_fb_ggtt_view(&view, fb, rotation);
2307
2308         if (view.type == I915_GGTT_VIEW_NORMAL)
2309                 i915_gem_object_unpin_fence(obj);
2310
2311         i915_gem_object_unpin_from_display_plane(obj, &view);
2312 }
2313
2314 /*
2315  * Adjust the tile offset by moving the difference into
2316  * the x/y offsets.
2317  *
2318  * Input tile dimensions and pitch must already be
2319  * rotated to match x and y, and in pixel units.
2320  */
2321 static u32 intel_adjust_tile_offset(int *x, int *y,
2322                                     unsigned int tile_width,
2323                                     unsigned int tile_height,
2324                                     unsigned int tile_size,
2325                                     unsigned int pitch_tiles,
2326                                     u32 old_offset,
2327                                     u32 new_offset)
2328 {
2329         unsigned int tiles;
2330
2331         WARN_ON(old_offset & (tile_size - 1));
2332         WARN_ON(new_offset & (tile_size - 1));
2333         WARN_ON(new_offset > old_offset);
2334
2335         tiles = (old_offset - new_offset) / tile_size;
2336
2337         *y += tiles / pitch_tiles * tile_height;
2338         *x += tiles % pitch_tiles * tile_width;
2339
2340         return new_offset;
2341 }
2342
2343 /*
2344  * Computes the linear offset to the base tile and adjusts
2345  * x, y. bytes per pixel is assumed to be a power-of-two.
2346  *
2347  * In the 90/270 rotated case, x and y are assumed
2348  * to be already rotated to match the rotated GTT view, and
2349  * pitch is the tile_height aligned framebuffer height.
2350  */
2351 u32 intel_compute_tile_offset(int *x, int *y,
2352                               const struct drm_framebuffer *fb, int plane,
2353                               unsigned int pitch,
2354                               unsigned int rotation)
2355 {
2356         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2357         uint64_t fb_modifier = fb->modifier[plane];
2358         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2359         u32 offset, offset_aligned, alignment;
2360
2361         alignment = intel_surf_alignment(dev_priv, fb_modifier);
2362         if (alignment)
2363                 alignment--;
2364
2365         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2366                 unsigned int tile_size, tile_width, tile_height;
2367                 unsigned int tile_rows, tiles, pitch_tiles;
2368
2369                 tile_size = intel_tile_size(dev_priv);
2370                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2371                                 fb_modifier, cpp);
2372
2373                 if (intel_rotation_90_or_270(rotation)) {
2374                         pitch_tiles = pitch / tile_height;
2375                         swap(tile_width, tile_height);
2376                 } else {
2377                         pitch_tiles = pitch / (tile_width * cpp);
2378                 }
2379
2380                 tile_rows = *y / tile_height;
2381                 *y %= tile_height;
2382
2383                 tiles = *x / tile_width;
2384                 *x %= tile_width;
2385
2386                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2387                 offset_aligned = offset & ~alignment;
2388
2389                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2390                                          tile_size, pitch_tiles,
2391                                          offset, offset_aligned);
2392         } else {
2393                 offset = *y * pitch + *x * cpp;
2394                 offset_aligned = offset & ~alignment;
2395
2396                 *y = (offset & alignment) / pitch;
2397                 *x = ((offset & alignment) - *y * pitch) / cpp;
2398         }
2399
2400         return offset_aligned;
2401 }
2402
2403 static int i9xx_format_to_fourcc(int format)
2404 {
2405         switch (format) {
2406         case DISPPLANE_8BPP:
2407                 return DRM_FORMAT_C8;
2408         case DISPPLANE_BGRX555:
2409                 return DRM_FORMAT_XRGB1555;
2410         case DISPPLANE_BGRX565:
2411                 return DRM_FORMAT_RGB565;
2412         default:
2413         case DISPPLANE_BGRX888:
2414                 return DRM_FORMAT_XRGB8888;
2415         case DISPPLANE_RGBX888:
2416                 return DRM_FORMAT_XBGR8888;
2417         case DISPPLANE_BGRX101010:
2418                 return DRM_FORMAT_XRGB2101010;
2419         case DISPPLANE_RGBX101010:
2420                 return DRM_FORMAT_XBGR2101010;
2421         }
2422 }
2423
2424 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2425 {
2426         switch (format) {
2427         case PLANE_CTL_FORMAT_RGB_565:
2428                 return DRM_FORMAT_RGB565;
2429         default:
2430         case PLANE_CTL_FORMAT_XRGB_8888:
2431                 if (rgb_order) {
2432                         if (alpha)
2433                                 return DRM_FORMAT_ABGR8888;
2434                         else
2435                                 return DRM_FORMAT_XBGR8888;
2436                 } else {
2437                         if (alpha)
2438                                 return DRM_FORMAT_ARGB8888;
2439                         else
2440                                 return DRM_FORMAT_XRGB8888;
2441                 }
2442         case PLANE_CTL_FORMAT_XRGB_2101010:
2443                 if (rgb_order)
2444                         return DRM_FORMAT_XBGR2101010;
2445                 else
2446                         return DRM_FORMAT_XRGB2101010;
2447         }
2448 }
2449
2450 static bool
2451 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2452                               struct intel_initial_plane_config *plane_config)
2453 {
2454         struct drm_device *dev = crtc->base.dev;
2455         struct drm_i915_private *dev_priv = to_i915(dev);
2456         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2457         struct drm_i915_gem_object *obj = NULL;
2458         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2459         struct drm_framebuffer *fb = &plane_config->fb->base;
2460         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2461         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2462                                     PAGE_SIZE);
2463
2464         size_aligned -= base_aligned;
2465
2466         if (plane_config->size == 0)
2467                 return false;
2468
2469         /* If the FB is too big, just don't use it since fbdev is not very
2470          * important and we should probably use that space with FBC or other
2471          * features. */
2472         if (size_aligned * 2 > ggtt->stolen_usable_size)
2473                 return false;
2474
2475         mutex_lock(&dev->struct_mutex);
2476
2477         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2478                                                              base_aligned,
2479                                                              base_aligned,
2480                                                              size_aligned);
2481         if (!obj) {
2482                 mutex_unlock(&dev->struct_mutex);
2483                 return false;
2484         }
2485
2486         obj->tiling_mode = plane_config->tiling;
2487         if (obj->tiling_mode == I915_TILING_X)
2488                 obj->stride = fb->pitches[0];
2489
2490         mode_cmd.pixel_format = fb->pixel_format;
2491         mode_cmd.width = fb->width;
2492         mode_cmd.height = fb->height;
2493         mode_cmd.pitches[0] = fb->pitches[0];
2494         mode_cmd.modifier[0] = fb->modifier[0];
2495         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2496
2497         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2498                                    &mode_cmd, obj)) {
2499                 DRM_DEBUG_KMS("intel fb init failed\n");
2500                 goto out_unref_obj;
2501         }
2502
2503         mutex_unlock(&dev->struct_mutex);
2504
2505         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2506         return true;
2507
2508 out_unref_obj:
2509         drm_gem_object_unreference(&obj->base);
2510         mutex_unlock(&dev->struct_mutex);
2511         return false;
2512 }
2513
2514 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2515 static void
2516 update_state_fb(struct drm_plane *plane)
2517 {
2518         if (plane->fb == plane->state->fb)
2519                 return;
2520
2521         if (plane->state->fb)
2522                 drm_framebuffer_unreference(plane->state->fb);
2523         plane->state->fb = plane->fb;
2524         if (plane->state->fb)
2525                 drm_framebuffer_reference(plane->state->fb);
2526 }
2527
2528 static void
2529 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2530                              struct intel_initial_plane_config *plane_config)
2531 {
2532         struct drm_device *dev = intel_crtc->base.dev;
2533         struct drm_i915_private *dev_priv = dev->dev_private;
2534         struct drm_crtc *c;
2535         struct intel_crtc *i;
2536         struct drm_i915_gem_object *obj;
2537         struct drm_plane *primary = intel_crtc->base.primary;
2538         struct drm_plane_state *plane_state = primary->state;
2539         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2540         struct intel_plane *intel_plane = to_intel_plane(primary);
2541         struct intel_plane_state *intel_state =
2542                 to_intel_plane_state(plane_state);
2543         struct drm_framebuffer *fb;
2544
2545         if (!plane_config->fb)
2546                 return;
2547
2548         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2549                 fb = &plane_config->fb->base;
2550                 goto valid_fb;
2551         }
2552
2553         kfree(plane_config->fb);
2554
2555         /*
2556          * Failed to alloc the obj, check to see if we should share
2557          * an fb with another CRTC instead
2558          */
2559         for_each_crtc(dev, c) {
2560                 i = to_intel_crtc(c);
2561
2562                 if (c == &intel_crtc->base)
2563                         continue;
2564
2565                 if (!i->active)
2566                         continue;
2567
2568                 fb = c->primary->fb;
2569                 if (!fb)
2570                         continue;
2571
2572                 obj = intel_fb_obj(fb);
2573                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2574                         drm_framebuffer_reference(fb);
2575                         goto valid_fb;
2576                 }
2577         }
2578
2579         /*
2580          * We've failed to reconstruct the BIOS FB.  Current display state
2581          * indicates that the primary plane is visible, but has a NULL FB,
2582          * which will lead to problems later if we don't fix it up.  The
2583          * simplest solution is to just disable the primary plane now and
2584          * pretend the BIOS never had it enabled.
2585          */
2586         to_intel_plane_state(plane_state)->visible = false;
2587         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2588         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2589         intel_plane->disable_plane(primary, &intel_crtc->base);
2590
2591         return;
2592
2593 valid_fb:
2594         plane_state->src_x = 0;
2595         plane_state->src_y = 0;
2596         plane_state->src_w = fb->width << 16;
2597         plane_state->src_h = fb->height << 16;
2598
2599         plane_state->crtc_x = 0;
2600         plane_state->crtc_y = 0;
2601         plane_state->crtc_w = fb->width;
2602         plane_state->crtc_h = fb->height;
2603
2604         intel_state->src.x1 = plane_state->src_x;
2605         intel_state->src.y1 = plane_state->src_y;
2606         intel_state->src.x2 = plane_state->src_x + plane_state->src_w;
2607         intel_state->src.y2 = plane_state->src_y + plane_state->src_h;
2608         intel_state->dst.x1 = plane_state->crtc_x;
2609         intel_state->dst.y1 = plane_state->crtc_y;
2610         intel_state->dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2611         intel_state->dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2612
2613         obj = intel_fb_obj(fb);
2614         if (obj->tiling_mode != I915_TILING_NONE)
2615                 dev_priv->preserve_bios_swizzle = true;
2616
2617         drm_framebuffer_reference(fb);
2618         primary->fb = primary->state->fb = fb;
2619         primary->crtc = primary->state->crtc = &intel_crtc->base;
2620         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2621         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2622 }
2623
2624 static void i9xx_update_primary_plane(struct drm_plane *primary,
2625                                       const struct intel_crtc_state *crtc_state,
2626                                       const struct intel_plane_state *plane_state)
2627 {
2628         struct drm_device *dev = primary->dev;
2629         struct drm_i915_private *dev_priv = dev->dev_private;
2630         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2631         struct drm_framebuffer *fb = plane_state->base.fb;
2632         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2633         int plane = intel_crtc->plane;
2634         u32 linear_offset;
2635         u32 dspcntr;
2636         i915_reg_t reg = DSPCNTR(plane);
2637         unsigned int rotation = plane_state->base.rotation;
2638         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2639         int x = plane_state->src.x1 >> 16;
2640         int y = plane_state->src.y1 >> 16;
2641
2642         dspcntr = DISPPLANE_GAMMA_ENABLE;
2643
2644         dspcntr |= DISPLAY_PLANE_ENABLE;
2645
2646         if (INTEL_INFO(dev)->gen < 4) {
2647                 if (intel_crtc->pipe == PIPE_B)
2648                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2649
2650                 /* pipesrc and dspsize control the size that is scaled from,
2651                  * which should always be the user's requested size.
2652                  */
2653                 I915_WRITE(DSPSIZE(plane),
2654                            ((crtc_state->pipe_src_h - 1) << 16) |
2655                            (crtc_state->pipe_src_w - 1));
2656                 I915_WRITE(DSPPOS(plane), 0);
2657         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2658                 I915_WRITE(PRIMSIZE(plane),
2659                            ((crtc_state->pipe_src_h - 1) << 16) |
2660                            (crtc_state->pipe_src_w - 1));
2661                 I915_WRITE(PRIMPOS(plane), 0);
2662                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2663         }
2664
2665         switch (fb->pixel_format) {
2666         case DRM_FORMAT_C8:
2667                 dspcntr |= DISPPLANE_8BPP;
2668                 break;
2669         case DRM_FORMAT_XRGB1555:
2670                 dspcntr |= DISPPLANE_BGRX555;
2671                 break;
2672         case DRM_FORMAT_RGB565:
2673                 dspcntr |= DISPPLANE_BGRX565;
2674                 break;
2675         case DRM_FORMAT_XRGB8888:
2676                 dspcntr |= DISPPLANE_BGRX888;
2677                 break;
2678         case DRM_FORMAT_XBGR8888:
2679                 dspcntr |= DISPPLANE_RGBX888;
2680                 break;
2681         case DRM_FORMAT_XRGB2101010:
2682                 dspcntr |= DISPPLANE_BGRX101010;
2683                 break;
2684         case DRM_FORMAT_XBGR2101010:
2685                 dspcntr |= DISPPLANE_RGBX101010;
2686                 break;
2687         default:
2688                 BUG();
2689         }
2690
2691         if (INTEL_INFO(dev)->gen >= 4 &&
2692             obj->tiling_mode != I915_TILING_NONE)
2693                 dspcntr |= DISPPLANE_TILED;
2694
2695         if (IS_G4X(dev))
2696                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2697
2698         linear_offset = y * fb->pitches[0] + x * cpp;
2699
2700         if (INTEL_INFO(dev)->gen >= 4) {
2701                 intel_crtc->dspaddr_offset =
2702                         intel_compute_tile_offset(&x, &y, fb, 0,
2703                                                   fb->pitches[0], rotation);
2704                 linear_offset -= intel_crtc->dspaddr_offset;
2705         } else {
2706                 intel_crtc->dspaddr_offset = linear_offset;
2707         }
2708
2709         if (rotation == BIT(DRM_ROTATE_180)) {
2710                 dspcntr |= DISPPLANE_ROTATE_180;
2711
2712                 x += (crtc_state->pipe_src_w - 1);
2713                 y += (crtc_state->pipe_src_h - 1);
2714
2715                 /* Finding the last pixel of the last line of the display
2716                 data and adding to linear_offset*/
2717                 linear_offset +=
2718                         (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2719                         (crtc_state->pipe_src_w - 1) * cpp;
2720         }
2721
2722         intel_crtc->adjusted_x = x;
2723         intel_crtc->adjusted_y = y;
2724
2725         I915_WRITE(reg, dspcntr);
2726
2727         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2728         if (INTEL_INFO(dev)->gen >= 4) {
2729                 I915_WRITE(DSPSURF(plane),
2730                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2731                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2732                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2733         } else
2734                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2735         POSTING_READ(reg);
2736 }
2737
2738 static void i9xx_disable_primary_plane(struct drm_plane *primary,
2739                                        struct drm_crtc *crtc)
2740 {
2741         struct drm_device *dev = crtc->dev;
2742         struct drm_i915_private *dev_priv = dev->dev_private;
2743         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2744         int plane = intel_crtc->plane;
2745
2746         I915_WRITE(DSPCNTR(plane), 0);
2747         if (INTEL_INFO(dev_priv)->gen >= 4)
2748                 I915_WRITE(DSPSURF(plane), 0);
2749         else
2750                 I915_WRITE(DSPADDR(plane), 0);
2751         POSTING_READ(DSPCNTR(plane));
2752 }
2753
2754 static void ironlake_update_primary_plane(struct drm_plane *primary,
2755                                           const struct intel_crtc_state *crtc_state,
2756                                           const struct intel_plane_state *plane_state)
2757 {
2758         struct drm_device *dev = primary->dev;
2759         struct drm_i915_private *dev_priv = dev->dev_private;
2760         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2761         struct drm_framebuffer *fb = plane_state->base.fb;
2762         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2763         int plane = intel_crtc->plane;
2764         u32 linear_offset;
2765         u32 dspcntr;
2766         i915_reg_t reg = DSPCNTR(plane);
2767         unsigned int rotation = plane_state->base.rotation;
2768         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2769         int x = plane_state->src.x1 >> 16;
2770         int y = plane_state->src.y1 >> 16;
2771
2772         dspcntr = DISPPLANE_GAMMA_ENABLE;
2773         dspcntr |= DISPLAY_PLANE_ENABLE;
2774
2775         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2776                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2777
2778         switch (fb->pixel_format) {
2779         case DRM_FORMAT_C8:
2780                 dspcntr |= DISPPLANE_8BPP;
2781                 break;
2782         case DRM_FORMAT_RGB565:
2783                 dspcntr |= DISPPLANE_BGRX565;
2784                 break;
2785         case DRM_FORMAT_XRGB8888:
2786                 dspcntr |= DISPPLANE_BGRX888;
2787                 break;
2788         case DRM_FORMAT_XBGR8888:
2789                 dspcntr |= DISPPLANE_RGBX888;
2790                 break;
2791         case DRM_FORMAT_XRGB2101010:
2792                 dspcntr |= DISPPLANE_BGRX101010;
2793                 break;
2794         case DRM_FORMAT_XBGR2101010:
2795                 dspcntr |= DISPPLANE_RGBX101010;
2796                 break;
2797         default:
2798                 BUG();
2799         }
2800
2801         if (obj->tiling_mode != I915_TILING_NONE)
2802                 dspcntr |= DISPPLANE_TILED;
2803
2804         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2805                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2806
2807         linear_offset = y * fb->pitches[0] + x * cpp;
2808         intel_crtc->dspaddr_offset =
2809                 intel_compute_tile_offset(&x, &y, fb, 0,
2810                                           fb->pitches[0], rotation);
2811         linear_offset -= intel_crtc->dspaddr_offset;
2812         if (rotation == BIT(DRM_ROTATE_180)) {
2813                 dspcntr |= DISPPLANE_ROTATE_180;
2814
2815                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2816                         x += (crtc_state->pipe_src_w - 1);
2817                         y += (crtc_state->pipe_src_h - 1);
2818
2819                         /* Finding the last pixel of the last line of the display
2820                         data and adding to linear_offset*/
2821                         linear_offset +=
2822                                 (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2823                                 (crtc_state->pipe_src_w - 1) * cpp;
2824                 }
2825         }
2826
2827         intel_crtc->adjusted_x = x;
2828         intel_crtc->adjusted_y = y;
2829
2830         I915_WRITE(reg, dspcntr);
2831
2832         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2833         I915_WRITE(DSPSURF(plane),
2834                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2835         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2836                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2837         } else {
2838                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2839                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2840         }
2841         POSTING_READ(reg);
2842 }
2843
2844 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
2845                               uint64_t fb_modifier, uint32_t pixel_format)
2846 {
2847         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
2848                 return 64;
2849         } else {
2850                 int cpp = drm_format_plane_cpp(pixel_format, 0);
2851
2852                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2853         }
2854 }
2855
2856 u32 intel_plane_obj_offset(struct intel_plane *intel_plane,
2857                            struct drm_i915_gem_object *obj,
2858                            unsigned int plane)
2859 {
2860         struct i915_ggtt_view view;
2861         struct i915_vma *vma;
2862         u64 offset;
2863
2864         intel_fill_fb_ggtt_view(&view, intel_plane->base.state->fb,
2865                                 intel_plane->base.state->rotation);
2866
2867         vma = i915_gem_obj_to_ggtt_view(obj, &view);
2868         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
2869                 view.type))
2870                 return -1;
2871
2872         offset = vma->node.start;
2873
2874         if (plane == 1) {
2875                 offset += vma->ggtt_view.params.rotated.uv_start_page *
2876                           PAGE_SIZE;
2877         }
2878
2879         WARN_ON(upper_32_bits(offset));
2880
2881         return lower_32_bits(offset);
2882 }
2883
2884 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2885 {
2886         struct drm_device *dev = intel_crtc->base.dev;
2887         struct drm_i915_private *dev_priv = dev->dev_private;
2888
2889         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2890         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2891         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2892 }
2893
2894 /*
2895  * This function detaches (aka. unbinds) unused scalers in hardware
2896  */
2897 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2898 {
2899         struct intel_crtc_scaler_state *scaler_state;
2900         int i;
2901
2902         scaler_state = &intel_crtc->config->scaler_state;
2903
2904         /* loop through and disable scalers that aren't in use */
2905         for (i = 0; i < intel_crtc->num_scalers; i++) {
2906                 if (!scaler_state->scalers[i].in_use)
2907                         skl_detach_scaler(intel_crtc, i);
2908         }
2909 }
2910
2911 u32 skl_plane_ctl_format(uint32_t pixel_format)
2912 {
2913         switch (pixel_format) {
2914         case DRM_FORMAT_C8:
2915                 return PLANE_CTL_FORMAT_INDEXED;
2916         case DRM_FORMAT_RGB565:
2917                 return PLANE_CTL_FORMAT_RGB_565;
2918         case DRM_FORMAT_XBGR8888:
2919                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2920         case DRM_FORMAT_XRGB8888:
2921                 return PLANE_CTL_FORMAT_XRGB_8888;
2922         /*
2923          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2924          * to be already pre-multiplied. We need to add a knob (or a different
2925          * DRM_FORMAT) for user-space to configure that.
2926          */
2927         case DRM_FORMAT_ABGR8888:
2928                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2929                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2930         case DRM_FORMAT_ARGB8888:
2931                 return PLANE_CTL_FORMAT_XRGB_8888 |
2932                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2933         case DRM_FORMAT_XRGB2101010:
2934                 return PLANE_CTL_FORMAT_XRGB_2101010;
2935         case DRM_FORMAT_XBGR2101010:
2936                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2937         case DRM_FORMAT_YUYV:
2938                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2939         case DRM_FORMAT_YVYU:
2940                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2941         case DRM_FORMAT_UYVY:
2942                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2943         case DRM_FORMAT_VYUY:
2944                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2945         default:
2946                 MISSING_CASE(pixel_format);
2947         }
2948
2949         return 0;
2950 }
2951
2952 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2953 {
2954         switch (fb_modifier) {
2955         case DRM_FORMAT_MOD_NONE:
2956                 break;
2957         case I915_FORMAT_MOD_X_TILED:
2958                 return PLANE_CTL_TILED_X;
2959         case I915_FORMAT_MOD_Y_TILED:
2960                 return PLANE_CTL_TILED_Y;
2961         case I915_FORMAT_MOD_Yf_TILED:
2962                 return PLANE_CTL_TILED_YF;
2963         default:
2964                 MISSING_CASE(fb_modifier);
2965         }
2966
2967         return 0;
2968 }
2969
2970 u32 skl_plane_ctl_rotation(unsigned int rotation)
2971 {
2972         switch (rotation) {
2973         case BIT(DRM_ROTATE_0):
2974                 break;
2975         /*
2976          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
2977          * while i915 HW rotation is clockwise, thats why this swapping.
2978          */
2979         case BIT(DRM_ROTATE_90):
2980                 return PLANE_CTL_ROTATE_270;
2981         case BIT(DRM_ROTATE_180):
2982                 return PLANE_CTL_ROTATE_180;
2983         case BIT(DRM_ROTATE_270):
2984                 return PLANE_CTL_ROTATE_90;
2985         default:
2986                 MISSING_CASE(rotation);
2987         }
2988
2989         return 0;
2990 }
2991
2992 static void skylake_update_primary_plane(struct drm_plane *plane,
2993                                          const struct intel_crtc_state *crtc_state,
2994                                          const struct intel_plane_state *plane_state)
2995 {
2996         struct drm_device *dev = plane->dev;
2997         struct drm_i915_private *dev_priv = dev->dev_private;
2998         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2999         struct drm_framebuffer *fb = plane_state->base.fb;
3000         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
3001         int pipe = intel_crtc->pipe;
3002         u32 plane_ctl, stride_div, stride;
3003         u32 tile_height, plane_offset, plane_size;
3004         unsigned int rotation = plane_state->base.rotation;
3005         int x_offset, y_offset;
3006         u32 surf_addr;
3007         int scaler_id = plane_state->scaler_id;
3008         int src_x = plane_state->src.x1 >> 16;
3009         int src_y = plane_state->src.y1 >> 16;
3010         int src_w = drm_rect_width(&plane_state->src) >> 16;
3011         int src_h = drm_rect_height(&plane_state->src) >> 16;
3012         int dst_x = plane_state->dst.x1;
3013         int dst_y = plane_state->dst.y1;
3014         int dst_w = drm_rect_width(&plane_state->dst);
3015         int dst_h = drm_rect_height(&plane_state->dst);
3016
3017         plane_ctl = PLANE_CTL_ENABLE |
3018                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3019                     PLANE_CTL_PIPE_CSC_ENABLE;
3020
3021         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3022         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3023         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3024         plane_ctl |= skl_plane_ctl_rotation(rotation);
3025
3026         stride_div = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3027                                                fb->pixel_format);
3028         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj, 0);
3029
3030         WARN_ON(drm_rect_width(&plane_state->src) == 0);
3031
3032         if (intel_rotation_90_or_270(rotation)) {
3033                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
3034
3035                 /* stride = Surface height in tiles */
3036                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], cpp);
3037                 stride = DIV_ROUND_UP(fb->height, tile_height);
3038                 x_offset = stride * tile_height - src_y - src_h;
3039                 y_offset = src_x;
3040                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3041         } else {
3042                 stride = fb->pitches[0] / stride_div;
3043                 x_offset = src_x;
3044                 y_offset = src_y;
3045                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3046         }
3047         plane_offset = y_offset << 16 | x_offset;
3048
3049         intel_crtc->adjusted_x = x_offset;
3050         intel_crtc->adjusted_y = y_offset;
3051
3052         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3053         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3054         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3055         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3056
3057         if (scaler_id >= 0) {
3058                 uint32_t ps_ctrl = 0;
3059
3060                 WARN_ON(!dst_w || !dst_h);
3061                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3062                         crtc_state->scaler_state.scalers[scaler_id].mode;
3063                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3064                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3065                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3066                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3067                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3068         } else {
3069                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3070         }
3071
3072         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3073
3074         POSTING_READ(PLANE_SURF(pipe, 0));
3075 }
3076
3077 static void skylake_disable_primary_plane(struct drm_plane *primary,
3078                                           struct drm_crtc *crtc)
3079 {
3080         struct drm_device *dev = crtc->dev;
3081         struct drm_i915_private *dev_priv = dev->dev_private;
3082         int pipe = to_intel_crtc(crtc)->pipe;
3083
3084         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3085         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3086         POSTING_READ(PLANE_SURF(pipe, 0));
3087 }
3088
3089 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3090 static int
3091 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3092                            int x, int y, enum mode_set_atomic state)
3093 {
3094         /* Support for kgdboc is disabled, this needs a major rework. */
3095         DRM_ERROR("legacy panic handler not supported any more.\n");
3096
3097         return -ENODEV;
3098 }
3099
3100 static void intel_complete_page_flips(struct drm_device *dev)
3101 {
3102         struct drm_crtc *crtc;
3103
3104         for_each_crtc(dev, crtc) {
3105                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3106                 enum plane plane = intel_crtc->plane;
3107
3108                 intel_prepare_page_flip(dev, plane);
3109                 intel_finish_page_flip_plane(dev, plane);
3110         }
3111 }
3112
3113 static void intel_update_primary_planes(struct drm_device *dev)
3114 {
3115         struct drm_crtc *crtc;
3116
3117         for_each_crtc(dev, crtc) {
3118                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3119                 struct intel_plane_state *plane_state;
3120
3121                 drm_modeset_lock_crtc(crtc, &plane->base);
3122                 plane_state = to_intel_plane_state(plane->base.state);
3123
3124                 if (plane_state->visible)
3125                         plane->update_plane(&plane->base,
3126                                             to_intel_crtc_state(crtc->state),
3127                                             plane_state);
3128
3129                 drm_modeset_unlock_crtc(crtc);
3130         }
3131 }
3132
3133 void intel_prepare_reset(struct drm_device *dev)
3134 {
3135         /* no reset support for gen2 */
3136         if (IS_GEN2(dev))
3137                 return;
3138
3139         /* reset doesn't touch the display */
3140         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3141                 return;
3142
3143         drm_modeset_lock_all(dev);
3144         /*
3145          * Disabling the crtcs gracefully seems nicer. Also the
3146          * g33 docs say we should at least disable all the planes.
3147          */
3148         intel_display_suspend(dev);
3149 }
3150
3151 void intel_finish_reset(struct drm_device *dev)
3152 {
3153         struct drm_i915_private *dev_priv = to_i915(dev);
3154
3155         /*
3156          * Flips in the rings will be nuked by the reset,
3157          * so complete all pending flips so that user space
3158          * will get its events and not get stuck.
3159          */
3160         intel_complete_page_flips(dev);
3161
3162         /* no reset support for gen2 */
3163         if (IS_GEN2(dev))
3164                 return;
3165
3166         /* reset doesn't touch the display */
3167         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3168                 /*
3169                  * Flips in the rings have been nuked by the reset,
3170                  * so update the base address of all primary
3171                  * planes to the the last fb to make sure we're
3172                  * showing the correct fb after a reset.
3173                  *
3174                  * FIXME: Atomic will make this obsolete since we won't schedule
3175                  * CS-based flips (which might get lost in gpu resets) any more.
3176                  */
3177                 intel_update_primary_planes(dev);
3178                 return;
3179         }
3180
3181         /*
3182          * The display has been reset as well,
3183          * so need a full re-initialization.
3184          */
3185         intel_runtime_pm_disable_interrupts(dev_priv);
3186         intel_runtime_pm_enable_interrupts(dev_priv);
3187
3188         intel_modeset_init_hw(dev);
3189
3190         spin_lock_irq(&dev_priv->irq_lock);
3191         if (dev_priv->display.hpd_irq_setup)
3192                 dev_priv->display.hpd_irq_setup(dev);
3193         spin_unlock_irq(&dev_priv->irq_lock);
3194
3195         intel_display_resume(dev);
3196
3197         intel_hpd_init(dev_priv);
3198
3199         drm_modeset_unlock_all(dev);
3200 }
3201
3202 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3203 {
3204         struct drm_device *dev = crtc->dev;
3205         struct drm_i915_private *dev_priv = dev->dev_private;
3206         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3207         bool pending;
3208
3209         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3210             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3211                 return false;
3212
3213         spin_lock_irq(&dev->event_lock);
3214         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3215         spin_unlock_irq(&dev->event_lock);
3216
3217         return pending;
3218 }
3219
3220 static void intel_update_pipe_config(struct intel_crtc *crtc,
3221                                      struct intel_crtc_state *old_crtc_state)
3222 {
3223         struct drm_device *dev = crtc->base.dev;
3224         struct drm_i915_private *dev_priv = dev->dev_private;
3225         struct intel_crtc_state *pipe_config =
3226                 to_intel_crtc_state(crtc->base.state);
3227
3228         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3229         crtc->base.mode = crtc->base.state->mode;
3230
3231         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3232                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3233                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3234
3235         /*
3236          * Update pipe size and adjust fitter if needed: the reason for this is
3237          * that in compute_mode_changes we check the native mode (not the pfit
3238          * mode) to see if we can flip rather than do a full mode set. In the
3239          * fastboot case, we'll flip, but if we don't update the pipesrc and
3240          * pfit state, we'll end up with a big fb scanned out into the wrong
3241          * sized surface.
3242          */
3243
3244         I915_WRITE(PIPESRC(crtc->pipe),
3245                    ((pipe_config->pipe_src_w - 1) << 16) |
3246                    (pipe_config->pipe_src_h - 1));
3247
3248         /* on skylake this is done by detaching scalers */
3249         if (INTEL_INFO(dev)->gen >= 9) {
3250                 skl_detach_scalers(crtc);
3251
3252                 if (pipe_config->pch_pfit.enabled)
3253                         skylake_pfit_enable(crtc);
3254         } else if (HAS_PCH_SPLIT(dev)) {
3255                 if (pipe_config->pch_pfit.enabled)
3256                         ironlake_pfit_enable(crtc);
3257                 else if (old_crtc_state->pch_pfit.enabled)
3258                         ironlake_pfit_disable(crtc, true);
3259         }
3260 }
3261
3262 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3263 {
3264         struct drm_device *dev = crtc->dev;
3265         struct drm_i915_private *dev_priv = dev->dev_private;
3266         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3267         int pipe = intel_crtc->pipe;
3268         i915_reg_t reg;
3269         u32 temp;
3270
3271         /* enable normal train */
3272         reg = FDI_TX_CTL(pipe);
3273         temp = I915_READ(reg);
3274         if (IS_IVYBRIDGE(dev)) {
3275                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3276                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3277         } else {
3278                 temp &= ~FDI_LINK_TRAIN_NONE;
3279                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3280         }
3281         I915_WRITE(reg, temp);
3282
3283         reg = FDI_RX_CTL(pipe);
3284         temp = I915_READ(reg);
3285         if (HAS_PCH_CPT(dev)) {
3286                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3287                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3288         } else {
3289                 temp &= ~FDI_LINK_TRAIN_NONE;
3290                 temp |= FDI_LINK_TRAIN_NONE;
3291         }
3292         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3293
3294         /* wait one idle pattern time */
3295         POSTING_READ(reg);
3296         udelay(1000);
3297
3298         /* IVB wants error correction enabled */
3299         if (IS_IVYBRIDGE(dev))
3300                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3301                            FDI_FE_ERRC_ENABLE);
3302 }
3303
3304 /* The FDI link training functions for ILK/Ibexpeak. */
3305 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3306 {
3307         struct drm_device *dev = crtc->dev;
3308         struct drm_i915_private *dev_priv = dev->dev_private;
3309         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3310         int pipe = intel_crtc->pipe;
3311         i915_reg_t reg;
3312         u32 temp, tries;
3313
3314         /* FDI needs bits from pipe first */
3315         assert_pipe_enabled(dev_priv, pipe);
3316
3317         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3318            for train result */
3319         reg = FDI_RX_IMR(pipe);
3320         temp = I915_READ(reg);
3321         temp &= ~FDI_RX_SYMBOL_LOCK;
3322         temp &= ~FDI_RX_BIT_LOCK;
3323         I915_WRITE(reg, temp);
3324         I915_READ(reg);
3325         udelay(150);
3326
3327         /* enable CPU FDI TX and PCH FDI RX */
3328         reg = FDI_TX_CTL(pipe);
3329         temp = I915_READ(reg);
3330         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3331         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3332         temp &= ~FDI_LINK_TRAIN_NONE;
3333         temp |= FDI_LINK_TRAIN_PATTERN_1;
3334         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3335
3336         reg = FDI_RX_CTL(pipe);
3337         temp = I915_READ(reg);
3338         temp &= ~FDI_LINK_TRAIN_NONE;
3339         temp |= FDI_LINK_TRAIN_PATTERN_1;
3340         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3341
3342         POSTING_READ(reg);
3343         udelay(150);
3344
3345         /* Ironlake workaround, enable clock pointer after FDI enable*/
3346         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3347         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3348                    FDI_RX_PHASE_SYNC_POINTER_EN);
3349
3350         reg = FDI_RX_IIR(pipe);
3351         for (tries = 0; tries < 5; tries++) {
3352                 temp = I915_READ(reg);
3353                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3354
3355                 if ((temp & FDI_RX_BIT_LOCK)) {
3356                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3357                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3358                         break;
3359                 }
3360         }
3361         if (tries == 5)
3362                 DRM_ERROR("FDI train 1 fail!\n");
3363
3364         /* Train 2 */
3365         reg = FDI_TX_CTL(pipe);
3366         temp = I915_READ(reg);
3367         temp &= ~FDI_LINK_TRAIN_NONE;
3368         temp |= FDI_LINK_TRAIN_PATTERN_2;
3369         I915_WRITE(reg, temp);
3370
3371         reg = FDI_RX_CTL(pipe);
3372         temp = I915_READ(reg);
3373         temp &= ~FDI_LINK_TRAIN_NONE;
3374         temp |= FDI_LINK_TRAIN_PATTERN_2;
3375         I915_WRITE(reg, temp);
3376
3377         POSTING_READ(reg);
3378         udelay(150);
3379
3380         reg = FDI_RX_IIR(pipe);
3381         for (tries = 0; tries < 5; tries++) {
3382                 temp = I915_READ(reg);
3383                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3384
3385                 if (temp & FDI_RX_SYMBOL_LOCK) {
3386                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3387                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3388                         break;
3389                 }
3390         }
3391         if (tries == 5)
3392                 DRM_ERROR("FDI train 2 fail!\n");
3393
3394         DRM_DEBUG_KMS("FDI train done\n");
3395
3396 }
3397
3398 static const int snb_b_fdi_train_param[] = {
3399         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3400         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3401         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3402         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3403 };
3404
3405 /* The FDI link training functions for SNB/Cougarpoint. */
3406 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3407 {
3408         struct drm_device *dev = crtc->dev;
3409         struct drm_i915_private *dev_priv = dev->dev_private;
3410         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3411         int pipe = intel_crtc->pipe;
3412         i915_reg_t reg;
3413         u32 temp, i, retry;
3414
3415         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3416            for train result */
3417         reg = FDI_RX_IMR(pipe);
3418         temp = I915_READ(reg);
3419         temp &= ~FDI_RX_SYMBOL_LOCK;
3420         temp &= ~FDI_RX_BIT_LOCK;
3421         I915_WRITE(reg, temp);
3422
3423         POSTING_READ(reg);
3424         udelay(150);
3425
3426         /* enable CPU FDI TX and PCH FDI RX */
3427         reg = FDI_TX_CTL(pipe);
3428         temp = I915_READ(reg);
3429         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3430         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3431         temp &= ~FDI_LINK_TRAIN_NONE;
3432         temp |= FDI_LINK_TRAIN_PATTERN_1;
3433         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3434         /* SNB-B */
3435         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3436         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3437
3438         I915_WRITE(FDI_RX_MISC(pipe),
3439                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3440
3441         reg = FDI_RX_CTL(pipe);
3442         temp = I915_READ(reg);
3443         if (HAS_PCH_CPT(dev)) {
3444                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3445                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3446         } else {
3447                 temp &= ~FDI_LINK_TRAIN_NONE;
3448                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3449         }
3450         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3451
3452         POSTING_READ(reg);
3453         udelay(150);
3454
3455         for (i = 0; i < 4; i++) {
3456                 reg = FDI_TX_CTL(pipe);
3457                 temp = I915_READ(reg);
3458                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3459                 temp |= snb_b_fdi_train_param[i];
3460                 I915_WRITE(reg, temp);
3461
3462                 POSTING_READ(reg);
3463                 udelay(500);
3464
3465                 for (retry = 0; retry < 5; retry++) {
3466                         reg = FDI_RX_IIR(pipe);
3467                         temp = I915_READ(reg);
3468                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3469                         if (temp & FDI_RX_BIT_LOCK) {
3470                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3471                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3472                                 break;
3473                         }
3474                         udelay(50);
3475                 }
3476                 if (retry < 5)
3477                         break;
3478         }
3479         if (i == 4)
3480                 DRM_ERROR("FDI train 1 fail!\n");
3481
3482         /* Train 2 */
3483         reg = FDI_TX_CTL(pipe);
3484         temp = I915_READ(reg);
3485         temp &= ~FDI_LINK_TRAIN_NONE;
3486         temp |= FDI_LINK_TRAIN_PATTERN_2;
3487         if (IS_GEN6(dev)) {
3488                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3489                 /* SNB-B */
3490                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3491         }
3492         I915_WRITE(reg, temp);
3493
3494         reg = FDI_RX_CTL(pipe);
3495         temp = I915_READ(reg);
3496         if (HAS_PCH_CPT(dev)) {
3497                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3498                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3499         } else {
3500                 temp &= ~FDI_LINK_TRAIN_NONE;
3501                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3502         }
3503         I915_WRITE(reg, temp);
3504
3505         POSTING_READ(reg);
3506         udelay(150);
3507
3508         for (i = 0; i < 4; i++) {
3509                 reg = FDI_TX_CTL(pipe);
3510                 temp = I915_READ(reg);
3511                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3512                 temp |= snb_b_fdi_train_param[i];
3513                 I915_WRITE(reg, temp);
3514
3515                 POSTING_READ(reg);
3516                 udelay(500);
3517
3518                 for (retry = 0; retry < 5; retry++) {
3519                         reg = FDI_RX_IIR(pipe);
3520                         temp = I915_READ(reg);
3521                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3522                         if (temp & FDI_RX_SYMBOL_LOCK) {
3523                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3524                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3525                                 break;
3526                         }
3527                         udelay(50);
3528                 }
3529                 if (retry < 5)
3530                         break;
3531         }
3532         if (i == 4)
3533                 DRM_ERROR("FDI train 2 fail!\n");
3534
3535         DRM_DEBUG_KMS("FDI train done.\n");
3536 }
3537
3538 /* Manual link training for Ivy Bridge A0 parts */
3539 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3540 {
3541         struct drm_device *dev = crtc->dev;
3542         struct drm_i915_private *dev_priv = dev->dev_private;
3543         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3544         int pipe = intel_crtc->pipe;
3545         i915_reg_t reg;
3546         u32 temp, i, j;
3547
3548         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3549            for train result */
3550         reg = FDI_RX_IMR(pipe);
3551         temp = I915_READ(reg);
3552         temp &= ~FDI_RX_SYMBOL_LOCK;
3553         temp &= ~FDI_RX_BIT_LOCK;
3554         I915_WRITE(reg, temp);
3555
3556         POSTING_READ(reg);
3557         udelay(150);
3558
3559         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3560                       I915_READ(FDI_RX_IIR(pipe)));
3561
3562         /* Try each vswing and preemphasis setting twice before moving on */
3563         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3564                 /* disable first in case we need to retry */
3565                 reg = FDI_TX_CTL(pipe);
3566                 temp = I915_READ(reg);
3567                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3568                 temp &= ~FDI_TX_ENABLE;
3569                 I915_WRITE(reg, temp);
3570
3571                 reg = FDI_RX_CTL(pipe);
3572                 temp = I915_READ(reg);
3573                 temp &= ~FDI_LINK_TRAIN_AUTO;
3574                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3575                 temp &= ~FDI_RX_ENABLE;
3576                 I915_WRITE(reg, temp);
3577
3578                 /* enable CPU FDI TX and PCH FDI RX */
3579                 reg = FDI_TX_CTL(pipe);
3580                 temp = I915_READ(reg);
3581                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3582                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3583                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3584                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3585                 temp |= snb_b_fdi_train_param[j/2];
3586                 temp |= FDI_COMPOSITE_SYNC;
3587                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3588
3589                 I915_WRITE(FDI_RX_MISC(pipe),
3590                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3591
3592                 reg = FDI_RX_CTL(pipe);
3593                 temp = I915_READ(reg);
3594                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3595                 temp |= FDI_COMPOSITE_SYNC;
3596                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3597
3598                 POSTING_READ(reg);
3599                 udelay(1); /* should be 0.5us */
3600
3601                 for (i = 0; i < 4; i++) {
3602                         reg = FDI_RX_IIR(pipe);
3603                         temp = I915_READ(reg);
3604                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3605
3606                         if (temp & FDI_RX_BIT_LOCK ||
3607                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3608                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3609                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3610                                               i);
3611                                 break;
3612                         }
3613                         udelay(1); /* should be 0.5us */
3614                 }
3615                 if (i == 4) {
3616                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3617                         continue;
3618                 }
3619
3620                 /* Train 2 */
3621                 reg = FDI_TX_CTL(pipe);
3622                 temp = I915_READ(reg);
3623                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3624                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3625                 I915_WRITE(reg, temp);
3626
3627                 reg = FDI_RX_CTL(pipe);
3628                 temp = I915_READ(reg);
3629                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3630                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3631                 I915_WRITE(reg, temp);
3632
3633                 POSTING_READ(reg);
3634                 udelay(2); /* should be 1.5us */
3635
3636                 for (i = 0; i < 4; i++) {
3637                         reg = FDI_RX_IIR(pipe);
3638                         temp = I915_READ(reg);
3639                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3640
3641                         if (temp & FDI_RX_SYMBOL_LOCK ||
3642                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3643                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3644                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3645                                               i);
3646                                 goto train_done;
3647                         }
3648                         udelay(2); /* should be 1.5us */
3649                 }
3650                 if (i == 4)
3651                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3652         }
3653
3654 train_done:
3655         DRM_DEBUG_KMS("FDI train done.\n");
3656 }
3657
3658 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3659 {
3660         struct drm_device *dev = intel_crtc->base.dev;
3661         struct drm_i915_private *dev_priv = dev->dev_private;
3662         int pipe = intel_crtc->pipe;
3663         i915_reg_t reg;
3664         u32 temp;
3665
3666         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3667         reg = FDI_RX_CTL(pipe);
3668         temp = I915_READ(reg);
3669         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3670         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3671         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3672         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3673
3674         POSTING_READ(reg);
3675         udelay(200);
3676
3677         /* Switch from Rawclk to PCDclk */
3678         temp = I915_READ(reg);
3679         I915_WRITE(reg, temp | FDI_PCDCLK);
3680
3681         POSTING_READ(reg);
3682         udelay(200);
3683
3684         /* Enable CPU FDI TX PLL, always on for Ironlake */
3685         reg = FDI_TX_CTL(pipe);
3686         temp = I915_READ(reg);
3687         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3688                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3689
3690                 POSTING_READ(reg);
3691                 udelay(100);
3692         }
3693 }
3694
3695 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3696 {
3697         struct drm_device *dev = intel_crtc->base.dev;
3698         struct drm_i915_private *dev_priv = dev->dev_private;
3699         int pipe = intel_crtc->pipe;
3700         i915_reg_t reg;
3701         u32 temp;
3702
3703         /* Switch from PCDclk to Rawclk */
3704         reg = FDI_RX_CTL(pipe);
3705         temp = I915_READ(reg);
3706         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3707
3708         /* Disable CPU FDI TX PLL */
3709         reg = FDI_TX_CTL(pipe);
3710         temp = I915_READ(reg);
3711         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3712
3713         POSTING_READ(reg);
3714         udelay(100);
3715
3716         reg = FDI_RX_CTL(pipe);
3717         temp = I915_READ(reg);
3718         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3719
3720         /* Wait for the clocks to turn off. */
3721         POSTING_READ(reg);
3722         udelay(100);
3723 }
3724
3725 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3726 {
3727         struct drm_device *dev = crtc->dev;
3728         struct drm_i915_private *dev_priv = dev->dev_private;
3729         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3730         int pipe = intel_crtc->pipe;
3731         i915_reg_t reg;
3732         u32 temp;
3733
3734         /* disable CPU FDI tx and PCH FDI rx */
3735         reg = FDI_TX_CTL(pipe);
3736         temp = I915_READ(reg);
3737         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3738         POSTING_READ(reg);
3739
3740         reg = FDI_RX_CTL(pipe);
3741         temp = I915_READ(reg);
3742         temp &= ~(0x7 << 16);
3743         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3744         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3745
3746         POSTING_READ(reg);
3747         udelay(100);
3748
3749         /* Ironlake workaround, disable clock pointer after downing FDI */
3750         if (HAS_PCH_IBX(dev))
3751                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3752
3753         /* still set train pattern 1 */
3754         reg = FDI_TX_CTL(pipe);
3755         temp = I915_READ(reg);
3756         temp &= ~FDI_LINK_TRAIN_NONE;
3757         temp |= FDI_LINK_TRAIN_PATTERN_1;
3758         I915_WRITE(reg, temp);
3759
3760         reg = FDI_RX_CTL(pipe);
3761         temp = I915_READ(reg);
3762         if (HAS_PCH_CPT(dev)) {
3763                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3764                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3765         } else {
3766                 temp &= ~FDI_LINK_TRAIN_NONE;
3767                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3768         }
3769         /* BPC in FDI rx is consistent with that in PIPECONF */
3770         temp &= ~(0x07 << 16);
3771         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3772         I915_WRITE(reg, temp);
3773
3774         POSTING_READ(reg);
3775         udelay(100);
3776 }
3777
3778 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3779 {
3780         struct intel_crtc *crtc;
3781
3782         /* Note that we don't need to be called with mode_config.lock here
3783          * as our list of CRTC objects is static for the lifetime of the
3784          * device and so cannot disappear as we iterate. Similarly, we can
3785          * happily treat the predicates as racy, atomic checks as userspace
3786          * cannot claim and pin a new fb without at least acquring the
3787          * struct_mutex and so serialising with us.
3788          */
3789         for_each_intel_crtc(dev, crtc) {
3790                 if (atomic_read(&crtc->unpin_work_count) == 0)
3791                         continue;
3792
3793                 if (crtc->unpin_work)
3794                         intel_wait_for_vblank(dev, crtc->pipe);
3795
3796                 return true;
3797         }
3798
3799         return false;
3800 }
3801
3802 static void page_flip_completed(struct intel_crtc *intel_crtc)
3803 {
3804         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3805         struct intel_unpin_work *work = intel_crtc->unpin_work;
3806
3807         /* ensure that the unpin work is consistent wrt ->pending. */
3808         smp_rmb();
3809         intel_crtc->unpin_work = NULL;
3810
3811         if (work->event)
3812                 drm_send_vblank_event(intel_crtc->base.dev,
3813                                       intel_crtc->pipe,
3814                                       work->event);
3815
3816         drm_crtc_vblank_put(&intel_crtc->base);
3817
3818         wake_up_all(&dev_priv->pending_flip_queue);
3819         queue_work(dev_priv->wq, &work->work);
3820
3821         trace_i915_flip_complete(intel_crtc->plane,
3822                                  work->pending_flip_obj);
3823 }
3824
3825 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3826 {
3827         struct drm_device *dev = crtc->dev;
3828         struct drm_i915_private *dev_priv = dev->dev_private;
3829         long ret;
3830
3831         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3832
3833         ret = wait_event_interruptible_timeout(
3834                                         dev_priv->pending_flip_queue,
3835                                         !intel_crtc_has_pending_flip(crtc),
3836                                         60*HZ);
3837
3838         if (ret < 0)
3839                 return ret;
3840
3841         if (ret == 0) {
3842                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3843
3844                 spin_lock_irq(&dev->event_lock);
3845                 if (intel_crtc->unpin_work) {
3846                         WARN_ONCE(1, "Removing stuck page flip\n");
3847                         page_flip_completed(intel_crtc);
3848                 }
3849                 spin_unlock_irq(&dev->event_lock);
3850         }
3851
3852         return 0;
3853 }
3854
3855 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
3856 {
3857         u32 temp;
3858
3859         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3860
3861         mutex_lock(&dev_priv->sb_lock);
3862
3863         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3864         temp |= SBI_SSCCTL_DISABLE;
3865         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3866
3867         mutex_unlock(&dev_priv->sb_lock);
3868 }
3869
3870 /* Program iCLKIP clock to the desired frequency */
3871 static void lpt_program_iclkip(struct drm_crtc *crtc)
3872 {
3873         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
3874         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3875         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3876         u32 temp;
3877
3878         lpt_disable_iclkip(dev_priv);
3879
3880         /* The iCLK virtual clock root frequency is in MHz,
3881          * but the adjusted_mode->crtc_clock in in KHz. To get the
3882          * divisors, it is necessary to divide one by another, so we
3883          * convert the virtual clock precision to KHz here for higher
3884          * precision.
3885          */
3886         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
3887                 u32 iclk_virtual_root_freq = 172800 * 1000;
3888                 u32 iclk_pi_range = 64;
3889                 u32 desired_divisor;
3890
3891                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3892                                                     clock << auxdiv);
3893                 divsel = (desired_divisor / iclk_pi_range) - 2;
3894                 phaseinc = desired_divisor % iclk_pi_range;
3895
3896                 /*
3897                  * Near 20MHz is a corner case which is
3898                  * out of range for the 7-bit divisor
3899                  */
3900                 if (divsel <= 0x7f)
3901                         break;
3902         }
3903
3904         /* This should not happen with any sane values */
3905         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3906                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3907         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3908                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3909
3910         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3911                         clock,
3912                         auxdiv,
3913                         divsel,
3914                         phasedir,
3915                         phaseinc);
3916
3917         mutex_lock(&dev_priv->sb_lock);
3918
3919         /* Program SSCDIVINTPHASE6 */
3920         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3921         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3922         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3923         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3924         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3925         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3926         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3927         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3928
3929         /* Program SSCAUXDIV */
3930         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3931         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3932         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3933         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3934
3935         /* Enable modulator and associated divider */
3936         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3937         temp &= ~SBI_SSCCTL_DISABLE;
3938         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3939
3940         mutex_unlock(&dev_priv->sb_lock);
3941
3942         /* Wait for initialization time */
3943         udelay(24);
3944
3945         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3946 }
3947
3948 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
3949 {
3950         u32 divsel, phaseinc, auxdiv;
3951         u32 iclk_virtual_root_freq = 172800 * 1000;
3952         u32 iclk_pi_range = 64;
3953         u32 desired_divisor;
3954         u32 temp;
3955
3956         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
3957                 return 0;
3958
3959         mutex_lock(&dev_priv->sb_lock);
3960
3961         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3962         if (temp & SBI_SSCCTL_DISABLE) {
3963                 mutex_unlock(&dev_priv->sb_lock);
3964                 return 0;
3965         }
3966
3967         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3968         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
3969                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
3970         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
3971                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
3972
3973         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3974         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
3975                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
3976
3977         mutex_unlock(&dev_priv->sb_lock);
3978
3979         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
3980
3981         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3982                                  desired_divisor << auxdiv);
3983 }
3984
3985 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3986                                                 enum pipe pch_transcoder)
3987 {
3988         struct drm_device *dev = crtc->base.dev;
3989         struct drm_i915_private *dev_priv = dev->dev_private;
3990         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3991
3992         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3993                    I915_READ(HTOTAL(cpu_transcoder)));
3994         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3995                    I915_READ(HBLANK(cpu_transcoder)));
3996         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
3997                    I915_READ(HSYNC(cpu_transcoder)));
3998
3999         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4000                    I915_READ(VTOTAL(cpu_transcoder)));
4001         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4002                    I915_READ(VBLANK(cpu_transcoder)));
4003         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4004                    I915_READ(VSYNC(cpu_transcoder)));
4005         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4006                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4007 }
4008
4009 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4010 {
4011         struct drm_i915_private *dev_priv = dev->dev_private;
4012         uint32_t temp;
4013
4014         temp = I915_READ(SOUTH_CHICKEN1);
4015         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4016                 return;
4017
4018         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4019         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4020
4021         temp &= ~FDI_BC_BIFURCATION_SELECT;
4022         if (enable)
4023                 temp |= FDI_BC_BIFURCATION_SELECT;
4024
4025         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4026         I915_WRITE(SOUTH_CHICKEN1, temp);
4027         POSTING_READ(SOUTH_CHICKEN1);
4028 }
4029
4030 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4031 {
4032         struct drm_device *dev = intel_crtc->base.dev;
4033
4034         switch (intel_crtc->pipe) {
4035         case PIPE_A:
4036                 break;
4037         case PIPE_B:
4038                 if (intel_crtc->config->fdi_lanes > 2)
4039                         cpt_set_fdi_bc_bifurcation(dev, false);
4040                 else
4041                         cpt_set_fdi_bc_bifurcation(dev, true);
4042
4043                 break;
4044         case PIPE_C:
4045                 cpt_set_fdi_bc_bifurcation(dev, true);
4046
4047                 break;
4048         default:
4049                 BUG();
4050         }
4051 }
4052
4053 /* Return which DP Port should be selected for Transcoder DP control */
4054 static enum port
4055 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4056 {
4057         struct drm_device *dev = crtc->dev;
4058         struct intel_encoder *encoder;
4059
4060         for_each_encoder_on_crtc(dev, crtc, encoder) {
4061                 if (encoder->type == INTEL_OUTPUT_DISPLAYPORT ||
4062                     encoder->type == INTEL_OUTPUT_EDP)
4063                         return enc_to_dig_port(&encoder->base)->port;
4064         }
4065
4066         return -1;
4067 }
4068
4069 /*
4070  * Enable PCH resources required for PCH ports:
4071  *   - PCH PLLs
4072  *   - FDI training & RX/TX
4073  *   - update transcoder timings
4074  *   - DP transcoding bits
4075  *   - transcoder
4076  */
4077 static void ironlake_pch_enable(struct drm_crtc *crtc)
4078 {
4079         struct drm_device *dev = crtc->dev;
4080         struct drm_i915_private *dev_priv = dev->dev_private;
4081         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4082         int pipe = intel_crtc->pipe;
4083         u32 temp;
4084
4085         assert_pch_transcoder_disabled(dev_priv, pipe);
4086
4087         if (IS_IVYBRIDGE(dev))
4088                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4089
4090         /* Write the TU size bits before fdi link training, so that error
4091          * detection works. */
4092         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4093                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4094
4095         /*
4096          * Sometimes spurious CPU pipe underruns happen during FDI
4097          * training, at least with VGA+HDMI cloning. Suppress them.
4098          */
4099         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
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         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4136
4137         /* For PCH DP, enable TRANS_DP_CTL */
4138         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4139                 const struct drm_display_mode *adjusted_mode =
4140                         &intel_crtc->config->base.adjusted_mode;
4141                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4142                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4143                 temp = I915_READ(reg);
4144                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4145                           TRANS_DP_SYNC_MASK |
4146                           TRANS_DP_BPC_MASK);
4147                 temp |= TRANS_DP_OUTPUT_ENABLE;
4148                 temp |= bpc << 9; /* same format but at 11:9 */
4149
4150                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4151                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4152                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4153                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4154
4155                 switch (intel_trans_dp_port_sel(crtc)) {
4156                 case PORT_B:
4157                         temp |= TRANS_DP_PORT_SEL_B;
4158                         break;
4159                 case PORT_C:
4160                         temp |= TRANS_DP_PORT_SEL_C;
4161                         break;
4162                 case PORT_D:
4163                         temp |= TRANS_DP_PORT_SEL_D;
4164                         break;
4165                 default:
4166                         BUG();
4167                 }
4168
4169                 I915_WRITE(reg, temp);
4170         }
4171
4172         ironlake_enable_pch_transcoder(dev_priv, pipe);
4173 }
4174
4175 static void lpt_pch_enable(struct drm_crtc *crtc)
4176 {
4177         struct drm_device *dev = crtc->dev;
4178         struct drm_i915_private *dev_priv = dev->dev_private;
4179         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4180         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4181
4182         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4183
4184         lpt_program_iclkip(crtc);
4185
4186         /* Set transcoder timing. */
4187         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4188
4189         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4190 }
4191
4192 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4193 {
4194         struct drm_i915_private *dev_priv = dev->dev_private;
4195         i915_reg_t dslreg = PIPEDSL(pipe);
4196         u32 temp;
4197
4198         temp = I915_READ(dslreg);
4199         udelay(500);
4200         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4201                 if (wait_for(I915_READ(dslreg) != temp, 5))
4202                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4203         }
4204 }
4205
4206 static int
4207 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4208                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4209                   int src_w, int src_h, int dst_w, int dst_h)
4210 {
4211         struct intel_crtc_scaler_state *scaler_state =
4212                 &crtc_state->scaler_state;
4213         struct intel_crtc *intel_crtc =
4214                 to_intel_crtc(crtc_state->base.crtc);
4215         int need_scaling;
4216
4217         need_scaling = intel_rotation_90_or_270(rotation) ?
4218                 (src_h != dst_w || src_w != dst_h):
4219                 (src_w != dst_w || src_h != dst_h);
4220
4221         /*
4222          * if plane is being disabled or scaler is no more required or force detach
4223          *  - free scaler binded to this plane/crtc
4224          *  - in order to do this, update crtc->scaler_usage
4225          *
4226          * Here scaler state in crtc_state is set free so that
4227          * scaler can be assigned to other user. Actual register
4228          * update to free the scaler is done in plane/panel-fit programming.
4229          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4230          */
4231         if (force_detach || !need_scaling) {
4232                 if (*scaler_id >= 0) {
4233                         scaler_state->scaler_users &= ~(1 << scaler_user);
4234                         scaler_state->scalers[*scaler_id].in_use = 0;
4235
4236                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4237                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4238                                 intel_crtc->pipe, scaler_user, *scaler_id,
4239                                 scaler_state->scaler_users);
4240                         *scaler_id = -1;
4241                 }
4242                 return 0;
4243         }
4244
4245         /* range checks */
4246         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4247                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4248
4249                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4250                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4251                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4252                         "size is out of scaler range\n",
4253                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4254                 return -EINVAL;
4255         }
4256
4257         /* mark this plane as a scaler user in crtc_state */
4258         scaler_state->scaler_users |= (1 << scaler_user);
4259         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4260                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4261                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4262                 scaler_state->scaler_users);
4263
4264         return 0;
4265 }
4266
4267 /**
4268  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4269  *
4270  * @state: crtc's scaler state
4271  *
4272  * Return
4273  *     0 - scaler_usage updated successfully
4274  *    error - requested scaling cannot be supported or other error condition
4275  */
4276 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4277 {
4278         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4279         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4280
4281         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4282                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4283
4284         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4285                 &state->scaler_state.scaler_id, BIT(DRM_ROTATE_0),
4286                 state->pipe_src_w, state->pipe_src_h,
4287                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4288 }
4289
4290 /**
4291  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4292  *
4293  * @state: crtc's scaler state
4294  * @plane_state: atomic plane state to update
4295  *
4296  * Return
4297  *     0 - scaler_usage updated successfully
4298  *    error - requested scaling cannot be supported or other error condition
4299  */
4300 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4301                                    struct intel_plane_state *plane_state)
4302 {
4303
4304         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4305         struct intel_plane *intel_plane =
4306                 to_intel_plane(plane_state->base.plane);
4307         struct drm_framebuffer *fb = plane_state->base.fb;
4308         int ret;
4309
4310         bool force_detach = !fb || !plane_state->visible;
4311
4312         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4313                       intel_plane->base.base.id, intel_crtc->pipe,
4314                       drm_plane_index(&intel_plane->base));
4315
4316         ret = skl_update_scaler(crtc_state, force_detach,
4317                                 drm_plane_index(&intel_plane->base),
4318                                 &plane_state->scaler_id,
4319                                 plane_state->base.rotation,
4320                                 drm_rect_width(&plane_state->src) >> 16,
4321                                 drm_rect_height(&plane_state->src) >> 16,
4322                                 drm_rect_width(&plane_state->dst),
4323                                 drm_rect_height(&plane_state->dst));
4324
4325         if (ret || plane_state->scaler_id < 0)
4326                 return ret;
4327
4328         /* check colorkey */
4329         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4330                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4331                               intel_plane->base.base.id);
4332                 return -EINVAL;
4333         }
4334
4335         /* Check src format */
4336         switch (fb->pixel_format) {
4337         case DRM_FORMAT_RGB565:
4338         case DRM_FORMAT_XBGR8888:
4339         case DRM_FORMAT_XRGB8888:
4340         case DRM_FORMAT_ABGR8888:
4341         case DRM_FORMAT_ARGB8888:
4342         case DRM_FORMAT_XRGB2101010:
4343         case DRM_FORMAT_XBGR2101010:
4344         case DRM_FORMAT_YUYV:
4345         case DRM_FORMAT_YVYU:
4346         case DRM_FORMAT_UYVY:
4347         case DRM_FORMAT_VYUY:
4348                 break;
4349         default:
4350                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4351                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4352                 return -EINVAL;
4353         }
4354
4355         return 0;
4356 }
4357
4358 static void skylake_scaler_disable(struct intel_crtc *crtc)
4359 {
4360         int i;
4361
4362         for (i = 0; i < crtc->num_scalers; i++)
4363                 skl_detach_scaler(crtc, i);
4364 }
4365
4366 static void skylake_pfit_enable(struct intel_crtc *crtc)
4367 {
4368         struct drm_device *dev = crtc->base.dev;
4369         struct drm_i915_private *dev_priv = dev->dev_private;
4370         int pipe = crtc->pipe;
4371         struct intel_crtc_scaler_state *scaler_state =
4372                 &crtc->config->scaler_state;
4373
4374         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4375
4376         if (crtc->config->pch_pfit.enabled) {
4377                 int id;
4378
4379                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4380                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4381                         return;
4382                 }
4383
4384                 id = scaler_state->scaler_id;
4385                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4386                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4387                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4388                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4389
4390                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4391         }
4392 }
4393
4394 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4395 {
4396         struct drm_device *dev = crtc->base.dev;
4397         struct drm_i915_private *dev_priv = dev->dev_private;
4398         int pipe = crtc->pipe;
4399
4400         if (crtc->config->pch_pfit.enabled) {
4401                 /* Force use of hard-coded filter coefficients
4402                  * as some pre-programmed values are broken,
4403                  * e.g. x201.
4404                  */
4405                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4406                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4407                                                  PF_PIPE_SEL_IVB(pipe));
4408                 else
4409                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4410                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4411                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4412         }
4413 }
4414
4415 void hsw_enable_ips(struct intel_crtc *crtc)
4416 {
4417         struct drm_device *dev = crtc->base.dev;
4418         struct drm_i915_private *dev_priv = dev->dev_private;
4419
4420         if (!crtc->config->ips_enabled)
4421                 return;
4422
4423         /*
4424          * We can only enable IPS after we enable a plane and wait for a vblank
4425          * This function is called from post_plane_update, which is run after
4426          * a vblank wait.
4427          */
4428
4429         assert_plane_enabled(dev_priv, crtc->plane);
4430         if (IS_BROADWELL(dev)) {
4431                 mutex_lock(&dev_priv->rps.hw_lock);
4432                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4433                 mutex_unlock(&dev_priv->rps.hw_lock);
4434                 /* Quoting Art Runyan: "its not safe to expect any particular
4435                  * value in IPS_CTL bit 31 after enabling IPS through the
4436                  * mailbox." Moreover, the mailbox may return a bogus state,
4437                  * so we need to just enable it and continue on.
4438                  */
4439         } else {
4440                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4441                 /* The bit only becomes 1 in the next vblank, so this wait here
4442                  * is essentially intel_wait_for_vblank. If we don't have this
4443                  * and don't wait for vblanks until the end of crtc_enable, then
4444                  * the HW state readout code will complain that the expected
4445                  * IPS_CTL value is not the one we read. */
4446                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4447                         DRM_ERROR("Timed out waiting for IPS enable\n");
4448         }
4449 }
4450
4451 void hsw_disable_ips(struct intel_crtc *crtc)
4452 {
4453         struct drm_device *dev = crtc->base.dev;
4454         struct drm_i915_private *dev_priv = dev->dev_private;
4455
4456         if (!crtc->config->ips_enabled)
4457                 return;
4458
4459         assert_plane_enabled(dev_priv, crtc->plane);
4460         if (IS_BROADWELL(dev)) {
4461                 mutex_lock(&dev_priv->rps.hw_lock);
4462                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4463                 mutex_unlock(&dev_priv->rps.hw_lock);
4464                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4465                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4466                         DRM_ERROR("Timed out waiting for IPS disable\n");
4467         } else {
4468                 I915_WRITE(IPS_CTL, 0);
4469                 POSTING_READ(IPS_CTL);
4470         }
4471
4472         /* We need to wait for a vblank before we can disable the plane. */
4473         intel_wait_for_vblank(dev, crtc->pipe);
4474 }
4475
4476 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4477 {
4478         if (intel_crtc->overlay) {
4479                 struct drm_device *dev = intel_crtc->base.dev;
4480                 struct drm_i915_private *dev_priv = dev->dev_private;
4481
4482                 mutex_lock(&dev->struct_mutex);
4483                 dev_priv->mm.interruptible = false;
4484                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4485                 dev_priv->mm.interruptible = true;
4486                 mutex_unlock(&dev->struct_mutex);
4487         }
4488
4489         /* Let userspace switch the overlay on again. In most cases userspace
4490          * has to recompute where to put it anyway.
4491          */
4492 }
4493
4494 /**
4495  * intel_post_enable_primary - Perform operations after enabling primary plane
4496  * @crtc: the CRTC whose primary plane was just enabled
4497  *
4498  * Performs potentially sleeping operations that must be done after the primary
4499  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4500  * called due to an explicit primary plane update, or due to an implicit
4501  * re-enable that is caused when a sprite plane is updated to no longer
4502  * completely hide the primary plane.
4503  */
4504 static void
4505 intel_post_enable_primary(struct drm_crtc *crtc)
4506 {
4507         struct drm_device *dev = crtc->dev;
4508         struct drm_i915_private *dev_priv = dev->dev_private;
4509         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4510         int pipe = intel_crtc->pipe;
4511
4512         /*
4513          * FIXME IPS should be fine as long as one plane is
4514          * enabled, but in practice it seems to have problems
4515          * when going from primary only to sprite only and vice
4516          * versa.
4517          */
4518         hsw_enable_ips(intel_crtc);
4519
4520         /*
4521          * Gen2 reports pipe underruns whenever all planes are disabled.
4522          * So don't enable underrun reporting before at least some planes
4523          * are enabled.
4524          * FIXME: Need to fix the logic to work when we turn off all planes
4525          * but leave the pipe running.
4526          */
4527         if (IS_GEN2(dev))
4528                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4529
4530         /* Underruns don't always raise interrupts, so check manually. */
4531         intel_check_cpu_fifo_underruns(dev_priv);
4532         intel_check_pch_fifo_underruns(dev_priv);
4533 }
4534
4535 /* FIXME move all this to pre_plane_update() with proper state tracking */
4536 static void
4537 intel_pre_disable_primary(struct drm_crtc *crtc)
4538 {
4539         struct drm_device *dev = crtc->dev;
4540         struct drm_i915_private *dev_priv = dev->dev_private;
4541         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4542         int pipe = intel_crtc->pipe;
4543
4544         /*
4545          * Gen2 reports pipe underruns whenever all planes are disabled.
4546          * So diasble underrun reporting before all the planes get disabled.
4547          * FIXME: Need to fix the logic to work when we turn off all planes
4548          * but leave the pipe running.
4549          */
4550         if (IS_GEN2(dev))
4551                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4552
4553         /*
4554          * FIXME IPS should be fine as long as one plane is
4555          * enabled, but in practice it seems to have problems
4556          * when going from primary only to sprite only and vice
4557          * versa.
4558          */
4559         hsw_disable_ips(intel_crtc);
4560 }
4561
4562 /* FIXME get rid of this and use pre_plane_update */
4563 static void
4564 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4565 {
4566         struct drm_device *dev = crtc->dev;
4567         struct drm_i915_private *dev_priv = dev->dev_private;
4568         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4569         int pipe = intel_crtc->pipe;
4570
4571         intel_pre_disable_primary(crtc);
4572
4573         /*
4574          * Vblank time updates from the shadow to live plane control register
4575          * are blocked if the memory self-refresh mode is active at that
4576          * moment. So to make sure the plane gets truly disabled, disable
4577          * first the self-refresh mode. The self-refresh enable bit in turn
4578          * will be checked/applied by the HW only at the next frame start
4579          * event which is after the vblank start event, so we need to have a
4580          * wait-for-vblank between disabling the plane and the pipe.
4581          */
4582         if (HAS_GMCH_DISPLAY(dev)) {
4583                 intel_set_memory_cxsr(dev_priv, false);
4584                 dev_priv->wm.vlv.cxsr = false;
4585                 intel_wait_for_vblank(dev, pipe);
4586         }
4587 }
4588
4589 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4590 {
4591         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4592         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4593         struct intel_crtc_state *pipe_config =
4594                 to_intel_crtc_state(crtc->base.state);
4595         struct drm_device *dev = crtc->base.dev;
4596         struct drm_plane *primary = crtc->base.primary;
4597         struct drm_plane_state *old_pri_state =
4598                 drm_atomic_get_existing_plane_state(old_state, primary);
4599
4600         intel_frontbuffer_flip(dev, pipe_config->fb_bits);
4601
4602         crtc->wm.cxsr_allowed = true;
4603
4604         if (pipe_config->update_wm_post && pipe_config->base.active)
4605                 intel_update_watermarks(&crtc->base);
4606
4607         if (old_pri_state) {
4608                 struct intel_plane_state *primary_state =
4609                         to_intel_plane_state(primary->state);
4610                 struct intel_plane_state *old_primary_state =
4611                         to_intel_plane_state(old_pri_state);
4612
4613                 intel_fbc_post_update(crtc);
4614
4615                 if (primary_state->visible &&
4616                     (needs_modeset(&pipe_config->base) ||
4617                      !old_primary_state->visible))
4618                         intel_post_enable_primary(&crtc->base);
4619         }
4620 }
4621
4622 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
4623 {
4624         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4625         struct drm_device *dev = crtc->base.dev;
4626         struct drm_i915_private *dev_priv = dev->dev_private;
4627         struct intel_crtc_state *pipe_config =
4628                 to_intel_crtc_state(crtc->base.state);
4629         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4630         struct drm_plane *primary = crtc->base.primary;
4631         struct drm_plane_state *old_pri_state =
4632                 drm_atomic_get_existing_plane_state(old_state, primary);
4633         bool modeset = needs_modeset(&pipe_config->base);
4634
4635         if (old_pri_state) {
4636                 struct intel_plane_state *primary_state =
4637                         to_intel_plane_state(primary->state);
4638                 struct intel_plane_state *old_primary_state =
4639                         to_intel_plane_state(old_pri_state);
4640
4641                 intel_fbc_pre_update(crtc);
4642
4643                 if (old_primary_state->visible &&
4644                     (modeset || !primary_state->visible))
4645                         intel_pre_disable_primary(&crtc->base);
4646         }
4647
4648         if (pipe_config->disable_cxsr) {
4649                 crtc->wm.cxsr_allowed = false;
4650
4651                 /*
4652                  * Vblank time updates from the shadow to live plane control register
4653                  * are blocked if the memory self-refresh mode is active at that
4654                  * moment. So to make sure the plane gets truly disabled, disable
4655                  * first the self-refresh mode. The self-refresh enable bit in turn
4656                  * will be checked/applied by the HW only at the next frame start
4657                  * event which is after the vblank start event, so we need to have a
4658                  * wait-for-vblank between disabling the plane and the pipe.
4659                  */
4660                 if (old_crtc_state->base.active) {
4661                         intel_set_memory_cxsr(dev_priv, false);
4662                         dev_priv->wm.vlv.cxsr = false;
4663                         intel_wait_for_vblank(dev, crtc->pipe);
4664                 }
4665         }
4666
4667         /*
4668          * IVB workaround: must disable low power watermarks for at least
4669          * one frame before enabling scaling.  LP watermarks can be re-enabled
4670          * when scaling is disabled.
4671          *
4672          * WaCxSRDisabledForSpriteScaling:ivb
4673          */
4674         if (pipe_config->disable_lp_wm) {
4675                 ilk_disable_lp_wm(dev);
4676                 intel_wait_for_vblank(dev, crtc->pipe);
4677         }
4678
4679         /*
4680          * If we're doing a modeset, we're done.  No need to do any pre-vblank
4681          * watermark programming here.
4682          */
4683         if (needs_modeset(&pipe_config->base))
4684                 return;
4685
4686         /*
4687          * For platforms that support atomic watermarks, program the
4688          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
4689          * will be the intermediate values that are safe for both pre- and
4690          * post- vblank; when vblank happens, the 'active' values will be set
4691          * to the final 'target' values and we'll do this again to get the
4692          * optimal watermarks.  For gen9+ platforms, the values we program here
4693          * will be the final target values which will get automatically latched
4694          * at vblank time; no further programming will be necessary.
4695          *
4696          * If a platform hasn't been transitioned to atomic watermarks yet,
4697          * we'll continue to update watermarks the old way, if flags tell
4698          * us to.
4699          */
4700         if (dev_priv->display.initial_watermarks != NULL)
4701                 dev_priv->display.initial_watermarks(pipe_config);
4702         else if (pipe_config->update_wm_pre)
4703                 intel_update_watermarks(&crtc->base);
4704 }
4705
4706 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4707 {
4708         struct drm_device *dev = crtc->dev;
4709         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4710         struct drm_plane *p;
4711         int pipe = intel_crtc->pipe;
4712
4713         intel_crtc_dpms_overlay_disable(intel_crtc);
4714
4715         drm_for_each_plane_mask(p, dev, plane_mask)
4716                 to_intel_plane(p)->disable_plane(p, crtc);
4717
4718         /*
4719          * FIXME: Once we grow proper nuclear flip support out of this we need
4720          * to compute the mask of flip planes precisely. For the time being
4721          * consider this a flip to a NULL plane.
4722          */
4723         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4724 }
4725
4726 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4727 {
4728         struct drm_device *dev = crtc->dev;
4729         struct drm_i915_private *dev_priv = dev->dev_private;
4730         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4731         struct intel_encoder *encoder;
4732         int pipe = intel_crtc->pipe;
4733         struct intel_crtc_state *pipe_config =
4734                 to_intel_crtc_state(crtc->state);
4735
4736         if (WARN_ON(intel_crtc->active))
4737                 return;
4738
4739         if (intel_crtc->config->has_pch_encoder)
4740                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4741
4742         if (intel_crtc->config->has_pch_encoder)
4743                 intel_prepare_shared_dpll(intel_crtc);
4744
4745         if (intel_crtc->config->has_dp_encoder)
4746                 intel_dp_set_m_n(intel_crtc, M1_N1);
4747
4748         intel_set_pipe_timings(intel_crtc);
4749         intel_set_pipe_src_size(intel_crtc);
4750
4751         if (intel_crtc->config->has_pch_encoder) {
4752                 intel_cpu_transcoder_set_m_n(intel_crtc,
4753                                      &intel_crtc->config->fdi_m_n, NULL);
4754         }
4755
4756         ironlake_set_pipeconf(crtc);
4757
4758         intel_crtc->active = true;
4759
4760         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4761
4762         for_each_encoder_on_crtc(dev, crtc, encoder)
4763                 if (encoder->pre_enable)
4764                         encoder->pre_enable(encoder);
4765
4766         if (intel_crtc->config->has_pch_encoder) {
4767                 /* Note: FDI PLL enabling _must_ be done before we enable the
4768                  * cpu pipes, hence this is separate from all the other fdi/pch
4769                  * enabling. */
4770                 ironlake_fdi_pll_enable(intel_crtc);
4771         } else {
4772                 assert_fdi_tx_disabled(dev_priv, pipe);
4773                 assert_fdi_rx_disabled(dev_priv, pipe);
4774         }
4775
4776         ironlake_pfit_enable(intel_crtc);
4777
4778         /*
4779          * On ILK+ LUT must be loaded before the pipe is running but with
4780          * clocks enabled
4781          */
4782         intel_color_load_luts(&pipe_config->base);
4783
4784         if (dev_priv->display.initial_watermarks != NULL)
4785                 dev_priv->display.initial_watermarks(intel_crtc->config);
4786         intel_enable_pipe(intel_crtc);
4787
4788         if (intel_crtc->config->has_pch_encoder)
4789                 ironlake_pch_enable(crtc);
4790
4791         assert_vblank_disabled(crtc);
4792         drm_crtc_vblank_on(crtc);
4793
4794         for_each_encoder_on_crtc(dev, crtc, encoder)
4795                 encoder->enable(encoder);
4796
4797         if (HAS_PCH_CPT(dev))
4798                 cpt_verify_modeset(dev, intel_crtc->pipe);
4799
4800         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
4801         if (intel_crtc->config->has_pch_encoder)
4802                 intel_wait_for_vblank(dev, pipe);
4803         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4804 }
4805
4806 /* IPS only exists on ULT machines and is tied to pipe A. */
4807 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4808 {
4809         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4810 }
4811
4812 static void haswell_crtc_enable(struct drm_crtc *crtc)
4813 {
4814         struct drm_device *dev = crtc->dev;
4815         struct drm_i915_private *dev_priv = dev->dev_private;
4816         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4817         struct intel_encoder *encoder;
4818         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4819         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4820         struct intel_crtc_state *pipe_config =
4821                 to_intel_crtc_state(crtc->state);
4822
4823         if (WARN_ON(intel_crtc->active))
4824                 return;
4825
4826         if (intel_crtc->config->has_pch_encoder)
4827                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4828                                                       false);
4829
4830         if (intel_crtc->config->shared_dpll)
4831                 intel_enable_shared_dpll(intel_crtc);
4832
4833         if (intel_crtc->config->has_dp_encoder)
4834                 intel_dp_set_m_n(intel_crtc, M1_N1);
4835
4836         if (!intel_crtc->config->has_dsi_encoder)
4837                 intel_set_pipe_timings(intel_crtc);
4838
4839         intel_set_pipe_src_size(intel_crtc);
4840
4841         if (cpu_transcoder != TRANSCODER_EDP &&
4842             !transcoder_is_dsi(cpu_transcoder)) {
4843                 I915_WRITE(PIPE_MULT(cpu_transcoder),
4844                            intel_crtc->config->pixel_multiplier - 1);
4845         }
4846
4847         if (intel_crtc->config->has_pch_encoder) {
4848                 intel_cpu_transcoder_set_m_n(intel_crtc,
4849                                      &intel_crtc->config->fdi_m_n, NULL);
4850         }
4851
4852         if (!intel_crtc->config->has_dsi_encoder)
4853                 haswell_set_pipeconf(crtc);
4854
4855         haswell_set_pipemisc(crtc);
4856
4857         intel_color_set_csc(&pipe_config->base);
4858
4859         intel_crtc->active = true;
4860
4861         if (intel_crtc->config->has_pch_encoder)
4862                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4863         else
4864                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4865
4866         for_each_encoder_on_crtc(dev, crtc, encoder) {
4867                 if (encoder->pre_enable)
4868                         encoder->pre_enable(encoder);
4869         }
4870
4871         if (intel_crtc->config->has_pch_encoder)
4872                 dev_priv->display.fdi_link_train(crtc);
4873
4874         if (!intel_crtc->config->has_dsi_encoder)
4875                 intel_ddi_enable_pipe_clock(intel_crtc);
4876
4877         if (INTEL_INFO(dev)->gen >= 9)
4878                 skylake_pfit_enable(intel_crtc);
4879         else
4880                 ironlake_pfit_enable(intel_crtc);
4881
4882         /*
4883          * On ILK+ LUT must be loaded before the pipe is running but with
4884          * clocks enabled
4885          */
4886         intel_color_load_luts(&pipe_config->base);
4887
4888         intel_ddi_set_pipe_settings(crtc);
4889         if (!intel_crtc->config->has_dsi_encoder)
4890                 intel_ddi_enable_transcoder_func(crtc);
4891
4892         if (dev_priv->display.initial_watermarks != NULL)
4893                 dev_priv->display.initial_watermarks(pipe_config);
4894         else
4895                 intel_update_watermarks(crtc);
4896
4897         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
4898         if (!intel_crtc->config->has_dsi_encoder)
4899                 intel_enable_pipe(intel_crtc);
4900
4901         if (intel_crtc->config->has_pch_encoder)
4902                 lpt_pch_enable(crtc);
4903
4904         if (intel_crtc->config->dp_encoder_is_mst)
4905                 intel_ddi_set_vc_payload_alloc(crtc, true);
4906
4907         assert_vblank_disabled(crtc);
4908         drm_crtc_vblank_on(crtc);
4909
4910         for_each_encoder_on_crtc(dev, crtc, encoder) {
4911                 encoder->enable(encoder);
4912                 intel_opregion_notify_encoder(encoder, true);
4913         }
4914
4915         if (intel_crtc->config->has_pch_encoder) {
4916                 intel_wait_for_vblank(dev, pipe);
4917                 intel_wait_for_vblank(dev, pipe);
4918                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4919                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4920                                                       true);
4921         }
4922
4923         /* If we change the relative order between pipe/planes enabling, we need
4924          * to change the workaround. */
4925         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4926         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4927                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4928                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4929         }
4930 }
4931
4932 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
4933 {
4934         struct drm_device *dev = crtc->base.dev;
4935         struct drm_i915_private *dev_priv = dev->dev_private;
4936         int pipe = crtc->pipe;
4937
4938         /* To avoid upsetting the power well on haswell only disable the pfit if
4939          * it's in use. The hw state code will make sure we get this right. */
4940         if (force || crtc->config->pch_pfit.enabled) {
4941                 I915_WRITE(PF_CTL(pipe), 0);
4942                 I915_WRITE(PF_WIN_POS(pipe), 0);
4943                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4944         }
4945 }
4946
4947 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4948 {
4949         struct drm_device *dev = crtc->dev;
4950         struct drm_i915_private *dev_priv = dev->dev_private;
4951         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4952         struct intel_encoder *encoder;
4953         int pipe = intel_crtc->pipe;
4954
4955         if (intel_crtc->config->has_pch_encoder)
4956                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4957
4958         for_each_encoder_on_crtc(dev, crtc, encoder)
4959                 encoder->disable(encoder);
4960
4961         drm_crtc_vblank_off(crtc);
4962         assert_vblank_disabled(crtc);
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
4972         intel_disable_pipe(intel_crtc);
4973
4974         ironlake_pfit_disable(intel_crtc, false);
4975
4976         if (intel_crtc->config->has_pch_encoder) {
4977                 ironlake_fdi_disable(crtc);
4978                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4979         }
4980
4981         for_each_encoder_on_crtc(dev, crtc, encoder)
4982                 if (encoder->post_disable)
4983                         encoder->post_disable(encoder);
4984
4985         if (intel_crtc->config->has_pch_encoder) {
4986                 ironlake_disable_pch_transcoder(dev_priv, pipe);
4987
4988                 if (HAS_PCH_CPT(dev)) {
4989                         i915_reg_t reg;
4990                         u32 temp;
4991
4992                         /* disable TRANS_DP_CTL */
4993                         reg = TRANS_DP_CTL(pipe);
4994                         temp = I915_READ(reg);
4995                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
4996                                   TRANS_DP_PORT_SEL_MASK);
4997                         temp |= TRANS_DP_PORT_SEL_NONE;
4998                         I915_WRITE(reg, temp);
4999
5000                         /* disable DPLL_SEL */
5001                         temp = I915_READ(PCH_DPLL_SEL);
5002                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5003                         I915_WRITE(PCH_DPLL_SEL, temp);
5004                 }
5005
5006                 ironlake_fdi_pll_disable(intel_crtc);
5007         }
5008
5009         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5010 }
5011
5012 static void haswell_crtc_disable(struct drm_crtc *crtc)
5013 {
5014         struct drm_device *dev = crtc->dev;
5015         struct drm_i915_private *dev_priv = dev->dev_private;
5016         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5017         struct intel_encoder *encoder;
5018         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5019
5020         if (intel_crtc->config->has_pch_encoder)
5021                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5022                                                       false);
5023
5024         for_each_encoder_on_crtc(dev, crtc, encoder) {
5025                 intel_opregion_notify_encoder(encoder, false);
5026                 encoder->disable(encoder);
5027         }
5028
5029         drm_crtc_vblank_off(crtc);
5030         assert_vblank_disabled(crtc);
5031
5032         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5033         if (!intel_crtc->config->has_dsi_encoder)
5034                 intel_disable_pipe(intel_crtc);
5035
5036         if (intel_crtc->config->dp_encoder_is_mst)
5037                 intel_ddi_set_vc_payload_alloc(crtc, false);
5038
5039         if (!intel_crtc->config->has_dsi_encoder)
5040                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5041
5042         if (INTEL_INFO(dev)->gen >= 9)
5043                 skylake_scaler_disable(intel_crtc);
5044         else
5045                 ironlake_pfit_disable(intel_crtc, false);
5046
5047         if (!intel_crtc->config->has_dsi_encoder)
5048                 intel_ddi_disable_pipe_clock(intel_crtc);
5049
5050         for_each_encoder_on_crtc(dev, crtc, encoder)
5051                 if (encoder->post_disable)
5052                         encoder->post_disable(encoder);
5053
5054         if (intel_crtc->config->has_pch_encoder) {
5055                 lpt_disable_pch_transcoder(dev_priv);
5056                 lpt_disable_iclkip(dev_priv);
5057                 intel_ddi_fdi_disable(crtc);
5058
5059                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5060                                                       true);
5061         }
5062 }
5063
5064 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5065 {
5066         struct drm_device *dev = crtc->base.dev;
5067         struct drm_i915_private *dev_priv = dev->dev_private;
5068         struct intel_crtc_state *pipe_config = crtc->config;
5069
5070         if (!pipe_config->gmch_pfit.control)
5071                 return;
5072
5073         /*
5074          * The panel fitter should only be adjusted whilst the pipe is disabled,
5075          * according to register description and PRM.
5076          */
5077         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5078         assert_pipe_disabled(dev_priv, crtc->pipe);
5079
5080         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5081         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5082
5083         /* Border color in case we don't scale up to the full screen. Black by
5084          * default, change to something else for debugging. */
5085         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5086 }
5087
5088 static enum intel_display_power_domain port_to_power_domain(enum port port)
5089 {
5090         switch (port) {
5091         case PORT_A:
5092                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5093         case PORT_B:
5094                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5095         case PORT_C:
5096                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5097         case PORT_D:
5098                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5099         case PORT_E:
5100                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5101         default:
5102                 MISSING_CASE(port);
5103                 return POWER_DOMAIN_PORT_OTHER;
5104         }
5105 }
5106
5107 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5108 {
5109         switch (port) {
5110         case PORT_A:
5111                 return POWER_DOMAIN_AUX_A;
5112         case PORT_B:
5113                 return POWER_DOMAIN_AUX_B;
5114         case PORT_C:
5115                 return POWER_DOMAIN_AUX_C;
5116         case PORT_D:
5117                 return POWER_DOMAIN_AUX_D;
5118         case PORT_E:
5119                 /* FIXME: Check VBT for actual wiring of PORT E */
5120                 return POWER_DOMAIN_AUX_D;
5121         default:
5122                 MISSING_CASE(port);
5123                 return POWER_DOMAIN_AUX_A;
5124         }
5125 }
5126
5127 enum intel_display_power_domain
5128 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5129 {
5130         struct drm_device *dev = intel_encoder->base.dev;
5131         struct intel_digital_port *intel_dig_port;
5132
5133         switch (intel_encoder->type) {
5134         case INTEL_OUTPUT_UNKNOWN:
5135                 /* Only DDI platforms should ever use this output type */
5136                 WARN_ON_ONCE(!HAS_DDI(dev));
5137         case INTEL_OUTPUT_DISPLAYPORT:
5138         case INTEL_OUTPUT_HDMI:
5139         case INTEL_OUTPUT_EDP:
5140                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5141                 return port_to_power_domain(intel_dig_port->port);
5142         case INTEL_OUTPUT_DP_MST:
5143                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5144                 return port_to_power_domain(intel_dig_port->port);
5145         case INTEL_OUTPUT_ANALOG:
5146                 return POWER_DOMAIN_PORT_CRT;
5147         case INTEL_OUTPUT_DSI:
5148                 return POWER_DOMAIN_PORT_DSI;
5149         default:
5150                 return POWER_DOMAIN_PORT_OTHER;
5151         }
5152 }
5153
5154 enum intel_display_power_domain
5155 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5156 {
5157         struct drm_device *dev = intel_encoder->base.dev;
5158         struct intel_digital_port *intel_dig_port;
5159
5160         switch (intel_encoder->type) {
5161         case INTEL_OUTPUT_UNKNOWN:
5162         case INTEL_OUTPUT_HDMI:
5163                 /*
5164                  * Only DDI platforms should ever use these output types.
5165                  * We can get here after the HDMI detect code has already set
5166                  * the type of the shared encoder. Since we can't be sure
5167                  * what's the status of the given connectors, play safe and
5168                  * run the DP detection too.
5169                  */
5170                 WARN_ON_ONCE(!HAS_DDI(dev));
5171         case INTEL_OUTPUT_DISPLAYPORT:
5172         case INTEL_OUTPUT_EDP:
5173                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5174                 return port_to_aux_power_domain(intel_dig_port->port);
5175         case INTEL_OUTPUT_DP_MST:
5176                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5177                 return port_to_aux_power_domain(intel_dig_port->port);
5178         default:
5179                 MISSING_CASE(intel_encoder->type);
5180                 return POWER_DOMAIN_AUX_A;
5181         }
5182 }
5183
5184 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5185                                             struct intel_crtc_state *crtc_state)
5186 {
5187         struct drm_device *dev = crtc->dev;
5188         struct drm_encoder *encoder;
5189         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5190         enum pipe pipe = intel_crtc->pipe;
5191         unsigned long mask;
5192         enum transcoder transcoder = crtc_state->cpu_transcoder;
5193
5194         if (!crtc_state->base.active)
5195                 return 0;
5196
5197         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5198         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5199         if (crtc_state->pch_pfit.enabled ||
5200             crtc_state->pch_pfit.force_thru)
5201                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5202
5203         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5204                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5205
5206                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5207         }
5208
5209         if (crtc_state->shared_dpll)
5210                 mask |= BIT(POWER_DOMAIN_PLLS);
5211
5212         return mask;
5213 }
5214
5215 static unsigned long
5216 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5217                                struct intel_crtc_state *crtc_state)
5218 {
5219         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5220         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5221         enum intel_display_power_domain domain;
5222         unsigned long domains, new_domains, old_domains;
5223
5224         old_domains = intel_crtc->enabled_power_domains;
5225         intel_crtc->enabled_power_domains = new_domains =
5226                 get_crtc_power_domains(crtc, crtc_state);
5227
5228         domains = new_domains & ~old_domains;
5229
5230         for_each_power_domain(domain, domains)
5231                 intel_display_power_get(dev_priv, domain);
5232
5233         return old_domains & ~new_domains;
5234 }
5235
5236 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5237                                       unsigned long domains)
5238 {
5239         enum intel_display_power_domain domain;
5240
5241         for_each_power_domain(domain, domains)
5242                 intel_display_power_put(dev_priv, domain);
5243 }
5244
5245 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5246 {
5247         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5248
5249         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5250             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5251                 return max_cdclk_freq;
5252         else if (IS_CHERRYVIEW(dev_priv))
5253                 return max_cdclk_freq*95/100;
5254         else if (INTEL_INFO(dev_priv)->gen < 4)
5255                 return 2*max_cdclk_freq*90/100;
5256         else
5257                 return max_cdclk_freq*90/100;
5258 }
5259
5260 static void intel_update_max_cdclk(struct drm_device *dev)
5261 {
5262         struct drm_i915_private *dev_priv = dev->dev_private;
5263
5264         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5265                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5266
5267                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5268                         dev_priv->max_cdclk_freq = 675000;
5269                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5270                         dev_priv->max_cdclk_freq = 540000;
5271                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5272                         dev_priv->max_cdclk_freq = 450000;
5273                 else
5274                         dev_priv->max_cdclk_freq = 337500;
5275         } else if (IS_BROADWELL(dev))  {
5276                 /*
5277                  * FIXME with extra cooling we can allow
5278                  * 540 MHz for ULX and 675 Mhz for ULT.
5279                  * How can we know if extra cooling is
5280                  * available? PCI ID, VTB, something else?
5281                  */
5282                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5283                         dev_priv->max_cdclk_freq = 450000;
5284                 else if (IS_BDW_ULX(dev))
5285                         dev_priv->max_cdclk_freq = 450000;
5286                 else if (IS_BDW_ULT(dev))
5287                         dev_priv->max_cdclk_freq = 540000;
5288                 else
5289                         dev_priv->max_cdclk_freq = 675000;
5290         } else if (IS_CHERRYVIEW(dev)) {
5291                 dev_priv->max_cdclk_freq = 320000;
5292         } else if (IS_VALLEYVIEW(dev)) {
5293                 dev_priv->max_cdclk_freq = 400000;
5294         } else {
5295                 /* otherwise assume cdclk is fixed */
5296                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5297         }
5298
5299         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5300
5301         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5302                          dev_priv->max_cdclk_freq);
5303
5304         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5305                          dev_priv->max_dotclk_freq);
5306 }
5307
5308 static void intel_update_cdclk(struct drm_device *dev)
5309 {
5310         struct drm_i915_private *dev_priv = dev->dev_private;
5311
5312         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5313         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5314                          dev_priv->cdclk_freq);
5315
5316         /*
5317          * Program the gmbus_freq based on the cdclk frequency.
5318          * BSpec erroneously claims we should aim for 4MHz, but
5319          * in fact 1MHz is the correct frequency.
5320          */
5321         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
5322                 /*
5323                  * Program the gmbus_freq based on the cdclk frequency.
5324                  * BSpec erroneously claims we should aim for 4MHz, but
5325                  * in fact 1MHz is the correct frequency.
5326                  */
5327                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5328         }
5329
5330         if (dev_priv->max_cdclk_freq == 0)
5331                 intel_update_max_cdclk(dev);
5332 }
5333
5334 static void broxton_set_cdclk(struct drm_device *dev, int frequency)
5335 {
5336         struct drm_i915_private *dev_priv = dev->dev_private;
5337         uint32_t divider;
5338         uint32_t ratio;
5339         uint32_t current_freq;
5340         int ret;
5341
5342         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5343         switch (frequency) {
5344         case 144000:
5345                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5346                 ratio = BXT_DE_PLL_RATIO(60);
5347                 break;
5348         case 288000:
5349                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5350                 ratio = BXT_DE_PLL_RATIO(60);
5351                 break;
5352         case 384000:
5353                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5354                 ratio = BXT_DE_PLL_RATIO(60);
5355                 break;
5356         case 576000:
5357                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5358                 ratio = BXT_DE_PLL_RATIO(60);
5359                 break;
5360         case 624000:
5361                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5362                 ratio = BXT_DE_PLL_RATIO(65);
5363                 break;
5364         case 19200:
5365                 /*
5366                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5367                  * to suppress GCC warning.
5368                  */
5369                 ratio = 0;
5370                 divider = 0;
5371                 break;
5372         default:
5373                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5374
5375                 return;
5376         }
5377
5378         mutex_lock(&dev_priv->rps.hw_lock);
5379         /* Inform power controller of upcoming frequency change */
5380         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5381                                       0x80000000);
5382         mutex_unlock(&dev_priv->rps.hw_lock);
5383
5384         if (ret) {
5385                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5386                           ret, frequency);
5387                 return;
5388         }
5389
5390         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5391         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5392         current_freq = current_freq * 500 + 1000;
5393
5394         /*
5395          * DE PLL has to be disabled when
5396          * - setting to 19.2MHz (bypass, PLL isn't used)
5397          * - before setting to 624MHz (PLL needs toggling)
5398          * - before setting to any frequency from 624MHz (PLL needs toggling)
5399          */
5400         if (frequency == 19200 || frequency == 624000 ||
5401             current_freq == 624000) {
5402                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5403                 /* Timeout 200us */
5404                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5405                              1))
5406                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5407         }
5408
5409         if (frequency != 19200) {
5410                 uint32_t val;
5411
5412                 val = I915_READ(BXT_DE_PLL_CTL);
5413                 val &= ~BXT_DE_PLL_RATIO_MASK;
5414                 val |= ratio;
5415                 I915_WRITE(BXT_DE_PLL_CTL, val);
5416
5417                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5418                 /* Timeout 200us */
5419                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5420                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5421
5422                 val = I915_READ(CDCLK_CTL);
5423                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5424                 val |= divider;
5425                 /*
5426                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5427                  * enable otherwise.
5428                  */
5429                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5430                 if (frequency >= 500000)
5431                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5432
5433                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5434                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5435                 val |= (frequency - 1000) / 500;
5436                 I915_WRITE(CDCLK_CTL, val);
5437         }
5438
5439         mutex_lock(&dev_priv->rps.hw_lock);
5440         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5441                                       DIV_ROUND_UP(frequency, 25000));
5442         mutex_unlock(&dev_priv->rps.hw_lock);
5443
5444         if (ret) {
5445                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5446                           ret, frequency);
5447                 return;
5448         }
5449
5450         intel_update_cdclk(dev);
5451 }
5452
5453 void broxton_init_cdclk(struct drm_device *dev)
5454 {
5455         struct drm_i915_private *dev_priv = dev->dev_private;
5456         uint32_t val;
5457
5458         /*
5459          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5460          * or else the reset will hang because there is no PCH to respond.
5461          * Move the handshake programming to initialization sequence.
5462          * Previously was left up to BIOS.
5463          */
5464         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5465         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5466         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5467
5468         /* Enable PG1 for cdclk */
5469         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5470
5471         /* check if cd clock is enabled */
5472         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5473                 DRM_DEBUG_KMS("Display already initialized\n");
5474                 return;
5475         }
5476
5477         /*
5478          * FIXME:
5479          * - The initial CDCLK needs to be read from VBT.
5480          *   Need to make this change after VBT has changes for BXT.
5481          * - check if setting the max (or any) cdclk freq is really necessary
5482          *   here, it belongs to modeset time
5483          */
5484         broxton_set_cdclk(dev, 624000);
5485
5486         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5487         POSTING_READ(DBUF_CTL);
5488
5489         udelay(10);
5490
5491         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5492                 DRM_ERROR("DBuf power enable timeout!\n");
5493 }
5494
5495 void broxton_uninit_cdclk(struct drm_device *dev)
5496 {
5497         struct drm_i915_private *dev_priv = dev->dev_private;
5498
5499         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5500         POSTING_READ(DBUF_CTL);
5501
5502         udelay(10);
5503
5504         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5505                 DRM_ERROR("DBuf power disable timeout!\n");
5506
5507         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5508         broxton_set_cdclk(dev, 19200);
5509
5510         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5511 }
5512
5513 static const struct skl_cdclk_entry {
5514         unsigned int freq;
5515         unsigned int vco;
5516 } skl_cdclk_frequencies[] = {
5517         { .freq = 308570, .vco = 8640 },
5518         { .freq = 337500, .vco = 8100 },
5519         { .freq = 432000, .vco = 8640 },
5520         { .freq = 450000, .vco = 8100 },
5521         { .freq = 540000, .vco = 8100 },
5522         { .freq = 617140, .vco = 8640 },
5523         { .freq = 675000, .vco = 8100 },
5524 };
5525
5526 static unsigned int skl_cdclk_decimal(unsigned int freq)
5527 {
5528         return (freq - 1000) / 500;
5529 }
5530
5531 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5532 {
5533         unsigned int i;
5534
5535         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5536                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5537
5538                 if (e->freq == freq)
5539                         return e->vco;
5540         }
5541
5542         return 8100;
5543 }
5544
5545 static void
5546 skl_dpll0_enable(struct drm_i915_private *dev_priv, unsigned int required_vco)
5547 {
5548         unsigned int min_freq;
5549         u32 val;
5550
5551         /* select the minimum CDCLK before enabling DPLL 0 */
5552         val = I915_READ(CDCLK_CTL);
5553         val &= ~CDCLK_FREQ_SEL_MASK | ~CDCLK_FREQ_DECIMAL_MASK;
5554         val |= CDCLK_FREQ_337_308;
5555
5556         if (required_vco == 8640)
5557                 min_freq = 308570;
5558         else
5559                 min_freq = 337500;
5560
5561         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_freq);
5562
5563         I915_WRITE(CDCLK_CTL, val);
5564         POSTING_READ(CDCLK_CTL);
5565
5566         /*
5567          * We always enable DPLL0 with the lowest link rate possible, but still
5568          * taking into account the VCO required to operate the eDP panel at the
5569          * desired frequency. The usual DP link rates operate with a VCO of
5570          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5571          * The modeset code is responsible for the selection of the exact link
5572          * rate later on, with the constraint of choosing a frequency that
5573          * works with required_vco.
5574          */
5575         val = I915_READ(DPLL_CTRL1);
5576
5577         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5578                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5579         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5580         if (required_vco == 8640)
5581                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5582                                             SKL_DPLL0);
5583         else
5584                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5585                                             SKL_DPLL0);
5586
5587         I915_WRITE(DPLL_CTRL1, val);
5588         POSTING_READ(DPLL_CTRL1);
5589
5590         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5591
5592         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5593                 DRM_ERROR("DPLL0 not locked\n");
5594 }
5595
5596 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5597 {
5598         int ret;
5599         u32 val;
5600
5601         /* inform PCU we want to change CDCLK */
5602         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5603         mutex_lock(&dev_priv->rps.hw_lock);
5604         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5605         mutex_unlock(&dev_priv->rps.hw_lock);
5606
5607         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5608 }
5609
5610 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5611 {
5612         unsigned int i;
5613
5614         for (i = 0; i < 15; i++) {
5615                 if (skl_cdclk_pcu_ready(dev_priv))
5616                         return true;
5617                 udelay(10);
5618         }
5619
5620         return false;
5621 }
5622
5623 static void skl_set_cdclk(struct drm_i915_private *dev_priv, unsigned int freq)
5624 {
5625         struct drm_device *dev = dev_priv->dev;
5626         u32 freq_select, pcu_ack;
5627
5628         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", freq);
5629
5630         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5631                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5632                 return;
5633         }
5634
5635         /* set CDCLK_CTL */
5636         switch(freq) {
5637         case 450000:
5638         case 432000:
5639                 freq_select = CDCLK_FREQ_450_432;
5640                 pcu_ack = 1;
5641                 break;
5642         case 540000:
5643                 freq_select = CDCLK_FREQ_540;
5644                 pcu_ack = 2;
5645                 break;
5646         case 308570:
5647         case 337500:
5648         default:
5649                 freq_select = CDCLK_FREQ_337_308;
5650                 pcu_ack = 0;
5651                 break;
5652         case 617140:
5653         case 675000:
5654                 freq_select = CDCLK_FREQ_675_617;
5655                 pcu_ack = 3;
5656                 break;
5657         }
5658
5659         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(freq));
5660         POSTING_READ(CDCLK_CTL);
5661
5662         /* inform PCU of the change */
5663         mutex_lock(&dev_priv->rps.hw_lock);
5664         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5665         mutex_unlock(&dev_priv->rps.hw_lock);
5666
5667         intel_update_cdclk(dev);
5668 }
5669
5670 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5671 {
5672         /* disable DBUF power */
5673         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5674         POSTING_READ(DBUF_CTL);
5675
5676         udelay(10);
5677
5678         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5679                 DRM_ERROR("DBuf power disable timeout\n");
5680
5681         /* disable DPLL0 */
5682         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5683         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5684                 DRM_ERROR("Couldn't disable DPLL0\n");
5685 }
5686
5687 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5688 {
5689         unsigned int required_vco;
5690
5691         /* DPLL0 not enabled (happens on early BIOS versions) */
5692         if (!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE)) {
5693                 /* enable DPLL0 */
5694                 required_vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5695                 skl_dpll0_enable(dev_priv, required_vco);
5696         }
5697
5698         /* set CDCLK to the frequency the BIOS chose */
5699         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5700
5701         /* enable DBUF power */
5702         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5703         POSTING_READ(DBUF_CTL);
5704
5705         udelay(10);
5706
5707         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5708                 DRM_ERROR("DBuf power enable timeout\n");
5709 }
5710
5711 int skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5712 {
5713         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
5714         uint32_t cdctl = I915_READ(CDCLK_CTL);
5715         int freq = dev_priv->skl_boot_cdclk;
5716
5717         /*
5718          * check if the pre-os intialized the display
5719          * There is SWF18 scratchpad register defined which is set by the
5720          * pre-os which can be used by the OS drivers to check the status
5721          */
5722         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5723                 goto sanitize;
5724
5725         /* Is PLL enabled and locked ? */
5726         if (!((lcpll1 & LCPLL_PLL_ENABLE) && (lcpll1 & LCPLL_PLL_LOCK)))
5727                 goto sanitize;
5728
5729         /* DPLL okay; verify the cdclock
5730          *
5731          * Noticed in some instances that the freq selection is correct but
5732          * decimal part is programmed wrong from BIOS where pre-os does not
5733          * enable display. Verify the same as well.
5734          */
5735         if (cdctl == ((cdctl & CDCLK_FREQ_SEL_MASK) | skl_cdclk_decimal(freq)))
5736                 /* All well; nothing to sanitize */
5737                 return false;
5738 sanitize:
5739         /*
5740          * As of now initialize with max cdclk till
5741          * we get dynamic cdclk support
5742          * */
5743         dev_priv->skl_boot_cdclk = dev_priv->max_cdclk_freq;
5744         skl_init_cdclk(dev_priv);
5745
5746         /* we did have to sanitize */
5747         return true;
5748 }
5749
5750 /* Adjust CDclk dividers to allow high res or save power if possible */
5751 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5752 {
5753         struct drm_i915_private *dev_priv = dev->dev_private;
5754         u32 val, cmd;
5755
5756         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5757                                         != dev_priv->cdclk_freq);
5758
5759         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5760                 cmd = 2;
5761         else if (cdclk == 266667)
5762                 cmd = 1;
5763         else
5764                 cmd = 0;
5765
5766         mutex_lock(&dev_priv->rps.hw_lock);
5767         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5768         val &= ~DSPFREQGUAR_MASK;
5769         val |= (cmd << DSPFREQGUAR_SHIFT);
5770         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5771         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5772                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5773                      50)) {
5774                 DRM_ERROR("timed out waiting for CDclk change\n");
5775         }
5776         mutex_unlock(&dev_priv->rps.hw_lock);
5777
5778         mutex_lock(&dev_priv->sb_lock);
5779
5780         if (cdclk == 400000) {
5781                 u32 divider;
5782
5783                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5784
5785                 /* adjust cdclk divider */
5786                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5787                 val &= ~CCK_FREQUENCY_VALUES;
5788                 val |= divider;
5789                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5790
5791                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5792                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
5793                              50))
5794                         DRM_ERROR("timed out waiting for CDclk change\n");
5795         }
5796
5797         /* adjust self-refresh exit latency value */
5798         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5799         val &= ~0x7f;
5800
5801         /*
5802          * For high bandwidth configs, we set a higher latency in the bunit
5803          * so that the core display fetch happens in time to avoid underruns.
5804          */
5805         if (cdclk == 400000)
5806                 val |= 4500 / 250; /* 4.5 usec */
5807         else
5808                 val |= 3000 / 250; /* 3.0 usec */
5809         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5810
5811         mutex_unlock(&dev_priv->sb_lock);
5812
5813         intel_update_cdclk(dev);
5814 }
5815
5816 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5817 {
5818         struct drm_i915_private *dev_priv = dev->dev_private;
5819         u32 val, cmd;
5820
5821         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5822                                                 != dev_priv->cdclk_freq);
5823
5824         switch (cdclk) {
5825         case 333333:
5826         case 320000:
5827         case 266667:
5828         case 200000:
5829                 break;
5830         default:
5831                 MISSING_CASE(cdclk);
5832                 return;
5833         }
5834
5835         /*
5836          * Specs are full of misinformation, but testing on actual
5837          * hardware has shown that we just need to write the desired
5838          * CCK divider into the Punit register.
5839          */
5840         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5841
5842         mutex_lock(&dev_priv->rps.hw_lock);
5843         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5844         val &= ~DSPFREQGUAR_MASK_CHV;
5845         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5846         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5847         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5848                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5849                      50)) {
5850                 DRM_ERROR("timed out waiting for CDclk change\n");
5851         }
5852         mutex_unlock(&dev_priv->rps.hw_lock);
5853
5854         intel_update_cdclk(dev);
5855 }
5856
5857 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5858                                  int max_pixclk)
5859 {
5860         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5861         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5862
5863         /*
5864          * Really only a few cases to deal with, as only 4 CDclks are supported:
5865          *   200MHz
5866          *   267MHz
5867          *   320/333MHz (depends on HPLL freq)
5868          *   400MHz (VLV only)
5869          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5870          * of the lower bin and adjust if needed.
5871          *
5872          * We seem to get an unstable or solid color picture at 200MHz.
5873          * Not sure what's wrong. For now use 200MHz only when all pipes
5874          * are off.
5875          */
5876         if (!IS_CHERRYVIEW(dev_priv) &&
5877             max_pixclk > freq_320*limit/100)
5878                 return 400000;
5879         else if (max_pixclk > 266667*limit/100)
5880                 return freq_320;
5881         else if (max_pixclk > 0)
5882                 return 266667;
5883         else
5884                 return 200000;
5885 }
5886
5887 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
5888                               int max_pixclk)
5889 {
5890         /*
5891          * FIXME:
5892          * - remove the guardband, it's not needed on BXT
5893          * - set 19.2MHz bypass frequency if there are no active pipes
5894          */
5895         if (max_pixclk > 576000*9/10)
5896                 return 624000;
5897         else if (max_pixclk > 384000*9/10)
5898                 return 576000;
5899         else if (max_pixclk > 288000*9/10)
5900                 return 384000;
5901         else if (max_pixclk > 144000*9/10)
5902                 return 288000;
5903         else
5904                 return 144000;
5905 }
5906
5907 /* Compute the max pixel clock for new configuration. */
5908 static int intel_mode_max_pixclk(struct drm_device *dev,
5909                                  struct drm_atomic_state *state)
5910 {
5911         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
5912         struct drm_i915_private *dev_priv = dev->dev_private;
5913         struct drm_crtc *crtc;
5914         struct drm_crtc_state *crtc_state;
5915         unsigned max_pixclk = 0, i;
5916         enum pipe pipe;
5917
5918         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
5919                sizeof(intel_state->min_pixclk));
5920
5921         for_each_crtc_in_state(state, crtc, crtc_state, i) {
5922                 int pixclk = 0;
5923
5924                 if (crtc_state->enable)
5925                         pixclk = crtc_state->adjusted_mode.crtc_clock;
5926
5927                 intel_state->min_pixclk[i] = pixclk;
5928         }
5929
5930         for_each_pipe(dev_priv, pipe)
5931                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
5932
5933         return max_pixclk;
5934 }
5935
5936 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
5937 {
5938         struct drm_device *dev = state->dev;
5939         struct drm_i915_private *dev_priv = dev->dev_private;
5940         int max_pixclk = intel_mode_max_pixclk(dev, state);
5941         struct intel_atomic_state *intel_state =
5942                 to_intel_atomic_state(state);
5943
5944         if (max_pixclk < 0)
5945                 return max_pixclk;
5946
5947         intel_state->cdclk = intel_state->dev_cdclk =
5948                 valleyview_calc_cdclk(dev_priv, max_pixclk);
5949
5950         if (!intel_state->active_crtcs)
5951                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
5952
5953         return 0;
5954 }
5955
5956 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
5957 {
5958         struct drm_device *dev = state->dev;
5959         struct drm_i915_private *dev_priv = dev->dev_private;
5960         int max_pixclk = intel_mode_max_pixclk(dev, state);
5961         struct intel_atomic_state *intel_state =
5962                 to_intel_atomic_state(state);
5963
5964         if (max_pixclk < 0)
5965                 return max_pixclk;
5966
5967         intel_state->cdclk = intel_state->dev_cdclk =
5968                 broxton_calc_cdclk(dev_priv, max_pixclk);
5969
5970         if (!intel_state->active_crtcs)
5971                 intel_state->dev_cdclk = broxton_calc_cdclk(dev_priv, 0);
5972
5973         return 0;
5974 }
5975
5976 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5977 {
5978         unsigned int credits, default_credits;
5979
5980         if (IS_CHERRYVIEW(dev_priv))
5981                 default_credits = PFI_CREDIT(12);
5982         else
5983                 default_credits = PFI_CREDIT(8);
5984
5985         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
5986                 /* CHV suggested value is 31 or 63 */
5987                 if (IS_CHERRYVIEW(dev_priv))
5988                         credits = PFI_CREDIT_63;
5989                 else
5990                         credits = PFI_CREDIT(15);
5991         } else {
5992                 credits = default_credits;
5993         }
5994
5995         /*
5996          * WA - write default credits before re-programming
5997          * FIXME: should we also set the resend bit here?
5998          */
5999         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6000                    default_credits);
6001
6002         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
6003                    credits | PFI_CREDIT_RESEND);
6004
6005         /*
6006          * FIXME is this guaranteed to clear
6007          * immediately or should we poll for it?
6008          */
6009         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6010 }
6011
6012 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6013 {
6014         struct drm_device *dev = old_state->dev;
6015         struct drm_i915_private *dev_priv = dev->dev_private;
6016         struct intel_atomic_state *old_intel_state =
6017                 to_intel_atomic_state(old_state);
6018         unsigned req_cdclk = old_intel_state->dev_cdclk;
6019
6020         /*
6021          * FIXME: We can end up here with all power domains off, yet
6022          * with a CDCLK frequency other than the minimum. To account
6023          * for this take the PIPE-A power domain, which covers the HW
6024          * blocks needed for the following programming. This can be
6025          * removed once it's guaranteed that we get here either with
6026          * the minimum CDCLK set, or the required power domains
6027          * enabled.
6028          */
6029         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6030
6031         if (IS_CHERRYVIEW(dev))
6032                 cherryview_set_cdclk(dev, req_cdclk);
6033         else
6034                 valleyview_set_cdclk(dev, req_cdclk);
6035
6036         vlv_program_pfi_credits(dev_priv);
6037
6038         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6039 }
6040
6041 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6042 {
6043         struct drm_device *dev = crtc->dev;
6044         struct drm_i915_private *dev_priv = to_i915(dev);
6045         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6046         struct intel_encoder *encoder;
6047         struct intel_crtc_state *pipe_config =
6048                 to_intel_crtc_state(crtc->state);
6049         int pipe = intel_crtc->pipe;
6050
6051         if (WARN_ON(intel_crtc->active))
6052                 return;
6053
6054         if (intel_crtc->config->has_dp_encoder)
6055                 intel_dp_set_m_n(intel_crtc, M1_N1);
6056
6057         intel_set_pipe_timings(intel_crtc);
6058         intel_set_pipe_src_size(intel_crtc);
6059
6060         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6061                 struct drm_i915_private *dev_priv = dev->dev_private;
6062
6063                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6064                 I915_WRITE(CHV_CANVAS(pipe), 0);
6065         }
6066
6067         i9xx_set_pipeconf(intel_crtc);
6068
6069         intel_crtc->active = true;
6070
6071         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6072
6073         for_each_encoder_on_crtc(dev, crtc, encoder)
6074                 if (encoder->pre_pll_enable)
6075                         encoder->pre_pll_enable(encoder);
6076
6077         if (!intel_crtc->config->has_dsi_encoder) {
6078                 if (IS_CHERRYVIEW(dev)) {
6079                         chv_prepare_pll(intel_crtc, intel_crtc->config);
6080                         chv_enable_pll(intel_crtc, intel_crtc->config);
6081                 } else {
6082                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
6083                         vlv_enable_pll(intel_crtc, intel_crtc->config);
6084                 }
6085         }
6086
6087         for_each_encoder_on_crtc(dev, crtc, encoder)
6088                 if (encoder->pre_enable)
6089                         encoder->pre_enable(encoder);
6090
6091         i9xx_pfit_enable(intel_crtc);
6092
6093         intel_color_load_luts(&pipe_config->base);
6094
6095         intel_update_watermarks(crtc);
6096         intel_enable_pipe(intel_crtc);
6097
6098         assert_vblank_disabled(crtc);
6099         drm_crtc_vblank_on(crtc);
6100
6101         for_each_encoder_on_crtc(dev, crtc, encoder)
6102                 encoder->enable(encoder);
6103 }
6104
6105 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6106 {
6107         struct drm_device *dev = crtc->base.dev;
6108         struct drm_i915_private *dev_priv = dev->dev_private;
6109
6110         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6111         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6112 }
6113
6114 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6115 {
6116         struct drm_device *dev = crtc->dev;
6117         struct drm_i915_private *dev_priv = to_i915(dev);
6118         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6119         struct intel_encoder *encoder;
6120         struct intel_crtc_state *pipe_config =
6121                 to_intel_crtc_state(crtc->state);
6122         int pipe = intel_crtc->pipe;
6123
6124         if (WARN_ON(intel_crtc->active))
6125                 return;
6126
6127         i9xx_set_pll_dividers(intel_crtc);
6128
6129         if (intel_crtc->config->has_dp_encoder)
6130                 intel_dp_set_m_n(intel_crtc, M1_N1);
6131
6132         intel_set_pipe_timings(intel_crtc);
6133         intel_set_pipe_src_size(intel_crtc);
6134
6135         i9xx_set_pipeconf(intel_crtc);
6136
6137         intel_crtc->active = true;
6138
6139         if (!IS_GEN2(dev))
6140                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6141
6142         for_each_encoder_on_crtc(dev, crtc, encoder)
6143                 if (encoder->pre_enable)
6144                         encoder->pre_enable(encoder);
6145
6146         i9xx_enable_pll(intel_crtc);
6147
6148         i9xx_pfit_enable(intel_crtc);
6149
6150         intel_color_load_luts(&pipe_config->base);
6151
6152         intel_update_watermarks(crtc);
6153         intel_enable_pipe(intel_crtc);
6154
6155         assert_vblank_disabled(crtc);
6156         drm_crtc_vblank_on(crtc);
6157
6158         for_each_encoder_on_crtc(dev, crtc, encoder)
6159                 encoder->enable(encoder);
6160 }
6161
6162 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6163 {
6164         struct drm_device *dev = crtc->base.dev;
6165         struct drm_i915_private *dev_priv = dev->dev_private;
6166
6167         if (!crtc->config->gmch_pfit.control)
6168                 return;
6169
6170         assert_pipe_disabled(dev_priv, crtc->pipe);
6171
6172         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6173                          I915_READ(PFIT_CONTROL));
6174         I915_WRITE(PFIT_CONTROL, 0);
6175 }
6176
6177 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6178 {
6179         struct drm_device *dev = crtc->dev;
6180         struct drm_i915_private *dev_priv = dev->dev_private;
6181         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6182         struct intel_encoder *encoder;
6183         int pipe = intel_crtc->pipe;
6184
6185         /*
6186          * On gen2 planes are double buffered but the pipe isn't, so we must
6187          * wait for planes to fully turn off before disabling the pipe.
6188          */
6189         if (IS_GEN2(dev))
6190                 intel_wait_for_vblank(dev, pipe);
6191
6192         for_each_encoder_on_crtc(dev, crtc, encoder)
6193                 encoder->disable(encoder);
6194
6195         drm_crtc_vblank_off(crtc);
6196         assert_vblank_disabled(crtc);
6197
6198         intel_disable_pipe(intel_crtc);
6199
6200         i9xx_pfit_disable(intel_crtc);
6201
6202         for_each_encoder_on_crtc(dev, crtc, encoder)
6203                 if (encoder->post_disable)
6204                         encoder->post_disable(encoder);
6205
6206         if (!intel_crtc->config->has_dsi_encoder) {
6207                 if (IS_CHERRYVIEW(dev))
6208                         chv_disable_pll(dev_priv, pipe);
6209                 else if (IS_VALLEYVIEW(dev))
6210                         vlv_disable_pll(dev_priv, pipe);
6211                 else
6212                         i9xx_disable_pll(intel_crtc);
6213         }
6214
6215         for_each_encoder_on_crtc(dev, crtc, encoder)
6216                 if (encoder->post_pll_disable)
6217                         encoder->post_pll_disable(encoder);
6218
6219         if (!IS_GEN2(dev))
6220                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6221 }
6222
6223 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6224 {
6225         struct intel_encoder *encoder;
6226         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6227         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6228         enum intel_display_power_domain domain;
6229         unsigned long domains;
6230
6231         if (!intel_crtc->active)
6232                 return;
6233
6234         if (to_intel_plane_state(crtc->primary->state)->visible) {
6235                 WARN_ON(intel_crtc->unpin_work);
6236
6237                 intel_pre_disable_primary_noatomic(crtc);
6238
6239                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6240                 to_intel_plane_state(crtc->primary->state)->visible = false;
6241         }
6242
6243         dev_priv->display.crtc_disable(crtc);
6244
6245         DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was enabled, now disabled\n",
6246                       crtc->base.id);
6247
6248         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6249         crtc->state->active = false;
6250         intel_crtc->active = false;
6251         crtc->enabled = false;
6252         crtc->state->connector_mask = 0;
6253         crtc->state->encoder_mask = 0;
6254
6255         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6256                 encoder->base.crtc = NULL;
6257
6258         intel_fbc_disable(intel_crtc);
6259         intel_update_watermarks(crtc);
6260         intel_disable_shared_dpll(intel_crtc);
6261
6262         domains = intel_crtc->enabled_power_domains;
6263         for_each_power_domain(domain, domains)
6264                 intel_display_power_put(dev_priv, domain);
6265         intel_crtc->enabled_power_domains = 0;
6266
6267         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6268         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6269 }
6270
6271 /*
6272  * turn all crtc's off, but do not adjust state
6273  * This has to be paired with a call to intel_modeset_setup_hw_state.
6274  */
6275 int intel_display_suspend(struct drm_device *dev)
6276 {
6277         struct drm_i915_private *dev_priv = to_i915(dev);
6278         struct drm_atomic_state *state;
6279         int ret;
6280
6281         state = drm_atomic_helper_suspend(dev);
6282         ret = PTR_ERR_OR_ZERO(state);
6283         if (ret)
6284                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6285         else
6286                 dev_priv->modeset_restore_state = state;
6287         return ret;
6288 }
6289
6290 void intel_encoder_destroy(struct drm_encoder *encoder)
6291 {
6292         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6293
6294         drm_encoder_cleanup(encoder);
6295         kfree(intel_encoder);
6296 }
6297
6298 /* Cross check the actual hw state with our own modeset state tracking (and it's
6299  * internal consistency). */
6300 static void intel_connector_check_state(struct intel_connector *connector)
6301 {
6302         struct drm_crtc *crtc = connector->base.state->crtc;
6303
6304         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6305                       connector->base.base.id,
6306                       connector->base.name);
6307
6308         if (connector->get_hw_state(connector)) {
6309                 struct intel_encoder *encoder = connector->encoder;
6310                 struct drm_connector_state *conn_state = connector->base.state;
6311
6312                 I915_STATE_WARN(!crtc,
6313                          "connector enabled without attached crtc\n");
6314
6315                 if (!crtc)
6316                         return;
6317
6318                 I915_STATE_WARN(!crtc->state->active,
6319                       "connector is active, but attached crtc isn't\n");
6320
6321                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6322                         return;
6323
6324                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6325                         "atomic encoder doesn't match attached encoder\n");
6326
6327                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6328                         "attached encoder crtc differs from connector crtc\n");
6329         } else {
6330                 I915_STATE_WARN(crtc && crtc->state->active,
6331                         "attached crtc is active, but connector isn't\n");
6332                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6333                         "best encoder set without crtc!\n");
6334         }
6335 }
6336
6337 int intel_connector_init(struct intel_connector *connector)
6338 {
6339         drm_atomic_helper_connector_reset(&connector->base);
6340
6341         if (!connector->base.state)
6342                 return -ENOMEM;
6343
6344         return 0;
6345 }
6346
6347 struct intel_connector *intel_connector_alloc(void)
6348 {
6349         struct intel_connector *connector;
6350
6351         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6352         if (!connector)
6353                 return NULL;
6354
6355         if (intel_connector_init(connector) < 0) {
6356                 kfree(connector);
6357                 return NULL;
6358         }
6359
6360         return connector;
6361 }
6362
6363 /* Simple connector->get_hw_state implementation for encoders that support only
6364  * one connector and no cloning and hence the encoder state determines the state
6365  * of the connector. */
6366 bool intel_connector_get_hw_state(struct intel_connector *connector)
6367 {
6368         enum pipe pipe = 0;
6369         struct intel_encoder *encoder = connector->encoder;
6370
6371         return encoder->get_hw_state(encoder, &pipe);
6372 }
6373
6374 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6375 {
6376         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6377                 return crtc_state->fdi_lanes;
6378
6379         return 0;
6380 }
6381
6382 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6383                                      struct intel_crtc_state *pipe_config)
6384 {
6385         struct drm_atomic_state *state = pipe_config->base.state;
6386         struct intel_crtc *other_crtc;
6387         struct intel_crtc_state *other_crtc_state;
6388
6389         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6390                       pipe_name(pipe), pipe_config->fdi_lanes);
6391         if (pipe_config->fdi_lanes > 4) {
6392                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6393                               pipe_name(pipe), pipe_config->fdi_lanes);
6394                 return -EINVAL;
6395         }
6396
6397         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6398                 if (pipe_config->fdi_lanes > 2) {
6399                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6400                                       pipe_config->fdi_lanes);
6401                         return -EINVAL;
6402                 } else {
6403                         return 0;
6404                 }
6405         }
6406
6407         if (INTEL_INFO(dev)->num_pipes == 2)
6408                 return 0;
6409
6410         /* Ivybridge 3 pipe is really complicated */
6411         switch (pipe) {
6412         case PIPE_A:
6413                 return 0;
6414         case PIPE_B:
6415                 if (pipe_config->fdi_lanes <= 2)
6416                         return 0;
6417
6418                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6419                 other_crtc_state =
6420                         intel_atomic_get_crtc_state(state, other_crtc);
6421                 if (IS_ERR(other_crtc_state))
6422                         return PTR_ERR(other_crtc_state);
6423
6424                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6425                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6426                                       pipe_name(pipe), pipe_config->fdi_lanes);
6427                         return -EINVAL;
6428                 }
6429                 return 0;
6430         case PIPE_C:
6431                 if (pipe_config->fdi_lanes > 2) {
6432                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6433                                       pipe_name(pipe), pipe_config->fdi_lanes);
6434                         return -EINVAL;
6435                 }
6436
6437                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6438                 other_crtc_state =
6439                         intel_atomic_get_crtc_state(state, other_crtc);
6440                 if (IS_ERR(other_crtc_state))
6441                         return PTR_ERR(other_crtc_state);
6442
6443                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6444                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6445                         return -EINVAL;
6446                 }
6447                 return 0;
6448         default:
6449                 BUG();
6450         }
6451 }
6452
6453 #define RETRY 1
6454 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6455                                        struct intel_crtc_state *pipe_config)
6456 {
6457         struct drm_device *dev = intel_crtc->base.dev;
6458         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6459         int lane, link_bw, fdi_dotclock, ret;
6460         bool needs_recompute = false;
6461
6462 retry:
6463         /* FDI is a binary signal running at ~2.7GHz, encoding
6464          * each output octet as 10 bits. The actual frequency
6465          * is stored as a divider into a 100MHz clock, and the
6466          * mode pixel clock is stored in units of 1KHz.
6467          * Hence the bw of each lane in terms of the mode signal
6468          * is:
6469          */
6470         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6471
6472         fdi_dotclock = adjusted_mode->crtc_clock;
6473
6474         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6475                                            pipe_config->pipe_bpp);
6476
6477         pipe_config->fdi_lanes = lane;
6478
6479         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6480                                link_bw, &pipe_config->fdi_m_n);
6481
6482         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6483         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6484                 pipe_config->pipe_bpp -= 2*3;
6485                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6486                               pipe_config->pipe_bpp);
6487                 needs_recompute = true;
6488                 pipe_config->bw_constrained = true;
6489
6490                 goto retry;
6491         }
6492
6493         if (needs_recompute)
6494                 return RETRY;
6495
6496         return ret;
6497 }
6498
6499 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6500                                      struct intel_crtc_state *pipe_config)
6501 {
6502         if (pipe_config->pipe_bpp > 24)
6503                 return false;
6504
6505         /* HSW can handle pixel rate up to cdclk? */
6506         if (IS_HASWELL(dev_priv->dev))
6507                 return true;
6508
6509         /*
6510          * We compare against max which means we must take
6511          * the increased cdclk requirement into account when
6512          * calculating the new cdclk.
6513          *
6514          * Should measure whether using a lower cdclk w/o IPS
6515          */
6516         return ilk_pipe_pixel_rate(pipe_config) <=
6517                 dev_priv->max_cdclk_freq * 95 / 100;
6518 }
6519
6520 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6521                                    struct intel_crtc_state *pipe_config)
6522 {
6523         struct drm_device *dev = crtc->base.dev;
6524         struct drm_i915_private *dev_priv = dev->dev_private;
6525
6526         pipe_config->ips_enabled = i915.enable_ips &&
6527                 hsw_crtc_supports_ips(crtc) &&
6528                 pipe_config_supports_ips(dev_priv, pipe_config);
6529 }
6530
6531 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6532 {
6533         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6534
6535         /* GDG double wide on either pipe, otherwise pipe A only */
6536         return INTEL_INFO(dev_priv)->gen < 4 &&
6537                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6538 }
6539
6540 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6541                                      struct intel_crtc_state *pipe_config)
6542 {
6543         struct drm_device *dev = crtc->base.dev;
6544         struct drm_i915_private *dev_priv = dev->dev_private;
6545         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6546
6547         /* FIXME should check pixel clock limits on all platforms */
6548         if (INTEL_INFO(dev)->gen < 4) {
6549                 int clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6550
6551                 /*
6552                  * Enable double wide mode when the dot clock
6553                  * is > 90% of the (display) core speed.
6554                  */
6555                 if (intel_crtc_supports_double_wide(crtc) &&
6556                     adjusted_mode->crtc_clock > clock_limit) {
6557                         clock_limit *= 2;
6558                         pipe_config->double_wide = true;
6559                 }
6560
6561                 if (adjusted_mode->crtc_clock > clock_limit) {
6562                         DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6563                                       adjusted_mode->crtc_clock, clock_limit,
6564                                       yesno(pipe_config->double_wide));
6565                         return -EINVAL;
6566                 }
6567         }
6568
6569         /*
6570          * Pipe horizontal size must be even in:
6571          * - DVO ganged mode
6572          * - LVDS dual channel mode
6573          * - Double wide pipe
6574          */
6575         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6576              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6577                 pipe_config->pipe_src_w &= ~1;
6578
6579         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6580          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6581          */
6582         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6583                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6584                 return -EINVAL;
6585
6586         if (HAS_IPS(dev))
6587                 hsw_compute_ips_config(crtc, pipe_config);
6588
6589         if (pipe_config->has_pch_encoder)
6590                 return ironlake_fdi_compute_config(crtc, pipe_config);
6591
6592         return 0;
6593 }
6594
6595 static int skylake_get_display_clock_speed(struct drm_device *dev)
6596 {
6597         struct drm_i915_private *dev_priv = to_i915(dev);
6598         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6599         uint32_t cdctl = I915_READ(CDCLK_CTL);
6600         uint32_t linkrate;
6601
6602         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6603                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6604
6605         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6606                 return 540000;
6607
6608         linkrate = (I915_READ(DPLL_CTRL1) &
6609                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6610
6611         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6612             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6613                 /* vco 8640 */
6614                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6615                 case CDCLK_FREQ_450_432:
6616                         return 432000;
6617                 case CDCLK_FREQ_337_308:
6618                         return 308570;
6619                 case CDCLK_FREQ_675_617:
6620                         return 617140;
6621                 default:
6622                         WARN(1, "Unknown cd freq selection\n");
6623                 }
6624         } else {
6625                 /* vco 8100 */
6626                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6627                 case CDCLK_FREQ_450_432:
6628                         return 450000;
6629                 case CDCLK_FREQ_337_308:
6630                         return 337500;
6631                 case CDCLK_FREQ_675_617:
6632                         return 675000;
6633                 default:
6634                         WARN(1, "Unknown cd freq selection\n");
6635                 }
6636         }
6637
6638         /* error case, do as if DPLL0 isn't enabled */
6639         return 24000;
6640 }
6641
6642 static int broxton_get_display_clock_speed(struct drm_device *dev)
6643 {
6644         struct drm_i915_private *dev_priv = to_i915(dev);
6645         uint32_t cdctl = I915_READ(CDCLK_CTL);
6646         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6647         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6648         int cdclk;
6649
6650         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6651                 return 19200;
6652
6653         cdclk = 19200 * pll_ratio / 2;
6654
6655         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6656         case BXT_CDCLK_CD2X_DIV_SEL_1:
6657                 return cdclk;  /* 576MHz or 624MHz */
6658         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6659                 return cdclk * 2 / 3; /* 384MHz */
6660         case BXT_CDCLK_CD2X_DIV_SEL_2:
6661                 return cdclk / 2; /* 288MHz */
6662         case BXT_CDCLK_CD2X_DIV_SEL_4:
6663                 return cdclk / 4; /* 144MHz */
6664         }
6665
6666         /* error case, do as if DE PLL isn't enabled */
6667         return 19200;
6668 }
6669
6670 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6671 {
6672         struct drm_i915_private *dev_priv = dev->dev_private;
6673         uint32_t lcpll = I915_READ(LCPLL_CTL);
6674         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6675
6676         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6677                 return 800000;
6678         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6679                 return 450000;
6680         else if (freq == LCPLL_CLK_FREQ_450)
6681                 return 450000;
6682         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6683                 return 540000;
6684         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6685                 return 337500;
6686         else
6687                 return 675000;
6688 }
6689
6690 static int haswell_get_display_clock_speed(struct drm_device *dev)
6691 {
6692         struct drm_i915_private *dev_priv = dev->dev_private;
6693         uint32_t lcpll = I915_READ(LCPLL_CTL);
6694         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6695
6696         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6697                 return 800000;
6698         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6699                 return 450000;
6700         else if (freq == LCPLL_CLK_FREQ_450)
6701                 return 450000;
6702         else if (IS_HSW_ULT(dev))
6703                 return 337500;
6704         else
6705                 return 540000;
6706 }
6707
6708 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6709 {
6710         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6711                                       CCK_DISPLAY_CLOCK_CONTROL);
6712 }
6713
6714 static int ilk_get_display_clock_speed(struct drm_device *dev)
6715 {
6716         return 450000;
6717 }
6718
6719 static int i945_get_display_clock_speed(struct drm_device *dev)
6720 {
6721         return 400000;
6722 }
6723
6724 static int i915_get_display_clock_speed(struct drm_device *dev)
6725 {
6726         return 333333;
6727 }
6728
6729 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6730 {
6731         return 200000;
6732 }
6733
6734 static int pnv_get_display_clock_speed(struct drm_device *dev)
6735 {
6736         u16 gcfgc = 0;
6737
6738         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6739
6740         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6741         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6742                 return 266667;
6743         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6744                 return 333333;
6745         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6746                 return 444444;
6747         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6748                 return 200000;
6749         default:
6750                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6751         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6752                 return 133333;
6753         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6754                 return 166667;
6755         }
6756 }
6757
6758 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6759 {
6760         u16 gcfgc = 0;
6761
6762         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6763
6764         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6765                 return 133333;
6766         else {
6767                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6768                 case GC_DISPLAY_CLOCK_333_MHZ:
6769                         return 333333;
6770                 default:
6771                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6772                         return 190000;
6773                 }
6774         }
6775 }
6776
6777 static int i865_get_display_clock_speed(struct drm_device *dev)
6778 {
6779         return 266667;
6780 }
6781
6782 static int i85x_get_display_clock_speed(struct drm_device *dev)
6783 {
6784         u16 hpllcc = 0;
6785
6786         /*
6787          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6788          * encoding is different :(
6789          * FIXME is this the right way to detect 852GM/852GMV?
6790          */
6791         if (dev->pdev->revision == 0x1)
6792                 return 133333;
6793
6794         pci_bus_read_config_word(dev->pdev->bus,
6795                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6796
6797         /* Assume that the hardware is in the high speed state.  This
6798          * should be the default.
6799          */
6800         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6801         case GC_CLOCK_133_200:
6802         case GC_CLOCK_133_200_2:
6803         case GC_CLOCK_100_200:
6804                 return 200000;
6805         case GC_CLOCK_166_250:
6806                 return 250000;
6807         case GC_CLOCK_100_133:
6808                 return 133333;
6809         case GC_CLOCK_133_266:
6810         case GC_CLOCK_133_266_2:
6811         case GC_CLOCK_166_266:
6812                 return 266667;
6813         }
6814
6815         /* Shouldn't happen */
6816         return 0;
6817 }
6818
6819 static int i830_get_display_clock_speed(struct drm_device *dev)
6820 {
6821         return 133333;
6822 }
6823
6824 static unsigned int intel_hpll_vco(struct drm_device *dev)
6825 {
6826         struct drm_i915_private *dev_priv = dev->dev_private;
6827         static const unsigned int blb_vco[8] = {
6828                 [0] = 3200000,
6829                 [1] = 4000000,
6830                 [2] = 5333333,
6831                 [3] = 4800000,
6832                 [4] = 6400000,
6833         };
6834         static const unsigned int pnv_vco[8] = {
6835                 [0] = 3200000,
6836                 [1] = 4000000,
6837                 [2] = 5333333,
6838                 [3] = 4800000,
6839                 [4] = 2666667,
6840         };
6841         static const unsigned int cl_vco[8] = {
6842                 [0] = 3200000,
6843                 [1] = 4000000,
6844                 [2] = 5333333,
6845                 [3] = 6400000,
6846                 [4] = 3333333,
6847                 [5] = 3566667,
6848                 [6] = 4266667,
6849         };
6850         static const unsigned int elk_vco[8] = {
6851                 [0] = 3200000,
6852                 [1] = 4000000,
6853                 [2] = 5333333,
6854                 [3] = 4800000,
6855         };
6856         static const unsigned int ctg_vco[8] = {
6857                 [0] = 3200000,
6858                 [1] = 4000000,
6859                 [2] = 5333333,
6860                 [3] = 6400000,
6861                 [4] = 2666667,
6862                 [5] = 4266667,
6863         };
6864         const unsigned int *vco_table;
6865         unsigned int vco;
6866         uint8_t tmp = 0;
6867
6868         /* FIXME other chipsets? */
6869         if (IS_GM45(dev))
6870                 vco_table = ctg_vco;
6871         else if (IS_G4X(dev))
6872                 vco_table = elk_vco;
6873         else if (IS_CRESTLINE(dev))
6874                 vco_table = cl_vco;
6875         else if (IS_PINEVIEW(dev))
6876                 vco_table = pnv_vco;
6877         else if (IS_G33(dev))
6878                 vco_table = blb_vco;
6879         else
6880                 return 0;
6881
6882         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6883
6884         vco = vco_table[tmp & 0x7];
6885         if (vco == 0)
6886                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6887         else
6888                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6889
6890         return vco;
6891 }
6892
6893 static int gm45_get_display_clock_speed(struct drm_device *dev)
6894 {
6895         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6896         uint16_t tmp = 0;
6897
6898         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6899
6900         cdclk_sel = (tmp >> 12) & 0x1;
6901
6902         switch (vco) {
6903         case 2666667:
6904         case 4000000:
6905         case 5333333:
6906                 return cdclk_sel ? 333333 : 222222;
6907         case 3200000:
6908                 return cdclk_sel ? 320000 : 228571;
6909         default:
6910                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6911                 return 222222;
6912         }
6913 }
6914
6915 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6916 {
6917         static const uint8_t div_3200[] = { 16, 10,  8 };
6918         static const uint8_t div_4000[] = { 20, 12, 10 };
6919         static const uint8_t div_5333[] = { 24, 16, 14 };
6920         const uint8_t *div_table;
6921         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6922         uint16_t tmp = 0;
6923
6924         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6925
6926         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6927
6928         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6929                 goto fail;
6930
6931         switch (vco) {
6932         case 3200000:
6933                 div_table = div_3200;
6934                 break;
6935         case 4000000:
6936                 div_table = div_4000;
6937                 break;
6938         case 5333333:
6939                 div_table = div_5333;
6940                 break;
6941         default:
6942                 goto fail;
6943         }
6944
6945         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6946
6947 fail:
6948         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
6949         return 200000;
6950 }
6951
6952 static int g33_get_display_clock_speed(struct drm_device *dev)
6953 {
6954         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
6955         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
6956         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
6957         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
6958         const uint8_t *div_table;
6959         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6960         uint16_t tmp = 0;
6961
6962         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6963
6964         cdclk_sel = (tmp >> 4) & 0x7;
6965
6966         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6967                 goto fail;
6968
6969         switch (vco) {
6970         case 3200000:
6971                 div_table = div_3200;
6972                 break;
6973         case 4000000:
6974                 div_table = div_4000;
6975                 break;
6976         case 4800000:
6977                 div_table = div_4800;
6978                 break;
6979         case 5333333:
6980                 div_table = div_5333;
6981                 break;
6982         default:
6983                 goto fail;
6984         }
6985
6986         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6987
6988 fail:
6989         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
6990         return 190476;
6991 }
6992
6993 static void
6994 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6995 {
6996         while (*num > DATA_LINK_M_N_MASK ||
6997                *den > DATA_LINK_M_N_MASK) {
6998                 *num >>= 1;
6999                 *den >>= 1;
7000         }
7001 }
7002
7003 static void compute_m_n(unsigned int m, unsigned int n,
7004                         uint32_t *ret_m, uint32_t *ret_n)
7005 {
7006         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
7007         *ret_m = div_u64((uint64_t) m * *ret_n, n);
7008         intel_reduce_m_n_ratio(ret_m, ret_n);
7009 }
7010
7011 void
7012 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7013                        int pixel_clock, int link_clock,
7014                        struct intel_link_m_n *m_n)
7015 {
7016         m_n->tu = 64;
7017
7018         compute_m_n(bits_per_pixel * pixel_clock,
7019                     link_clock * nlanes * 8,
7020                     &m_n->gmch_m, &m_n->gmch_n);
7021
7022         compute_m_n(pixel_clock, link_clock,
7023                     &m_n->link_m, &m_n->link_n);
7024 }
7025
7026 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7027 {
7028         if (i915.panel_use_ssc >= 0)
7029                 return i915.panel_use_ssc != 0;
7030         return dev_priv->vbt.lvds_use_ssc
7031                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7032 }
7033
7034 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7035 {
7036         return (1 << dpll->n) << 16 | dpll->m2;
7037 }
7038
7039 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7040 {
7041         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7042 }
7043
7044 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7045                                      struct intel_crtc_state *crtc_state,
7046                                      intel_clock_t *reduced_clock)
7047 {
7048         struct drm_device *dev = crtc->base.dev;
7049         u32 fp, fp2 = 0;
7050
7051         if (IS_PINEVIEW(dev)) {
7052                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7053                 if (reduced_clock)
7054                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7055         } else {
7056                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7057                 if (reduced_clock)
7058                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7059         }
7060
7061         crtc_state->dpll_hw_state.fp0 = fp;
7062
7063         crtc->lowfreq_avail = false;
7064         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7065             reduced_clock) {
7066                 crtc_state->dpll_hw_state.fp1 = fp2;
7067                 crtc->lowfreq_avail = true;
7068         } else {
7069                 crtc_state->dpll_hw_state.fp1 = fp;
7070         }
7071 }
7072
7073 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7074                 pipe)
7075 {
7076         u32 reg_val;
7077
7078         /*
7079          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7080          * and set it to a reasonable value instead.
7081          */
7082         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7083         reg_val &= 0xffffff00;
7084         reg_val |= 0x00000030;
7085         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7086
7087         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7088         reg_val &= 0x8cffffff;
7089         reg_val = 0x8c000000;
7090         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7091
7092         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7093         reg_val &= 0xffffff00;
7094         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7095
7096         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7097         reg_val &= 0x00ffffff;
7098         reg_val |= 0xb0000000;
7099         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7100 }
7101
7102 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7103                                          struct intel_link_m_n *m_n)
7104 {
7105         struct drm_device *dev = crtc->base.dev;
7106         struct drm_i915_private *dev_priv = dev->dev_private;
7107         int pipe = crtc->pipe;
7108
7109         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7110         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7111         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7112         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7113 }
7114
7115 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7116                                          struct intel_link_m_n *m_n,
7117                                          struct intel_link_m_n *m2_n2)
7118 {
7119         struct drm_device *dev = crtc->base.dev;
7120         struct drm_i915_private *dev_priv = dev->dev_private;
7121         int pipe = crtc->pipe;
7122         enum transcoder transcoder = crtc->config->cpu_transcoder;
7123
7124         if (INTEL_INFO(dev)->gen >= 5) {
7125                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7126                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7127                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7128                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7129                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7130                  * for gen < 8) and if DRRS is supported (to make sure the
7131                  * registers are not unnecessarily accessed).
7132                  */
7133                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7134                         crtc->config->has_drrs) {
7135                         I915_WRITE(PIPE_DATA_M2(transcoder),
7136                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7137                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7138                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7139                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7140                 }
7141         } else {
7142                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7143                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7144                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7145                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7146         }
7147 }
7148
7149 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7150 {
7151         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7152
7153         if (m_n == M1_N1) {
7154                 dp_m_n = &crtc->config->dp_m_n;
7155                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7156         } else if (m_n == M2_N2) {
7157
7158                 /*
7159                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7160                  * needs to be programmed into M1_N1.
7161                  */
7162                 dp_m_n = &crtc->config->dp_m2_n2;
7163         } else {
7164                 DRM_ERROR("Unsupported divider value\n");
7165                 return;
7166         }
7167
7168         if (crtc->config->has_pch_encoder)
7169                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7170         else
7171                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7172 }
7173
7174 static void vlv_compute_dpll(struct intel_crtc *crtc,
7175                              struct intel_crtc_state *pipe_config)
7176 {
7177         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7178                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7179                 DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV;
7180         if (crtc->pipe != PIPE_A)
7181                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7182
7183         pipe_config->dpll_hw_state.dpll_md =
7184                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7185 }
7186
7187 static void chv_compute_dpll(struct intel_crtc *crtc,
7188                              struct intel_crtc_state *pipe_config)
7189 {
7190         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7191                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7192                 DPLL_VCO_ENABLE;
7193         if (crtc->pipe != PIPE_A)
7194                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7195
7196         pipe_config->dpll_hw_state.dpll_md =
7197                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7198 }
7199
7200 static void vlv_prepare_pll(struct intel_crtc *crtc,
7201                             const struct intel_crtc_state *pipe_config)
7202 {
7203         struct drm_device *dev = crtc->base.dev;
7204         struct drm_i915_private *dev_priv = dev->dev_private;
7205         int pipe = crtc->pipe;
7206         u32 mdiv;
7207         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7208         u32 coreclk, reg_val;
7209
7210         mutex_lock(&dev_priv->sb_lock);
7211
7212         bestn = pipe_config->dpll.n;
7213         bestm1 = pipe_config->dpll.m1;
7214         bestm2 = pipe_config->dpll.m2;
7215         bestp1 = pipe_config->dpll.p1;
7216         bestp2 = pipe_config->dpll.p2;
7217
7218         /* See eDP HDMI DPIO driver vbios notes doc */
7219
7220         /* PLL B needs special handling */
7221         if (pipe == PIPE_B)
7222                 vlv_pllb_recal_opamp(dev_priv, pipe);
7223
7224         /* Set up Tx target for periodic Rcomp update */
7225         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7226
7227         /* Disable target IRef on PLL */
7228         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7229         reg_val &= 0x00ffffff;
7230         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7231
7232         /* Disable fast lock */
7233         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7234
7235         /* Set idtafcrecal before PLL is enabled */
7236         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7237         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7238         mdiv |= ((bestn << DPIO_N_SHIFT));
7239         mdiv |= (1 << DPIO_K_SHIFT);
7240
7241         /*
7242          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7243          * but we don't support that).
7244          * Note: don't use the DAC post divider as it seems unstable.
7245          */
7246         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7247         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7248
7249         mdiv |= DPIO_ENABLE_CALIBRATION;
7250         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7251
7252         /* Set HBR and RBR LPF coefficients */
7253         if (pipe_config->port_clock == 162000 ||
7254             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7255             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7256                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7257                                  0x009f0003);
7258         else
7259                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7260                                  0x00d0000f);
7261
7262         if (pipe_config->has_dp_encoder) {
7263                 /* Use SSC source */
7264                 if (pipe == PIPE_A)
7265                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7266                                          0x0df40000);
7267                 else
7268                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7269                                          0x0df70000);
7270         } else { /* HDMI or VGA */
7271                 /* Use bend source */
7272                 if (pipe == PIPE_A)
7273                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7274                                          0x0df70000);
7275                 else
7276                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7277                                          0x0df40000);
7278         }
7279
7280         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7281         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7282         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7283             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7284                 coreclk |= 0x01000000;
7285         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7286
7287         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7288         mutex_unlock(&dev_priv->sb_lock);
7289 }
7290
7291 static void chv_prepare_pll(struct intel_crtc *crtc,
7292                             const struct intel_crtc_state *pipe_config)
7293 {
7294         struct drm_device *dev = crtc->base.dev;
7295         struct drm_i915_private *dev_priv = dev->dev_private;
7296         int pipe = crtc->pipe;
7297         i915_reg_t dpll_reg = DPLL(crtc->pipe);
7298         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7299         u32 loopfilter, tribuf_calcntr;
7300         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7301         u32 dpio_val;
7302         int vco;
7303
7304         bestn = pipe_config->dpll.n;
7305         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7306         bestm1 = pipe_config->dpll.m1;
7307         bestm2 = pipe_config->dpll.m2 >> 22;
7308         bestp1 = pipe_config->dpll.p1;
7309         bestp2 = pipe_config->dpll.p2;
7310         vco = pipe_config->dpll.vco;
7311         dpio_val = 0;
7312         loopfilter = 0;
7313
7314         /*
7315          * Enable Refclk and SSC
7316          */
7317         I915_WRITE(dpll_reg,
7318                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7319
7320         mutex_lock(&dev_priv->sb_lock);
7321
7322         /* p1 and p2 divider */
7323         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7324                         5 << DPIO_CHV_S1_DIV_SHIFT |
7325                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7326                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7327                         1 << DPIO_CHV_K_DIV_SHIFT);
7328
7329         /* Feedback post-divider - m2 */
7330         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7331
7332         /* Feedback refclk divider - n and m1 */
7333         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7334                         DPIO_CHV_M1_DIV_BY_2 |
7335                         1 << DPIO_CHV_N_DIV_SHIFT);
7336
7337         /* M2 fraction division */
7338         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7339
7340         /* M2 fraction division enable */
7341         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7342         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7343         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7344         if (bestm2_frac)
7345                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7346         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7347
7348         /* Program digital lock detect threshold */
7349         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7350         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7351                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7352         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7353         if (!bestm2_frac)
7354                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7355         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7356
7357         /* Loop filter */
7358         if (vco == 5400000) {
7359                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7360                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7361                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7362                 tribuf_calcntr = 0x9;
7363         } else if (vco <= 6200000) {
7364                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7365                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7366                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7367                 tribuf_calcntr = 0x9;
7368         } else if (vco <= 6480000) {
7369                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7370                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7371                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7372                 tribuf_calcntr = 0x8;
7373         } else {
7374                 /* Not supported. Apply the same limits as in the max case */
7375                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7376                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7377                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7378                 tribuf_calcntr = 0;
7379         }
7380         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7381
7382         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7383         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7384         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7385         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7386
7387         /* AFC Recal */
7388         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7389                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7390                         DPIO_AFC_RECAL);
7391
7392         mutex_unlock(&dev_priv->sb_lock);
7393 }
7394
7395 /**
7396  * vlv_force_pll_on - forcibly enable just the PLL
7397  * @dev_priv: i915 private structure
7398  * @pipe: pipe PLL to enable
7399  * @dpll: PLL configuration
7400  *
7401  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7402  * in cases where we need the PLL enabled even when @pipe is not going to
7403  * be enabled.
7404  */
7405 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7406                      const struct dpll *dpll)
7407 {
7408         struct intel_crtc *crtc =
7409                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7410         struct intel_crtc_state *pipe_config;
7411
7412         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7413         if (!pipe_config)
7414                 return -ENOMEM;
7415
7416         pipe_config->base.crtc = &crtc->base;
7417         pipe_config->pixel_multiplier = 1;
7418         pipe_config->dpll = *dpll;
7419
7420         if (IS_CHERRYVIEW(dev)) {
7421                 chv_compute_dpll(crtc, pipe_config);
7422                 chv_prepare_pll(crtc, pipe_config);
7423                 chv_enable_pll(crtc, pipe_config);
7424         } else {
7425                 vlv_compute_dpll(crtc, pipe_config);
7426                 vlv_prepare_pll(crtc, pipe_config);
7427                 vlv_enable_pll(crtc, pipe_config);
7428         }
7429
7430         kfree(pipe_config);
7431
7432         return 0;
7433 }
7434
7435 /**
7436  * vlv_force_pll_off - forcibly disable just the PLL
7437  * @dev_priv: i915 private structure
7438  * @pipe: pipe PLL to disable
7439  *
7440  * Disable the PLL for @pipe. To be used in cases where we need
7441  * the PLL enabled even when @pipe is not going to be enabled.
7442  */
7443 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7444 {
7445         if (IS_CHERRYVIEW(dev))
7446                 chv_disable_pll(to_i915(dev), pipe);
7447         else
7448                 vlv_disable_pll(to_i915(dev), pipe);
7449 }
7450
7451 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7452                               struct intel_crtc_state *crtc_state,
7453                               intel_clock_t *reduced_clock)
7454 {
7455         struct drm_device *dev = crtc->base.dev;
7456         struct drm_i915_private *dev_priv = dev->dev_private;
7457         u32 dpll;
7458         bool is_sdvo;
7459         struct dpll *clock = &crtc_state->dpll;
7460
7461         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7462
7463         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7464                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7465
7466         dpll = DPLL_VGA_MODE_DIS;
7467
7468         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7469                 dpll |= DPLLB_MODE_LVDS;
7470         else
7471                 dpll |= DPLLB_MODE_DAC_SERIAL;
7472
7473         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7474                 dpll |= (crtc_state->pixel_multiplier - 1)
7475                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7476         }
7477
7478         if (is_sdvo)
7479                 dpll |= DPLL_SDVO_HIGH_SPEED;
7480
7481         if (crtc_state->has_dp_encoder)
7482                 dpll |= DPLL_SDVO_HIGH_SPEED;
7483
7484         /* compute bitmask from p1 value */
7485         if (IS_PINEVIEW(dev))
7486                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7487         else {
7488                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7489                 if (IS_G4X(dev) && reduced_clock)
7490                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7491         }
7492         switch (clock->p2) {
7493         case 5:
7494                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7495                 break;
7496         case 7:
7497                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7498                 break;
7499         case 10:
7500                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7501                 break;
7502         case 14:
7503                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7504                 break;
7505         }
7506         if (INTEL_INFO(dev)->gen >= 4)
7507                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7508
7509         if (crtc_state->sdvo_tv_clock)
7510                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7511         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7512                  intel_panel_use_ssc(dev_priv))
7513                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7514         else
7515                 dpll |= PLL_REF_INPUT_DREFCLK;
7516
7517         dpll |= DPLL_VCO_ENABLE;
7518         crtc_state->dpll_hw_state.dpll = dpll;
7519
7520         if (INTEL_INFO(dev)->gen >= 4) {
7521                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7522                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7523                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7524         }
7525 }
7526
7527 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7528                               struct intel_crtc_state *crtc_state,
7529                               intel_clock_t *reduced_clock)
7530 {
7531         struct drm_device *dev = crtc->base.dev;
7532         struct drm_i915_private *dev_priv = dev->dev_private;
7533         u32 dpll;
7534         struct dpll *clock = &crtc_state->dpll;
7535
7536         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7537
7538         dpll = DPLL_VGA_MODE_DIS;
7539
7540         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7541                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7542         } else {
7543                 if (clock->p1 == 2)
7544                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7545                 else
7546                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7547                 if (clock->p2 == 4)
7548                         dpll |= PLL_P2_DIVIDE_BY_4;
7549         }
7550
7551         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7552                 dpll |= DPLL_DVO_2X_MODE;
7553
7554         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7555             intel_panel_use_ssc(dev_priv))
7556                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7557         else
7558                 dpll |= PLL_REF_INPUT_DREFCLK;
7559
7560         dpll |= DPLL_VCO_ENABLE;
7561         crtc_state->dpll_hw_state.dpll = dpll;
7562 }
7563
7564 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7565 {
7566         struct drm_device *dev = intel_crtc->base.dev;
7567         struct drm_i915_private *dev_priv = dev->dev_private;
7568         enum pipe pipe = intel_crtc->pipe;
7569         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7570         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7571         uint32_t crtc_vtotal, crtc_vblank_end;
7572         int vsyncshift = 0;
7573
7574         /* We need to be careful not to changed the adjusted mode, for otherwise
7575          * the hw state checker will get angry at the mismatch. */
7576         crtc_vtotal = adjusted_mode->crtc_vtotal;
7577         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7578
7579         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7580                 /* the chip adds 2 halflines automatically */
7581                 crtc_vtotal -= 1;
7582                 crtc_vblank_end -= 1;
7583
7584                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7585                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7586                 else
7587                         vsyncshift = adjusted_mode->crtc_hsync_start -
7588                                 adjusted_mode->crtc_htotal / 2;
7589                 if (vsyncshift < 0)
7590                         vsyncshift += adjusted_mode->crtc_htotal;
7591         }
7592
7593         if (INTEL_INFO(dev)->gen > 3)
7594                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7595
7596         I915_WRITE(HTOTAL(cpu_transcoder),
7597                    (adjusted_mode->crtc_hdisplay - 1) |
7598                    ((adjusted_mode->crtc_htotal - 1) << 16));
7599         I915_WRITE(HBLANK(cpu_transcoder),
7600                    (adjusted_mode->crtc_hblank_start - 1) |
7601                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7602         I915_WRITE(HSYNC(cpu_transcoder),
7603                    (adjusted_mode->crtc_hsync_start - 1) |
7604                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7605
7606         I915_WRITE(VTOTAL(cpu_transcoder),
7607                    (adjusted_mode->crtc_vdisplay - 1) |
7608                    ((crtc_vtotal - 1) << 16));
7609         I915_WRITE(VBLANK(cpu_transcoder),
7610                    (adjusted_mode->crtc_vblank_start - 1) |
7611                    ((crtc_vblank_end - 1) << 16));
7612         I915_WRITE(VSYNC(cpu_transcoder),
7613                    (adjusted_mode->crtc_vsync_start - 1) |
7614                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7615
7616         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7617          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7618          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7619          * bits. */
7620         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7621             (pipe == PIPE_B || pipe == PIPE_C))
7622                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7623
7624 }
7625
7626 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7627 {
7628         struct drm_device *dev = intel_crtc->base.dev;
7629         struct drm_i915_private *dev_priv = dev->dev_private;
7630         enum pipe pipe = intel_crtc->pipe;
7631
7632         /* pipesrc controls the size that is scaled from, which should
7633          * always be the user's requested size.
7634          */
7635         I915_WRITE(PIPESRC(pipe),
7636                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7637                    (intel_crtc->config->pipe_src_h - 1));
7638 }
7639
7640 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7641                                    struct intel_crtc_state *pipe_config)
7642 {
7643         struct drm_device *dev = crtc->base.dev;
7644         struct drm_i915_private *dev_priv = dev->dev_private;
7645         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7646         uint32_t tmp;
7647
7648         tmp = I915_READ(HTOTAL(cpu_transcoder));
7649         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7650         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7651         tmp = I915_READ(HBLANK(cpu_transcoder));
7652         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7653         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7654         tmp = I915_READ(HSYNC(cpu_transcoder));
7655         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7656         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7657
7658         tmp = I915_READ(VTOTAL(cpu_transcoder));
7659         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7660         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7661         tmp = I915_READ(VBLANK(cpu_transcoder));
7662         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7663         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7664         tmp = I915_READ(VSYNC(cpu_transcoder));
7665         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7666         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7667
7668         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7669                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7670                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7671                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7672         }
7673 }
7674
7675 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7676                                     struct intel_crtc_state *pipe_config)
7677 {
7678         struct drm_device *dev = crtc->base.dev;
7679         struct drm_i915_private *dev_priv = dev->dev_private;
7680         u32 tmp;
7681
7682         tmp = I915_READ(PIPESRC(crtc->pipe));
7683         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7684         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7685
7686         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7687         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7688 }
7689
7690 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7691                                  struct intel_crtc_state *pipe_config)
7692 {
7693         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7694         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7695         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7696         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7697
7698         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7699         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7700         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7701         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7702
7703         mode->flags = pipe_config->base.adjusted_mode.flags;
7704         mode->type = DRM_MODE_TYPE_DRIVER;
7705
7706         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7707         mode->flags |= pipe_config->base.adjusted_mode.flags;
7708
7709         mode->hsync = drm_mode_hsync(mode);
7710         mode->vrefresh = drm_mode_vrefresh(mode);
7711         drm_mode_set_name(mode);
7712 }
7713
7714 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7715 {
7716         struct drm_device *dev = intel_crtc->base.dev;
7717         struct drm_i915_private *dev_priv = dev->dev_private;
7718         uint32_t pipeconf;
7719
7720         pipeconf = 0;
7721
7722         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7723             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7724                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7725
7726         if (intel_crtc->config->double_wide)
7727                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7728
7729         /* only g4x and later have fancy bpc/dither controls */
7730         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
7731                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7732                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7733                         pipeconf |= PIPECONF_DITHER_EN |
7734                                     PIPECONF_DITHER_TYPE_SP;
7735
7736                 switch (intel_crtc->config->pipe_bpp) {
7737                 case 18:
7738                         pipeconf |= PIPECONF_6BPC;
7739                         break;
7740                 case 24:
7741                         pipeconf |= PIPECONF_8BPC;
7742                         break;
7743                 case 30:
7744                         pipeconf |= PIPECONF_10BPC;
7745                         break;
7746                 default:
7747                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7748                         BUG();
7749                 }
7750         }
7751
7752         if (HAS_PIPE_CXSR(dev)) {
7753                 if (intel_crtc->lowfreq_avail) {
7754                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7755                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7756                 } else {
7757                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7758                 }
7759         }
7760
7761         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7762                 if (INTEL_INFO(dev)->gen < 4 ||
7763                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7764                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7765                 else
7766                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7767         } else
7768                 pipeconf |= PIPECONF_PROGRESSIVE;
7769
7770         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
7771              intel_crtc->config->limited_color_range)
7772                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7773
7774         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7775         POSTING_READ(PIPECONF(intel_crtc->pipe));
7776 }
7777
7778 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7779                                    struct intel_crtc_state *crtc_state)
7780 {
7781         struct drm_device *dev = crtc->base.dev;
7782         struct drm_i915_private *dev_priv = dev->dev_private;
7783         const intel_limit_t *limit;
7784         int refclk = 48000;
7785
7786         memset(&crtc_state->dpll_hw_state, 0,
7787                sizeof(crtc_state->dpll_hw_state));
7788
7789         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7790                 if (intel_panel_use_ssc(dev_priv)) {
7791                         refclk = dev_priv->vbt.lvds_ssc_freq;
7792                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7793                 }
7794
7795                 limit = &intel_limits_i8xx_lvds;
7796         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO)) {
7797                 limit = &intel_limits_i8xx_dvo;
7798         } else {
7799                 limit = &intel_limits_i8xx_dac;
7800         }
7801
7802         if (!crtc_state->clock_set &&
7803             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7804                                  refclk, NULL, &crtc_state->dpll)) {
7805                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7806                 return -EINVAL;
7807         }
7808
7809         i8xx_compute_dpll(crtc, crtc_state, NULL);
7810
7811         return 0;
7812 }
7813
7814 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7815                                   struct intel_crtc_state *crtc_state)
7816 {
7817         struct drm_device *dev = crtc->base.dev;
7818         struct drm_i915_private *dev_priv = dev->dev_private;
7819         const intel_limit_t *limit;
7820         int refclk = 96000;
7821
7822         memset(&crtc_state->dpll_hw_state, 0,
7823                sizeof(crtc_state->dpll_hw_state));
7824
7825         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7826                 if (intel_panel_use_ssc(dev_priv)) {
7827                         refclk = dev_priv->vbt.lvds_ssc_freq;
7828                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7829                 }
7830
7831                 if (intel_is_dual_link_lvds(dev))
7832                         limit = &intel_limits_g4x_dual_channel_lvds;
7833                 else
7834                         limit = &intel_limits_g4x_single_channel_lvds;
7835         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7836                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7837                 limit = &intel_limits_g4x_hdmi;
7838         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7839                 limit = &intel_limits_g4x_sdvo;
7840         } else {
7841                 /* The option is for other outputs */
7842                 limit = &intel_limits_i9xx_sdvo;
7843         }
7844
7845         if (!crtc_state->clock_set &&
7846             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7847                                 refclk, NULL, &crtc_state->dpll)) {
7848                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7849                 return -EINVAL;
7850         }
7851
7852         i9xx_compute_dpll(crtc, crtc_state, NULL);
7853
7854         return 0;
7855 }
7856
7857 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7858                                   struct intel_crtc_state *crtc_state)
7859 {
7860         struct drm_device *dev = crtc->base.dev;
7861         struct drm_i915_private *dev_priv = dev->dev_private;
7862         const intel_limit_t *limit;
7863         int refclk = 96000;
7864
7865         memset(&crtc_state->dpll_hw_state, 0,
7866                sizeof(crtc_state->dpll_hw_state));
7867
7868         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7869                 if (intel_panel_use_ssc(dev_priv)) {
7870                         refclk = dev_priv->vbt.lvds_ssc_freq;
7871                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7872                 }
7873
7874                 limit = &intel_limits_pineview_lvds;
7875         } else {
7876                 limit = &intel_limits_pineview_sdvo;
7877         }
7878
7879         if (!crtc_state->clock_set &&
7880             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7881                                 refclk, NULL, &crtc_state->dpll)) {
7882                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7883                 return -EINVAL;
7884         }
7885
7886         i9xx_compute_dpll(crtc, crtc_state, NULL);
7887
7888         return 0;
7889 }
7890
7891 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7892                                    struct intel_crtc_state *crtc_state)
7893 {
7894         struct drm_device *dev = crtc->base.dev;
7895         struct drm_i915_private *dev_priv = dev->dev_private;
7896         const intel_limit_t *limit;
7897         int refclk = 96000;
7898
7899         memset(&crtc_state->dpll_hw_state, 0,
7900                sizeof(crtc_state->dpll_hw_state));
7901
7902         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7903                 if (intel_panel_use_ssc(dev_priv)) {
7904                         refclk = dev_priv->vbt.lvds_ssc_freq;
7905                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7906                 }
7907
7908                 limit = &intel_limits_i9xx_lvds;
7909         } else {
7910                 limit = &intel_limits_i9xx_sdvo;
7911         }
7912
7913         if (!crtc_state->clock_set &&
7914             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7915                                  refclk, NULL, &crtc_state->dpll)) {
7916                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7917                 return -EINVAL;
7918         }
7919
7920         i9xx_compute_dpll(crtc, crtc_state, NULL);
7921
7922         return 0;
7923 }
7924
7925 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7926                                   struct intel_crtc_state *crtc_state)
7927 {
7928         int refclk = 100000;
7929         const intel_limit_t *limit = &intel_limits_chv;
7930
7931         memset(&crtc_state->dpll_hw_state, 0,
7932                sizeof(crtc_state->dpll_hw_state));
7933
7934         if (crtc_state->has_dsi_encoder)
7935                 return 0;
7936
7937         if (!crtc_state->clock_set &&
7938             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7939                                 refclk, NULL, &crtc_state->dpll)) {
7940                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7941                 return -EINVAL;
7942         }
7943
7944         chv_compute_dpll(crtc, crtc_state);
7945
7946         return 0;
7947 }
7948
7949 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7950                                   struct intel_crtc_state *crtc_state)
7951 {
7952         int refclk = 100000;
7953         const intel_limit_t *limit = &intel_limits_vlv;
7954
7955         memset(&crtc_state->dpll_hw_state, 0,
7956                sizeof(crtc_state->dpll_hw_state));
7957
7958         if (crtc_state->has_dsi_encoder)
7959                 return 0;
7960
7961         if (!crtc_state->clock_set &&
7962             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7963                                 refclk, NULL, &crtc_state->dpll)) {
7964                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7965                 return -EINVAL;
7966         }
7967
7968         vlv_compute_dpll(crtc, crtc_state);
7969
7970         return 0;
7971 }
7972
7973 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7974                                  struct intel_crtc_state *pipe_config)
7975 {
7976         struct drm_device *dev = crtc->base.dev;
7977         struct drm_i915_private *dev_priv = dev->dev_private;
7978         uint32_t tmp;
7979
7980         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7981                 return;
7982
7983         tmp = I915_READ(PFIT_CONTROL);
7984         if (!(tmp & PFIT_ENABLE))
7985                 return;
7986
7987         /* Check whether the pfit is attached to our pipe. */
7988         if (INTEL_INFO(dev)->gen < 4) {
7989                 if (crtc->pipe != PIPE_B)
7990                         return;
7991         } else {
7992                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7993                         return;
7994         }
7995
7996         pipe_config->gmch_pfit.control = tmp;
7997         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7998         if (INTEL_INFO(dev)->gen < 5)
7999                 pipe_config->gmch_pfit.lvds_border_bits =
8000                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
8001 }
8002
8003 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8004                                struct intel_crtc_state *pipe_config)
8005 {
8006         struct drm_device *dev = crtc->base.dev;
8007         struct drm_i915_private *dev_priv = dev->dev_private;
8008         int pipe = pipe_config->cpu_transcoder;
8009         intel_clock_t clock;
8010         u32 mdiv;
8011         int refclk = 100000;
8012
8013         /* In case of MIPI DPLL will not even be used */
8014         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
8015                 return;
8016
8017         mutex_lock(&dev_priv->sb_lock);
8018         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8019         mutex_unlock(&dev_priv->sb_lock);
8020
8021         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8022         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8023         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8024         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8025         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8026
8027         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8028 }
8029
8030 static void
8031 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8032                               struct intel_initial_plane_config *plane_config)
8033 {
8034         struct drm_device *dev = crtc->base.dev;
8035         struct drm_i915_private *dev_priv = dev->dev_private;
8036         u32 val, base, offset;
8037         int pipe = crtc->pipe, plane = crtc->plane;
8038         int fourcc, pixel_format;
8039         unsigned int aligned_height;
8040         struct drm_framebuffer *fb;
8041         struct intel_framebuffer *intel_fb;
8042
8043         val = I915_READ(DSPCNTR(plane));
8044         if (!(val & DISPLAY_PLANE_ENABLE))
8045                 return;
8046
8047         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8048         if (!intel_fb) {
8049                 DRM_DEBUG_KMS("failed to alloc fb\n");
8050                 return;
8051         }
8052
8053         fb = &intel_fb->base;
8054
8055         if (INTEL_INFO(dev)->gen >= 4) {
8056                 if (val & DISPPLANE_TILED) {
8057                         plane_config->tiling = I915_TILING_X;
8058                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8059                 }
8060         }
8061
8062         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8063         fourcc = i9xx_format_to_fourcc(pixel_format);
8064         fb->pixel_format = fourcc;
8065         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8066
8067         if (INTEL_INFO(dev)->gen >= 4) {
8068                 if (plane_config->tiling)
8069                         offset = I915_READ(DSPTILEOFF(plane));
8070                 else
8071                         offset = I915_READ(DSPLINOFF(plane));
8072                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8073         } else {
8074                 base = I915_READ(DSPADDR(plane));
8075         }
8076         plane_config->base = base;
8077
8078         val = I915_READ(PIPESRC(pipe));
8079         fb->width = ((val >> 16) & 0xfff) + 1;
8080         fb->height = ((val >> 0) & 0xfff) + 1;
8081
8082         val = I915_READ(DSPSTRIDE(pipe));
8083         fb->pitches[0] = val & 0xffffffc0;
8084
8085         aligned_height = intel_fb_align_height(dev, fb->height,
8086                                                fb->pixel_format,
8087                                                fb->modifier[0]);
8088
8089         plane_config->size = fb->pitches[0] * aligned_height;
8090
8091         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8092                       pipe_name(pipe), plane, fb->width, fb->height,
8093                       fb->bits_per_pixel, base, fb->pitches[0],
8094                       plane_config->size);
8095
8096         plane_config->fb = intel_fb;
8097 }
8098
8099 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8100                                struct intel_crtc_state *pipe_config)
8101 {
8102         struct drm_device *dev = crtc->base.dev;
8103         struct drm_i915_private *dev_priv = dev->dev_private;
8104         int pipe = pipe_config->cpu_transcoder;
8105         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8106         intel_clock_t clock;
8107         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8108         int refclk = 100000;
8109
8110         mutex_lock(&dev_priv->sb_lock);
8111         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8112         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8113         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8114         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8115         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8116         mutex_unlock(&dev_priv->sb_lock);
8117
8118         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8119         clock.m2 = (pll_dw0 & 0xff) << 22;
8120         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8121                 clock.m2 |= pll_dw2 & 0x3fffff;
8122         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8123         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8124         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8125
8126         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8127 }
8128
8129 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8130                                  struct intel_crtc_state *pipe_config)
8131 {
8132         struct drm_device *dev = crtc->base.dev;
8133         struct drm_i915_private *dev_priv = dev->dev_private;
8134         enum intel_display_power_domain power_domain;
8135         uint32_t tmp;
8136         bool ret;
8137
8138         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8139         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8140                 return false;
8141
8142         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8143         pipe_config->shared_dpll = NULL;
8144
8145         ret = false;
8146
8147         tmp = I915_READ(PIPECONF(crtc->pipe));
8148         if (!(tmp & PIPECONF_ENABLE))
8149                 goto out;
8150
8151         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8152                 switch (tmp & PIPECONF_BPC_MASK) {
8153                 case PIPECONF_6BPC:
8154                         pipe_config->pipe_bpp = 18;
8155                         break;
8156                 case PIPECONF_8BPC:
8157                         pipe_config->pipe_bpp = 24;
8158                         break;
8159                 case PIPECONF_10BPC:
8160                         pipe_config->pipe_bpp = 30;
8161                         break;
8162                 default:
8163                         break;
8164                 }
8165         }
8166
8167         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8168             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8169                 pipe_config->limited_color_range = true;
8170
8171         if (INTEL_INFO(dev)->gen < 4)
8172                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8173
8174         intel_get_pipe_timings(crtc, pipe_config);
8175         intel_get_pipe_src_size(crtc, pipe_config);
8176
8177         i9xx_get_pfit_config(crtc, pipe_config);
8178
8179         if (INTEL_INFO(dev)->gen >= 4) {
8180                 /* No way to read it out on pipes B and C */
8181                 if (IS_CHERRYVIEW(dev) && crtc->pipe != PIPE_A)
8182                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8183                 else
8184                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8185                 pipe_config->pixel_multiplier =
8186                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8187                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8188                 pipe_config->dpll_hw_state.dpll_md = tmp;
8189         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8190                 tmp = I915_READ(DPLL(crtc->pipe));
8191                 pipe_config->pixel_multiplier =
8192                         ((tmp & SDVO_MULTIPLIER_MASK)
8193                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8194         } else {
8195                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8196                  * port and will be fixed up in the encoder->get_config
8197                  * function. */
8198                 pipe_config->pixel_multiplier = 1;
8199         }
8200         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8201         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8202                 /*
8203                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8204                  * on 830. Filter it out here so that we don't
8205                  * report errors due to that.
8206                  */
8207                 if (IS_I830(dev))
8208                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8209
8210                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8211                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8212         } else {
8213                 /* Mask out read-only status bits. */
8214                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8215                                                      DPLL_PORTC_READY_MASK |
8216                                                      DPLL_PORTB_READY_MASK);
8217         }
8218
8219         if (IS_CHERRYVIEW(dev))
8220                 chv_crtc_clock_get(crtc, pipe_config);
8221         else if (IS_VALLEYVIEW(dev))
8222                 vlv_crtc_clock_get(crtc, pipe_config);
8223         else
8224                 i9xx_crtc_clock_get(crtc, pipe_config);
8225
8226         /*
8227          * Normally the dotclock is filled in by the encoder .get_config()
8228          * but in case the pipe is enabled w/o any ports we need a sane
8229          * default.
8230          */
8231         pipe_config->base.adjusted_mode.crtc_clock =
8232                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8233
8234         ret = true;
8235
8236 out:
8237         intel_display_power_put(dev_priv, power_domain);
8238
8239         return ret;
8240 }
8241
8242 static void ironlake_init_pch_refclk(struct drm_device *dev)
8243 {
8244         struct drm_i915_private *dev_priv = dev->dev_private;
8245         struct intel_encoder *encoder;
8246         u32 val, final;
8247         bool has_lvds = false;
8248         bool has_cpu_edp = false;
8249         bool has_panel = false;
8250         bool has_ck505 = false;
8251         bool can_ssc = false;
8252
8253         /* We need to take the global config into account */
8254         for_each_intel_encoder(dev, encoder) {
8255                 switch (encoder->type) {
8256                 case INTEL_OUTPUT_LVDS:
8257                         has_panel = true;
8258                         has_lvds = true;
8259                         break;
8260                 case INTEL_OUTPUT_EDP:
8261                         has_panel = true;
8262                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8263                                 has_cpu_edp = true;
8264                         break;
8265                 default:
8266                         break;
8267                 }
8268         }
8269
8270         if (HAS_PCH_IBX(dev)) {
8271                 has_ck505 = dev_priv->vbt.display_clock_mode;
8272                 can_ssc = has_ck505;
8273         } else {
8274                 has_ck505 = false;
8275                 can_ssc = true;
8276         }
8277
8278         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8279                       has_panel, has_lvds, has_ck505);
8280
8281         /* Ironlake: try to setup display ref clock before DPLL
8282          * enabling. This is only under driver's control after
8283          * PCH B stepping, previous chipset stepping should be
8284          * ignoring this setting.
8285          */
8286         val = I915_READ(PCH_DREF_CONTROL);
8287
8288         /* As we must carefully and slowly disable/enable each source in turn,
8289          * compute the final state we want first and check if we need to
8290          * make any changes at all.
8291          */
8292         final = val;
8293         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8294         if (has_ck505)
8295                 final |= DREF_NONSPREAD_CK505_ENABLE;
8296         else
8297                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8298
8299         final &= ~DREF_SSC_SOURCE_MASK;
8300         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8301         final &= ~DREF_SSC1_ENABLE;
8302
8303         if (has_panel) {
8304                 final |= DREF_SSC_SOURCE_ENABLE;
8305
8306                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8307                         final |= DREF_SSC1_ENABLE;
8308
8309                 if (has_cpu_edp) {
8310                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8311                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8312                         else
8313                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8314                 } else
8315                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8316         } else {
8317                 final |= DREF_SSC_SOURCE_DISABLE;
8318                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8319         }
8320
8321         if (final == val)
8322                 return;
8323
8324         /* Always enable nonspread source */
8325         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8326
8327         if (has_ck505)
8328                 val |= DREF_NONSPREAD_CK505_ENABLE;
8329         else
8330                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8331
8332         if (has_panel) {
8333                 val &= ~DREF_SSC_SOURCE_MASK;
8334                 val |= DREF_SSC_SOURCE_ENABLE;
8335
8336                 /* SSC must be turned on before enabling the CPU output  */
8337                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8338                         DRM_DEBUG_KMS("Using SSC on panel\n");
8339                         val |= DREF_SSC1_ENABLE;
8340                 } else
8341                         val &= ~DREF_SSC1_ENABLE;
8342
8343                 /* Get SSC going before enabling the outputs */
8344                 I915_WRITE(PCH_DREF_CONTROL, val);
8345                 POSTING_READ(PCH_DREF_CONTROL);
8346                 udelay(200);
8347
8348                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8349
8350                 /* Enable CPU source on CPU attached eDP */
8351                 if (has_cpu_edp) {
8352                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8353                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8354                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8355                         } else
8356                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8357                 } else
8358                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8359
8360                 I915_WRITE(PCH_DREF_CONTROL, val);
8361                 POSTING_READ(PCH_DREF_CONTROL);
8362                 udelay(200);
8363         } else {
8364                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8365
8366                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8367
8368                 /* Turn off CPU output */
8369                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8370
8371                 I915_WRITE(PCH_DREF_CONTROL, val);
8372                 POSTING_READ(PCH_DREF_CONTROL);
8373                 udelay(200);
8374
8375                 /* Turn off the SSC source */
8376                 val &= ~DREF_SSC_SOURCE_MASK;
8377                 val |= DREF_SSC_SOURCE_DISABLE;
8378
8379                 /* Turn off SSC1 */
8380                 val &= ~DREF_SSC1_ENABLE;
8381
8382                 I915_WRITE(PCH_DREF_CONTROL, val);
8383                 POSTING_READ(PCH_DREF_CONTROL);
8384                 udelay(200);
8385         }
8386
8387         BUG_ON(val != final);
8388 }
8389
8390 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8391 {
8392         uint32_t tmp;
8393
8394         tmp = I915_READ(SOUTH_CHICKEN2);
8395         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8396         I915_WRITE(SOUTH_CHICKEN2, tmp);
8397
8398         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8399                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8400                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8401
8402         tmp = I915_READ(SOUTH_CHICKEN2);
8403         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8404         I915_WRITE(SOUTH_CHICKEN2, tmp);
8405
8406         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8407                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8408                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8409 }
8410
8411 /* WaMPhyProgramming:hsw */
8412 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8413 {
8414         uint32_t tmp;
8415
8416         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8417         tmp &= ~(0xFF << 24);
8418         tmp |= (0x12 << 24);
8419         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8420
8421         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8422         tmp |= (1 << 11);
8423         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8424
8425         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8426         tmp |= (1 << 11);
8427         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8428
8429         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8430         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8431         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8432
8433         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8434         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8435         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8436
8437         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8438         tmp &= ~(7 << 13);
8439         tmp |= (5 << 13);
8440         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8441
8442         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8443         tmp &= ~(7 << 13);
8444         tmp |= (5 << 13);
8445         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8446
8447         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8448         tmp &= ~0xFF;
8449         tmp |= 0x1C;
8450         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8451
8452         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8453         tmp &= ~0xFF;
8454         tmp |= 0x1C;
8455         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8456
8457         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8458         tmp &= ~(0xFF << 16);
8459         tmp |= (0x1C << 16);
8460         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8461
8462         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8463         tmp &= ~(0xFF << 16);
8464         tmp |= (0x1C << 16);
8465         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8466
8467         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8468         tmp |= (1 << 27);
8469         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8470
8471         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8472         tmp |= (1 << 27);
8473         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8474
8475         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8476         tmp &= ~(0xF << 28);
8477         tmp |= (4 << 28);
8478         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8479
8480         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8481         tmp &= ~(0xF << 28);
8482         tmp |= (4 << 28);
8483         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8484 }
8485
8486 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8487  * Programming" based on the parameters passed:
8488  * - Sequence to enable CLKOUT_DP
8489  * - Sequence to enable CLKOUT_DP without spread
8490  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8491  */
8492 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8493                                  bool with_fdi)
8494 {
8495         struct drm_i915_private *dev_priv = dev->dev_private;
8496         uint32_t reg, tmp;
8497
8498         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8499                 with_spread = true;
8500         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8501                 with_fdi = false;
8502
8503         mutex_lock(&dev_priv->sb_lock);
8504
8505         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8506         tmp &= ~SBI_SSCCTL_DISABLE;
8507         tmp |= SBI_SSCCTL_PATHALT;
8508         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8509
8510         udelay(24);
8511
8512         if (with_spread) {
8513                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8514                 tmp &= ~SBI_SSCCTL_PATHALT;
8515                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8516
8517                 if (with_fdi) {
8518                         lpt_reset_fdi_mphy(dev_priv);
8519                         lpt_program_fdi_mphy(dev_priv);
8520                 }
8521         }
8522
8523         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8524         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8525         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8526         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8527
8528         mutex_unlock(&dev_priv->sb_lock);
8529 }
8530
8531 /* Sequence to disable CLKOUT_DP */
8532 static void lpt_disable_clkout_dp(struct drm_device *dev)
8533 {
8534         struct drm_i915_private *dev_priv = dev->dev_private;
8535         uint32_t reg, tmp;
8536
8537         mutex_lock(&dev_priv->sb_lock);
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         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8545         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8546                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8547                         tmp |= SBI_SSCCTL_PATHALT;
8548                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8549                         udelay(32);
8550                 }
8551                 tmp |= SBI_SSCCTL_DISABLE;
8552                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8553         }
8554
8555         mutex_unlock(&dev_priv->sb_lock);
8556 }
8557
8558 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8559
8560 static const uint16_t sscdivintphase[] = {
8561         [BEND_IDX( 50)] = 0x3B23,
8562         [BEND_IDX( 45)] = 0x3B23,
8563         [BEND_IDX( 40)] = 0x3C23,
8564         [BEND_IDX( 35)] = 0x3C23,
8565         [BEND_IDX( 30)] = 0x3D23,
8566         [BEND_IDX( 25)] = 0x3D23,
8567         [BEND_IDX( 20)] = 0x3E23,
8568         [BEND_IDX( 15)] = 0x3E23,
8569         [BEND_IDX( 10)] = 0x3F23,
8570         [BEND_IDX(  5)] = 0x3F23,
8571         [BEND_IDX(  0)] = 0x0025,
8572         [BEND_IDX( -5)] = 0x0025,
8573         [BEND_IDX(-10)] = 0x0125,
8574         [BEND_IDX(-15)] = 0x0125,
8575         [BEND_IDX(-20)] = 0x0225,
8576         [BEND_IDX(-25)] = 0x0225,
8577         [BEND_IDX(-30)] = 0x0325,
8578         [BEND_IDX(-35)] = 0x0325,
8579         [BEND_IDX(-40)] = 0x0425,
8580         [BEND_IDX(-45)] = 0x0425,
8581         [BEND_IDX(-50)] = 0x0525,
8582 };
8583
8584 /*
8585  * Bend CLKOUT_DP
8586  * steps -50 to 50 inclusive, in steps of 5
8587  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8588  * change in clock period = -(steps / 10) * 5.787 ps
8589  */
8590 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8591 {
8592         uint32_t tmp;
8593         int idx = BEND_IDX(steps);
8594
8595         if (WARN_ON(steps % 5 != 0))
8596                 return;
8597
8598         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8599                 return;
8600
8601         mutex_lock(&dev_priv->sb_lock);
8602
8603         if (steps % 10 != 0)
8604                 tmp = 0xAAAAAAAB;
8605         else
8606                 tmp = 0x00000000;
8607         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8608
8609         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8610         tmp &= 0xffff0000;
8611         tmp |= sscdivintphase[idx];
8612         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8613
8614         mutex_unlock(&dev_priv->sb_lock);
8615 }
8616
8617 #undef BEND_IDX
8618
8619 static void lpt_init_pch_refclk(struct drm_device *dev)
8620 {
8621         struct intel_encoder *encoder;
8622         bool has_vga = false;
8623
8624         for_each_intel_encoder(dev, encoder) {
8625                 switch (encoder->type) {
8626                 case INTEL_OUTPUT_ANALOG:
8627                         has_vga = true;
8628                         break;
8629                 default:
8630                         break;
8631                 }
8632         }
8633
8634         if (has_vga) {
8635                 lpt_bend_clkout_dp(to_i915(dev), 0);
8636                 lpt_enable_clkout_dp(dev, true, true);
8637         } else {
8638                 lpt_disable_clkout_dp(dev);
8639         }
8640 }
8641
8642 /*
8643  * Initialize reference clocks when the driver loads
8644  */
8645 void intel_init_pch_refclk(struct drm_device *dev)
8646 {
8647         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8648                 ironlake_init_pch_refclk(dev);
8649         else if (HAS_PCH_LPT(dev))
8650                 lpt_init_pch_refclk(dev);
8651 }
8652
8653 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8654 {
8655         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8656         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8657         int pipe = intel_crtc->pipe;
8658         uint32_t val;
8659
8660         val = 0;
8661
8662         switch (intel_crtc->config->pipe_bpp) {
8663         case 18:
8664                 val |= PIPECONF_6BPC;
8665                 break;
8666         case 24:
8667                 val |= PIPECONF_8BPC;
8668                 break;
8669         case 30:
8670                 val |= PIPECONF_10BPC;
8671                 break;
8672         case 36:
8673                 val |= PIPECONF_12BPC;
8674                 break;
8675         default:
8676                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8677                 BUG();
8678         }
8679
8680         if (intel_crtc->config->dither)
8681                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8682
8683         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8684                 val |= PIPECONF_INTERLACED_ILK;
8685         else
8686                 val |= PIPECONF_PROGRESSIVE;
8687
8688         if (intel_crtc->config->limited_color_range)
8689                 val |= PIPECONF_COLOR_RANGE_SELECT;
8690
8691         I915_WRITE(PIPECONF(pipe), val);
8692         POSTING_READ(PIPECONF(pipe));
8693 }
8694
8695 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8696 {
8697         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8698         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8699         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8700         u32 val = 0;
8701
8702         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8703                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8704
8705         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8706                 val |= PIPECONF_INTERLACED_ILK;
8707         else
8708                 val |= PIPECONF_PROGRESSIVE;
8709
8710         I915_WRITE(PIPECONF(cpu_transcoder), val);
8711         POSTING_READ(PIPECONF(cpu_transcoder));
8712 }
8713
8714 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8715 {
8716         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8717         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8718
8719         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8720                 u32 val = 0;
8721
8722                 switch (intel_crtc->config->pipe_bpp) {
8723                 case 18:
8724                         val |= PIPEMISC_DITHER_6_BPC;
8725                         break;
8726                 case 24:
8727                         val |= PIPEMISC_DITHER_8_BPC;
8728                         break;
8729                 case 30:
8730                         val |= PIPEMISC_DITHER_10_BPC;
8731                         break;
8732                 case 36:
8733                         val |= PIPEMISC_DITHER_12_BPC;
8734                         break;
8735                 default:
8736                         /* Case prevented by pipe_config_set_bpp. */
8737                         BUG();
8738                 }
8739
8740                 if (intel_crtc->config->dither)
8741                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8742
8743                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8744         }
8745 }
8746
8747 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8748 {
8749         /*
8750          * Account for spread spectrum to avoid
8751          * oversubscribing the link. Max center spread
8752          * is 2.5%; use 5% for safety's sake.
8753          */
8754         u32 bps = target_clock * bpp * 21 / 20;
8755         return DIV_ROUND_UP(bps, link_bw * 8);
8756 }
8757
8758 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8759 {
8760         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8761 }
8762
8763 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8764                                   struct intel_crtc_state *crtc_state,
8765                                   intel_clock_t *reduced_clock)
8766 {
8767         struct drm_crtc *crtc = &intel_crtc->base;
8768         struct drm_device *dev = crtc->dev;
8769         struct drm_i915_private *dev_priv = dev->dev_private;
8770         struct drm_atomic_state *state = crtc_state->base.state;
8771         struct drm_connector *connector;
8772         struct drm_connector_state *connector_state;
8773         struct intel_encoder *encoder;
8774         u32 dpll, fp, fp2;
8775         int factor, i;
8776         bool is_lvds = false, is_sdvo = false;
8777
8778         for_each_connector_in_state(state, connector, connector_state, i) {
8779                 if (connector_state->crtc != crtc_state->base.crtc)
8780                         continue;
8781
8782                 encoder = to_intel_encoder(connector_state->best_encoder);
8783
8784                 switch (encoder->type) {
8785                 case INTEL_OUTPUT_LVDS:
8786                         is_lvds = true;
8787                         break;
8788                 case INTEL_OUTPUT_SDVO:
8789                 case INTEL_OUTPUT_HDMI:
8790                         is_sdvo = true;
8791                         break;
8792                 default:
8793                         break;
8794                 }
8795         }
8796
8797         /* Enable autotuning of the PLL clock (if permissible) */
8798         factor = 21;
8799         if (is_lvds) {
8800                 if ((intel_panel_use_ssc(dev_priv) &&
8801                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8802                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8803                         factor = 25;
8804         } else if (crtc_state->sdvo_tv_clock)
8805                 factor = 20;
8806
8807         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8808
8809         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8810                 fp |= FP_CB_TUNE;
8811
8812         if (reduced_clock) {
8813                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8814
8815                 if (reduced_clock->m < factor * reduced_clock->n)
8816                         fp2 |= FP_CB_TUNE;
8817         } else {
8818                 fp2 = fp;
8819         }
8820
8821         dpll = 0;
8822
8823         if (is_lvds)
8824                 dpll |= DPLLB_MODE_LVDS;
8825         else
8826                 dpll |= DPLLB_MODE_DAC_SERIAL;
8827
8828         dpll |= (crtc_state->pixel_multiplier - 1)
8829                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8830
8831         if (is_sdvo)
8832                 dpll |= DPLL_SDVO_HIGH_SPEED;
8833         if (crtc_state->has_dp_encoder)
8834                 dpll |= DPLL_SDVO_HIGH_SPEED;
8835
8836         /* compute bitmask from p1 value */
8837         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8838         /* also FPA1 */
8839         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8840
8841         switch (crtc_state->dpll.p2) {
8842         case 5:
8843                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8844                 break;
8845         case 7:
8846                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8847                 break;
8848         case 10:
8849                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8850                 break;
8851         case 14:
8852                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8853                 break;
8854         }
8855
8856         if (is_lvds && intel_panel_use_ssc(dev_priv))
8857                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8858         else
8859                 dpll |= PLL_REF_INPUT_DREFCLK;
8860
8861         dpll |= DPLL_VCO_ENABLE;
8862
8863         crtc_state->dpll_hw_state.dpll = dpll;
8864         crtc_state->dpll_hw_state.fp0 = fp;
8865         crtc_state->dpll_hw_state.fp1 = fp2;
8866 }
8867
8868 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8869                                        struct intel_crtc_state *crtc_state)
8870 {
8871         struct drm_device *dev = crtc->base.dev;
8872         struct drm_i915_private *dev_priv = dev->dev_private;
8873         intel_clock_t reduced_clock;
8874         bool has_reduced_clock = false;
8875         struct intel_shared_dpll *pll;
8876         const intel_limit_t *limit;
8877         int refclk = 120000;
8878
8879         memset(&crtc_state->dpll_hw_state, 0,
8880                sizeof(crtc_state->dpll_hw_state));
8881
8882         crtc->lowfreq_avail = false;
8883
8884         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8885         if (!crtc_state->has_pch_encoder)
8886                 return 0;
8887
8888         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8889                 if (intel_panel_use_ssc(dev_priv)) {
8890                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8891                                       dev_priv->vbt.lvds_ssc_freq);
8892                         refclk = dev_priv->vbt.lvds_ssc_freq;
8893                 }
8894
8895                 if (intel_is_dual_link_lvds(dev)) {
8896                         if (refclk == 100000)
8897                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8898                         else
8899                                 limit = &intel_limits_ironlake_dual_lvds;
8900                 } else {
8901                         if (refclk == 100000)
8902                                 limit = &intel_limits_ironlake_single_lvds_100m;
8903                         else
8904                                 limit = &intel_limits_ironlake_single_lvds;
8905                 }
8906         } else {
8907                 limit = &intel_limits_ironlake_dac;
8908         }
8909
8910         if (!crtc_state->clock_set &&
8911             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8912                                 refclk, NULL, &crtc_state->dpll)) {
8913                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8914                 return -EINVAL;
8915         }
8916
8917         ironlake_compute_dpll(crtc, crtc_state,
8918                               has_reduced_clock ? &reduced_clock : NULL);
8919
8920         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
8921         if (pll == NULL) {
8922                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8923                                  pipe_name(crtc->pipe));
8924                 return -EINVAL;
8925         }
8926
8927         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8928             has_reduced_clock)
8929                 crtc->lowfreq_avail = true;
8930
8931         return 0;
8932 }
8933
8934 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8935                                          struct intel_link_m_n *m_n)
8936 {
8937         struct drm_device *dev = crtc->base.dev;
8938         struct drm_i915_private *dev_priv = dev->dev_private;
8939         enum pipe pipe = crtc->pipe;
8940
8941         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8942         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8943         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8944                 & ~TU_SIZE_MASK;
8945         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8946         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8947                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8948 }
8949
8950 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8951                                          enum transcoder transcoder,
8952                                          struct intel_link_m_n *m_n,
8953                                          struct intel_link_m_n *m2_n2)
8954 {
8955         struct drm_device *dev = crtc->base.dev;
8956         struct drm_i915_private *dev_priv = dev->dev_private;
8957         enum pipe pipe = crtc->pipe;
8958
8959         if (INTEL_INFO(dev)->gen >= 5) {
8960                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8961                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8962                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8963                         & ~TU_SIZE_MASK;
8964                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8965                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8966                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8967                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8968                  * gen < 8) and if DRRS is supported (to make sure the
8969                  * registers are not unnecessarily read).
8970                  */
8971                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8972                         crtc->config->has_drrs) {
8973                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8974                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8975                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8976                                         & ~TU_SIZE_MASK;
8977                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8978                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8979                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8980                 }
8981         } else {
8982                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8983                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8984                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8985                         & ~TU_SIZE_MASK;
8986                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8987                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8988                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8989         }
8990 }
8991
8992 void intel_dp_get_m_n(struct intel_crtc *crtc,
8993                       struct intel_crtc_state *pipe_config)
8994 {
8995         if (pipe_config->has_pch_encoder)
8996                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8997         else
8998                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8999                                              &pipe_config->dp_m_n,
9000                                              &pipe_config->dp_m2_n2);
9001 }
9002
9003 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
9004                                         struct intel_crtc_state *pipe_config)
9005 {
9006         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9007                                      &pipe_config->fdi_m_n, NULL);
9008 }
9009
9010 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9011                                     struct intel_crtc_state *pipe_config)
9012 {
9013         struct drm_device *dev = crtc->base.dev;
9014         struct drm_i915_private *dev_priv = dev->dev_private;
9015         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9016         uint32_t ps_ctrl = 0;
9017         int id = -1;
9018         int i;
9019
9020         /* find scaler attached to this pipe */
9021         for (i = 0; i < crtc->num_scalers; i++) {
9022                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9023                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9024                         id = i;
9025                         pipe_config->pch_pfit.enabled = true;
9026                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9027                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9028                         break;
9029                 }
9030         }
9031
9032         scaler_state->scaler_id = id;
9033         if (id >= 0) {
9034                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9035         } else {
9036                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9037         }
9038 }
9039
9040 static void
9041 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9042                                  struct intel_initial_plane_config *plane_config)
9043 {
9044         struct drm_device *dev = crtc->base.dev;
9045         struct drm_i915_private *dev_priv = dev->dev_private;
9046         u32 val, base, offset, stride_mult, tiling;
9047         int pipe = crtc->pipe;
9048         int fourcc, pixel_format;
9049         unsigned int aligned_height;
9050         struct drm_framebuffer *fb;
9051         struct intel_framebuffer *intel_fb;
9052
9053         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9054         if (!intel_fb) {
9055                 DRM_DEBUG_KMS("failed to alloc fb\n");
9056                 return;
9057         }
9058
9059         fb = &intel_fb->base;
9060
9061         val = I915_READ(PLANE_CTL(pipe, 0));
9062         if (!(val & PLANE_CTL_ENABLE))
9063                 goto error;
9064
9065         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9066         fourcc = skl_format_to_fourcc(pixel_format,
9067                                       val & PLANE_CTL_ORDER_RGBX,
9068                                       val & PLANE_CTL_ALPHA_MASK);
9069         fb->pixel_format = fourcc;
9070         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9071
9072         tiling = val & PLANE_CTL_TILED_MASK;
9073         switch (tiling) {
9074         case PLANE_CTL_TILED_LINEAR:
9075                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9076                 break;
9077         case PLANE_CTL_TILED_X:
9078                 plane_config->tiling = I915_TILING_X;
9079                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9080                 break;
9081         case PLANE_CTL_TILED_Y:
9082                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9083                 break;
9084         case PLANE_CTL_TILED_YF:
9085                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9086                 break;
9087         default:
9088                 MISSING_CASE(tiling);
9089                 goto error;
9090         }
9091
9092         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9093         plane_config->base = base;
9094
9095         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9096
9097         val = I915_READ(PLANE_SIZE(pipe, 0));
9098         fb->height = ((val >> 16) & 0xfff) + 1;
9099         fb->width = ((val >> 0) & 0x1fff) + 1;
9100
9101         val = I915_READ(PLANE_STRIDE(pipe, 0));
9102         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9103                                                 fb->pixel_format);
9104         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9105
9106         aligned_height = intel_fb_align_height(dev, fb->height,
9107                                                fb->pixel_format,
9108                                                fb->modifier[0]);
9109
9110         plane_config->size = fb->pitches[0] * aligned_height;
9111
9112         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9113                       pipe_name(pipe), fb->width, fb->height,
9114                       fb->bits_per_pixel, base, fb->pitches[0],
9115                       plane_config->size);
9116
9117         plane_config->fb = intel_fb;
9118         return;
9119
9120 error:
9121         kfree(fb);
9122 }
9123
9124 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9125                                      struct intel_crtc_state *pipe_config)
9126 {
9127         struct drm_device *dev = crtc->base.dev;
9128         struct drm_i915_private *dev_priv = dev->dev_private;
9129         uint32_t tmp;
9130
9131         tmp = I915_READ(PF_CTL(crtc->pipe));
9132
9133         if (tmp & PF_ENABLE) {
9134                 pipe_config->pch_pfit.enabled = true;
9135                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9136                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9137
9138                 /* We currently do not free assignements of panel fitters on
9139                  * ivb/hsw (since we don't use the higher upscaling modes which
9140                  * differentiates them) so just WARN about this case for now. */
9141                 if (IS_GEN7(dev)) {
9142                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9143                                 PF_PIPE_SEL_IVB(crtc->pipe));
9144                 }
9145         }
9146 }
9147
9148 static void
9149 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9150                                   struct intel_initial_plane_config *plane_config)
9151 {
9152         struct drm_device *dev = crtc->base.dev;
9153         struct drm_i915_private *dev_priv = dev->dev_private;
9154         u32 val, base, offset;
9155         int pipe = crtc->pipe;
9156         int fourcc, pixel_format;
9157         unsigned int aligned_height;
9158         struct drm_framebuffer *fb;
9159         struct intel_framebuffer *intel_fb;
9160
9161         val = I915_READ(DSPCNTR(pipe));
9162         if (!(val & DISPLAY_PLANE_ENABLE))
9163                 return;
9164
9165         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9166         if (!intel_fb) {
9167                 DRM_DEBUG_KMS("failed to alloc fb\n");
9168                 return;
9169         }
9170
9171         fb = &intel_fb->base;
9172
9173         if (INTEL_INFO(dev)->gen >= 4) {
9174                 if (val & DISPPLANE_TILED) {
9175                         plane_config->tiling = I915_TILING_X;
9176                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9177                 }
9178         }
9179
9180         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9181         fourcc = i9xx_format_to_fourcc(pixel_format);
9182         fb->pixel_format = fourcc;
9183         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9184
9185         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9186         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9187                 offset = I915_READ(DSPOFFSET(pipe));
9188         } else {
9189                 if (plane_config->tiling)
9190                         offset = I915_READ(DSPTILEOFF(pipe));
9191                 else
9192                         offset = I915_READ(DSPLINOFF(pipe));
9193         }
9194         plane_config->base = base;
9195
9196         val = I915_READ(PIPESRC(pipe));
9197         fb->width = ((val >> 16) & 0xfff) + 1;
9198         fb->height = ((val >> 0) & 0xfff) + 1;
9199
9200         val = I915_READ(DSPSTRIDE(pipe));
9201         fb->pitches[0] = val & 0xffffffc0;
9202
9203         aligned_height = intel_fb_align_height(dev, fb->height,
9204                                                fb->pixel_format,
9205                                                fb->modifier[0]);
9206
9207         plane_config->size = fb->pitches[0] * aligned_height;
9208
9209         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9210                       pipe_name(pipe), fb->width, fb->height,
9211                       fb->bits_per_pixel, base, fb->pitches[0],
9212                       plane_config->size);
9213
9214         plane_config->fb = intel_fb;
9215 }
9216
9217 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9218                                      struct intel_crtc_state *pipe_config)
9219 {
9220         struct drm_device *dev = crtc->base.dev;
9221         struct drm_i915_private *dev_priv = dev->dev_private;
9222         enum intel_display_power_domain power_domain;
9223         uint32_t tmp;
9224         bool ret;
9225
9226         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9227         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9228                 return false;
9229
9230         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9231         pipe_config->shared_dpll = NULL;
9232
9233         ret = false;
9234         tmp = I915_READ(PIPECONF(crtc->pipe));
9235         if (!(tmp & PIPECONF_ENABLE))
9236                 goto out;
9237
9238         switch (tmp & PIPECONF_BPC_MASK) {
9239         case PIPECONF_6BPC:
9240                 pipe_config->pipe_bpp = 18;
9241                 break;
9242         case PIPECONF_8BPC:
9243                 pipe_config->pipe_bpp = 24;
9244                 break;
9245         case PIPECONF_10BPC:
9246                 pipe_config->pipe_bpp = 30;
9247                 break;
9248         case PIPECONF_12BPC:
9249                 pipe_config->pipe_bpp = 36;
9250                 break;
9251         default:
9252                 break;
9253         }
9254
9255         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9256                 pipe_config->limited_color_range = true;
9257
9258         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9259                 struct intel_shared_dpll *pll;
9260                 enum intel_dpll_id pll_id;
9261
9262                 pipe_config->has_pch_encoder = true;
9263
9264                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9265                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9266                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9267
9268                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9269
9270                 if (HAS_PCH_IBX(dev_priv->dev)) {
9271                         pll_id = (enum intel_dpll_id) crtc->pipe;
9272                 } else {
9273                         tmp = I915_READ(PCH_DPLL_SEL);
9274                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9275                                 pll_id = DPLL_ID_PCH_PLL_B;
9276                         else
9277                                 pll_id= DPLL_ID_PCH_PLL_A;
9278                 }
9279
9280                 pipe_config->shared_dpll =
9281                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9282                 pll = pipe_config->shared_dpll;
9283
9284                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9285                                                  &pipe_config->dpll_hw_state));
9286
9287                 tmp = pipe_config->dpll_hw_state.dpll;
9288                 pipe_config->pixel_multiplier =
9289                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9290                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9291
9292                 ironlake_pch_clock_get(crtc, pipe_config);
9293         } else {
9294                 pipe_config->pixel_multiplier = 1;
9295         }
9296
9297         intel_get_pipe_timings(crtc, pipe_config);
9298         intel_get_pipe_src_size(crtc, pipe_config);
9299
9300         ironlake_get_pfit_config(crtc, pipe_config);
9301
9302         ret = true;
9303
9304 out:
9305         intel_display_power_put(dev_priv, power_domain);
9306
9307         return ret;
9308 }
9309
9310 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9311 {
9312         struct drm_device *dev = dev_priv->dev;
9313         struct intel_crtc *crtc;
9314
9315         for_each_intel_crtc(dev, crtc)
9316                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9317                      pipe_name(crtc->pipe));
9318
9319         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9320         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9321         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9322         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9323         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9324         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9325              "CPU PWM1 enabled\n");
9326         if (IS_HASWELL(dev))
9327                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9328                      "CPU PWM2 enabled\n");
9329         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9330              "PCH PWM1 enabled\n");
9331         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9332              "Utility pin enabled\n");
9333         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9334
9335         /*
9336          * In theory we can still leave IRQs enabled, as long as only the HPD
9337          * interrupts remain enabled. We used to check for that, but since it's
9338          * gen-specific and since we only disable LCPLL after we fully disable
9339          * the interrupts, the check below should be enough.
9340          */
9341         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9342 }
9343
9344 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9345 {
9346         struct drm_device *dev = dev_priv->dev;
9347
9348         if (IS_HASWELL(dev))
9349                 return I915_READ(D_COMP_HSW);
9350         else
9351                 return I915_READ(D_COMP_BDW);
9352 }
9353
9354 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9355 {
9356         struct drm_device *dev = dev_priv->dev;
9357
9358         if (IS_HASWELL(dev)) {
9359                 mutex_lock(&dev_priv->rps.hw_lock);
9360                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9361                                             val))
9362                         DRM_ERROR("Failed to write to D_COMP\n");
9363                 mutex_unlock(&dev_priv->rps.hw_lock);
9364         } else {
9365                 I915_WRITE(D_COMP_BDW, val);
9366                 POSTING_READ(D_COMP_BDW);
9367         }
9368 }
9369
9370 /*
9371  * This function implements pieces of two sequences from BSpec:
9372  * - Sequence for display software to disable LCPLL
9373  * - Sequence for display software to allow package C8+
9374  * The steps implemented here are just the steps that actually touch the LCPLL
9375  * register. Callers should take care of disabling all the display engine
9376  * functions, doing the mode unset, fixing interrupts, etc.
9377  */
9378 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9379                               bool switch_to_fclk, bool allow_power_down)
9380 {
9381         uint32_t val;
9382
9383         assert_can_disable_lcpll(dev_priv);
9384
9385         val = I915_READ(LCPLL_CTL);
9386
9387         if (switch_to_fclk) {
9388                 val |= LCPLL_CD_SOURCE_FCLK;
9389                 I915_WRITE(LCPLL_CTL, val);
9390
9391                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9392                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9393                         DRM_ERROR("Switching to FCLK failed\n");
9394
9395                 val = I915_READ(LCPLL_CTL);
9396         }
9397
9398         val |= LCPLL_PLL_DISABLE;
9399         I915_WRITE(LCPLL_CTL, val);
9400         POSTING_READ(LCPLL_CTL);
9401
9402         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9403                 DRM_ERROR("LCPLL still locked\n");
9404
9405         val = hsw_read_dcomp(dev_priv);
9406         val |= D_COMP_COMP_DISABLE;
9407         hsw_write_dcomp(dev_priv, val);
9408         ndelay(100);
9409
9410         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9411                      1))
9412                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9413
9414         if (allow_power_down) {
9415                 val = I915_READ(LCPLL_CTL);
9416                 val |= LCPLL_POWER_DOWN_ALLOW;
9417                 I915_WRITE(LCPLL_CTL, val);
9418                 POSTING_READ(LCPLL_CTL);
9419         }
9420 }
9421
9422 /*
9423  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9424  * source.
9425  */
9426 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9427 {
9428         uint32_t val;
9429
9430         val = I915_READ(LCPLL_CTL);
9431
9432         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9433                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9434                 return;
9435
9436         /*
9437          * Make sure we're not on PC8 state before disabling PC8, otherwise
9438          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9439          */
9440         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9441
9442         if (val & LCPLL_POWER_DOWN_ALLOW) {
9443                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9444                 I915_WRITE(LCPLL_CTL, val);
9445                 POSTING_READ(LCPLL_CTL);
9446         }
9447
9448         val = hsw_read_dcomp(dev_priv);
9449         val |= D_COMP_COMP_FORCE;
9450         val &= ~D_COMP_COMP_DISABLE;
9451         hsw_write_dcomp(dev_priv, val);
9452
9453         val = I915_READ(LCPLL_CTL);
9454         val &= ~LCPLL_PLL_DISABLE;
9455         I915_WRITE(LCPLL_CTL, val);
9456
9457         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9458                 DRM_ERROR("LCPLL not locked yet\n");
9459
9460         if (val & LCPLL_CD_SOURCE_FCLK) {
9461                 val = I915_READ(LCPLL_CTL);
9462                 val &= ~LCPLL_CD_SOURCE_FCLK;
9463                 I915_WRITE(LCPLL_CTL, val);
9464
9465                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9466                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9467                         DRM_ERROR("Switching back to LCPLL failed\n");
9468         }
9469
9470         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9471         intel_update_cdclk(dev_priv->dev);
9472 }
9473
9474 /*
9475  * Package states C8 and deeper are really deep PC states that can only be
9476  * reached when all the devices on the system allow it, so even if the graphics
9477  * device allows PC8+, it doesn't mean the system will actually get to these
9478  * states. Our driver only allows PC8+ when going into runtime PM.
9479  *
9480  * The requirements for PC8+ are that all the outputs are disabled, the power
9481  * well is disabled and most interrupts are disabled, and these are also
9482  * requirements for runtime PM. When these conditions are met, we manually do
9483  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9484  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9485  * hang the machine.
9486  *
9487  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9488  * the state of some registers, so when we come back from PC8+ we need to
9489  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9490  * need to take care of the registers kept by RC6. Notice that this happens even
9491  * if we don't put the device in PCI D3 state (which is what currently happens
9492  * because of the runtime PM support).
9493  *
9494  * For more, read "Display Sequences for Package C8" on the hardware
9495  * documentation.
9496  */
9497 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9498 {
9499         struct drm_device *dev = dev_priv->dev;
9500         uint32_t val;
9501
9502         DRM_DEBUG_KMS("Enabling package C8+\n");
9503
9504         if (HAS_PCH_LPT_LP(dev)) {
9505                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9506                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9507                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9508         }
9509
9510         lpt_disable_clkout_dp(dev);
9511         hsw_disable_lcpll(dev_priv, true, true);
9512 }
9513
9514 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9515 {
9516         struct drm_device *dev = dev_priv->dev;
9517         uint32_t val;
9518
9519         DRM_DEBUG_KMS("Disabling package C8+\n");
9520
9521         hsw_restore_lcpll(dev_priv);
9522         lpt_init_pch_refclk(dev);
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
9531 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9532 {
9533         struct drm_device *dev = old_state->dev;
9534         struct intel_atomic_state *old_intel_state =
9535                 to_intel_atomic_state(old_state);
9536         unsigned int req_cdclk = old_intel_state->dev_cdclk;
9537
9538         broxton_set_cdclk(dev, req_cdclk);
9539 }
9540
9541 /* compute the max rate for new configuration */
9542 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9543 {
9544         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9545         struct drm_i915_private *dev_priv = state->dev->dev_private;
9546         struct drm_crtc *crtc;
9547         struct drm_crtc_state *cstate;
9548         struct intel_crtc_state *crtc_state;
9549         unsigned max_pixel_rate = 0, i;
9550         enum pipe pipe;
9551
9552         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
9553                sizeof(intel_state->min_pixclk));
9554
9555         for_each_crtc_in_state(state, crtc, cstate, i) {
9556                 int pixel_rate;
9557
9558                 crtc_state = to_intel_crtc_state(cstate);
9559                 if (!crtc_state->base.enable) {
9560                         intel_state->min_pixclk[i] = 0;
9561                         continue;
9562                 }
9563
9564                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9565
9566                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9567                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
9568                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9569
9570                 intel_state->min_pixclk[i] = pixel_rate;
9571         }
9572
9573         for_each_pipe(dev_priv, pipe)
9574                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
9575
9576         return max_pixel_rate;
9577 }
9578
9579 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9580 {
9581         struct drm_i915_private *dev_priv = dev->dev_private;
9582         uint32_t val, data;
9583         int ret;
9584
9585         if (WARN((I915_READ(LCPLL_CTL) &
9586                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9587                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9588                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9589                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9590                  "trying to change cdclk frequency with cdclk not enabled\n"))
9591                 return;
9592
9593         mutex_lock(&dev_priv->rps.hw_lock);
9594         ret = sandybridge_pcode_write(dev_priv,
9595                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9596         mutex_unlock(&dev_priv->rps.hw_lock);
9597         if (ret) {
9598                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9599                 return;
9600         }
9601
9602         val = I915_READ(LCPLL_CTL);
9603         val |= LCPLL_CD_SOURCE_FCLK;
9604         I915_WRITE(LCPLL_CTL, val);
9605
9606         if (wait_for_us(I915_READ(LCPLL_CTL) &
9607                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
9608                 DRM_ERROR("Switching to FCLK failed\n");
9609
9610         val = I915_READ(LCPLL_CTL);
9611         val &= ~LCPLL_CLK_FREQ_MASK;
9612
9613         switch (cdclk) {
9614         case 450000:
9615                 val |= LCPLL_CLK_FREQ_450;
9616                 data = 0;
9617                 break;
9618         case 540000:
9619                 val |= LCPLL_CLK_FREQ_54O_BDW;
9620                 data = 1;
9621                 break;
9622         case 337500:
9623                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9624                 data = 2;
9625                 break;
9626         case 675000:
9627                 val |= LCPLL_CLK_FREQ_675_BDW;
9628                 data = 3;
9629                 break;
9630         default:
9631                 WARN(1, "invalid cdclk frequency\n");
9632                 return;
9633         }
9634
9635         I915_WRITE(LCPLL_CTL, val);
9636
9637         val = I915_READ(LCPLL_CTL);
9638         val &= ~LCPLL_CD_SOURCE_FCLK;
9639         I915_WRITE(LCPLL_CTL, val);
9640
9641         if (wait_for_us((I915_READ(LCPLL_CTL) &
9642                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9643                 DRM_ERROR("Switching back to LCPLL failed\n");
9644
9645         mutex_lock(&dev_priv->rps.hw_lock);
9646         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9647         mutex_unlock(&dev_priv->rps.hw_lock);
9648
9649         intel_update_cdclk(dev);
9650
9651         WARN(cdclk != dev_priv->cdclk_freq,
9652              "cdclk requested %d kHz but got %d kHz\n",
9653              cdclk, dev_priv->cdclk_freq);
9654 }
9655
9656 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9657 {
9658         struct drm_i915_private *dev_priv = to_i915(state->dev);
9659         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9660         int max_pixclk = ilk_max_pixel_rate(state);
9661         int cdclk;
9662
9663         /*
9664          * FIXME should also account for plane ratio
9665          * once 64bpp pixel formats are supported.
9666          */
9667         if (max_pixclk > 540000)
9668                 cdclk = 675000;
9669         else if (max_pixclk > 450000)
9670                 cdclk = 540000;
9671         else if (max_pixclk > 337500)
9672                 cdclk = 450000;
9673         else
9674                 cdclk = 337500;
9675
9676         if (cdclk > dev_priv->max_cdclk_freq) {
9677                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9678                               cdclk, dev_priv->max_cdclk_freq);
9679                 return -EINVAL;
9680         }
9681
9682         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9683         if (!intel_state->active_crtcs)
9684                 intel_state->dev_cdclk = 337500;
9685
9686         return 0;
9687 }
9688
9689 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9690 {
9691         struct drm_device *dev = old_state->dev;
9692         struct intel_atomic_state *old_intel_state =
9693                 to_intel_atomic_state(old_state);
9694         unsigned req_cdclk = old_intel_state->dev_cdclk;
9695
9696         broadwell_set_cdclk(dev, req_cdclk);
9697 }
9698
9699 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9700                                       struct intel_crtc_state *crtc_state)
9701 {
9702         struct intel_encoder *intel_encoder =
9703                 intel_ddi_get_crtc_new_encoder(crtc_state);
9704
9705         if (intel_encoder->type != INTEL_OUTPUT_DSI) {
9706                 if (!intel_ddi_pll_select(crtc, crtc_state))
9707                         return -EINVAL;
9708         }
9709
9710         crtc->lowfreq_avail = false;
9711
9712         return 0;
9713 }
9714
9715 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9716                                 enum port port,
9717                                 struct intel_crtc_state *pipe_config)
9718 {
9719         enum intel_dpll_id id;
9720
9721         switch (port) {
9722         case PORT_A:
9723                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9724                 id = DPLL_ID_SKL_DPLL0;
9725                 break;
9726         case PORT_B:
9727                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9728                 id = DPLL_ID_SKL_DPLL1;
9729                 break;
9730         case PORT_C:
9731                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9732                 id = DPLL_ID_SKL_DPLL2;
9733                 break;
9734         default:
9735                 DRM_ERROR("Incorrect port type\n");
9736                 return;
9737         }
9738
9739         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9740 }
9741
9742 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9743                                 enum port port,
9744                                 struct intel_crtc_state *pipe_config)
9745 {
9746         enum intel_dpll_id id;
9747         u32 temp;
9748
9749         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9750         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9751
9752         switch (pipe_config->ddi_pll_sel) {
9753         case SKL_DPLL0:
9754                 id = DPLL_ID_SKL_DPLL0;
9755                 break;
9756         case SKL_DPLL1:
9757                 id = DPLL_ID_SKL_DPLL1;
9758                 break;
9759         case SKL_DPLL2:
9760                 id = DPLL_ID_SKL_DPLL2;
9761                 break;
9762         case SKL_DPLL3:
9763                 id = DPLL_ID_SKL_DPLL3;
9764                 break;
9765         default:
9766                 MISSING_CASE(pipe_config->ddi_pll_sel);
9767                 return;
9768         }
9769
9770         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9771 }
9772
9773 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9774                                 enum port port,
9775                                 struct intel_crtc_state *pipe_config)
9776 {
9777         enum intel_dpll_id id;
9778
9779         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9780
9781         switch (pipe_config->ddi_pll_sel) {
9782         case PORT_CLK_SEL_WRPLL1:
9783                 id = DPLL_ID_WRPLL1;
9784                 break;
9785         case PORT_CLK_SEL_WRPLL2:
9786                 id = DPLL_ID_WRPLL2;
9787                 break;
9788         case PORT_CLK_SEL_SPLL:
9789                 id = DPLL_ID_SPLL;
9790                 break;
9791         case PORT_CLK_SEL_LCPLL_810:
9792                 id = DPLL_ID_LCPLL_810;
9793                 break;
9794         case PORT_CLK_SEL_LCPLL_1350:
9795                 id = DPLL_ID_LCPLL_1350;
9796                 break;
9797         case PORT_CLK_SEL_LCPLL_2700:
9798                 id = DPLL_ID_LCPLL_2700;
9799                 break;
9800         default:
9801                 MISSING_CASE(pipe_config->ddi_pll_sel);
9802                 /* fall through */
9803         case PORT_CLK_SEL_NONE:
9804                 return;
9805         }
9806
9807         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9808 }
9809
9810 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9811                                      struct intel_crtc_state *pipe_config,
9812                                      unsigned long *power_domain_mask)
9813 {
9814         struct drm_device *dev = crtc->base.dev;
9815         struct drm_i915_private *dev_priv = dev->dev_private;
9816         enum intel_display_power_domain power_domain;
9817         u32 tmp;
9818
9819         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9820
9821         /*
9822          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9823          * consistency and less surprising code; it's in always on power).
9824          */
9825         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9826         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9827                 enum pipe trans_edp_pipe;
9828                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9829                 default:
9830                         WARN(1, "unknown pipe linked to edp transcoder\n");
9831                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9832                 case TRANS_DDI_EDP_INPUT_A_ON:
9833                         trans_edp_pipe = PIPE_A;
9834                         break;
9835                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9836                         trans_edp_pipe = PIPE_B;
9837                         break;
9838                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9839                         trans_edp_pipe = PIPE_C;
9840                         break;
9841                 }
9842
9843                 if (trans_edp_pipe == crtc->pipe)
9844                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9845         }
9846
9847         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9848         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9849                 return false;
9850         *power_domain_mask |= BIT(power_domain);
9851
9852         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9853
9854         return tmp & PIPECONF_ENABLE;
9855 }
9856
9857 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9858                                          struct intel_crtc_state *pipe_config,
9859                                          unsigned long *power_domain_mask)
9860 {
9861         struct drm_device *dev = crtc->base.dev;
9862         struct drm_i915_private *dev_priv = dev->dev_private;
9863         enum intel_display_power_domain power_domain;
9864         enum port port;
9865         enum transcoder cpu_transcoder;
9866         u32 tmp;
9867
9868         pipe_config->has_dsi_encoder = false;
9869
9870         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9871                 if (port == PORT_A)
9872                         cpu_transcoder = TRANSCODER_DSI_A;
9873                 else
9874                         cpu_transcoder = TRANSCODER_DSI_C;
9875
9876                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9877                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9878                         continue;
9879                 *power_domain_mask |= BIT(power_domain);
9880
9881                 /*
9882                  * The PLL needs to be enabled with a valid divider
9883                  * configuration, otherwise accessing DSI registers will hang
9884                  * the machine. See BSpec North Display Engine
9885                  * registers/MIPI[BXT]. We can break out here early, since we
9886                  * need the same DSI PLL to be enabled for both DSI ports.
9887                  */
9888                 if (!intel_dsi_pll_is_enabled(dev_priv))
9889                         break;
9890
9891                 /* XXX: this works for video mode only */
9892                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9893                 if (!(tmp & DPI_ENABLE))
9894                         continue;
9895
9896                 tmp = I915_READ(MIPI_CTRL(port));
9897                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9898                         continue;
9899
9900                 pipe_config->cpu_transcoder = cpu_transcoder;
9901                 pipe_config->has_dsi_encoder = true;
9902                 break;
9903         }
9904
9905         return pipe_config->has_dsi_encoder;
9906 }
9907
9908 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9909                                        struct intel_crtc_state *pipe_config)
9910 {
9911         struct drm_device *dev = crtc->base.dev;
9912         struct drm_i915_private *dev_priv = dev->dev_private;
9913         struct intel_shared_dpll *pll;
9914         enum port port;
9915         uint32_t tmp;
9916
9917         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9918
9919         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9920
9921         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
9922                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9923         else if (IS_BROXTON(dev))
9924                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9925         else
9926                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9927
9928         pll = pipe_config->shared_dpll;
9929         if (pll) {
9930                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9931                                                  &pipe_config->dpll_hw_state));
9932         }
9933
9934         /*
9935          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9936          * DDI E. So just check whether this pipe is wired to DDI E and whether
9937          * the PCH transcoder is on.
9938          */
9939         if (INTEL_INFO(dev)->gen < 9 &&
9940             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9941                 pipe_config->has_pch_encoder = true;
9942
9943                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9944                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9945                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9946
9947                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9948         }
9949 }
9950
9951 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9952                                     struct intel_crtc_state *pipe_config)
9953 {
9954         struct drm_device *dev = crtc->base.dev;
9955         struct drm_i915_private *dev_priv = dev->dev_private;
9956         enum intel_display_power_domain power_domain;
9957         unsigned long power_domain_mask;
9958         bool active;
9959
9960         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9961         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9962                 return false;
9963         power_domain_mask = BIT(power_domain);
9964
9965         pipe_config->shared_dpll = NULL;
9966
9967         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9968
9969         if (IS_BROXTON(dev_priv)) {
9970                 bxt_get_dsi_transcoder_state(crtc, pipe_config,
9971                                              &power_domain_mask);
9972                 WARN_ON(active && pipe_config->has_dsi_encoder);
9973                 if (pipe_config->has_dsi_encoder)
9974                         active = true;
9975         }
9976
9977         if (!active)
9978                 goto out;
9979
9980         if (!pipe_config->has_dsi_encoder) {
9981                 haswell_get_ddi_port_state(crtc, pipe_config);
9982                 intel_get_pipe_timings(crtc, pipe_config);
9983         }
9984
9985         intel_get_pipe_src_size(crtc, pipe_config);
9986
9987         pipe_config->gamma_mode =
9988                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9989
9990         if (INTEL_INFO(dev)->gen >= 9) {
9991                 skl_init_scalers(dev, crtc, pipe_config);
9992         }
9993
9994         if (INTEL_INFO(dev)->gen >= 9) {
9995                 pipe_config->scaler_state.scaler_id = -1;
9996                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9997         }
9998
9999         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
10000         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
10001                 power_domain_mask |= BIT(power_domain);
10002                 if (INTEL_INFO(dev)->gen >= 9)
10003                         skylake_get_pfit_config(crtc, pipe_config);
10004                 else
10005                         ironlake_get_pfit_config(crtc, pipe_config);
10006         }
10007
10008         if (IS_HASWELL(dev))
10009                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10010                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10011
10012         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10013             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10014                 pipe_config->pixel_multiplier =
10015                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10016         } else {
10017                 pipe_config->pixel_multiplier = 1;
10018         }
10019
10020 out:
10021         for_each_power_domain(power_domain, power_domain_mask)
10022                 intel_display_power_put(dev_priv, power_domain);
10023
10024         return active;
10025 }
10026
10027 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10028                                const struct intel_plane_state *plane_state)
10029 {
10030         struct drm_device *dev = crtc->dev;
10031         struct drm_i915_private *dev_priv = dev->dev_private;
10032         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10033         uint32_t cntl = 0, size = 0;
10034
10035         if (plane_state && plane_state->visible) {
10036                 unsigned int width = plane_state->base.crtc_w;
10037                 unsigned int height = plane_state->base.crtc_h;
10038                 unsigned int stride = roundup_pow_of_two(width) * 4;
10039
10040                 switch (stride) {
10041                 default:
10042                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10043                                   width, stride);
10044                         stride = 256;
10045                         /* fallthrough */
10046                 case 256:
10047                 case 512:
10048                 case 1024:
10049                 case 2048:
10050                         break;
10051                 }
10052
10053                 cntl |= CURSOR_ENABLE |
10054                         CURSOR_GAMMA_ENABLE |
10055                         CURSOR_FORMAT_ARGB |
10056                         CURSOR_STRIDE(stride);
10057
10058                 size = (height << 12) | width;
10059         }
10060
10061         if (intel_crtc->cursor_cntl != 0 &&
10062             (intel_crtc->cursor_base != base ||
10063              intel_crtc->cursor_size != size ||
10064              intel_crtc->cursor_cntl != cntl)) {
10065                 /* On these chipsets we can only modify the base/size/stride
10066                  * whilst the cursor is disabled.
10067                  */
10068                 I915_WRITE(CURCNTR(PIPE_A), 0);
10069                 POSTING_READ(CURCNTR(PIPE_A));
10070                 intel_crtc->cursor_cntl = 0;
10071         }
10072
10073         if (intel_crtc->cursor_base != base) {
10074                 I915_WRITE(CURBASE(PIPE_A), base);
10075                 intel_crtc->cursor_base = base;
10076         }
10077
10078         if (intel_crtc->cursor_size != size) {
10079                 I915_WRITE(CURSIZE, size);
10080                 intel_crtc->cursor_size = size;
10081         }
10082
10083         if (intel_crtc->cursor_cntl != cntl) {
10084                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10085                 POSTING_READ(CURCNTR(PIPE_A));
10086                 intel_crtc->cursor_cntl = cntl;
10087         }
10088 }
10089
10090 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10091                                const struct intel_plane_state *plane_state)
10092 {
10093         struct drm_device *dev = crtc->dev;
10094         struct drm_i915_private *dev_priv = dev->dev_private;
10095         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10096         int pipe = intel_crtc->pipe;
10097         uint32_t cntl = 0;
10098
10099         if (plane_state && plane_state->visible) {
10100                 cntl = MCURSOR_GAMMA_ENABLE;
10101                 switch (plane_state->base.crtc_w) {
10102                         case 64:
10103                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10104                                 break;
10105                         case 128:
10106                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10107                                 break;
10108                         case 256:
10109                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10110                                 break;
10111                         default:
10112                                 MISSING_CASE(plane_state->base.crtc_w);
10113                                 return;
10114                 }
10115                 cntl |= pipe << 28; /* Connect to correct pipe */
10116
10117                 if (HAS_DDI(dev))
10118                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10119
10120                 if (plane_state->base.rotation == BIT(DRM_ROTATE_180))
10121                         cntl |= CURSOR_ROTATE_180;
10122         }
10123
10124         if (intel_crtc->cursor_cntl != cntl) {
10125                 I915_WRITE(CURCNTR(pipe), cntl);
10126                 POSTING_READ(CURCNTR(pipe));
10127                 intel_crtc->cursor_cntl = cntl;
10128         }
10129
10130         /* and commit changes on next vblank */
10131         I915_WRITE(CURBASE(pipe), base);
10132         POSTING_READ(CURBASE(pipe));
10133
10134         intel_crtc->cursor_base = base;
10135 }
10136
10137 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10138 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10139                                      const struct intel_plane_state *plane_state)
10140 {
10141         struct drm_device *dev = crtc->dev;
10142         struct drm_i915_private *dev_priv = dev->dev_private;
10143         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10144         int pipe = intel_crtc->pipe;
10145         u32 base = intel_crtc->cursor_addr;
10146         u32 pos = 0;
10147
10148         if (plane_state) {
10149                 int x = plane_state->base.crtc_x;
10150                 int y = plane_state->base.crtc_y;
10151
10152                 if (x < 0) {
10153                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10154                         x = -x;
10155                 }
10156                 pos |= x << CURSOR_X_SHIFT;
10157
10158                 if (y < 0) {
10159                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10160                         y = -y;
10161                 }
10162                 pos |= y << CURSOR_Y_SHIFT;
10163
10164                 /* ILK+ do this automagically */
10165                 if (HAS_GMCH_DISPLAY(dev) &&
10166                     plane_state->base.rotation == BIT(DRM_ROTATE_180)) {
10167                         base += (plane_state->base.crtc_h *
10168                                  plane_state->base.crtc_w - 1) * 4;
10169                 }
10170         }
10171
10172         I915_WRITE(CURPOS(pipe), pos);
10173
10174         if (IS_845G(dev) || IS_I865G(dev))
10175                 i845_update_cursor(crtc, base, plane_state);
10176         else
10177                 i9xx_update_cursor(crtc, base, plane_state);
10178 }
10179
10180 static bool cursor_size_ok(struct drm_device *dev,
10181                            uint32_t width, uint32_t height)
10182 {
10183         if (width == 0 || height == 0)
10184                 return false;
10185
10186         /*
10187          * 845g/865g are special in that they are only limited by
10188          * the width of their cursors, the height is arbitrary up to
10189          * the precision of the register. Everything else requires
10190          * square cursors, limited to a few power-of-two sizes.
10191          */
10192         if (IS_845G(dev) || IS_I865G(dev)) {
10193                 if ((width & 63) != 0)
10194                         return false;
10195
10196                 if (width > (IS_845G(dev) ? 64 : 512))
10197                         return false;
10198
10199                 if (height > 1023)
10200                         return false;
10201         } else {
10202                 switch (width | height) {
10203                 case 256:
10204                 case 128:
10205                         if (IS_GEN2(dev))
10206                                 return false;
10207                 case 64:
10208                         break;
10209                 default:
10210                         return false;
10211                 }
10212         }
10213
10214         return true;
10215 }
10216
10217 /* VESA 640x480x72Hz mode to set on the pipe */
10218 static struct drm_display_mode load_detect_mode = {
10219         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10220                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10221 };
10222
10223 struct drm_framebuffer *
10224 __intel_framebuffer_create(struct drm_device *dev,
10225                            struct drm_mode_fb_cmd2 *mode_cmd,
10226                            struct drm_i915_gem_object *obj)
10227 {
10228         struct intel_framebuffer *intel_fb;
10229         int ret;
10230
10231         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10232         if (!intel_fb)
10233                 return ERR_PTR(-ENOMEM);
10234
10235         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10236         if (ret)
10237                 goto err;
10238
10239         return &intel_fb->base;
10240
10241 err:
10242         kfree(intel_fb);
10243         return ERR_PTR(ret);
10244 }
10245
10246 static struct drm_framebuffer *
10247 intel_framebuffer_create(struct drm_device *dev,
10248                          struct drm_mode_fb_cmd2 *mode_cmd,
10249                          struct drm_i915_gem_object *obj)
10250 {
10251         struct drm_framebuffer *fb;
10252         int ret;
10253
10254         ret = i915_mutex_lock_interruptible(dev);
10255         if (ret)
10256                 return ERR_PTR(ret);
10257         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10258         mutex_unlock(&dev->struct_mutex);
10259
10260         return fb;
10261 }
10262
10263 static u32
10264 intel_framebuffer_pitch_for_width(int width, int bpp)
10265 {
10266         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10267         return ALIGN(pitch, 64);
10268 }
10269
10270 static u32
10271 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10272 {
10273         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10274         return PAGE_ALIGN(pitch * mode->vdisplay);
10275 }
10276
10277 static struct drm_framebuffer *
10278 intel_framebuffer_create_for_mode(struct drm_device *dev,
10279                                   struct drm_display_mode *mode,
10280                                   int depth, int bpp)
10281 {
10282         struct drm_framebuffer *fb;
10283         struct drm_i915_gem_object *obj;
10284         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10285
10286         obj = i915_gem_alloc_object(dev,
10287                                     intel_framebuffer_size_for_mode(mode, bpp));
10288         if (obj == NULL)
10289                 return ERR_PTR(-ENOMEM);
10290
10291         mode_cmd.width = mode->hdisplay;
10292         mode_cmd.height = mode->vdisplay;
10293         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10294                                                                 bpp);
10295         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10296
10297         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10298         if (IS_ERR(fb))
10299                 drm_gem_object_unreference_unlocked(&obj->base);
10300
10301         return fb;
10302 }
10303
10304 static struct drm_framebuffer *
10305 mode_fits_in_fbdev(struct drm_device *dev,
10306                    struct drm_display_mode *mode)
10307 {
10308 #ifdef CONFIG_DRM_FBDEV_EMULATION
10309         struct drm_i915_private *dev_priv = dev->dev_private;
10310         struct drm_i915_gem_object *obj;
10311         struct drm_framebuffer *fb;
10312
10313         if (!dev_priv->fbdev)
10314                 return NULL;
10315
10316         if (!dev_priv->fbdev->fb)
10317                 return NULL;
10318
10319         obj = dev_priv->fbdev->fb->obj;
10320         BUG_ON(!obj);
10321
10322         fb = &dev_priv->fbdev->fb->base;
10323         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10324                                                                fb->bits_per_pixel))
10325                 return NULL;
10326
10327         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10328                 return NULL;
10329
10330         drm_framebuffer_reference(fb);
10331         return fb;
10332 #else
10333         return NULL;
10334 #endif
10335 }
10336
10337 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10338                                            struct drm_crtc *crtc,
10339                                            struct drm_display_mode *mode,
10340                                            struct drm_framebuffer *fb,
10341                                            int x, int y)
10342 {
10343         struct drm_plane_state *plane_state;
10344         int hdisplay, vdisplay;
10345         int ret;
10346
10347         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10348         if (IS_ERR(plane_state))
10349                 return PTR_ERR(plane_state);
10350
10351         if (mode)
10352                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10353         else
10354                 hdisplay = vdisplay = 0;
10355
10356         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10357         if (ret)
10358                 return ret;
10359         drm_atomic_set_fb_for_plane(plane_state, fb);
10360         plane_state->crtc_x = 0;
10361         plane_state->crtc_y = 0;
10362         plane_state->crtc_w = hdisplay;
10363         plane_state->crtc_h = vdisplay;
10364         plane_state->src_x = x << 16;
10365         plane_state->src_y = y << 16;
10366         plane_state->src_w = hdisplay << 16;
10367         plane_state->src_h = vdisplay << 16;
10368
10369         return 0;
10370 }
10371
10372 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10373                                 struct drm_display_mode *mode,
10374                                 struct intel_load_detect_pipe *old,
10375                                 struct drm_modeset_acquire_ctx *ctx)
10376 {
10377         struct intel_crtc *intel_crtc;
10378         struct intel_encoder *intel_encoder =
10379                 intel_attached_encoder(connector);
10380         struct drm_crtc *possible_crtc;
10381         struct drm_encoder *encoder = &intel_encoder->base;
10382         struct drm_crtc *crtc = NULL;
10383         struct drm_device *dev = encoder->dev;
10384         struct drm_framebuffer *fb;
10385         struct drm_mode_config *config = &dev->mode_config;
10386         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10387         struct drm_connector_state *connector_state;
10388         struct intel_crtc_state *crtc_state;
10389         int ret, i = -1;
10390
10391         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10392                       connector->base.id, connector->name,
10393                       encoder->base.id, encoder->name);
10394
10395         old->restore_state = NULL;
10396
10397 retry:
10398         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10399         if (ret)
10400                 goto fail;
10401
10402         /*
10403          * Algorithm gets a little messy:
10404          *
10405          *   - if the connector already has an assigned crtc, use it (but make
10406          *     sure it's on first)
10407          *
10408          *   - try to find the first unused crtc that can drive this connector,
10409          *     and use that if we find one
10410          */
10411
10412         /* See if we already have a CRTC for this connector */
10413         if (connector->state->crtc) {
10414                 crtc = connector->state->crtc;
10415
10416                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10417                 if (ret)
10418                         goto fail;
10419
10420                 /* Make sure the crtc and connector are running */
10421                 goto found;
10422         }
10423
10424         /* Find an unused one (if possible) */
10425         for_each_crtc(dev, possible_crtc) {
10426                 i++;
10427                 if (!(encoder->possible_crtcs & (1 << i)))
10428                         continue;
10429
10430                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10431                 if (ret)
10432                         goto fail;
10433
10434                 if (possible_crtc->state->enable) {
10435                         drm_modeset_unlock(&possible_crtc->mutex);
10436                         continue;
10437                 }
10438
10439                 crtc = possible_crtc;
10440                 break;
10441         }
10442
10443         /*
10444          * If we didn't find an unused CRTC, don't use any.
10445          */
10446         if (!crtc) {
10447                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10448                 goto fail;
10449         }
10450
10451 found:
10452         intel_crtc = to_intel_crtc(crtc);
10453
10454         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10455         if (ret)
10456                 goto fail;
10457
10458         state = drm_atomic_state_alloc(dev);
10459         restore_state = drm_atomic_state_alloc(dev);
10460         if (!state || !restore_state) {
10461                 ret = -ENOMEM;
10462                 goto fail;
10463         }
10464
10465         state->acquire_ctx = ctx;
10466         restore_state->acquire_ctx = ctx;
10467
10468         connector_state = drm_atomic_get_connector_state(state, connector);
10469         if (IS_ERR(connector_state)) {
10470                 ret = PTR_ERR(connector_state);
10471                 goto fail;
10472         }
10473
10474         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10475         if (ret)
10476                 goto fail;
10477
10478         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10479         if (IS_ERR(crtc_state)) {
10480                 ret = PTR_ERR(crtc_state);
10481                 goto fail;
10482         }
10483
10484         crtc_state->base.active = crtc_state->base.enable = true;
10485
10486         if (!mode)
10487                 mode = &load_detect_mode;
10488
10489         /* We need a framebuffer large enough to accommodate all accesses
10490          * that the plane may generate whilst we perform load detection.
10491          * We can not rely on the fbcon either being present (we get called
10492          * during its initialisation to detect all boot displays, or it may
10493          * not even exist) or that it is large enough to satisfy the
10494          * requested mode.
10495          */
10496         fb = mode_fits_in_fbdev(dev, mode);
10497         if (fb == NULL) {
10498                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10499                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10500         } else
10501                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10502         if (IS_ERR(fb)) {
10503                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10504                 goto fail;
10505         }
10506
10507         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10508         if (ret)
10509                 goto fail;
10510
10511         drm_framebuffer_unreference(fb);
10512
10513         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10514         if (ret)
10515                 goto fail;
10516
10517         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10518         if (!ret)
10519                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10520         if (!ret)
10521                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10522         if (ret) {
10523                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10524                 goto fail;
10525         }
10526
10527         ret = drm_atomic_commit(state);
10528         if (ret) {
10529                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10530                 goto fail;
10531         }
10532
10533         old->restore_state = restore_state;
10534
10535         /* let the connector get through one full cycle before testing */
10536         intel_wait_for_vblank(dev, intel_crtc->pipe);
10537         return true;
10538
10539 fail:
10540         drm_atomic_state_free(state);
10541         drm_atomic_state_free(restore_state);
10542         restore_state = state = NULL;
10543
10544         if (ret == -EDEADLK) {
10545                 drm_modeset_backoff(ctx);
10546                 goto retry;
10547         }
10548
10549         return false;
10550 }
10551
10552 void intel_release_load_detect_pipe(struct drm_connector *connector,
10553                                     struct intel_load_detect_pipe *old,
10554                                     struct drm_modeset_acquire_ctx *ctx)
10555 {
10556         struct intel_encoder *intel_encoder =
10557                 intel_attached_encoder(connector);
10558         struct drm_encoder *encoder = &intel_encoder->base;
10559         struct drm_atomic_state *state = old->restore_state;
10560         int ret;
10561
10562         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10563                       connector->base.id, connector->name,
10564                       encoder->base.id, encoder->name);
10565
10566         if (!state)
10567                 return;
10568
10569         ret = drm_atomic_commit(state);
10570         if (ret) {
10571                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10572                 drm_atomic_state_free(state);
10573         }
10574 }
10575
10576 static int i9xx_pll_refclk(struct drm_device *dev,
10577                            const struct intel_crtc_state *pipe_config)
10578 {
10579         struct drm_i915_private *dev_priv = dev->dev_private;
10580         u32 dpll = pipe_config->dpll_hw_state.dpll;
10581
10582         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10583                 return dev_priv->vbt.lvds_ssc_freq;
10584         else if (HAS_PCH_SPLIT(dev))
10585                 return 120000;
10586         else if (!IS_GEN2(dev))
10587                 return 96000;
10588         else
10589                 return 48000;
10590 }
10591
10592 /* Returns the clock of the currently programmed mode of the given pipe. */
10593 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10594                                 struct intel_crtc_state *pipe_config)
10595 {
10596         struct drm_device *dev = crtc->base.dev;
10597         struct drm_i915_private *dev_priv = dev->dev_private;
10598         int pipe = pipe_config->cpu_transcoder;
10599         u32 dpll = pipe_config->dpll_hw_state.dpll;
10600         u32 fp;
10601         intel_clock_t clock;
10602         int port_clock;
10603         int refclk = i9xx_pll_refclk(dev, pipe_config);
10604
10605         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10606                 fp = pipe_config->dpll_hw_state.fp0;
10607         else
10608                 fp = pipe_config->dpll_hw_state.fp1;
10609
10610         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10611         if (IS_PINEVIEW(dev)) {
10612                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10613                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10614         } else {
10615                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10616                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10617         }
10618
10619         if (!IS_GEN2(dev)) {
10620                 if (IS_PINEVIEW(dev))
10621                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10622                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10623                 else
10624                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10625                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10626
10627                 switch (dpll & DPLL_MODE_MASK) {
10628                 case DPLLB_MODE_DAC_SERIAL:
10629                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10630                                 5 : 10;
10631                         break;
10632                 case DPLLB_MODE_LVDS:
10633                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10634                                 7 : 14;
10635                         break;
10636                 default:
10637                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10638                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10639                         return;
10640                 }
10641
10642                 if (IS_PINEVIEW(dev))
10643                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10644                 else
10645                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10646         } else {
10647                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10648                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10649
10650                 if (is_lvds) {
10651                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10652                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10653
10654                         if (lvds & LVDS_CLKB_POWER_UP)
10655                                 clock.p2 = 7;
10656                         else
10657                                 clock.p2 = 14;
10658                 } else {
10659                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10660                                 clock.p1 = 2;
10661                         else {
10662                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10663                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10664                         }
10665                         if (dpll & PLL_P2_DIVIDE_BY_4)
10666                                 clock.p2 = 4;
10667                         else
10668                                 clock.p2 = 2;
10669                 }
10670
10671                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10672         }
10673
10674         /*
10675          * This value includes pixel_multiplier. We will use
10676          * port_clock to compute adjusted_mode.crtc_clock in the
10677          * encoder's get_config() function.
10678          */
10679         pipe_config->port_clock = port_clock;
10680 }
10681
10682 int intel_dotclock_calculate(int link_freq,
10683                              const struct intel_link_m_n *m_n)
10684 {
10685         /*
10686          * The calculation for the data clock is:
10687          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10688          * But we want to avoid losing precison if possible, so:
10689          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10690          *
10691          * and the link clock is simpler:
10692          * link_clock = (m * link_clock) / n
10693          */
10694
10695         if (!m_n->link_n)
10696                 return 0;
10697
10698         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10699 }
10700
10701 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10702                                    struct intel_crtc_state *pipe_config)
10703 {
10704         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10705
10706         /* read out port_clock from the DPLL */
10707         i9xx_crtc_clock_get(crtc, pipe_config);
10708
10709         /*
10710          * In case there is an active pipe without active ports,
10711          * we may need some idea for the dotclock anyway.
10712          * Calculate one based on the FDI configuration.
10713          */
10714         pipe_config->base.adjusted_mode.crtc_clock =
10715                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10716                                          &pipe_config->fdi_m_n);
10717 }
10718
10719 /** Returns the currently programmed mode of the given pipe. */
10720 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10721                                              struct drm_crtc *crtc)
10722 {
10723         struct drm_i915_private *dev_priv = dev->dev_private;
10724         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10725         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10726         struct drm_display_mode *mode;
10727         struct intel_crtc_state *pipe_config;
10728         int htot = I915_READ(HTOTAL(cpu_transcoder));
10729         int hsync = I915_READ(HSYNC(cpu_transcoder));
10730         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10731         int vsync = I915_READ(VSYNC(cpu_transcoder));
10732         enum pipe pipe = intel_crtc->pipe;
10733
10734         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10735         if (!mode)
10736                 return NULL;
10737
10738         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10739         if (!pipe_config) {
10740                 kfree(mode);
10741                 return NULL;
10742         }
10743
10744         /*
10745          * Construct a pipe_config sufficient for getting the clock info
10746          * back out of crtc_clock_get.
10747          *
10748          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10749          * to use a real value here instead.
10750          */
10751         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10752         pipe_config->pixel_multiplier = 1;
10753         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10754         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10755         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10756         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10757
10758         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10759         mode->hdisplay = (htot & 0xffff) + 1;
10760         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10761         mode->hsync_start = (hsync & 0xffff) + 1;
10762         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10763         mode->vdisplay = (vtot & 0xffff) + 1;
10764         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10765         mode->vsync_start = (vsync & 0xffff) + 1;
10766         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10767
10768         drm_mode_set_name(mode);
10769
10770         kfree(pipe_config);
10771
10772         return mode;
10773 }
10774
10775 void intel_mark_busy(struct drm_device *dev)
10776 {
10777         struct drm_i915_private *dev_priv = dev->dev_private;
10778
10779         if (dev_priv->mm.busy)
10780                 return;
10781
10782         intel_runtime_pm_get(dev_priv);
10783         i915_update_gfx_val(dev_priv);
10784         if (INTEL_INFO(dev)->gen >= 6)
10785                 gen6_rps_busy(dev_priv);
10786         dev_priv->mm.busy = true;
10787 }
10788
10789 void intel_mark_idle(struct drm_device *dev)
10790 {
10791         struct drm_i915_private *dev_priv = dev->dev_private;
10792
10793         if (!dev_priv->mm.busy)
10794                 return;
10795
10796         dev_priv->mm.busy = false;
10797
10798         if (INTEL_INFO(dev)->gen >= 6)
10799                 gen6_rps_idle(dev->dev_private);
10800
10801         intel_runtime_pm_put(dev_priv);
10802 }
10803
10804 static void intel_crtc_destroy(struct drm_crtc *crtc)
10805 {
10806         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10807         struct drm_device *dev = crtc->dev;
10808         struct intel_unpin_work *work;
10809
10810         spin_lock_irq(&dev->event_lock);
10811         work = intel_crtc->unpin_work;
10812         intel_crtc->unpin_work = NULL;
10813         spin_unlock_irq(&dev->event_lock);
10814
10815         if (work) {
10816                 cancel_work_sync(&work->work);
10817                 kfree(work);
10818         }
10819
10820         drm_crtc_cleanup(crtc);
10821
10822         kfree(intel_crtc);
10823 }
10824
10825 static void intel_unpin_work_fn(struct work_struct *__work)
10826 {
10827         struct intel_unpin_work *work =
10828                 container_of(__work, struct intel_unpin_work, work);
10829         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10830         struct drm_device *dev = crtc->base.dev;
10831         struct drm_plane *primary = crtc->base.primary;
10832
10833         mutex_lock(&dev->struct_mutex);
10834         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
10835         drm_gem_object_unreference(&work->pending_flip_obj->base);
10836
10837         if (work->flip_queued_req)
10838                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10839         mutex_unlock(&dev->struct_mutex);
10840
10841         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10842         intel_fbc_post_update(crtc);
10843         drm_framebuffer_unreference(work->old_fb);
10844
10845         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10846         atomic_dec(&crtc->unpin_work_count);
10847
10848         kfree(work);
10849 }
10850
10851 static void do_intel_finish_page_flip(struct drm_device *dev,
10852                                       struct drm_crtc *crtc)
10853 {
10854         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10855         struct intel_unpin_work *work;
10856         unsigned long flags;
10857
10858         /* Ignore early vblank irqs */
10859         if (intel_crtc == NULL)
10860                 return;
10861
10862         /*
10863          * This is called both by irq handlers and the reset code (to complete
10864          * lost pageflips) so needs the full irqsave spinlocks.
10865          */
10866         spin_lock_irqsave(&dev->event_lock, flags);
10867         work = intel_crtc->unpin_work;
10868
10869         /* Ensure we don't miss a work->pending update ... */
10870         smp_rmb();
10871
10872         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10873                 spin_unlock_irqrestore(&dev->event_lock, flags);
10874                 return;
10875         }
10876
10877         page_flip_completed(intel_crtc);
10878
10879         spin_unlock_irqrestore(&dev->event_lock, flags);
10880 }
10881
10882 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10883 {
10884         struct drm_i915_private *dev_priv = dev->dev_private;
10885         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10886
10887         do_intel_finish_page_flip(dev, crtc);
10888 }
10889
10890 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10891 {
10892         struct drm_i915_private *dev_priv = dev->dev_private;
10893         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10894
10895         do_intel_finish_page_flip(dev, crtc);
10896 }
10897
10898 /* Is 'a' after or equal to 'b'? */
10899 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10900 {
10901         return !((a - b) & 0x80000000);
10902 }
10903
10904 static bool page_flip_finished(struct intel_crtc *crtc)
10905 {
10906         struct drm_device *dev = crtc->base.dev;
10907         struct drm_i915_private *dev_priv = dev->dev_private;
10908
10909         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10910             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10911                 return true;
10912
10913         /*
10914          * The relevant registers doen't exist on pre-ctg.
10915          * As the flip done interrupt doesn't trigger for mmio
10916          * flips on gmch platforms, a flip count check isn't
10917          * really needed there. But since ctg has the registers,
10918          * include it in the check anyway.
10919          */
10920         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10921                 return true;
10922
10923         /*
10924          * BDW signals flip done immediately if the plane
10925          * is disabled, even if the plane enable is already
10926          * armed to occur at the next vblank :(
10927          */
10928
10929         /*
10930          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10931          * used the same base address. In that case the mmio flip might
10932          * have completed, but the CS hasn't even executed the flip yet.
10933          *
10934          * A flip count check isn't enough as the CS might have updated
10935          * the base address just after start of vblank, but before we
10936          * managed to process the interrupt. This means we'd complete the
10937          * CS flip too soon.
10938          *
10939          * Combining both checks should get us a good enough result. It may
10940          * still happen that the CS flip has been executed, but has not
10941          * yet actually completed. But in case the base address is the same
10942          * anyway, we don't really care.
10943          */
10944         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10945                 crtc->unpin_work->gtt_offset &&
10946                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
10947                                     crtc->unpin_work->flip_count);
10948 }
10949
10950 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10951 {
10952         struct drm_i915_private *dev_priv = dev->dev_private;
10953         struct intel_crtc *intel_crtc =
10954                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10955         unsigned long flags;
10956
10957
10958         /*
10959          * This is called both by irq handlers and the reset code (to complete
10960          * lost pageflips) so needs the full irqsave spinlocks.
10961          *
10962          * NB: An MMIO update of the plane base pointer will also
10963          * generate a page-flip completion irq, i.e. every modeset
10964          * is also accompanied by a spurious intel_prepare_page_flip().
10965          */
10966         spin_lock_irqsave(&dev->event_lock, flags);
10967         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10968                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10969         spin_unlock_irqrestore(&dev->event_lock, flags);
10970 }
10971
10972 static inline void intel_mark_page_flip_active(struct intel_unpin_work *work)
10973 {
10974         /* Ensure that the work item is consistent when activating it ... */
10975         smp_wmb();
10976         atomic_set(&work->pending, INTEL_FLIP_PENDING);
10977         /* and that it is marked active as soon as the irq could fire. */
10978         smp_wmb();
10979 }
10980
10981 static int intel_gen2_queue_flip(struct drm_device *dev,
10982                                  struct drm_crtc *crtc,
10983                                  struct drm_framebuffer *fb,
10984                                  struct drm_i915_gem_object *obj,
10985                                  struct drm_i915_gem_request *req,
10986                                  uint32_t flags)
10987 {
10988         struct intel_engine_cs *engine = req->engine;
10989         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10990         u32 flip_mask;
10991         int ret;
10992
10993         ret = intel_ring_begin(req, 6);
10994         if (ret)
10995                 return ret;
10996
10997         /* Can't queue multiple flips, so wait for the previous
10998          * one to finish before executing the next.
10999          */
11000         if (intel_crtc->plane)
11001                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11002         else
11003                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11004         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11005         intel_ring_emit(engine, MI_NOOP);
11006         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11007                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11008         intel_ring_emit(engine, fb->pitches[0]);
11009         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11010         intel_ring_emit(engine, 0); /* aux display base address, unused */
11011
11012         intel_mark_page_flip_active(intel_crtc->unpin_work);
11013         return 0;
11014 }
11015
11016 static int intel_gen3_queue_flip(struct drm_device *dev,
11017                                  struct drm_crtc *crtc,
11018                                  struct drm_framebuffer *fb,
11019                                  struct drm_i915_gem_object *obj,
11020                                  struct drm_i915_gem_request *req,
11021                                  uint32_t flags)
11022 {
11023         struct intel_engine_cs *engine = req->engine;
11024         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11025         u32 flip_mask;
11026         int ret;
11027
11028         ret = intel_ring_begin(req, 6);
11029         if (ret)
11030                 return ret;
11031
11032         if (intel_crtc->plane)
11033                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11034         else
11035                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11036         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11037         intel_ring_emit(engine, MI_NOOP);
11038         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 |
11039                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11040         intel_ring_emit(engine, fb->pitches[0]);
11041         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11042         intel_ring_emit(engine, MI_NOOP);
11043
11044         intel_mark_page_flip_active(intel_crtc->unpin_work);
11045         return 0;
11046 }
11047
11048 static int intel_gen4_queue_flip(struct drm_device *dev,
11049                                  struct drm_crtc *crtc,
11050                                  struct drm_framebuffer *fb,
11051                                  struct drm_i915_gem_object *obj,
11052                                  struct drm_i915_gem_request *req,
11053                                  uint32_t flags)
11054 {
11055         struct intel_engine_cs *engine = req->engine;
11056         struct drm_i915_private *dev_priv = dev->dev_private;
11057         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11058         uint32_t pf, pipesrc;
11059         int ret;
11060
11061         ret = intel_ring_begin(req, 4);
11062         if (ret)
11063                 return ret;
11064
11065         /* i965+ uses the linear or tiled offsets from the
11066          * Display Registers (which do not change across a page-flip)
11067          * so we need only reprogram the base address.
11068          */
11069         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11070                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11071         intel_ring_emit(engine, fb->pitches[0]);
11072         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset |
11073                         obj->tiling_mode);
11074
11075         /* XXX Enabling the panel-fitter across page-flip is so far
11076          * untested on non-native modes, so ignore it for now.
11077          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11078          */
11079         pf = 0;
11080         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11081         intel_ring_emit(engine, pf | pipesrc);
11082
11083         intel_mark_page_flip_active(intel_crtc->unpin_work);
11084         return 0;
11085 }
11086
11087 static int intel_gen6_queue_flip(struct drm_device *dev,
11088                                  struct drm_crtc *crtc,
11089                                  struct drm_framebuffer *fb,
11090                                  struct drm_i915_gem_object *obj,
11091                                  struct drm_i915_gem_request *req,
11092                                  uint32_t flags)
11093 {
11094         struct intel_engine_cs *engine = req->engine;
11095         struct drm_i915_private *dev_priv = dev->dev_private;
11096         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11097         uint32_t pf, pipesrc;
11098         int ret;
11099
11100         ret = intel_ring_begin(req, 4);
11101         if (ret)
11102                 return ret;
11103
11104         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11105                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11106         intel_ring_emit(engine, fb->pitches[0] | obj->tiling_mode);
11107         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11108
11109         /* Contrary to the suggestions in the documentation,
11110          * "Enable Panel Fitter" does not seem to be required when page
11111          * flipping with a non-native mode, and worse causes a normal
11112          * modeset to fail.
11113          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11114          */
11115         pf = 0;
11116         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11117         intel_ring_emit(engine, pf | pipesrc);
11118
11119         intel_mark_page_flip_active(intel_crtc->unpin_work);
11120         return 0;
11121 }
11122
11123 static int intel_gen7_queue_flip(struct drm_device *dev,
11124                                  struct drm_crtc *crtc,
11125                                  struct drm_framebuffer *fb,
11126                                  struct drm_i915_gem_object *obj,
11127                                  struct drm_i915_gem_request *req,
11128                                  uint32_t flags)
11129 {
11130         struct intel_engine_cs *engine = req->engine;
11131         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11132         uint32_t plane_bit = 0;
11133         int len, ret;
11134
11135         switch (intel_crtc->plane) {
11136         case PLANE_A:
11137                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11138                 break;
11139         case PLANE_B:
11140                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11141                 break;
11142         case PLANE_C:
11143                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11144                 break;
11145         default:
11146                 WARN_ONCE(1, "unknown plane in flip command\n");
11147                 return -ENODEV;
11148         }
11149
11150         len = 4;
11151         if (engine->id == RCS) {
11152                 len += 6;
11153                 /*
11154                  * On Gen 8, SRM is now taking an extra dword to accommodate
11155                  * 48bits addresses, and we need a NOOP for the batch size to
11156                  * stay even.
11157                  */
11158                 if (IS_GEN8(dev))
11159                         len += 2;
11160         }
11161
11162         /*
11163          * BSpec MI_DISPLAY_FLIP for IVB:
11164          * "The full packet must be contained within the same cache line."
11165          *
11166          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11167          * cacheline, if we ever start emitting more commands before
11168          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11169          * then do the cacheline alignment, and finally emit the
11170          * MI_DISPLAY_FLIP.
11171          */
11172         ret = intel_ring_cacheline_align(req);
11173         if (ret)
11174                 return ret;
11175
11176         ret = intel_ring_begin(req, len);
11177         if (ret)
11178                 return ret;
11179
11180         /* Unmask the flip-done completion message. Note that the bspec says that
11181          * we should do this for both the BCS and RCS, and that we must not unmask
11182          * more than one flip event at any time (or ensure that one flip message
11183          * can be sent by waiting for flip-done prior to queueing new flips).
11184          * Experimentation says that BCS works despite DERRMR masking all
11185          * flip-done completion events and that unmasking all planes at once
11186          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11187          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11188          */
11189         if (engine->id == RCS) {
11190                 intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(1));
11191                 intel_ring_emit_reg(engine, DERRMR);
11192                 intel_ring_emit(engine, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11193                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11194                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11195                 if (IS_GEN8(dev))
11196                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM_GEN8 |
11197                                               MI_SRM_LRM_GLOBAL_GTT);
11198                 else
11199                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM |
11200                                               MI_SRM_LRM_GLOBAL_GTT);
11201                 intel_ring_emit_reg(engine, DERRMR);
11202                 intel_ring_emit(engine, engine->scratch.gtt_offset + 256);
11203                 if (IS_GEN8(dev)) {
11204                         intel_ring_emit(engine, 0);
11205                         intel_ring_emit(engine, MI_NOOP);
11206                 }
11207         }
11208
11209         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 | plane_bit);
11210         intel_ring_emit(engine, (fb->pitches[0] | obj->tiling_mode));
11211         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11212         intel_ring_emit(engine, (MI_NOOP));
11213
11214         intel_mark_page_flip_active(intel_crtc->unpin_work);
11215         return 0;
11216 }
11217
11218 static bool use_mmio_flip(struct intel_engine_cs *engine,
11219                           struct drm_i915_gem_object *obj)
11220 {
11221         /*
11222          * This is not being used for older platforms, because
11223          * non-availability of flip done interrupt forces us to use
11224          * CS flips. Older platforms derive flip done using some clever
11225          * tricks involving the flip_pending status bits and vblank irqs.
11226          * So using MMIO flips there would disrupt this mechanism.
11227          */
11228
11229         if (engine == NULL)
11230                 return true;
11231
11232         if (INTEL_INFO(engine->dev)->gen < 5)
11233                 return false;
11234
11235         if (i915.use_mmio_flip < 0)
11236                 return false;
11237         else if (i915.use_mmio_flip > 0)
11238                 return true;
11239         else if (i915.enable_execlists)
11240                 return true;
11241         else if (obj->base.dma_buf &&
11242                  !reservation_object_test_signaled_rcu(obj->base.dma_buf->resv,
11243                                                        false))
11244                 return true;
11245         else
11246                 return engine != i915_gem_request_get_engine(obj->last_write_req);
11247 }
11248
11249 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11250                              unsigned int rotation,
11251                              struct intel_unpin_work *work)
11252 {
11253         struct drm_device *dev = intel_crtc->base.dev;
11254         struct drm_i915_private *dev_priv = dev->dev_private;
11255         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11256         const enum pipe pipe = intel_crtc->pipe;
11257         u32 ctl, stride, tile_height;
11258
11259         ctl = I915_READ(PLANE_CTL(pipe, 0));
11260         ctl &= ~PLANE_CTL_TILED_MASK;
11261         switch (fb->modifier[0]) {
11262         case DRM_FORMAT_MOD_NONE:
11263                 break;
11264         case I915_FORMAT_MOD_X_TILED:
11265                 ctl |= PLANE_CTL_TILED_X;
11266                 break;
11267         case I915_FORMAT_MOD_Y_TILED:
11268                 ctl |= PLANE_CTL_TILED_Y;
11269                 break;
11270         case I915_FORMAT_MOD_Yf_TILED:
11271                 ctl |= PLANE_CTL_TILED_YF;
11272                 break;
11273         default:
11274                 MISSING_CASE(fb->modifier[0]);
11275         }
11276
11277         /*
11278          * The stride is either expressed as a multiple of 64 bytes chunks for
11279          * linear buffers or in number of tiles for tiled buffers.
11280          */
11281         if (intel_rotation_90_or_270(rotation)) {
11282                 /* stride = Surface height in tiles */
11283                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], 0);
11284                 stride = DIV_ROUND_UP(fb->height, tile_height);
11285         } else {
11286                 stride = fb->pitches[0] /
11287                         intel_fb_stride_alignment(dev_priv, fb->modifier[0],
11288                                                   fb->pixel_format);
11289         }
11290
11291         /*
11292          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11293          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11294          */
11295         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11296         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11297
11298         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11299         POSTING_READ(PLANE_SURF(pipe, 0));
11300 }
11301
11302 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11303                              struct intel_unpin_work *work)
11304 {
11305         struct drm_device *dev = intel_crtc->base.dev;
11306         struct drm_i915_private *dev_priv = dev->dev_private;
11307         struct intel_framebuffer *intel_fb =
11308                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11309         struct drm_i915_gem_object *obj = intel_fb->obj;
11310         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11311         u32 dspcntr;
11312
11313         dspcntr = I915_READ(reg);
11314
11315         if (obj->tiling_mode != I915_TILING_NONE)
11316                 dspcntr |= DISPPLANE_TILED;
11317         else
11318                 dspcntr &= ~DISPPLANE_TILED;
11319
11320         I915_WRITE(reg, dspcntr);
11321
11322         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11323         POSTING_READ(DSPSURF(intel_crtc->plane));
11324 }
11325
11326 /*
11327  * XXX: This is the temporary way to update the plane registers until we get
11328  * around to using the usual plane update functions for MMIO flips
11329  */
11330 static void intel_do_mmio_flip(struct intel_mmio_flip *mmio_flip)
11331 {
11332         struct intel_crtc *crtc = mmio_flip->crtc;
11333         struct intel_unpin_work *work;
11334
11335         spin_lock_irq(&crtc->base.dev->event_lock);
11336         work = crtc->unpin_work;
11337         spin_unlock_irq(&crtc->base.dev->event_lock);
11338         if (work == NULL)
11339                 return;
11340
11341         intel_mark_page_flip_active(work);
11342
11343         intel_pipe_update_start(crtc);
11344
11345         if (INTEL_INFO(mmio_flip->i915)->gen >= 9)
11346                 skl_do_mmio_flip(crtc, mmio_flip->rotation, work);
11347         else
11348                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11349                 ilk_do_mmio_flip(crtc, work);
11350
11351         intel_pipe_update_end(crtc);
11352 }
11353
11354 static void intel_mmio_flip_work_func(struct work_struct *work)
11355 {
11356         struct intel_mmio_flip *mmio_flip =
11357                 container_of(work, struct intel_mmio_flip, work);
11358         struct intel_framebuffer *intel_fb =
11359                 to_intel_framebuffer(mmio_flip->crtc->base.primary->fb);
11360         struct drm_i915_gem_object *obj = intel_fb->obj;
11361
11362         if (mmio_flip->req) {
11363                 WARN_ON(__i915_wait_request(mmio_flip->req,
11364                                             mmio_flip->crtc->reset_counter,
11365                                             false, NULL,
11366                                             &mmio_flip->i915->rps.mmioflips));
11367                 i915_gem_request_unreference__unlocked(mmio_flip->req);
11368         }
11369
11370         /* For framebuffer backed by dmabuf, wait for fence */
11371         if (obj->base.dma_buf)
11372                 WARN_ON(reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
11373                                                             false, false,
11374                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11375
11376         intel_do_mmio_flip(mmio_flip);
11377         kfree(mmio_flip);
11378 }
11379
11380 static int intel_queue_mmio_flip(struct drm_device *dev,
11381                                  struct drm_crtc *crtc,
11382                                  struct drm_i915_gem_object *obj)
11383 {
11384         struct intel_mmio_flip *mmio_flip;
11385
11386         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11387         if (mmio_flip == NULL)
11388                 return -ENOMEM;
11389
11390         mmio_flip->i915 = to_i915(dev);
11391         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11392         mmio_flip->crtc = to_intel_crtc(crtc);
11393         mmio_flip->rotation = crtc->primary->state->rotation;
11394
11395         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11396         schedule_work(&mmio_flip->work);
11397
11398         return 0;
11399 }
11400
11401 static int intel_default_queue_flip(struct drm_device *dev,
11402                                     struct drm_crtc *crtc,
11403                                     struct drm_framebuffer *fb,
11404                                     struct drm_i915_gem_object *obj,
11405                                     struct drm_i915_gem_request *req,
11406                                     uint32_t flags)
11407 {
11408         return -ENODEV;
11409 }
11410
11411 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11412                                          struct drm_crtc *crtc)
11413 {
11414         struct drm_i915_private *dev_priv = dev->dev_private;
11415         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11416         struct intel_unpin_work *work = intel_crtc->unpin_work;
11417         u32 addr;
11418
11419         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11420                 return true;
11421
11422         if (atomic_read(&work->pending) < INTEL_FLIP_PENDING)
11423                 return false;
11424
11425         if (!work->enable_stall_check)
11426                 return false;
11427
11428         if (work->flip_ready_vblank == 0) {
11429                 if (work->flip_queued_req &&
11430                     !i915_gem_request_completed(work->flip_queued_req, true))
11431                         return false;
11432
11433                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11434         }
11435
11436         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11437                 return false;
11438
11439         /* Potential stall - if we see that the flip has happened,
11440          * assume a missed interrupt. */
11441         if (INTEL_INFO(dev)->gen >= 4)
11442                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11443         else
11444                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11445
11446         /* There is a potential issue here with a false positive after a flip
11447          * to the same address. We could address this by checking for a
11448          * non-incrementing frame counter.
11449          */
11450         return addr == work->gtt_offset;
11451 }
11452
11453 void intel_check_page_flip(struct drm_device *dev, int pipe)
11454 {
11455         struct drm_i915_private *dev_priv = dev->dev_private;
11456         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11457         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11458         struct intel_unpin_work *work;
11459
11460         WARN_ON(!in_interrupt());
11461
11462         if (crtc == NULL)
11463                 return;
11464
11465         spin_lock(&dev->event_lock);
11466         work = intel_crtc->unpin_work;
11467         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11468                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11469                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11470                 page_flip_completed(intel_crtc);
11471                 work = NULL;
11472         }
11473         if (work != NULL &&
11474             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11475                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11476         spin_unlock(&dev->event_lock);
11477 }
11478
11479 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11480                                 struct drm_framebuffer *fb,
11481                                 struct drm_pending_vblank_event *event,
11482                                 uint32_t page_flip_flags)
11483 {
11484         struct drm_device *dev = crtc->dev;
11485         struct drm_i915_private *dev_priv = dev->dev_private;
11486         struct drm_framebuffer *old_fb = crtc->primary->fb;
11487         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11488         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11489         struct drm_plane *primary = crtc->primary;
11490         enum pipe pipe = intel_crtc->pipe;
11491         struct intel_unpin_work *work;
11492         struct intel_engine_cs *engine;
11493         bool mmio_flip;
11494         struct drm_i915_gem_request *request = NULL;
11495         int ret;
11496
11497         /*
11498          * drm_mode_page_flip_ioctl() should already catch this, but double
11499          * check to be safe.  In the future we may enable pageflipping from
11500          * a disabled primary plane.
11501          */
11502         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11503                 return -EBUSY;
11504
11505         /* Can't change pixel format via MI display flips. */
11506         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11507                 return -EINVAL;
11508
11509         /*
11510          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11511          * Note that pitch changes could also affect these register.
11512          */
11513         if (INTEL_INFO(dev)->gen > 3 &&
11514             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11515              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11516                 return -EINVAL;
11517
11518         if (i915_terminally_wedged(&dev_priv->gpu_error))
11519                 goto out_hang;
11520
11521         work = kzalloc(sizeof(*work), GFP_KERNEL);
11522         if (work == NULL)
11523                 return -ENOMEM;
11524
11525         work->event = event;
11526         work->crtc = crtc;
11527         work->old_fb = old_fb;
11528         INIT_WORK(&work->work, intel_unpin_work_fn);
11529
11530         ret = drm_crtc_vblank_get(crtc);
11531         if (ret)
11532                 goto free_work;
11533
11534         /* We borrow the event spin lock for protecting unpin_work */
11535         spin_lock_irq(&dev->event_lock);
11536         if (intel_crtc->unpin_work) {
11537                 /* Before declaring the flip queue wedged, check if
11538                  * the hardware completed the operation behind our backs.
11539                  */
11540                 if (__intel_pageflip_stall_check(dev, crtc)) {
11541                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11542                         page_flip_completed(intel_crtc);
11543                 } else {
11544                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11545                         spin_unlock_irq(&dev->event_lock);
11546
11547                         drm_crtc_vblank_put(crtc);
11548                         kfree(work);
11549                         return -EBUSY;
11550                 }
11551         }
11552         intel_crtc->unpin_work = work;
11553         spin_unlock_irq(&dev->event_lock);
11554
11555         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11556                 flush_workqueue(dev_priv->wq);
11557
11558         /* Reference the objects for the scheduled work. */
11559         drm_framebuffer_reference(work->old_fb);
11560         drm_gem_object_reference(&obj->base);
11561
11562         crtc->primary->fb = fb;
11563         update_state_fb(crtc->primary);
11564         intel_fbc_pre_update(intel_crtc);
11565
11566         work->pending_flip_obj = obj;
11567
11568         ret = i915_mutex_lock_interruptible(dev);
11569         if (ret)
11570                 goto cleanup;
11571
11572         atomic_inc(&intel_crtc->unpin_work_count);
11573         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11574
11575         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11576                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
11577
11578         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
11579                 engine = &dev_priv->engine[BCS];
11580                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11581                         /* vlv: DISPLAY_FLIP fails to change tiling */
11582                         engine = NULL;
11583         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11584                 engine = &dev_priv->engine[BCS];
11585         } else if (INTEL_INFO(dev)->gen >= 7) {
11586                 engine = i915_gem_request_get_engine(obj->last_write_req);
11587                 if (engine == NULL || engine->id != RCS)
11588                         engine = &dev_priv->engine[BCS];
11589         } else {
11590                 engine = &dev_priv->engine[RCS];
11591         }
11592
11593         mmio_flip = use_mmio_flip(engine, obj);
11594
11595         /* When using CS flips, we want to emit semaphores between rings.
11596          * However, when using mmio flips we will create a task to do the
11597          * synchronisation, so all we want here is to pin the framebuffer
11598          * into the display plane and skip any waits.
11599          */
11600         if (!mmio_flip) {
11601                 ret = i915_gem_object_sync(obj, engine, &request);
11602                 if (ret)
11603                         goto cleanup_pending;
11604         }
11605
11606         ret = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
11607         if (ret)
11608                 goto cleanup_pending;
11609
11610         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary),
11611                                                   obj, 0);
11612         work->gtt_offset += intel_crtc->dspaddr_offset;
11613
11614         if (mmio_flip) {
11615                 ret = intel_queue_mmio_flip(dev, crtc, obj);
11616                 if (ret)
11617                         goto cleanup_unpin;
11618
11619                 i915_gem_request_assign(&work->flip_queued_req,
11620                                         obj->last_write_req);
11621         } else {
11622                 if (!request) {
11623                         request = i915_gem_request_alloc(engine, NULL);
11624                         if (IS_ERR(request)) {
11625                                 ret = PTR_ERR(request);
11626                                 goto cleanup_unpin;
11627                         }
11628                 }
11629
11630                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11631                                                    page_flip_flags);
11632                 if (ret)
11633                         goto cleanup_unpin;
11634
11635                 i915_gem_request_assign(&work->flip_queued_req, request);
11636         }
11637
11638         if (request)
11639                 i915_add_request_no_flush(request);
11640
11641         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11642         work->enable_stall_check = true;
11643
11644         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11645                           to_intel_plane(primary)->frontbuffer_bit);
11646         mutex_unlock(&dev->struct_mutex);
11647
11648         intel_frontbuffer_flip_prepare(dev,
11649                                        to_intel_plane(primary)->frontbuffer_bit);
11650
11651         trace_i915_flip_request(intel_crtc->plane, obj);
11652
11653         return 0;
11654
11655 cleanup_unpin:
11656         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
11657 cleanup_pending:
11658         if (!IS_ERR_OR_NULL(request))
11659                 i915_gem_request_cancel(request);
11660         atomic_dec(&intel_crtc->unpin_work_count);
11661         mutex_unlock(&dev->struct_mutex);
11662 cleanup:
11663         crtc->primary->fb = old_fb;
11664         update_state_fb(crtc->primary);
11665
11666         drm_gem_object_unreference_unlocked(&obj->base);
11667         drm_framebuffer_unreference(work->old_fb);
11668
11669         spin_lock_irq(&dev->event_lock);
11670         intel_crtc->unpin_work = NULL;
11671         spin_unlock_irq(&dev->event_lock);
11672
11673         drm_crtc_vblank_put(crtc);
11674 free_work:
11675         kfree(work);
11676
11677         if (ret == -EIO) {
11678                 struct drm_atomic_state *state;
11679                 struct drm_plane_state *plane_state;
11680
11681 out_hang:
11682                 state = drm_atomic_state_alloc(dev);
11683                 if (!state)
11684                         return -ENOMEM;
11685                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11686
11687 retry:
11688                 plane_state = drm_atomic_get_plane_state(state, primary);
11689                 ret = PTR_ERR_OR_ZERO(plane_state);
11690                 if (!ret) {
11691                         drm_atomic_set_fb_for_plane(plane_state, fb);
11692
11693                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11694                         if (!ret)
11695                                 ret = drm_atomic_commit(state);
11696                 }
11697
11698                 if (ret == -EDEADLK) {
11699                         drm_modeset_backoff(state->acquire_ctx);
11700                         drm_atomic_state_clear(state);
11701                         goto retry;
11702                 }
11703
11704                 if (ret)
11705                         drm_atomic_state_free(state);
11706
11707                 if (ret == 0 && event) {
11708                         spin_lock_irq(&dev->event_lock);
11709                         drm_send_vblank_event(dev, pipe, event);
11710                         spin_unlock_irq(&dev->event_lock);
11711                 }
11712         }
11713         return ret;
11714 }
11715
11716
11717 /**
11718  * intel_wm_need_update - Check whether watermarks need updating
11719  * @plane: drm plane
11720  * @state: new plane state
11721  *
11722  * Check current plane state versus the new one to determine whether
11723  * watermarks need to be recalculated.
11724  *
11725  * Returns true or false.
11726  */
11727 static bool intel_wm_need_update(struct drm_plane *plane,
11728                                  struct drm_plane_state *state)
11729 {
11730         struct intel_plane_state *new = to_intel_plane_state(state);
11731         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11732
11733         /* Update watermarks on tiling or size changes. */
11734         if (new->visible != cur->visible)
11735                 return true;
11736
11737         if (!cur->base.fb || !new->base.fb)
11738                 return false;
11739
11740         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11741             cur->base.rotation != new->base.rotation ||
11742             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
11743             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
11744             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
11745             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
11746                 return true;
11747
11748         return false;
11749 }
11750
11751 static bool needs_scaling(struct intel_plane_state *state)
11752 {
11753         int src_w = drm_rect_width(&state->src) >> 16;
11754         int src_h = drm_rect_height(&state->src) >> 16;
11755         int dst_w = drm_rect_width(&state->dst);
11756         int dst_h = drm_rect_height(&state->dst);
11757
11758         return (src_w != dst_w || src_h != dst_h);
11759 }
11760
11761 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11762                                     struct drm_plane_state *plane_state)
11763 {
11764         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11765         struct drm_crtc *crtc = crtc_state->crtc;
11766         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11767         struct drm_plane *plane = plane_state->plane;
11768         struct drm_device *dev = crtc->dev;
11769         struct drm_i915_private *dev_priv = to_i915(dev);
11770         struct intel_plane_state *old_plane_state =
11771                 to_intel_plane_state(plane->state);
11772         int idx = intel_crtc->base.base.id, ret;
11773         bool mode_changed = needs_modeset(crtc_state);
11774         bool was_crtc_enabled = crtc->state->active;
11775         bool is_crtc_enabled = crtc_state->active;
11776         bool turn_off, turn_on, visible, was_visible;
11777         struct drm_framebuffer *fb = plane_state->fb;
11778
11779         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11780             plane->type != DRM_PLANE_TYPE_CURSOR) {
11781                 ret = skl_update_scaler_plane(
11782                         to_intel_crtc_state(crtc_state),
11783                         to_intel_plane_state(plane_state));
11784                 if (ret)
11785                         return ret;
11786         }
11787
11788         was_visible = old_plane_state->visible;
11789         visible = to_intel_plane_state(plane_state)->visible;
11790
11791         if (!was_crtc_enabled && WARN_ON(was_visible))
11792                 was_visible = false;
11793
11794         /*
11795          * Visibility is calculated as if the crtc was on, but
11796          * after scaler setup everything depends on it being off
11797          * when the crtc isn't active.
11798          */
11799         if (!is_crtc_enabled)
11800                 to_intel_plane_state(plane_state)->visible = visible = false;
11801
11802         if (!was_visible && !visible)
11803                 return 0;
11804
11805         if (fb != old_plane_state->base.fb)
11806                 pipe_config->fb_changed = true;
11807
11808         turn_off = was_visible && (!visible || mode_changed);
11809         turn_on = visible && (!was_visible || mode_changed);
11810
11811         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11812                          plane->base.id, fb ? fb->base.id : -1);
11813
11814         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11815                          plane->base.id, was_visible, visible,
11816                          turn_off, turn_on, mode_changed);
11817
11818         if (turn_on) {
11819                 pipe_config->update_wm_pre = true;
11820
11821                 /* must disable cxsr around plane enable/disable */
11822                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11823                         pipe_config->disable_cxsr = true;
11824         } else if (turn_off) {
11825                 pipe_config->update_wm_post = true;
11826
11827                 /* must disable cxsr around plane enable/disable */
11828                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11829                         pipe_config->disable_cxsr = true;
11830         } else if (intel_wm_need_update(plane, plane_state)) {
11831                 /* FIXME bollocks */
11832                 pipe_config->update_wm_pre = true;
11833                 pipe_config->update_wm_post = true;
11834         }
11835
11836         /* Pre-gen9 platforms need two-step watermark updates */
11837         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
11838             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
11839                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
11840
11841         if (visible || was_visible)
11842                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
11843
11844         /*
11845          * WaCxSRDisabledForSpriteScaling:ivb
11846          *
11847          * cstate->update_wm was already set above, so this flag will
11848          * take effect when we commit and program watermarks.
11849          */
11850         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
11851             needs_scaling(to_intel_plane_state(plane_state)) &&
11852             !needs_scaling(old_plane_state))
11853                 pipe_config->disable_lp_wm = true;
11854
11855         return 0;
11856 }
11857
11858 static bool encoders_cloneable(const struct intel_encoder *a,
11859                                const struct intel_encoder *b)
11860 {
11861         /* masks could be asymmetric, so check both ways */
11862         return a == b || (a->cloneable & (1 << b->type) &&
11863                           b->cloneable & (1 << a->type));
11864 }
11865
11866 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11867                                          struct intel_crtc *crtc,
11868                                          struct intel_encoder *encoder)
11869 {
11870         struct intel_encoder *source_encoder;
11871         struct drm_connector *connector;
11872         struct drm_connector_state *connector_state;
11873         int i;
11874
11875         for_each_connector_in_state(state, connector, connector_state, i) {
11876                 if (connector_state->crtc != &crtc->base)
11877                         continue;
11878
11879                 source_encoder =
11880                         to_intel_encoder(connector_state->best_encoder);
11881                 if (!encoders_cloneable(encoder, source_encoder))
11882                         return false;
11883         }
11884
11885         return true;
11886 }
11887
11888 static bool check_encoder_cloning(struct drm_atomic_state *state,
11889                                   struct intel_crtc *crtc)
11890 {
11891         struct intel_encoder *encoder;
11892         struct drm_connector *connector;
11893         struct drm_connector_state *connector_state;
11894         int i;
11895
11896         for_each_connector_in_state(state, connector, connector_state, i) {
11897                 if (connector_state->crtc != &crtc->base)
11898                         continue;
11899
11900                 encoder = to_intel_encoder(connector_state->best_encoder);
11901                 if (!check_single_encoder_cloning(state, crtc, encoder))
11902                         return false;
11903         }
11904
11905         return true;
11906 }
11907
11908 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11909                                    struct drm_crtc_state *crtc_state)
11910 {
11911         struct drm_device *dev = crtc->dev;
11912         struct drm_i915_private *dev_priv = dev->dev_private;
11913         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11914         struct intel_crtc_state *pipe_config =
11915                 to_intel_crtc_state(crtc_state);
11916         struct drm_atomic_state *state = crtc_state->state;
11917         int ret;
11918         bool mode_changed = needs_modeset(crtc_state);
11919
11920         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11921                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11922                 return -EINVAL;
11923         }
11924
11925         if (mode_changed && !crtc_state->active)
11926                 pipe_config->update_wm_post = true;
11927
11928         if (mode_changed && crtc_state->enable &&
11929             dev_priv->display.crtc_compute_clock &&
11930             !WARN_ON(pipe_config->shared_dpll)) {
11931                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11932                                                            pipe_config);
11933                 if (ret)
11934                         return ret;
11935         }
11936
11937         if (crtc_state->color_mgmt_changed) {
11938                 ret = intel_color_check(crtc, crtc_state);
11939                 if (ret)
11940                         return ret;
11941         }
11942
11943         ret = 0;
11944         if (dev_priv->display.compute_pipe_wm) {
11945                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11946                 if (ret) {
11947                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11948                         return ret;
11949                 }
11950         }
11951
11952         if (dev_priv->display.compute_intermediate_wm &&
11953             !to_intel_atomic_state(state)->skip_intermediate_wm) {
11954                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11955                         return 0;
11956
11957                 /*
11958                  * Calculate 'intermediate' watermarks that satisfy both the
11959                  * old state and the new state.  We can program these
11960                  * immediately.
11961                  */
11962                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
11963                                                                 intel_crtc,
11964                                                                 pipe_config);
11965                 if (ret) {
11966                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11967                         return ret;
11968                 }
11969         }
11970
11971         if (INTEL_INFO(dev)->gen >= 9) {
11972                 if (mode_changed)
11973                         ret = skl_update_scaler_crtc(pipe_config);
11974
11975                 if (!ret)
11976                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
11977                                                          pipe_config);
11978         }
11979
11980         return ret;
11981 }
11982
11983 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11984         .mode_set_base_atomic = intel_pipe_set_base_atomic,
11985         .atomic_begin = intel_begin_crtc_commit,
11986         .atomic_flush = intel_finish_crtc_commit,
11987         .atomic_check = intel_crtc_atomic_check,
11988 };
11989
11990 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11991 {
11992         struct intel_connector *connector;
11993
11994         for_each_intel_connector(dev, connector) {
11995                 if (connector->base.encoder) {
11996                         connector->base.state->best_encoder =
11997                                 connector->base.encoder;
11998                         connector->base.state->crtc =
11999                                 connector->base.encoder->crtc;
12000                 } else {
12001                         connector->base.state->best_encoder = NULL;
12002                         connector->base.state->crtc = NULL;
12003                 }
12004         }
12005 }
12006
12007 static void
12008 connected_sink_compute_bpp(struct intel_connector *connector,
12009                            struct intel_crtc_state *pipe_config)
12010 {
12011         int bpp = pipe_config->pipe_bpp;
12012
12013         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12014                 connector->base.base.id,
12015                 connector->base.name);
12016
12017         /* Don't use an invalid EDID bpc value */
12018         if (connector->base.display_info.bpc &&
12019             connector->base.display_info.bpc * 3 < bpp) {
12020                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12021                               bpp, connector->base.display_info.bpc*3);
12022                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12023         }
12024
12025         /* Clamp bpp to default limit on screens without EDID 1.4 */
12026         if (connector->base.display_info.bpc == 0) {
12027                 int type = connector->base.connector_type;
12028                 int clamp_bpp = 24;
12029
12030                 /* Fall back to 18 bpp when DP sink capability is unknown. */
12031                 if (type == DRM_MODE_CONNECTOR_DisplayPort ||
12032                     type == DRM_MODE_CONNECTOR_eDP)
12033                         clamp_bpp = 18;
12034
12035                 if (bpp > clamp_bpp) {
12036                         DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of %d\n",
12037                                       bpp, clamp_bpp);
12038                         pipe_config->pipe_bpp = clamp_bpp;
12039                 }
12040         }
12041 }
12042
12043 static int
12044 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12045                           struct intel_crtc_state *pipe_config)
12046 {
12047         struct drm_device *dev = crtc->base.dev;
12048         struct drm_atomic_state *state;
12049         struct drm_connector *connector;
12050         struct drm_connector_state *connector_state;
12051         int bpp, i;
12052
12053         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12054                 bpp = 10*3;
12055         else if (INTEL_INFO(dev)->gen >= 5)
12056                 bpp = 12*3;
12057         else
12058                 bpp = 8*3;
12059
12060
12061         pipe_config->pipe_bpp = bpp;
12062
12063         state = pipe_config->base.state;
12064
12065         /* Clamp display bpp to EDID value */
12066         for_each_connector_in_state(state, connector, connector_state, i) {
12067                 if (connector_state->crtc != &crtc->base)
12068                         continue;
12069
12070                 connected_sink_compute_bpp(to_intel_connector(connector),
12071                                            pipe_config);
12072         }
12073
12074         return bpp;
12075 }
12076
12077 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12078 {
12079         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12080                         "type: 0x%x flags: 0x%x\n",
12081                 mode->crtc_clock,
12082                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12083                 mode->crtc_hsync_end, mode->crtc_htotal,
12084                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12085                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12086 }
12087
12088 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12089                                    struct intel_crtc_state *pipe_config,
12090                                    const char *context)
12091 {
12092         struct drm_device *dev = crtc->base.dev;
12093         struct drm_plane *plane;
12094         struct intel_plane *intel_plane;
12095         struct intel_plane_state *state;
12096         struct drm_framebuffer *fb;
12097
12098         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
12099                       context, pipe_config, pipe_name(crtc->pipe));
12100
12101         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12102         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12103                       pipe_config->pipe_bpp, pipe_config->dither);
12104         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12105                       pipe_config->has_pch_encoder,
12106                       pipe_config->fdi_lanes,
12107                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12108                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12109                       pipe_config->fdi_m_n.tu);
12110         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12111                       pipe_config->has_dp_encoder,
12112                       pipe_config->lane_count,
12113                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12114                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12115                       pipe_config->dp_m_n.tu);
12116
12117         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12118                       pipe_config->has_dp_encoder,
12119                       pipe_config->lane_count,
12120                       pipe_config->dp_m2_n2.gmch_m,
12121                       pipe_config->dp_m2_n2.gmch_n,
12122                       pipe_config->dp_m2_n2.link_m,
12123                       pipe_config->dp_m2_n2.link_n,
12124                       pipe_config->dp_m2_n2.tu);
12125
12126         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12127                       pipe_config->has_audio,
12128                       pipe_config->has_infoframe);
12129
12130         DRM_DEBUG_KMS("requested mode:\n");
12131         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12132         DRM_DEBUG_KMS("adjusted mode:\n");
12133         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12134         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12135         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12136         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12137                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12138         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12139                       crtc->num_scalers,
12140                       pipe_config->scaler_state.scaler_users,
12141                       pipe_config->scaler_state.scaler_id);
12142         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12143                       pipe_config->gmch_pfit.control,
12144                       pipe_config->gmch_pfit.pgm_ratios,
12145                       pipe_config->gmch_pfit.lvds_border_bits);
12146         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12147                       pipe_config->pch_pfit.pos,
12148                       pipe_config->pch_pfit.size,
12149                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12150         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12151         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12152
12153         if (IS_BROXTON(dev)) {
12154                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12155                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12156                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12157                               pipe_config->ddi_pll_sel,
12158                               pipe_config->dpll_hw_state.ebb0,
12159                               pipe_config->dpll_hw_state.ebb4,
12160                               pipe_config->dpll_hw_state.pll0,
12161                               pipe_config->dpll_hw_state.pll1,
12162                               pipe_config->dpll_hw_state.pll2,
12163                               pipe_config->dpll_hw_state.pll3,
12164                               pipe_config->dpll_hw_state.pll6,
12165                               pipe_config->dpll_hw_state.pll8,
12166                               pipe_config->dpll_hw_state.pll9,
12167                               pipe_config->dpll_hw_state.pll10,
12168                               pipe_config->dpll_hw_state.pcsdw12);
12169         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12170                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12171                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12172                               pipe_config->ddi_pll_sel,
12173                               pipe_config->dpll_hw_state.ctrl1,
12174                               pipe_config->dpll_hw_state.cfgcr1,
12175                               pipe_config->dpll_hw_state.cfgcr2);
12176         } else if (HAS_DDI(dev)) {
12177                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12178                               pipe_config->ddi_pll_sel,
12179                               pipe_config->dpll_hw_state.wrpll,
12180                               pipe_config->dpll_hw_state.spll);
12181         } else {
12182                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12183                               "fp0: 0x%x, fp1: 0x%x\n",
12184                               pipe_config->dpll_hw_state.dpll,
12185                               pipe_config->dpll_hw_state.dpll_md,
12186                               pipe_config->dpll_hw_state.fp0,
12187                               pipe_config->dpll_hw_state.fp1);
12188         }
12189
12190         DRM_DEBUG_KMS("planes on this crtc\n");
12191         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12192                 intel_plane = to_intel_plane(plane);
12193                 if (intel_plane->pipe != crtc->pipe)
12194                         continue;
12195
12196                 state = to_intel_plane_state(plane->state);
12197                 fb = state->base.fb;
12198                 if (!fb) {
12199                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
12200                                 "disabled, scaler_id = %d\n",
12201                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12202                                 plane->base.id, intel_plane->pipe,
12203                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
12204                                 drm_plane_index(plane), state->scaler_id);
12205                         continue;
12206                 }
12207
12208                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
12209                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12210                         plane->base.id, intel_plane->pipe,
12211                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
12212                         drm_plane_index(plane));
12213                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
12214                         fb->base.id, fb->width, fb->height, fb->pixel_format);
12215                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
12216                         state->scaler_id,
12217                         state->src.x1 >> 16, state->src.y1 >> 16,
12218                         drm_rect_width(&state->src) >> 16,
12219                         drm_rect_height(&state->src) >> 16,
12220                         state->dst.x1, state->dst.y1,
12221                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
12222         }
12223 }
12224
12225 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12226 {
12227         struct drm_device *dev = state->dev;
12228         struct drm_connector *connector;
12229         unsigned int used_ports = 0;
12230
12231         /*
12232          * Walk the connector list instead of the encoder
12233          * list to detect the problem on ddi platforms
12234          * where there's just one encoder per digital port.
12235          */
12236         drm_for_each_connector(connector, dev) {
12237                 struct drm_connector_state *connector_state;
12238                 struct intel_encoder *encoder;
12239
12240                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12241                 if (!connector_state)
12242                         connector_state = connector->state;
12243
12244                 if (!connector_state->best_encoder)
12245                         continue;
12246
12247                 encoder = to_intel_encoder(connector_state->best_encoder);
12248
12249                 WARN_ON(!connector_state->crtc);
12250
12251                 switch (encoder->type) {
12252                         unsigned int port_mask;
12253                 case INTEL_OUTPUT_UNKNOWN:
12254                         if (WARN_ON(!HAS_DDI(dev)))
12255                                 break;
12256                 case INTEL_OUTPUT_DISPLAYPORT:
12257                 case INTEL_OUTPUT_HDMI:
12258                 case INTEL_OUTPUT_EDP:
12259                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12260
12261                         /* the same port mustn't appear more than once */
12262                         if (used_ports & port_mask)
12263                                 return false;
12264
12265                         used_ports |= port_mask;
12266                 default:
12267                         break;
12268                 }
12269         }
12270
12271         return true;
12272 }
12273
12274 static void
12275 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12276 {
12277         struct drm_crtc_state tmp_state;
12278         struct intel_crtc_scaler_state scaler_state;
12279         struct intel_dpll_hw_state dpll_hw_state;
12280         struct intel_shared_dpll *shared_dpll;
12281         uint32_t ddi_pll_sel;
12282         bool force_thru;
12283
12284         /* FIXME: before the switch to atomic started, a new pipe_config was
12285          * kzalloc'd. Code that depends on any field being zero should be
12286          * fixed, so that the crtc_state can be safely duplicated. For now,
12287          * only fields that are know to not cause problems are preserved. */
12288
12289         tmp_state = crtc_state->base;
12290         scaler_state = crtc_state->scaler_state;
12291         shared_dpll = crtc_state->shared_dpll;
12292         dpll_hw_state = crtc_state->dpll_hw_state;
12293         ddi_pll_sel = crtc_state->ddi_pll_sel;
12294         force_thru = crtc_state->pch_pfit.force_thru;
12295
12296         memset(crtc_state, 0, sizeof *crtc_state);
12297
12298         crtc_state->base = tmp_state;
12299         crtc_state->scaler_state = scaler_state;
12300         crtc_state->shared_dpll = shared_dpll;
12301         crtc_state->dpll_hw_state = dpll_hw_state;
12302         crtc_state->ddi_pll_sel = ddi_pll_sel;
12303         crtc_state->pch_pfit.force_thru = force_thru;
12304 }
12305
12306 static int
12307 intel_modeset_pipe_config(struct drm_crtc *crtc,
12308                           struct intel_crtc_state *pipe_config)
12309 {
12310         struct drm_atomic_state *state = pipe_config->base.state;
12311         struct intel_encoder *encoder;
12312         struct drm_connector *connector;
12313         struct drm_connector_state *connector_state;
12314         int base_bpp, ret = -EINVAL;
12315         int i;
12316         bool retry = true;
12317
12318         clear_intel_crtc_state(pipe_config);
12319
12320         pipe_config->cpu_transcoder =
12321                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12322
12323         /*
12324          * Sanitize sync polarity flags based on requested ones. If neither
12325          * positive or negative polarity is requested, treat this as meaning
12326          * negative polarity.
12327          */
12328         if (!(pipe_config->base.adjusted_mode.flags &
12329               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12330                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12331
12332         if (!(pipe_config->base.adjusted_mode.flags &
12333               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12334                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12335
12336         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12337                                              pipe_config);
12338         if (base_bpp < 0)
12339                 goto fail;
12340
12341         /*
12342          * Determine the real pipe dimensions. Note that stereo modes can
12343          * increase the actual pipe size due to the frame doubling and
12344          * insertion of additional space for blanks between the frame. This
12345          * is stored in the crtc timings. We use the requested mode to do this
12346          * computation to clearly distinguish it from the adjusted mode, which
12347          * can be changed by the connectors in the below retry loop.
12348          */
12349         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12350                                &pipe_config->pipe_src_w,
12351                                &pipe_config->pipe_src_h);
12352
12353 encoder_retry:
12354         /* Ensure the port clock defaults are reset when retrying. */
12355         pipe_config->port_clock = 0;
12356         pipe_config->pixel_multiplier = 1;
12357
12358         /* Fill in default crtc timings, allow encoders to overwrite them. */
12359         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12360                               CRTC_STEREO_DOUBLE);
12361
12362         /* Pass our mode to the connectors and the CRTC to give them a chance to
12363          * adjust it according to limitations or connector properties, and also
12364          * a chance to reject the mode entirely.
12365          */
12366         for_each_connector_in_state(state, connector, connector_state, i) {
12367                 if (connector_state->crtc != crtc)
12368                         continue;
12369
12370                 encoder = to_intel_encoder(connector_state->best_encoder);
12371
12372                 if (!(encoder->compute_config(encoder, pipe_config))) {
12373                         DRM_DEBUG_KMS("Encoder config failure\n");
12374                         goto fail;
12375                 }
12376         }
12377
12378         /* Set default port clock if not overwritten by the encoder. Needs to be
12379          * done afterwards in case the encoder adjusts the mode. */
12380         if (!pipe_config->port_clock)
12381                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12382                         * pipe_config->pixel_multiplier;
12383
12384         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12385         if (ret < 0) {
12386                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12387                 goto fail;
12388         }
12389
12390         if (ret == RETRY) {
12391                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12392                         ret = -EINVAL;
12393                         goto fail;
12394                 }
12395
12396                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12397                 retry = false;
12398                 goto encoder_retry;
12399         }
12400
12401         /* Dithering seems to not pass-through bits correctly when it should, so
12402          * only enable it on 6bpc panels. */
12403         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12404         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12405                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12406
12407 fail:
12408         return ret;
12409 }
12410
12411 static void
12412 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12413 {
12414         struct drm_crtc *crtc;
12415         struct drm_crtc_state *crtc_state;
12416         int i;
12417
12418         /* Double check state. */
12419         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12420                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12421
12422                 /* Update hwmode for vblank functions */
12423                 if (crtc->state->active)
12424                         crtc->hwmode = crtc->state->adjusted_mode;
12425                 else
12426                         crtc->hwmode.crtc_clock = 0;
12427
12428                 /*
12429                  * Update legacy state to satisfy fbc code. This can
12430                  * be removed when fbc uses the atomic state.
12431                  */
12432                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12433                         struct drm_plane_state *plane_state = crtc->primary->state;
12434
12435                         crtc->primary->fb = plane_state->fb;
12436                         crtc->x = plane_state->src_x >> 16;
12437                         crtc->y = plane_state->src_y >> 16;
12438                 }
12439         }
12440 }
12441
12442 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12443 {
12444         int diff;
12445
12446         if (clock1 == clock2)
12447                 return true;
12448
12449         if (!clock1 || !clock2)
12450                 return false;
12451
12452         diff = abs(clock1 - clock2);
12453
12454         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12455                 return true;
12456
12457         return false;
12458 }
12459
12460 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12461         list_for_each_entry((intel_crtc), \
12462                             &(dev)->mode_config.crtc_list, \
12463                             base.head) \
12464                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12465
12466 static bool
12467 intel_compare_m_n(unsigned int m, unsigned int n,
12468                   unsigned int m2, unsigned int n2,
12469                   bool exact)
12470 {
12471         if (m == m2 && n == n2)
12472                 return true;
12473
12474         if (exact || !m || !n || !m2 || !n2)
12475                 return false;
12476
12477         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12478
12479         if (n > n2) {
12480                 while (n > n2) {
12481                         m2 <<= 1;
12482                         n2 <<= 1;
12483                 }
12484         } else if (n < n2) {
12485                 while (n < n2) {
12486                         m <<= 1;
12487                         n <<= 1;
12488                 }
12489         }
12490
12491         if (n != n2)
12492                 return false;
12493
12494         return intel_fuzzy_clock_check(m, m2);
12495 }
12496
12497 static bool
12498 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12499                        struct intel_link_m_n *m2_n2,
12500                        bool adjust)
12501 {
12502         if (m_n->tu == m2_n2->tu &&
12503             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12504                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12505             intel_compare_m_n(m_n->link_m, m_n->link_n,
12506                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12507                 if (adjust)
12508                         *m2_n2 = *m_n;
12509
12510                 return true;
12511         }
12512
12513         return false;
12514 }
12515
12516 static bool
12517 intel_pipe_config_compare(struct drm_device *dev,
12518                           struct intel_crtc_state *current_config,
12519                           struct intel_crtc_state *pipe_config,
12520                           bool adjust)
12521 {
12522         bool ret = true;
12523
12524 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12525         do { \
12526                 if (!adjust) \
12527                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12528                 else \
12529                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12530         } while (0)
12531
12532 #define PIPE_CONF_CHECK_X(name) \
12533         if (current_config->name != pipe_config->name) { \
12534                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12535                           "(expected 0x%08x, found 0x%08x)\n", \
12536                           current_config->name, \
12537                           pipe_config->name); \
12538                 ret = false; \
12539         }
12540
12541 #define PIPE_CONF_CHECK_I(name) \
12542         if (current_config->name != pipe_config->name) { \
12543                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12544                           "(expected %i, found %i)\n", \
12545                           current_config->name, \
12546                           pipe_config->name); \
12547                 ret = false; \
12548         }
12549
12550 #define PIPE_CONF_CHECK_P(name) \
12551         if (current_config->name != pipe_config->name) { \
12552                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12553                           "(expected %p, found %p)\n", \
12554                           current_config->name, \
12555                           pipe_config->name); \
12556                 ret = false; \
12557         }
12558
12559 #define PIPE_CONF_CHECK_M_N(name) \
12560         if (!intel_compare_link_m_n(&current_config->name, \
12561                                     &pipe_config->name,\
12562                                     adjust)) { \
12563                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12564                           "(expected tu %i gmch %i/%i link %i/%i, " \
12565                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12566                           current_config->name.tu, \
12567                           current_config->name.gmch_m, \
12568                           current_config->name.gmch_n, \
12569                           current_config->name.link_m, \
12570                           current_config->name.link_n, \
12571                           pipe_config->name.tu, \
12572                           pipe_config->name.gmch_m, \
12573                           pipe_config->name.gmch_n, \
12574                           pipe_config->name.link_m, \
12575                           pipe_config->name.link_n); \
12576                 ret = false; \
12577         }
12578
12579 /* This is required for BDW+ where there is only one set of registers for
12580  * switching between high and low RR.
12581  * This macro can be used whenever a comparison has to be made between one
12582  * hw state and multiple sw state variables.
12583  */
12584 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12585         if (!intel_compare_link_m_n(&current_config->name, \
12586                                     &pipe_config->name, adjust) && \
12587             !intel_compare_link_m_n(&current_config->alt_name, \
12588                                     &pipe_config->name, adjust)) { \
12589                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12590                           "(expected tu %i gmch %i/%i link %i/%i, " \
12591                           "or tu %i gmch %i/%i link %i/%i, " \
12592                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12593                           current_config->name.tu, \
12594                           current_config->name.gmch_m, \
12595                           current_config->name.gmch_n, \
12596                           current_config->name.link_m, \
12597                           current_config->name.link_n, \
12598                           current_config->alt_name.tu, \
12599                           current_config->alt_name.gmch_m, \
12600                           current_config->alt_name.gmch_n, \
12601                           current_config->alt_name.link_m, \
12602                           current_config->alt_name.link_n, \
12603                           pipe_config->name.tu, \
12604                           pipe_config->name.gmch_m, \
12605                           pipe_config->name.gmch_n, \
12606                           pipe_config->name.link_m, \
12607                           pipe_config->name.link_n); \
12608                 ret = false; \
12609         }
12610
12611 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12612         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12613                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12614                           "(expected %i, found %i)\n", \
12615                           current_config->name & (mask), \
12616                           pipe_config->name & (mask)); \
12617                 ret = false; \
12618         }
12619
12620 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12621         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12622                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12623                           "(expected %i, found %i)\n", \
12624                           current_config->name, \
12625                           pipe_config->name); \
12626                 ret = false; \
12627         }
12628
12629 #define PIPE_CONF_QUIRK(quirk)  \
12630         ((current_config->quirks | pipe_config->quirks) & (quirk))
12631
12632         PIPE_CONF_CHECK_I(cpu_transcoder);
12633
12634         PIPE_CONF_CHECK_I(has_pch_encoder);
12635         PIPE_CONF_CHECK_I(fdi_lanes);
12636         PIPE_CONF_CHECK_M_N(fdi_m_n);
12637
12638         PIPE_CONF_CHECK_I(has_dp_encoder);
12639         PIPE_CONF_CHECK_I(lane_count);
12640
12641         if (INTEL_INFO(dev)->gen < 8) {
12642                 PIPE_CONF_CHECK_M_N(dp_m_n);
12643
12644                 if (current_config->has_drrs)
12645                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12646         } else
12647                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12648
12649         PIPE_CONF_CHECK_I(has_dsi_encoder);
12650
12651         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12652         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12653         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12654         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12655         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12656         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12657
12658         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12659         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12660         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12661         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12662         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12663         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12664
12665         PIPE_CONF_CHECK_I(pixel_multiplier);
12666         PIPE_CONF_CHECK_I(has_hdmi_sink);
12667         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12668             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12669                 PIPE_CONF_CHECK_I(limited_color_range);
12670         PIPE_CONF_CHECK_I(has_infoframe);
12671
12672         PIPE_CONF_CHECK_I(has_audio);
12673
12674         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12675                               DRM_MODE_FLAG_INTERLACE);
12676
12677         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12678                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12679                                       DRM_MODE_FLAG_PHSYNC);
12680                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12681                                       DRM_MODE_FLAG_NHSYNC);
12682                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12683                                       DRM_MODE_FLAG_PVSYNC);
12684                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12685                                       DRM_MODE_FLAG_NVSYNC);
12686         }
12687
12688         PIPE_CONF_CHECK_X(gmch_pfit.control);
12689         /* pfit ratios are autocomputed by the hw on gen4+ */
12690         if (INTEL_INFO(dev)->gen < 4)
12691                 PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12692         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12693
12694         if (!adjust) {
12695                 PIPE_CONF_CHECK_I(pipe_src_w);
12696                 PIPE_CONF_CHECK_I(pipe_src_h);
12697
12698                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12699                 if (current_config->pch_pfit.enabled) {
12700                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12701                         PIPE_CONF_CHECK_X(pch_pfit.size);
12702                 }
12703
12704                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12705         }
12706
12707         /* BDW+ don't expose a synchronous way to read the state */
12708         if (IS_HASWELL(dev))
12709                 PIPE_CONF_CHECK_I(ips_enabled);
12710
12711         PIPE_CONF_CHECK_I(double_wide);
12712
12713         PIPE_CONF_CHECK_X(ddi_pll_sel);
12714
12715         PIPE_CONF_CHECK_P(shared_dpll);
12716         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12717         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12718         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12719         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12720         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12721         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12722         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12723         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12724         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12725
12726         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12727                 PIPE_CONF_CHECK_I(pipe_bpp);
12728
12729         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12730         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12731
12732 #undef PIPE_CONF_CHECK_X
12733 #undef PIPE_CONF_CHECK_I
12734 #undef PIPE_CONF_CHECK_P
12735 #undef PIPE_CONF_CHECK_FLAGS
12736 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12737 #undef PIPE_CONF_QUIRK
12738 #undef INTEL_ERR_OR_DBG_KMS
12739
12740         return ret;
12741 }
12742
12743 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12744                                            const struct intel_crtc_state *pipe_config)
12745 {
12746         if (pipe_config->has_pch_encoder) {
12747                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12748                                                             &pipe_config->fdi_m_n);
12749                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12750
12751                 /*
12752                  * FDI already provided one idea for the dotclock.
12753                  * Yell if the encoder disagrees.
12754                  */
12755                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12756                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12757                      fdi_dotclock, dotclock);
12758         }
12759 }
12760
12761 static void check_wm_state(struct drm_device *dev)
12762 {
12763         struct drm_i915_private *dev_priv = dev->dev_private;
12764         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12765         struct intel_crtc *intel_crtc;
12766         int plane;
12767
12768         if (INTEL_INFO(dev)->gen < 9)
12769                 return;
12770
12771         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12772         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12773
12774         for_each_intel_crtc(dev, intel_crtc) {
12775                 struct skl_ddb_entry *hw_entry, *sw_entry;
12776                 const enum pipe pipe = intel_crtc->pipe;
12777
12778                 if (!intel_crtc->active)
12779                         continue;
12780
12781                 /* planes */
12782                 for_each_plane(dev_priv, pipe, plane) {
12783                         hw_entry = &hw_ddb.plane[pipe][plane];
12784                         sw_entry = &sw_ddb->plane[pipe][plane];
12785
12786                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12787                                 continue;
12788
12789                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12790                                   "(expected (%u,%u), found (%u,%u))\n",
12791                                   pipe_name(pipe), plane + 1,
12792                                   sw_entry->start, sw_entry->end,
12793                                   hw_entry->start, hw_entry->end);
12794                 }
12795
12796                 /* cursor */
12797                 hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12798                 sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12799
12800                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12801                         continue;
12802
12803                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12804                           "(expected (%u,%u), found (%u,%u))\n",
12805                           pipe_name(pipe),
12806                           sw_entry->start, sw_entry->end,
12807                           hw_entry->start, hw_entry->end);
12808         }
12809 }
12810
12811 static void
12812 check_connector_state(struct drm_device *dev,
12813                       struct drm_atomic_state *old_state)
12814 {
12815         struct drm_connector_state *old_conn_state;
12816         struct drm_connector *connector;
12817         int i;
12818
12819         for_each_connector_in_state(old_state, connector, old_conn_state, i) {
12820                 struct drm_encoder *encoder = connector->encoder;
12821                 struct drm_connector_state *state = connector->state;
12822
12823                 /* This also checks the encoder/connector hw state with the
12824                  * ->get_hw_state callbacks. */
12825                 intel_connector_check_state(to_intel_connector(connector));
12826
12827                 I915_STATE_WARN(state->best_encoder != encoder,
12828                      "connector's atomic encoder doesn't match legacy encoder\n");
12829         }
12830 }
12831
12832 static void
12833 check_encoder_state(struct drm_device *dev)
12834 {
12835         struct intel_encoder *encoder;
12836         struct intel_connector *connector;
12837
12838         for_each_intel_encoder(dev, encoder) {
12839                 bool enabled = false;
12840                 enum pipe pipe;
12841
12842                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12843                               encoder->base.base.id,
12844                               encoder->base.name);
12845
12846                 for_each_intel_connector(dev, connector) {
12847                         if (connector->base.state->best_encoder != &encoder->base)
12848                                 continue;
12849                         enabled = true;
12850
12851                         I915_STATE_WARN(connector->base.state->crtc !=
12852                                         encoder->base.crtc,
12853                              "connector's crtc doesn't match encoder crtc\n");
12854                 }
12855
12856                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12857                      "encoder's enabled state mismatch "
12858                      "(expected %i, found %i)\n",
12859                      !!encoder->base.crtc, enabled);
12860
12861                 if (!encoder->base.crtc) {
12862                         bool active;
12863
12864                         active = encoder->get_hw_state(encoder, &pipe);
12865                         I915_STATE_WARN(active,
12866                              "encoder detached but still enabled on pipe %c.\n",
12867                              pipe_name(pipe));
12868                 }
12869         }
12870 }
12871
12872 static void
12873 check_crtc_state(struct drm_device *dev, struct drm_atomic_state *old_state)
12874 {
12875         struct drm_i915_private *dev_priv = dev->dev_private;
12876         struct intel_encoder *encoder;
12877         struct drm_crtc_state *old_crtc_state;
12878         struct drm_crtc *crtc;
12879         int i;
12880
12881         for_each_crtc_in_state(old_state, crtc, old_crtc_state, i) {
12882                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12883                 struct intel_crtc_state *pipe_config, *sw_config;
12884                 bool active;
12885
12886                 if (!needs_modeset(crtc->state) &&
12887                     !to_intel_crtc_state(crtc->state)->update_pipe)
12888                         continue;
12889
12890                 __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12891                 pipe_config = to_intel_crtc_state(old_crtc_state);
12892                 memset(pipe_config, 0, sizeof(*pipe_config));
12893                 pipe_config->base.crtc = crtc;
12894                 pipe_config->base.state = old_state;
12895
12896                 DRM_DEBUG_KMS("[CRTC:%d]\n",
12897                               crtc->base.id);
12898
12899                 active = dev_priv->display.get_pipe_config(intel_crtc,
12900                                                            pipe_config);
12901
12902                 /* hw state is inconsistent with the pipe quirk */
12903                 if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12904                     (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12905                         active = crtc->state->active;
12906
12907                 I915_STATE_WARN(crtc->state->active != active,
12908                      "crtc active state doesn't match with hw state "
12909                      "(expected %i, found %i)\n", crtc->state->active, active);
12910
12911                 I915_STATE_WARN(intel_crtc->active != crtc->state->active,
12912                      "transitional active state does not match atomic hw state "
12913                      "(expected %i, found %i)\n", crtc->state->active, intel_crtc->active);
12914
12915                 for_each_encoder_on_crtc(dev, crtc, encoder) {
12916                         enum pipe pipe;
12917
12918                         active = encoder->get_hw_state(encoder, &pipe);
12919                         I915_STATE_WARN(active != crtc->state->active,
12920                                 "[ENCODER:%i] active %i with crtc active %i\n",
12921                                 encoder->base.base.id, active, crtc->state->active);
12922
12923                         I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12924                                         "Encoder connected to wrong pipe %c\n",
12925                                         pipe_name(pipe));
12926
12927                         if (active)
12928                                 encoder->get_config(encoder, pipe_config);
12929                 }
12930
12931                 if (!crtc->state->active)
12932                         continue;
12933
12934                 intel_pipe_config_sanity_check(dev_priv, pipe_config);
12935
12936                 sw_config = to_intel_crtc_state(crtc->state);
12937                 if (!intel_pipe_config_compare(dev, sw_config,
12938                                                pipe_config, false)) {
12939                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12940                         intel_dump_pipe_config(intel_crtc, pipe_config,
12941                                                "[hw state]");
12942                         intel_dump_pipe_config(intel_crtc, sw_config,
12943                                                "[sw state]");
12944                 }
12945         }
12946 }
12947
12948 static void
12949 check_shared_dpll_state(struct drm_device *dev)
12950 {
12951         struct drm_i915_private *dev_priv = dev->dev_private;
12952         struct intel_crtc *crtc;
12953         struct intel_dpll_hw_state dpll_hw_state;
12954         int i;
12955
12956         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12957                 struct intel_shared_dpll *pll =
12958                         intel_get_shared_dpll_by_id(dev_priv, i);
12959                 unsigned enabled_crtcs = 0, active_crtcs = 0;
12960                 bool active;
12961
12962                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12963
12964                 DRM_DEBUG_KMS("%s\n", pll->name);
12965
12966                 active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
12967
12968                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
12969                      "more active pll users than references: %x vs %x\n",
12970                      pll->active_mask, pll->config.crtc_mask);
12971
12972                 if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
12973                         I915_STATE_WARN(!pll->on && pll->active_mask,
12974                              "pll in active use but not on in sw tracking\n");
12975                         I915_STATE_WARN(pll->on && !pll->active_mask,
12976                              "pll is on but not used by any active crtc\n");
12977                         I915_STATE_WARN(pll->on != active,
12978                              "pll on state mismatch (expected %i, found %i)\n",
12979                              pll->on, active);
12980                 }
12981
12982                 for_each_intel_crtc(dev, crtc) {
12983                         if (crtc->base.state->enable && crtc->config->shared_dpll == pll)
12984                                 enabled_crtcs |= 1 << drm_crtc_index(&crtc->base);
12985                         if (crtc->base.state->active && crtc->config->shared_dpll == pll)
12986                                 active_crtcs |= 1 << drm_crtc_index(&crtc->base);
12987                 }
12988
12989                 I915_STATE_WARN(pll->active_mask != active_crtcs,
12990                      "pll active crtcs mismatch (expected %x, found %x)\n",
12991                      pll->active_mask, active_crtcs);
12992                 I915_STATE_WARN(pll->config.crtc_mask != enabled_crtcs,
12993                      "pll enabled crtcs mismatch (expected %x, found %x)\n",
12994                      pll->config.crtc_mask, enabled_crtcs);
12995
12996                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
12997                                        sizeof(dpll_hw_state)),
12998                      "pll hw state mismatch\n");
12999         }
13000 }
13001
13002 static void
13003 intel_modeset_check_state(struct drm_device *dev,
13004                           struct drm_atomic_state *old_state)
13005 {
13006         check_wm_state(dev);
13007         check_connector_state(dev, old_state);
13008         check_encoder_state(dev);
13009         check_crtc_state(dev, old_state);
13010         check_shared_dpll_state(dev);
13011 }
13012
13013 static void update_scanline_offset(struct intel_crtc *crtc)
13014 {
13015         struct drm_device *dev = crtc->base.dev;
13016
13017         /*
13018          * The scanline counter increments at the leading edge of hsync.
13019          *
13020          * On most platforms it starts counting from vtotal-1 on the
13021          * first active line. That means the scanline counter value is
13022          * always one less than what we would expect. Ie. just after
13023          * start of vblank, which also occurs at start of hsync (on the
13024          * last active line), the scanline counter will read vblank_start-1.
13025          *
13026          * On gen2 the scanline counter starts counting from 1 instead
13027          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13028          * to keep the value positive), instead of adding one.
13029          *
13030          * On HSW+ the behaviour of the scanline counter depends on the output
13031          * type. For DP ports it behaves like most other platforms, but on HDMI
13032          * there's an extra 1 line difference. So we need to add two instead of
13033          * one to the value.
13034          */
13035         if (IS_GEN2(dev)) {
13036                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13037                 int vtotal;
13038
13039                 vtotal = adjusted_mode->crtc_vtotal;
13040                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13041                         vtotal /= 2;
13042
13043                 crtc->scanline_offset = vtotal - 1;
13044         } else if (HAS_DDI(dev) &&
13045                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
13046                 crtc->scanline_offset = 2;
13047         } else
13048                 crtc->scanline_offset = 1;
13049 }
13050
13051 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13052 {
13053         struct drm_device *dev = state->dev;
13054         struct drm_i915_private *dev_priv = to_i915(dev);
13055         struct intel_shared_dpll_config *shared_dpll = NULL;
13056         struct drm_crtc *crtc;
13057         struct drm_crtc_state *crtc_state;
13058         int i;
13059
13060         if (!dev_priv->display.crtc_compute_clock)
13061                 return;
13062
13063         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13064                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13065                 struct intel_shared_dpll *old_dpll =
13066                         to_intel_crtc_state(crtc->state)->shared_dpll;
13067
13068                 if (!needs_modeset(crtc_state))
13069                         continue;
13070
13071                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13072
13073                 if (!old_dpll)
13074                         continue;
13075
13076                 if (!shared_dpll)
13077                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13078
13079                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13080         }
13081 }
13082
13083 /*
13084  * This implements the workaround described in the "notes" section of the mode
13085  * set sequence documentation. When going from no pipes or single pipe to
13086  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13087  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13088  */
13089 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13090 {
13091         struct drm_crtc_state *crtc_state;
13092         struct intel_crtc *intel_crtc;
13093         struct drm_crtc *crtc;
13094         struct intel_crtc_state *first_crtc_state = NULL;
13095         struct intel_crtc_state *other_crtc_state = NULL;
13096         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13097         int i;
13098
13099         /* look at all crtc's that are going to be enabled in during modeset */
13100         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13101                 intel_crtc = to_intel_crtc(crtc);
13102
13103                 if (!crtc_state->active || !needs_modeset(crtc_state))
13104                         continue;
13105
13106                 if (first_crtc_state) {
13107                         other_crtc_state = to_intel_crtc_state(crtc_state);
13108                         break;
13109                 } else {
13110                         first_crtc_state = to_intel_crtc_state(crtc_state);
13111                         first_pipe = intel_crtc->pipe;
13112                 }
13113         }
13114
13115         /* No workaround needed? */
13116         if (!first_crtc_state)
13117                 return 0;
13118
13119         /* w/a possibly needed, check how many crtc's are already enabled. */
13120         for_each_intel_crtc(state->dev, intel_crtc) {
13121                 struct intel_crtc_state *pipe_config;
13122
13123                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13124                 if (IS_ERR(pipe_config))
13125                         return PTR_ERR(pipe_config);
13126
13127                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13128
13129                 if (!pipe_config->base.active ||
13130                     needs_modeset(&pipe_config->base))
13131                         continue;
13132
13133                 /* 2 or more enabled crtcs means no need for w/a */
13134                 if (enabled_pipe != INVALID_PIPE)
13135                         return 0;
13136
13137                 enabled_pipe = intel_crtc->pipe;
13138         }
13139
13140         if (enabled_pipe != INVALID_PIPE)
13141                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13142         else if (other_crtc_state)
13143                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13144
13145         return 0;
13146 }
13147
13148 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13149 {
13150         struct drm_crtc *crtc;
13151         struct drm_crtc_state *crtc_state;
13152         int ret = 0;
13153
13154         /* add all active pipes to the state */
13155         for_each_crtc(state->dev, crtc) {
13156                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13157                 if (IS_ERR(crtc_state))
13158                         return PTR_ERR(crtc_state);
13159
13160                 if (!crtc_state->active || needs_modeset(crtc_state))
13161                         continue;
13162
13163                 crtc_state->mode_changed = true;
13164
13165                 ret = drm_atomic_add_affected_connectors(state, crtc);
13166                 if (ret)
13167                         break;
13168
13169                 ret = drm_atomic_add_affected_planes(state, crtc);
13170                 if (ret)
13171                         break;
13172         }
13173
13174         return ret;
13175 }
13176
13177 static int intel_modeset_checks(struct drm_atomic_state *state)
13178 {
13179         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13180         struct drm_i915_private *dev_priv = state->dev->dev_private;
13181         struct drm_crtc *crtc;
13182         struct drm_crtc_state *crtc_state;
13183         int ret = 0, i;
13184
13185         if (!check_digital_port_conflicts(state)) {
13186                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13187                 return -EINVAL;
13188         }
13189
13190         intel_state->modeset = true;
13191         intel_state->active_crtcs = dev_priv->active_crtcs;
13192
13193         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13194                 if (crtc_state->active)
13195                         intel_state->active_crtcs |= 1 << i;
13196                 else
13197                         intel_state->active_crtcs &= ~(1 << i);
13198         }
13199
13200         /*
13201          * See if the config requires any additional preparation, e.g.
13202          * to adjust global state with pipes off.  We need to do this
13203          * here so we can get the modeset_pipe updated config for the new
13204          * mode set on this crtc.  For other crtcs we need to use the
13205          * adjusted_mode bits in the crtc directly.
13206          */
13207         if (dev_priv->display.modeset_calc_cdclk) {
13208                 ret = dev_priv->display.modeset_calc_cdclk(state);
13209
13210                 if (!ret && intel_state->dev_cdclk != dev_priv->cdclk_freq)
13211                         ret = intel_modeset_all_pipes(state);
13212
13213                 if (ret < 0)
13214                         return ret;
13215
13216                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13217                               intel_state->cdclk, intel_state->dev_cdclk);
13218         } else
13219                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13220
13221         intel_modeset_clear_plls(state);
13222
13223         if (IS_HASWELL(dev_priv))
13224                 return haswell_mode_set_planes_workaround(state);
13225
13226         return 0;
13227 }
13228
13229 /*
13230  * Handle calculation of various watermark data at the end of the atomic check
13231  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13232  * handlers to ensure that all derived state has been updated.
13233  */
13234 static void calc_watermark_data(struct drm_atomic_state *state)
13235 {
13236         struct drm_device *dev = state->dev;
13237         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13238         struct drm_crtc *crtc;
13239         struct drm_crtc_state *cstate;
13240         struct drm_plane *plane;
13241         struct drm_plane_state *pstate;
13242
13243         /*
13244          * Calculate watermark configuration details now that derived
13245          * plane/crtc state is all properly updated.
13246          */
13247         drm_for_each_crtc(crtc, dev) {
13248                 cstate = drm_atomic_get_existing_crtc_state(state, crtc) ?:
13249                         crtc->state;
13250
13251                 if (cstate->active)
13252                         intel_state->wm_config.num_pipes_active++;
13253         }
13254         drm_for_each_legacy_plane(plane, dev) {
13255                 pstate = drm_atomic_get_existing_plane_state(state, plane) ?:
13256                         plane->state;
13257
13258                 if (!to_intel_plane_state(pstate)->visible)
13259                         continue;
13260
13261                 intel_state->wm_config.sprites_enabled = true;
13262                 if (pstate->crtc_w != pstate->src_w >> 16 ||
13263                     pstate->crtc_h != pstate->src_h >> 16)
13264                         intel_state->wm_config.sprites_scaled = true;
13265         }
13266 }
13267
13268 /**
13269  * intel_atomic_check - validate state object
13270  * @dev: drm device
13271  * @state: state to validate
13272  */
13273 static int intel_atomic_check(struct drm_device *dev,
13274                               struct drm_atomic_state *state)
13275 {
13276         struct drm_i915_private *dev_priv = to_i915(dev);
13277         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13278         struct drm_crtc *crtc;
13279         struct drm_crtc_state *crtc_state;
13280         int ret, i;
13281         bool any_ms = false;
13282
13283         ret = drm_atomic_helper_check_modeset(dev, state);
13284         if (ret)
13285                 return ret;
13286
13287         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13288                 struct intel_crtc_state *pipe_config =
13289                         to_intel_crtc_state(crtc_state);
13290
13291                 /* Catch I915_MODE_FLAG_INHERITED */
13292                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13293                         crtc_state->mode_changed = true;
13294
13295                 if (!crtc_state->enable) {
13296                         if (needs_modeset(crtc_state))
13297                                 any_ms = true;
13298                         continue;
13299                 }
13300
13301                 if (!needs_modeset(crtc_state))
13302                         continue;
13303
13304                 /* FIXME: For only active_changed we shouldn't need to do any
13305                  * state recomputation at all. */
13306
13307                 ret = drm_atomic_add_affected_connectors(state, crtc);
13308                 if (ret)
13309                         return ret;
13310
13311                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13312                 if (ret)
13313                         return ret;
13314
13315                 if (i915.fastboot &&
13316                     intel_pipe_config_compare(dev,
13317                                         to_intel_crtc_state(crtc->state),
13318                                         pipe_config, true)) {
13319                         crtc_state->mode_changed = false;
13320                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13321                 }
13322
13323                 if (needs_modeset(crtc_state)) {
13324                         any_ms = true;
13325
13326                         ret = drm_atomic_add_affected_planes(state, crtc);
13327                         if (ret)
13328                                 return ret;
13329                 }
13330
13331                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13332                                        needs_modeset(crtc_state) ?
13333                                        "[modeset]" : "[fastset]");
13334         }
13335
13336         if (any_ms) {
13337                 ret = intel_modeset_checks(state);
13338
13339                 if (ret)
13340                         return ret;
13341         } else
13342                 intel_state->cdclk = dev_priv->cdclk_freq;
13343
13344         ret = drm_atomic_helper_check_planes(dev, state);
13345         if (ret)
13346                 return ret;
13347
13348         intel_fbc_choose_crtc(dev_priv, state);
13349         calc_watermark_data(state);
13350
13351         return 0;
13352 }
13353
13354 static int intel_atomic_prepare_commit(struct drm_device *dev,
13355                                        struct drm_atomic_state *state,
13356                                        bool async)
13357 {
13358         struct drm_i915_private *dev_priv = dev->dev_private;
13359         struct drm_plane_state *plane_state;
13360         struct drm_crtc_state *crtc_state;
13361         struct drm_plane *plane;
13362         struct drm_crtc *crtc;
13363         int i, ret;
13364
13365         if (async) {
13366                 DRM_DEBUG_KMS("i915 does not yet support async commit\n");
13367                 return -EINVAL;
13368         }
13369
13370         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13371                 ret = intel_crtc_wait_for_pending_flips(crtc);
13372                 if (ret)
13373                         return ret;
13374
13375                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13376                         flush_workqueue(dev_priv->wq);
13377         }
13378
13379         ret = mutex_lock_interruptible(&dev->struct_mutex);
13380         if (ret)
13381                 return ret;
13382
13383         ret = drm_atomic_helper_prepare_planes(dev, state);
13384         if (!ret && !async && !i915_reset_in_progress(&dev_priv->gpu_error)) {
13385                 u32 reset_counter;
13386
13387                 reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
13388                 mutex_unlock(&dev->struct_mutex);
13389
13390                 for_each_plane_in_state(state, plane, plane_state, i) {
13391                         struct intel_plane_state *intel_plane_state =
13392                                 to_intel_plane_state(plane_state);
13393
13394                         if (!intel_plane_state->wait_req)
13395                                 continue;
13396
13397                         ret = __i915_wait_request(intel_plane_state->wait_req,
13398                                                   reset_counter, true,
13399                                                   NULL, NULL);
13400
13401                         /* Swallow -EIO errors to allow updates during hw lockup. */
13402                         if (ret == -EIO)
13403                                 ret = 0;
13404
13405                         if (ret)
13406                                 break;
13407                 }
13408
13409                 if (!ret)
13410                         return 0;
13411
13412                 mutex_lock(&dev->struct_mutex);
13413                 drm_atomic_helper_cleanup_planes(dev, state);
13414         }
13415
13416         mutex_unlock(&dev->struct_mutex);
13417         return ret;
13418 }
13419
13420 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
13421                                           struct drm_i915_private *dev_priv,
13422                                           unsigned crtc_mask)
13423 {
13424         unsigned last_vblank_count[I915_MAX_PIPES];
13425         enum pipe pipe;
13426         int ret;
13427
13428         if (!crtc_mask)
13429                 return;
13430
13431         for_each_pipe(dev_priv, pipe) {
13432                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13433
13434                 if (!((1 << pipe) & crtc_mask))
13435                         continue;
13436
13437                 ret = drm_crtc_vblank_get(crtc);
13438                 if (WARN_ON(ret != 0)) {
13439                         crtc_mask &= ~(1 << pipe);
13440                         continue;
13441                 }
13442
13443                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
13444         }
13445
13446         for_each_pipe(dev_priv, pipe) {
13447                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13448                 long lret;
13449
13450                 if (!((1 << pipe) & crtc_mask))
13451                         continue;
13452
13453                 lret = wait_event_timeout(dev->vblank[pipe].queue,
13454                                 last_vblank_count[pipe] !=
13455                                         drm_crtc_vblank_count(crtc),
13456                                 msecs_to_jiffies(50));
13457
13458                 WARN_ON(!lret);
13459
13460                 drm_crtc_vblank_put(crtc);
13461         }
13462 }
13463
13464 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
13465 {
13466         /* fb updated, need to unpin old fb */
13467         if (crtc_state->fb_changed)
13468                 return true;
13469
13470         /* wm changes, need vblank before final wm's */
13471         if (crtc_state->update_wm_post)
13472                 return true;
13473
13474         /*
13475          * cxsr is re-enabled after vblank.
13476          * This is already handled by crtc_state->update_wm_post,
13477          * but added for clarity.
13478          */
13479         if (crtc_state->disable_cxsr)
13480                 return true;
13481
13482         return false;
13483 }
13484
13485 /**
13486  * intel_atomic_commit - commit validated state object
13487  * @dev: DRM device
13488  * @state: the top-level driver state object
13489  * @async: asynchronous commit
13490  *
13491  * This function commits a top-level state object that has been validated
13492  * with drm_atomic_helper_check().
13493  *
13494  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13495  * we can only handle plane-related operations and do not yet support
13496  * asynchronous commit.
13497  *
13498  * RETURNS
13499  * Zero for success or -errno.
13500  */
13501 static int intel_atomic_commit(struct drm_device *dev,
13502                                struct drm_atomic_state *state,
13503                                bool async)
13504 {
13505         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13506         struct drm_i915_private *dev_priv = dev->dev_private;
13507         struct drm_crtc_state *old_crtc_state;
13508         struct drm_crtc *crtc;
13509         struct intel_crtc_state *intel_cstate;
13510         int ret = 0, i;
13511         bool hw_check = intel_state->modeset;
13512         unsigned long put_domains[I915_MAX_PIPES] = {};
13513         unsigned crtc_vblank_mask = 0;
13514
13515         ret = intel_atomic_prepare_commit(dev, state, async);
13516         if (ret) {
13517                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13518                 return ret;
13519         }
13520
13521         drm_atomic_helper_swap_state(dev, state);
13522         dev_priv->wm.config = intel_state->wm_config;
13523         intel_shared_dpll_commit(state);
13524
13525         if (intel_state->modeset) {
13526                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13527                        sizeof(intel_state->min_pixclk));
13528                 dev_priv->active_crtcs = intel_state->active_crtcs;
13529                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
13530
13531                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13532         }
13533
13534         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13535                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13536
13537                 if (needs_modeset(crtc->state) ||
13538                     to_intel_crtc_state(crtc->state)->update_pipe) {
13539                         hw_check = true;
13540
13541                         put_domains[to_intel_crtc(crtc)->pipe] =
13542                                 modeset_get_crtc_power_domains(crtc,
13543                                         to_intel_crtc_state(crtc->state));
13544                 }
13545
13546                 if (!needs_modeset(crtc->state))
13547                         continue;
13548
13549                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13550
13551                 if (old_crtc_state->active) {
13552                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13553                         dev_priv->display.crtc_disable(crtc);
13554                         intel_crtc->active = false;
13555                         intel_fbc_disable(intel_crtc);
13556                         intel_disable_shared_dpll(intel_crtc);
13557
13558                         /*
13559                          * Underruns don't always raise
13560                          * interrupts, so check manually.
13561                          */
13562                         intel_check_cpu_fifo_underruns(dev_priv);
13563                         intel_check_pch_fifo_underruns(dev_priv);
13564
13565                         if (!crtc->state->active)
13566                                 intel_update_watermarks(crtc);
13567                 }
13568         }
13569
13570         /* Only after disabling all output pipelines that will be changed can we
13571          * update the the output configuration. */
13572         intel_modeset_update_crtc_state(state);
13573
13574         if (intel_state->modeset) {
13575                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13576
13577                 if (dev_priv->display.modeset_commit_cdclk &&
13578                     intel_state->dev_cdclk != dev_priv->cdclk_freq)
13579                         dev_priv->display.modeset_commit_cdclk(state);
13580         }
13581
13582         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13583         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13584                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13585                 bool modeset = needs_modeset(crtc->state);
13586                 struct intel_crtc_state *pipe_config =
13587                         to_intel_crtc_state(crtc->state);
13588                 bool update_pipe = !modeset && pipe_config->update_pipe;
13589
13590                 if (modeset && crtc->state->active) {
13591                         update_scanline_offset(to_intel_crtc(crtc));
13592                         dev_priv->display.crtc_enable(crtc);
13593                 }
13594
13595                 if (!modeset)
13596                         intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13597
13598                 if (crtc->state->active &&
13599                     drm_atomic_get_existing_plane_state(state, crtc->primary))
13600                         intel_fbc_enable(intel_crtc);
13601
13602                 if (crtc->state->active &&
13603                     (crtc->state->planes_changed || update_pipe))
13604                         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
13605
13606                 if (pipe_config->base.active && needs_vblank_wait(pipe_config))
13607                         crtc_vblank_mask |= 1 << i;
13608         }
13609
13610         /* FIXME: add subpixel order */
13611
13612         if (!state->legacy_cursor_update)
13613                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13614
13615         /*
13616          * Now that the vblank has passed, we can go ahead and program the
13617          * optimal watermarks on platforms that need two-step watermark
13618          * programming.
13619          *
13620          * TODO: Move this (and other cleanup) to an async worker eventually.
13621          */
13622         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13623                 intel_cstate = to_intel_crtc_state(crtc->state);
13624
13625                 if (dev_priv->display.optimize_watermarks)
13626                         dev_priv->display.optimize_watermarks(intel_cstate);
13627         }
13628
13629         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13630                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13631
13632                 if (put_domains[i])
13633                         modeset_put_power_domains(dev_priv, put_domains[i]);
13634         }
13635
13636         if (intel_state->modeset)
13637                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13638
13639         mutex_lock(&dev->struct_mutex);
13640         drm_atomic_helper_cleanup_planes(dev, state);
13641         mutex_unlock(&dev->struct_mutex);
13642
13643         if (hw_check)
13644                 intel_modeset_check_state(dev, state);
13645
13646         drm_atomic_state_free(state);
13647
13648         /* As one of the primary mmio accessors, KMS has a high likelihood
13649          * of triggering bugs in unclaimed access. After we finish
13650          * modesetting, see if an error has been flagged, and if so
13651          * enable debugging for the next modeset - and hope we catch
13652          * the culprit.
13653          *
13654          * XXX note that we assume display power is on at this point.
13655          * This might hold true now but we need to add pm helper to check
13656          * unclaimed only when the hardware is on, as atomic commits
13657          * can happen also when the device is completely off.
13658          */
13659         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13660
13661         return 0;
13662 }
13663
13664 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13665 {
13666         struct drm_device *dev = crtc->dev;
13667         struct drm_atomic_state *state;
13668         struct drm_crtc_state *crtc_state;
13669         int ret;
13670
13671         state = drm_atomic_state_alloc(dev);
13672         if (!state) {
13673                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13674                               crtc->base.id);
13675                 return;
13676         }
13677
13678         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13679
13680 retry:
13681         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13682         ret = PTR_ERR_OR_ZERO(crtc_state);
13683         if (!ret) {
13684                 if (!crtc_state->active)
13685                         goto out;
13686
13687                 crtc_state->mode_changed = true;
13688                 ret = drm_atomic_commit(state);
13689         }
13690
13691         if (ret == -EDEADLK) {
13692                 drm_atomic_state_clear(state);
13693                 drm_modeset_backoff(state->acquire_ctx);
13694                 goto retry;
13695         }
13696
13697         if (ret)
13698 out:
13699                 drm_atomic_state_free(state);
13700 }
13701
13702 #undef for_each_intel_crtc_masked
13703
13704 static const struct drm_crtc_funcs intel_crtc_funcs = {
13705         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13706         .set_config = drm_atomic_helper_set_config,
13707         .set_property = drm_atomic_helper_crtc_set_property,
13708         .destroy = intel_crtc_destroy,
13709         .page_flip = intel_crtc_page_flip,
13710         .atomic_duplicate_state = intel_crtc_duplicate_state,
13711         .atomic_destroy_state = intel_crtc_destroy_state,
13712 };
13713
13714 /**
13715  * intel_prepare_plane_fb - Prepare fb for usage on plane
13716  * @plane: drm plane to prepare for
13717  * @fb: framebuffer to prepare for presentation
13718  *
13719  * Prepares a framebuffer for usage on a display plane.  Generally this
13720  * involves pinning the underlying object and updating the frontbuffer tracking
13721  * bits.  Some older platforms need special physical address handling for
13722  * cursor planes.
13723  *
13724  * Must be called with struct_mutex held.
13725  *
13726  * Returns 0 on success, negative error code on failure.
13727  */
13728 int
13729 intel_prepare_plane_fb(struct drm_plane *plane,
13730                        const struct drm_plane_state *new_state)
13731 {
13732         struct drm_device *dev = plane->dev;
13733         struct drm_framebuffer *fb = new_state->fb;
13734         struct intel_plane *intel_plane = to_intel_plane(plane);
13735         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13736         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13737         int ret = 0;
13738
13739         if (!obj && !old_obj)
13740                 return 0;
13741
13742         if (old_obj) {
13743                 struct drm_crtc_state *crtc_state =
13744                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
13745
13746                 /* Big Hammer, we also need to ensure that any pending
13747                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13748                  * current scanout is retired before unpinning the old
13749                  * framebuffer. Note that we rely on userspace rendering
13750                  * into the buffer attached to the pipe they are waiting
13751                  * on. If not, userspace generates a GPU hang with IPEHR
13752                  * point to the MI_WAIT_FOR_EVENT.
13753                  *
13754                  * This should only fail upon a hung GPU, in which case we
13755                  * can safely continue.
13756                  */
13757                 if (needs_modeset(crtc_state))
13758                         ret = i915_gem_object_wait_rendering(old_obj, true);
13759
13760                 /* Swallow -EIO errors to allow updates during hw lockup. */
13761                 if (ret && ret != -EIO)
13762                         return ret;
13763         }
13764
13765         /* For framebuffer backed by dmabuf, wait for fence */
13766         if (obj && obj->base.dma_buf) {
13767                 long lret;
13768
13769                 lret = reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
13770                                                            false, true,
13771                                                            MAX_SCHEDULE_TIMEOUT);
13772                 if (lret == -ERESTARTSYS)
13773                         return lret;
13774
13775                 WARN(lret < 0, "waiting returns %li\n", lret);
13776         }
13777
13778         if (!obj) {
13779                 ret = 0;
13780         } else if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13781             INTEL_INFO(dev)->cursor_needs_physical) {
13782                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13783                 ret = i915_gem_object_attach_phys(obj, align);
13784                 if (ret)
13785                         DRM_DEBUG_KMS("failed to attach phys object\n");
13786         } else {
13787                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
13788         }
13789
13790         if (ret == 0) {
13791                 if (obj) {
13792                         struct intel_plane_state *plane_state =
13793                                 to_intel_plane_state(new_state);
13794
13795                         i915_gem_request_assign(&plane_state->wait_req,
13796                                                 obj->last_write_req);
13797                 }
13798
13799                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13800         }
13801
13802         return ret;
13803 }
13804
13805 /**
13806  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13807  * @plane: drm plane to clean up for
13808  * @fb: old framebuffer that was on plane
13809  *
13810  * Cleans up a framebuffer that has just been removed from a plane.
13811  *
13812  * Must be called with struct_mutex held.
13813  */
13814 void
13815 intel_cleanup_plane_fb(struct drm_plane *plane,
13816                        const struct drm_plane_state *old_state)
13817 {
13818         struct drm_device *dev = plane->dev;
13819         struct intel_plane *intel_plane = to_intel_plane(plane);
13820         struct intel_plane_state *old_intel_state;
13821         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
13822         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
13823
13824         old_intel_state = to_intel_plane_state(old_state);
13825
13826         if (!obj && !old_obj)
13827                 return;
13828
13829         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
13830             !INTEL_INFO(dev)->cursor_needs_physical))
13831                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
13832
13833         /* prepare_fb aborted? */
13834         if ((old_obj && (old_obj->frontbuffer_bits & intel_plane->frontbuffer_bit)) ||
13835             (obj && !(obj->frontbuffer_bits & intel_plane->frontbuffer_bit)))
13836                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13837
13838         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
13839 }
13840
13841 int
13842 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13843 {
13844         int max_scale;
13845         struct drm_device *dev;
13846         struct drm_i915_private *dev_priv;
13847         int crtc_clock, cdclk;
13848
13849         if (!intel_crtc || !crtc_state->base.enable)
13850                 return DRM_PLANE_HELPER_NO_SCALING;
13851
13852         dev = intel_crtc->base.dev;
13853         dev_priv = dev->dev_private;
13854         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13855         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13856
13857         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
13858                 return DRM_PLANE_HELPER_NO_SCALING;
13859
13860         /*
13861          * skl max scale is lower of:
13862          *    close to 3 but not 3, -1 is for that purpose
13863          *            or
13864          *    cdclk/crtc_clock
13865          */
13866         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13867
13868         return max_scale;
13869 }
13870
13871 static int
13872 intel_check_primary_plane(struct drm_plane *plane,
13873                           struct intel_crtc_state *crtc_state,
13874                           struct intel_plane_state *state)
13875 {
13876         struct drm_crtc *crtc = state->base.crtc;
13877         struct drm_framebuffer *fb = state->base.fb;
13878         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13879         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13880         bool can_position = false;
13881
13882         if (INTEL_INFO(plane->dev)->gen >= 9) {
13883                 /* use scaler when colorkey is not required */
13884                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
13885                         min_scale = 1;
13886                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13887                 }
13888                 can_position = true;
13889         }
13890
13891         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13892                                              &state->dst, &state->clip,
13893                                              min_scale, max_scale,
13894                                              can_position, true,
13895                                              &state->visible);
13896 }
13897
13898 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13899                                     struct drm_crtc_state *old_crtc_state)
13900 {
13901         struct drm_device *dev = crtc->dev;
13902         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13903         struct intel_crtc_state *old_intel_state =
13904                 to_intel_crtc_state(old_crtc_state);
13905         bool modeset = needs_modeset(crtc->state);
13906
13907         /* Perform vblank evasion around commit operation */
13908         intel_pipe_update_start(intel_crtc);
13909
13910         if (modeset)
13911                 return;
13912
13913         if (crtc->state->color_mgmt_changed || to_intel_crtc_state(crtc->state)->update_pipe) {
13914                 intel_color_set_csc(crtc->state);
13915                 intel_color_load_luts(crtc->state);
13916         }
13917
13918         if (to_intel_crtc_state(crtc->state)->update_pipe)
13919                 intel_update_pipe_config(intel_crtc, old_intel_state);
13920         else if (INTEL_INFO(dev)->gen >= 9)
13921                 skl_detach_scalers(intel_crtc);
13922 }
13923
13924 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13925                                      struct drm_crtc_state *old_crtc_state)
13926 {
13927         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13928
13929         intel_pipe_update_end(intel_crtc);
13930 }
13931
13932 /**
13933  * intel_plane_destroy - destroy a plane
13934  * @plane: plane to destroy
13935  *
13936  * Common destruction function for all types of planes (primary, cursor,
13937  * sprite).
13938  */
13939 void intel_plane_destroy(struct drm_plane *plane)
13940 {
13941         struct intel_plane *intel_plane = to_intel_plane(plane);
13942         drm_plane_cleanup(plane);
13943         kfree(intel_plane);
13944 }
13945
13946 const struct drm_plane_funcs intel_plane_funcs = {
13947         .update_plane = drm_atomic_helper_update_plane,
13948         .disable_plane = drm_atomic_helper_disable_plane,
13949         .destroy = intel_plane_destroy,
13950         .set_property = drm_atomic_helper_plane_set_property,
13951         .atomic_get_property = intel_plane_atomic_get_property,
13952         .atomic_set_property = intel_plane_atomic_set_property,
13953         .atomic_duplicate_state = intel_plane_duplicate_state,
13954         .atomic_destroy_state = intel_plane_destroy_state,
13955
13956 };
13957
13958 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13959                                                     int pipe)
13960 {
13961         struct intel_plane *primary;
13962         struct intel_plane_state *state;
13963         const uint32_t *intel_primary_formats;
13964         unsigned int num_formats;
13965
13966         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13967         if (primary == NULL)
13968                 return NULL;
13969
13970         state = intel_create_plane_state(&primary->base);
13971         if (!state) {
13972                 kfree(primary);
13973                 return NULL;
13974         }
13975         primary->base.state = &state->base;
13976
13977         primary->can_scale = false;
13978         primary->max_downscale = 1;
13979         if (INTEL_INFO(dev)->gen >= 9) {
13980                 primary->can_scale = true;
13981                 state->scaler_id = -1;
13982         }
13983         primary->pipe = pipe;
13984         primary->plane = pipe;
13985         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13986         primary->check_plane = intel_check_primary_plane;
13987         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
13988                 primary->plane = !pipe;
13989
13990         if (INTEL_INFO(dev)->gen >= 9) {
13991                 intel_primary_formats = skl_primary_formats;
13992                 num_formats = ARRAY_SIZE(skl_primary_formats);
13993
13994                 primary->update_plane = skylake_update_primary_plane;
13995                 primary->disable_plane = skylake_disable_primary_plane;
13996         } else if (HAS_PCH_SPLIT(dev)) {
13997                 intel_primary_formats = i965_primary_formats;
13998                 num_formats = ARRAY_SIZE(i965_primary_formats);
13999
14000                 primary->update_plane = ironlake_update_primary_plane;
14001                 primary->disable_plane = i9xx_disable_primary_plane;
14002         } else if (INTEL_INFO(dev)->gen >= 4) {
14003                 intel_primary_formats = i965_primary_formats;
14004                 num_formats = ARRAY_SIZE(i965_primary_formats);
14005
14006                 primary->update_plane = i9xx_update_primary_plane;
14007                 primary->disable_plane = i9xx_disable_primary_plane;
14008         } else {
14009                 intel_primary_formats = i8xx_primary_formats;
14010                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14011
14012                 primary->update_plane = i9xx_update_primary_plane;
14013                 primary->disable_plane = i9xx_disable_primary_plane;
14014         }
14015
14016         drm_universal_plane_init(dev, &primary->base, 0,
14017                                  &intel_plane_funcs,
14018                                  intel_primary_formats, num_formats,
14019                                  DRM_PLANE_TYPE_PRIMARY, NULL);
14020
14021         if (INTEL_INFO(dev)->gen >= 4)
14022                 intel_create_rotation_property(dev, primary);
14023
14024         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14025
14026         return &primary->base;
14027 }
14028
14029 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14030 {
14031         if (!dev->mode_config.rotation_property) {
14032                 unsigned long flags = BIT(DRM_ROTATE_0) |
14033                         BIT(DRM_ROTATE_180);
14034
14035                 if (INTEL_INFO(dev)->gen >= 9)
14036                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
14037
14038                 dev->mode_config.rotation_property =
14039                         drm_mode_create_rotation_property(dev, flags);
14040         }
14041         if (dev->mode_config.rotation_property)
14042                 drm_object_attach_property(&plane->base.base,
14043                                 dev->mode_config.rotation_property,
14044                                 plane->base.state->rotation);
14045 }
14046
14047 static int
14048 intel_check_cursor_plane(struct drm_plane *plane,
14049                          struct intel_crtc_state *crtc_state,
14050                          struct intel_plane_state *state)
14051 {
14052         struct drm_crtc *crtc = crtc_state->base.crtc;
14053         struct drm_framebuffer *fb = state->base.fb;
14054         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14055         enum pipe pipe = to_intel_plane(plane)->pipe;
14056         unsigned stride;
14057         int ret;
14058
14059         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14060                                             &state->dst, &state->clip,
14061                                             DRM_PLANE_HELPER_NO_SCALING,
14062                                             DRM_PLANE_HELPER_NO_SCALING,
14063                                             true, true, &state->visible);
14064         if (ret)
14065                 return ret;
14066
14067         /* if we want to turn off the cursor ignore width and height */
14068         if (!obj)
14069                 return 0;
14070
14071         /* Check for which cursor types we support */
14072         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14073                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14074                           state->base.crtc_w, state->base.crtc_h);
14075                 return -EINVAL;
14076         }
14077
14078         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14079         if (obj->base.size < stride * state->base.crtc_h) {
14080                 DRM_DEBUG_KMS("buffer is too small\n");
14081                 return -ENOMEM;
14082         }
14083
14084         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14085                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14086                 return -EINVAL;
14087         }
14088
14089         /*
14090          * There's something wrong with the cursor on CHV pipe C.
14091          * If it straddles the left edge of the screen then
14092          * moving it away from the edge or disabling it often
14093          * results in a pipe underrun, and often that can lead to
14094          * dead pipe (constant underrun reported, and it scans
14095          * out just a solid color). To recover from that, the
14096          * display power well must be turned off and on again.
14097          * Refuse the put the cursor into that compromised position.
14098          */
14099         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
14100             state->visible && state->base.crtc_x < 0) {
14101                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
14102                 return -EINVAL;
14103         }
14104
14105         return 0;
14106 }
14107
14108 static void
14109 intel_disable_cursor_plane(struct drm_plane *plane,
14110                            struct drm_crtc *crtc)
14111 {
14112         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14113
14114         intel_crtc->cursor_addr = 0;
14115         intel_crtc_update_cursor(crtc, NULL);
14116 }
14117
14118 static void
14119 intel_update_cursor_plane(struct drm_plane *plane,
14120                           const struct intel_crtc_state *crtc_state,
14121                           const struct intel_plane_state *state)
14122 {
14123         struct drm_crtc *crtc = crtc_state->base.crtc;
14124         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14125         struct drm_device *dev = plane->dev;
14126         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14127         uint32_t addr;
14128
14129         if (!obj)
14130                 addr = 0;
14131         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14132                 addr = i915_gem_obj_ggtt_offset(obj);
14133         else
14134                 addr = obj->phys_handle->busaddr;
14135
14136         intel_crtc->cursor_addr = addr;
14137         intel_crtc_update_cursor(crtc, state);
14138 }
14139
14140 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14141                                                    int pipe)
14142 {
14143         struct intel_plane *cursor;
14144         struct intel_plane_state *state;
14145
14146         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14147         if (cursor == NULL)
14148                 return NULL;
14149
14150         state = intel_create_plane_state(&cursor->base);
14151         if (!state) {
14152                 kfree(cursor);
14153                 return NULL;
14154         }
14155         cursor->base.state = &state->base;
14156
14157         cursor->can_scale = false;
14158         cursor->max_downscale = 1;
14159         cursor->pipe = pipe;
14160         cursor->plane = pipe;
14161         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14162         cursor->check_plane = intel_check_cursor_plane;
14163         cursor->update_plane = intel_update_cursor_plane;
14164         cursor->disable_plane = intel_disable_cursor_plane;
14165
14166         drm_universal_plane_init(dev, &cursor->base, 0,
14167                                  &intel_plane_funcs,
14168                                  intel_cursor_formats,
14169                                  ARRAY_SIZE(intel_cursor_formats),
14170                                  DRM_PLANE_TYPE_CURSOR, NULL);
14171
14172         if (INTEL_INFO(dev)->gen >= 4) {
14173                 if (!dev->mode_config.rotation_property)
14174                         dev->mode_config.rotation_property =
14175                                 drm_mode_create_rotation_property(dev,
14176                                                         BIT(DRM_ROTATE_0) |
14177                                                         BIT(DRM_ROTATE_180));
14178                 if (dev->mode_config.rotation_property)
14179                         drm_object_attach_property(&cursor->base.base,
14180                                 dev->mode_config.rotation_property,
14181                                 state->base.rotation);
14182         }
14183
14184         if (INTEL_INFO(dev)->gen >=9)
14185                 state->scaler_id = -1;
14186
14187         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14188
14189         return &cursor->base;
14190 }
14191
14192 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14193         struct intel_crtc_state *crtc_state)
14194 {
14195         int i;
14196         struct intel_scaler *intel_scaler;
14197         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14198
14199         for (i = 0; i < intel_crtc->num_scalers; i++) {
14200                 intel_scaler = &scaler_state->scalers[i];
14201                 intel_scaler->in_use = 0;
14202                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14203         }
14204
14205         scaler_state->scaler_id = -1;
14206 }
14207
14208 static void intel_crtc_init(struct drm_device *dev, int pipe)
14209 {
14210         struct drm_i915_private *dev_priv = dev->dev_private;
14211         struct intel_crtc *intel_crtc;
14212         struct intel_crtc_state *crtc_state = NULL;
14213         struct drm_plane *primary = NULL;
14214         struct drm_plane *cursor = NULL;
14215         int ret;
14216
14217         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14218         if (intel_crtc == NULL)
14219                 return;
14220
14221         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14222         if (!crtc_state)
14223                 goto fail;
14224         intel_crtc->config = crtc_state;
14225         intel_crtc->base.state = &crtc_state->base;
14226         crtc_state->base.crtc = &intel_crtc->base;
14227
14228         /* initialize shared scalers */
14229         if (INTEL_INFO(dev)->gen >= 9) {
14230                 if (pipe == PIPE_C)
14231                         intel_crtc->num_scalers = 1;
14232                 else
14233                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14234
14235                 skl_init_scalers(dev, intel_crtc, crtc_state);
14236         }
14237
14238         primary = intel_primary_plane_create(dev, pipe);
14239         if (!primary)
14240                 goto fail;
14241
14242         cursor = intel_cursor_plane_create(dev, pipe);
14243         if (!cursor)
14244                 goto fail;
14245
14246         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14247                                         cursor, &intel_crtc_funcs, NULL);
14248         if (ret)
14249                 goto fail;
14250
14251         /*
14252          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14253          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14254          */
14255         intel_crtc->pipe = pipe;
14256         intel_crtc->plane = pipe;
14257         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14258                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14259                 intel_crtc->plane = !pipe;
14260         }
14261
14262         intel_crtc->cursor_base = ~0;
14263         intel_crtc->cursor_cntl = ~0;
14264         intel_crtc->cursor_size = ~0;
14265
14266         intel_crtc->wm.cxsr_allowed = true;
14267
14268         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14269                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14270         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14271         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14272
14273         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14274
14275         intel_color_init(&intel_crtc->base);
14276
14277         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14278         return;
14279
14280 fail:
14281         if (primary)
14282                 drm_plane_cleanup(primary);
14283         if (cursor)
14284                 drm_plane_cleanup(cursor);
14285         kfree(crtc_state);
14286         kfree(intel_crtc);
14287 }
14288
14289 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14290 {
14291         struct drm_encoder *encoder = connector->base.encoder;
14292         struct drm_device *dev = connector->base.dev;
14293
14294         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14295
14296         if (!encoder || WARN_ON(!encoder->crtc))
14297                 return INVALID_PIPE;
14298
14299         return to_intel_crtc(encoder->crtc)->pipe;
14300 }
14301
14302 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14303                                 struct drm_file *file)
14304 {
14305         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14306         struct drm_crtc *drmmode_crtc;
14307         struct intel_crtc *crtc;
14308
14309         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14310
14311         if (!drmmode_crtc) {
14312                 DRM_ERROR("no such CRTC id\n");
14313                 return -ENOENT;
14314         }
14315
14316         crtc = to_intel_crtc(drmmode_crtc);
14317         pipe_from_crtc_id->pipe = crtc->pipe;
14318
14319         return 0;
14320 }
14321
14322 static int intel_encoder_clones(struct intel_encoder *encoder)
14323 {
14324         struct drm_device *dev = encoder->base.dev;
14325         struct intel_encoder *source_encoder;
14326         int index_mask = 0;
14327         int entry = 0;
14328
14329         for_each_intel_encoder(dev, source_encoder) {
14330                 if (encoders_cloneable(encoder, source_encoder))
14331                         index_mask |= (1 << entry);
14332
14333                 entry++;
14334         }
14335
14336         return index_mask;
14337 }
14338
14339 static bool has_edp_a(struct drm_device *dev)
14340 {
14341         struct drm_i915_private *dev_priv = dev->dev_private;
14342
14343         if (!IS_MOBILE(dev))
14344                 return false;
14345
14346         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14347                 return false;
14348
14349         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14350                 return false;
14351
14352         return true;
14353 }
14354
14355 static bool intel_crt_present(struct drm_device *dev)
14356 {
14357         struct drm_i915_private *dev_priv = dev->dev_private;
14358
14359         if (INTEL_INFO(dev)->gen >= 9)
14360                 return false;
14361
14362         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14363                 return false;
14364
14365         if (IS_CHERRYVIEW(dev))
14366                 return false;
14367
14368         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14369                 return false;
14370
14371         /* DDI E can't be used if DDI A requires 4 lanes */
14372         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14373                 return false;
14374
14375         if (!dev_priv->vbt.int_crt_support)
14376                 return false;
14377
14378         return true;
14379 }
14380
14381 static void intel_setup_outputs(struct drm_device *dev)
14382 {
14383         struct drm_i915_private *dev_priv = dev->dev_private;
14384         struct intel_encoder *encoder;
14385         bool dpd_is_edp = false;
14386
14387         intel_lvds_init(dev);
14388
14389         if (intel_crt_present(dev))
14390                 intel_crt_init(dev);
14391
14392         if (IS_BROXTON(dev)) {
14393                 /*
14394                  * FIXME: Broxton doesn't support port detection via the
14395                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14396                  * detect the ports.
14397                  */
14398                 intel_ddi_init(dev, PORT_A);
14399                 intel_ddi_init(dev, PORT_B);
14400                 intel_ddi_init(dev, PORT_C);
14401
14402                 intel_dsi_init(dev);
14403         } else if (HAS_DDI(dev)) {
14404                 int found;
14405
14406                 /*
14407                  * Haswell uses DDI functions to detect digital outputs.
14408                  * On SKL pre-D0 the strap isn't connected, so we assume
14409                  * it's there.
14410                  */
14411                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14412                 /* WaIgnoreDDIAStrap: skl */
14413                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14414                         intel_ddi_init(dev, PORT_A);
14415
14416                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14417                  * register */
14418                 found = I915_READ(SFUSE_STRAP);
14419
14420                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14421                         intel_ddi_init(dev, PORT_B);
14422                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14423                         intel_ddi_init(dev, PORT_C);
14424                 if (found & SFUSE_STRAP_DDID_DETECTED)
14425                         intel_ddi_init(dev, PORT_D);
14426                 /*
14427                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14428                  */
14429                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
14430                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14431                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14432                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14433                         intel_ddi_init(dev, PORT_E);
14434
14435         } else if (HAS_PCH_SPLIT(dev)) {
14436                 int found;
14437                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14438
14439                 if (has_edp_a(dev))
14440                         intel_dp_init(dev, DP_A, PORT_A);
14441
14442                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14443                         /* PCH SDVOB multiplex with HDMIB */
14444                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
14445                         if (!found)
14446                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14447                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14448                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14449                 }
14450
14451                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14452                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14453
14454                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14455                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14456
14457                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14458                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14459
14460                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14461                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14462         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14463                 /*
14464                  * The DP_DETECTED bit is the latched state of the DDC
14465                  * SDA pin at boot. However since eDP doesn't require DDC
14466                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14467                  * eDP ports may have been muxed to an alternate function.
14468                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14469                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14470                  * detect eDP ports.
14471                  */
14472                 if (I915_READ(VLV_HDMIB) & SDVO_DETECTED &&
14473                     !intel_dp_is_edp(dev, PORT_B))
14474                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14475                 if (I915_READ(VLV_DP_B) & DP_DETECTED ||
14476                     intel_dp_is_edp(dev, PORT_B))
14477                         intel_dp_init(dev, VLV_DP_B, PORT_B);
14478
14479                 if (I915_READ(VLV_HDMIC) & SDVO_DETECTED &&
14480                     !intel_dp_is_edp(dev, PORT_C))
14481                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14482                 if (I915_READ(VLV_DP_C) & DP_DETECTED ||
14483                     intel_dp_is_edp(dev, PORT_C))
14484                         intel_dp_init(dev, VLV_DP_C, PORT_C);
14485
14486                 if (IS_CHERRYVIEW(dev)) {
14487                         /* eDP not supported on port D, so don't check VBT */
14488                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED)
14489                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14490                         if (I915_READ(CHV_DP_D) & DP_DETECTED)
14491                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14492                 }
14493
14494                 intel_dsi_init(dev);
14495         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14496                 bool found = false;
14497
14498                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14499                         DRM_DEBUG_KMS("probing SDVOB\n");
14500                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14501                         if (!found && IS_G4X(dev)) {
14502                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14503                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14504                         }
14505
14506                         if (!found && IS_G4X(dev))
14507                                 intel_dp_init(dev, DP_B, PORT_B);
14508                 }
14509
14510                 /* Before G4X SDVOC doesn't have its own detect register */
14511
14512                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14513                         DRM_DEBUG_KMS("probing SDVOC\n");
14514                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14515                 }
14516
14517                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14518
14519                         if (IS_G4X(dev)) {
14520                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14521                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14522                         }
14523                         if (IS_G4X(dev))
14524                                 intel_dp_init(dev, DP_C, PORT_C);
14525                 }
14526
14527                 if (IS_G4X(dev) &&
14528                     (I915_READ(DP_D) & DP_DETECTED))
14529                         intel_dp_init(dev, DP_D, PORT_D);
14530         } else if (IS_GEN2(dev))
14531                 intel_dvo_init(dev);
14532
14533         if (SUPPORTS_TV(dev))
14534                 intel_tv_init(dev);
14535
14536         intel_psr_init(dev);
14537
14538         for_each_intel_encoder(dev, encoder) {
14539                 encoder->base.possible_crtcs = encoder->crtc_mask;
14540                 encoder->base.possible_clones =
14541                         intel_encoder_clones(encoder);
14542         }
14543
14544         intel_init_pch_refclk(dev);
14545
14546         drm_helper_move_panel_connectors_to_head(dev);
14547 }
14548
14549 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14550 {
14551         struct drm_device *dev = fb->dev;
14552         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14553
14554         drm_framebuffer_cleanup(fb);
14555         mutex_lock(&dev->struct_mutex);
14556         WARN_ON(!intel_fb->obj->framebuffer_references--);
14557         drm_gem_object_unreference(&intel_fb->obj->base);
14558         mutex_unlock(&dev->struct_mutex);
14559         kfree(intel_fb);
14560 }
14561
14562 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14563                                                 struct drm_file *file,
14564                                                 unsigned int *handle)
14565 {
14566         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14567         struct drm_i915_gem_object *obj = intel_fb->obj;
14568
14569         if (obj->userptr.mm) {
14570                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14571                 return -EINVAL;
14572         }
14573
14574         return drm_gem_handle_create(file, &obj->base, handle);
14575 }
14576
14577 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14578                                         struct drm_file *file,
14579                                         unsigned flags, unsigned color,
14580                                         struct drm_clip_rect *clips,
14581                                         unsigned num_clips)
14582 {
14583         struct drm_device *dev = fb->dev;
14584         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14585         struct drm_i915_gem_object *obj = intel_fb->obj;
14586
14587         mutex_lock(&dev->struct_mutex);
14588         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14589         mutex_unlock(&dev->struct_mutex);
14590
14591         return 0;
14592 }
14593
14594 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14595         .destroy = intel_user_framebuffer_destroy,
14596         .create_handle = intel_user_framebuffer_create_handle,
14597         .dirty = intel_user_framebuffer_dirty,
14598 };
14599
14600 static
14601 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14602                          uint32_t pixel_format)
14603 {
14604         u32 gen = INTEL_INFO(dev)->gen;
14605
14606         if (gen >= 9) {
14607                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14608
14609                 /* "The stride in bytes must not exceed the of the size of 8K
14610                  *  pixels and 32K bytes."
14611                  */
14612                 return min(8192 * cpp, 32768);
14613         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14614                 return 32*1024;
14615         } else if (gen >= 4) {
14616                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14617                         return 16*1024;
14618                 else
14619                         return 32*1024;
14620         } else if (gen >= 3) {
14621                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14622                         return 8*1024;
14623                 else
14624                         return 16*1024;
14625         } else {
14626                 /* XXX DSPC is limited to 4k tiled */
14627                 return 8*1024;
14628         }
14629 }
14630
14631 static int intel_framebuffer_init(struct drm_device *dev,
14632                                   struct intel_framebuffer *intel_fb,
14633                                   struct drm_mode_fb_cmd2 *mode_cmd,
14634                                   struct drm_i915_gem_object *obj)
14635 {
14636         struct drm_i915_private *dev_priv = to_i915(dev);
14637         unsigned int aligned_height;
14638         int ret;
14639         u32 pitch_limit, stride_alignment;
14640
14641         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14642
14643         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14644                 /* Enforce that fb modifier and tiling mode match, but only for
14645                  * X-tiled. This is needed for FBC. */
14646                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14647                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14648                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14649                         return -EINVAL;
14650                 }
14651         } else {
14652                 if (obj->tiling_mode == I915_TILING_X)
14653                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14654                 else if (obj->tiling_mode == I915_TILING_Y) {
14655                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14656                         return -EINVAL;
14657                 }
14658         }
14659
14660         /* Passed in modifier sanity checking. */
14661         switch (mode_cmd->modifier[0]) {
14662         case I915_FORMAT_MOD_Y_TILED:
14663         case I915_FORMAT_MOD_Yf_TILED:
14664                 if (INTEL_INFO(dev)->gen < 9) {
14665                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14666                                   mode_cmd->modifier[0]);
14667                         return -EINVAL;
14668                 }
14669         case DRM_FORMAT_MOD_NONE:
14670         case I915_FORMAT_MOD_X_TILED:
14671                 break;
14672         default:
14673                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14674                           mode_cmd->modifier[0]);
14675                 return -EINVAL;
14676         }
14677
14678         stride_alignment = intel_fb_stride_alignment(dev_priv,
14679                                                      mode_cmd->modifier[0],
14680                                                      mode_cmd->pixel_format);
14681         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14682                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14683                           mode_cmd->pitches[0], stride_alignment);
14684                 return -EINVAL;
14685         }
14686
14687         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14688                                            mode_cmd->pixel_format);
14689         if (mode_cmd->pitches[0] > pitch_limit) {
14690                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14691                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14692                           "tiled" : "linear",
14693                           mode_cmd->pitches[0], pitch_limit);
14694                 return -EINVAL;
14695         }
14696
14697         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14698             mode_cmd->pitches[0] != obj->stride) {
14699                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14700                           mode_cmd->pitches[0], obj->stride);
14701                 return -EINVAL;
14702         }
14703
14704         /* Reject formats not supported by any plane early. */
14705         switch (mode_cmd->pixel_format) {
14706         case DRM_FORMAT_C8:
14707         case DRM_FORMAT_RGB565:
14708         case DRM_FORMAT_XRGB8888:
14709         case DRM_FORMAT_ARGB8888:
14710                 break;
14711         case DRM_FORMAT_XRGB1555:
14712                 if (INTEL_INFO(dev)->gen > 3) {
14713                         DRM_DEBUG("unsupported pixel format: %s\n",
14714                                   drm_get_format_name(mode_cmd->pixel_format));
14715                         return -EINVAL;
14716                 }
14717                 break;
14718         case DRM_FORMAT_ABGR8888:
14719                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
14720                     INTEL_INFO(dev)->gen < 9) {
14721                         DRM_DEBUG("unsupported pixel format: %s\n",
14722                                   drm_get_format_name(mode_cmd->pixel_format));
14723                         return -EINVAL;
14724                 }
14725                 break;
14726         case DRM_FORMAT_XBGR8888:
14727         case DRM_FORMAT_XRGB2101010:
14728         case DRM_FORMAT_XBGR2101010:
14729                 if (INTEL_INFO(dev)->gen < 4) {
14730                         DRM_DEBUG("unsupported pixel format: %s\n",
14731                                   drm_get_format_name(mode_cmd->pixel_format));
14732                         return -EINVAL;
14733                 }
14734                 break;
14735         case DRM_FORMAT_ABGR2101010:
14736                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14737                         DRM_DEBUG("unsupported pixel format: %s\n",
14738                                   drm_get_format_name(mode_cmd->pixel_format));
14739                         return -EINVAL;
14740                 }
14741                 break;
14742         case DRM_FORMAT_YUYV:
14743         case DRM_FORMAT_UYVY:
14744         case DRM_FORMAT_YVYU:
14745         case DRM_FORMAT_VYUY:
14746                 if (INTEL_INFO(dev)->gen < 5) {
14747                         DRM_DEBUG("unsupported pixel format: %s\n",
14748                                   drm_get_format_name(mode_cmd->pixel_format));
14749                         return -EINVAL;
14750                 }
14751                 break;
14752         default:
14753                 DRM_DEBUG("unsupported pixel format: %s\n",
14754                           drm_get_format_name(mode_cmd->pixel_format));
14755                 return -EINVAL;
14756         }
14757
14758         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14759         if (mode_cmd->offsets[0] != 0)
14760                 return -EINVAL;
14761
14762         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14763                                                mode_cmd->pixel_format,
14764                                                mode_cmd->modifier[0]);
14765         /* FIXME drm helper for size checks (especially planar formats)? */
14766         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14767                 return -EINVAL;
14768
14769         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14770         intel_fb->obj = obj;
14771
14772         intel_fill_fb_info(dev_priv, &intel_fb->base);
14773
14774         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14775         if (ret) {
14776                 DRM_ERROR("framebuffer init failed %d\n", ret);
14777                 return ret;
14778         }
14779
14780         intel_fb->obj->framebuffer_references++;
14781
14782         return 0;
14783 }
14784
14785 static struct drm_framebuffer *
14786 intel_user_framebuffer_create(struct drm_device *dev,
14787                               struct drm_file *filp,
14788                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14789 {
14790         struct drm_framebuffer *fb;
14791         struct drm_i915_gem_object *obj;
14792         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14793
14794         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14795                                                 mode_cmd.handles[0]));
14796         if (&obj->base == NULL)
14797                 return ERR_PTR(-ENOENT);
14798
14799         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
14800         if (IS_ERR(fb))
14801                 drm_gem_object_unreference_unlocked(&obj->base);
14802
14803         return fb;
14804 }
14805
14806 #ifndef CONFIG_DRM_FBDEV_EMULATION
14807 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14808 {
14809 }
14810 #endif
14811
14812 static const struct drm_mode_config_funcs intel_mode_funcs = {
14813         .fb_create = intel_user_framebuffer_create,
14814         .output_poll_changed = intel_fbdev_output_poll_changed,
14815         .atomic_check = intel_atomic_check,
14816         .atomic_commit = intel_atomic_commit,
14817         .atomic_state_alloc = intel_atomic_state_alloc,
14818         .atomic_state_clear = intel_atomic_state_clear,
14819 };
14820
14821 /**
14822  * intel_init_display_hooks - initialize the display modesetting hooks
14823  * @dev_priv: device private
14824  */
14825 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14826 {
14827         if (INTEL_INFO(dev_priv)->gen >= 9) {
14828                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14829                 dev_priv->display.get_initial_plane_config =
14830                         skylake_get_initial_plane_config;
14831                 dev_priv->display.crtc_compute_clock =
14832                         haswell_crtc_compute_clock;
14833                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14834                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14835         } else if (HAS_DDI(dev_priv)) {
14836                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14837                 dev_priv->display.get_initial_plane_config =
14838                         ironlake_get_initial_plane_config;
14839                 dev_priv->display.crtc_compute_clock =
14840                         haswell_crtc_compute_clock;
14841                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14842                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14843         } else if (HAS_PCH_SPLIT(dev_priv)) {
14844                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14845                 dev_priv->display.get_initial_plane_config =
14846                         ironlake_get_initial_plane_config;
14847                 dev_priv->display.crtc_compute_clock =
14848                         ironlake_crtc_compute_clock;
14849                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14850                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14851         } else if (IS_CHERRYVIEW(dev_priv)) {
14852                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14853                 dev_priv->display.get_initial_plane_config =
14854                         i9xx_get_initial_plane_config;
14855                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14856                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14857                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14858         } else if (IS_VALLEYVIEW(dev_priv)) {
14859                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14860                 dev_priv->display.get_initial_plane_config =
14861                         i9xx_get_initial_plane_config;
14862                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14863                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14864                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14865         } else if (IS_G4X(dev_priv)) {
14866                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14867                 dev_priv->display.get_initial_plane_config =
14868                         i9xx_get_initial_plane_config;
14869                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14870                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14871                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14872         } else if (IS_PINEVIEW(dev_priv)) {
14873                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14874                 dev_priv->display.get_initial_plane_config =
14875                         i9xx_get_initial_plane_config;
14876                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14877                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14878                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14879         } else if (!IS_GEN2(dev_priv)) {
14880                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14881                 dev_priv->display.get_initial_plane_config =
14882                         i9xx_get_initial_plane_config;
14883                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14884                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14885                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14886         } else {
14887                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14888                 dev_priv->display.get_initial_plane_config =
14889                         i9xx_get_initial_plane_config;
14890                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14891                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14892                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14893         }
14894
14895         /* Returns the core display clock speed */
14896         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
14897                 dev_priv->display.get_display_clock_speed =
14898                         skylake_get_display_clock_speed;
14899         else if (IS_BROXTON(dev_priv))
14900                 dev_priv->display.get_display_clock_speed =
14901                         broxton_get_display_clock_speed;
14902         else if (IS_BROADWELL(dev_priv))
14903                 dev_priv->display.get_display_clock_speed =
14904                         broadwell_get_display_clock_speed;
14905         else if (IS_HASWELL(dev_priv))
14906                 dev_priv->display.get_display_clock_speed =
14907                         haswell_get_display_clock_speed;
14908         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14909                 dev_priv->display.get_display_clock_speed =
14910                         valleyview_get_display_clock_speed;
14911         else if (IS_GEN5(dev_priv))
14912                 dev_priv->display.get_display_clock_speed =
14913                         ilk_get_display_clock_speed;
14914         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
14915                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
14916                 dev_priv->display.get_display_clock_speed =
14917                         i945_get_display_clock_speed;
14918         else if (IS_GM45(dev_priv))
14919                 dev_priv->display.get_display_clock_speed =
14920                         gm45_get_display_clock_speed;
14921         else if (IS_CRESTLINE(dev_priv))
14922                 dev_priv->display.get_display_clock_speed =
14923                         i965gm_get_display_clock_speed;
14924         else if (IS_PINEVIEW(dev_priv))
14925                 dev_priv->display.get_display_clock_speed =
14926                         pnv_get_display_clock_speed;
14927         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
14928                 dev_priv->display.get_display_clock_speed =
14929                         g33_get_display_clock_speed;
14930         else if (IS_I915G(dev_priv))
14931                 dev_priv->display.get_display_clock_speed =
14932                         i915_get_display_clock_speed;
14933         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
14934                 dev_priv->display.get_display_clock_speed =
14935                         i9xx_misc_get_display_clock_speed;
14936         else if (IS_I915GM(dev_priv))
14937                 dev_priv->display.get_display_clock_speed =
14938                         i915gm_get_display_clock_speed;
14939         else if (IS_I865G(dev_priv))
14940                 dev_priv->display.get_display_clock_speed =
14941                         i865_get_display_clock_speed;
14942         else if (IS_I85X(dev_priv))
14943                 dev_priv->display.get_display_clock_speed =
14944                         i85x_get_display_clock_speed;
14945         else { /* 830 */
14946                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
14947                 dev_priv->display.get_display_clock_speed =
14948                         i830_get_display_clock_speed;
14949         }
14950
14951         if (IS_GEN5(dev_priv)) {
14952                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14953         } else if (IS_GEN6(dev_priv)) {
14954                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14955         } else if (IS_IVYBRIDGE(dev_priv)) {
14956                 /* FIXME: detect B0+ stepping and use auto training */
14957                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14958         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14959                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14960                 if (IS_BROADWELL(dev_priv)) {
14961                         dev_priv->display.modeset_commit_cdclk =
14962                                 broadwell_modeset_commit_cdclk;
14963                         dev_priv->display.modeset_calc_cdclk =
14964                                 broadwell_modeset_calc_cdclk;
14965                 }
14966         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14967                 dev_priv->display.modeset_commit_cdclk =
14968                         valleyview_modeset_commit_cdclk;
14969                 dev_priv->display.modeset_calc_cdclk =
14970                         valleyview_modeset_calc_cdclk;
14971         } else if (IS_BROXTON(dev_priv)) {
14972                 dev_priv->display.modeset_commit_cdclk =
14973                         broxton_modeset_commit_cdclk;
14974                 dev_priv->display.modeset_calc_cdclk =
14975                         broxton_modeset_calc_cdclk;
14976         }
14977
14978         switch (INTEL_INFO(dev_priv)->gen) {
14979         case 2:
14980                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14981                 break;
14982
14983         case 3:
14984                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14985                 break;
14986
14987         case 4:
14988         case 5:
14989                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
14990                 break;
14991
14992         case 6:
14993                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
14994                 break;
14995         case 7:
14996         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
14997                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
14998                 break;
14999         case 9:
15000                 /* Drop through - unsupported since execlist only. */
15001         default:
15002                 /* Default just returns -ENODEV to indicate unsupported */
15003                 dev_priv->display.queue_flip = intel_default_queue_flip;
15004         }
15005 }
15006
15007 /*
15008  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
15009  * resume, or other times.  This quirk makes sure that's the case for
15010  * affected systems.
15011  */
15012 static void quirk_pipea_force(struct drm_device *dev)
15013 {
15014         struct drm_i915_private *dev_priv = dev->dev_private;
15015
15016         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
15017         DRM_INFO("applying pipe a force quirk\n");
15018 }
15019
15020 static void quirk_pipeb_force(struct drm_device *dev)
15021 {
15022         struct drm_i915_private *dev_priv = dev->dev_private;
15023
15024         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15025         DRM_INFO("applying pipe b force quirk\n");
15026 }
15027
15028 /*
15029  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15030  */
15031 static void quirk_ssc_force_disable(struct drm_device *dev)
15032 {
15033         struct drm_i915_private *dev_priv = dev->dev_private;
15034         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15035         DRM_INFO("applying lvds SSC disable quirk\n");
15036 }
15037
15038 /*
15039  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15040  * brightness value
15041  */
15042 static void quirk_invert_brightness(struct drm_device *dev)
15043 {
15044         struct drm_i915_private *dev_priv = dev->dev_private;
15045         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15046         DRM_INFO("applying inverted panel brightness quirk\n");
15047 }
15048
15049 /* Some VBT's incorrectly indicate no backlight is present */
15050 static void quirk_backlight_present(struct drm_device *dev)
15051 {
15052         struct drm_i915_private *dev_priv = dev->dev_private;
15053         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15054         DRM_INFO("applying backlight present quirk\n");
15055 }
15056
15057 struct intel_quirk {
15058         int device;
15059         int subsystem_vendor;
15060         int subsystem_device;
15061         void (*hook)(struct drm_device *dev);
15062 };
15063
15064 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15065 struct intel_dmi_quirk {
15066         void (*hook)(struct drm_device *dev);
15067         const struct dmi_system_id (*dmi_id_list)[];
15068 };
15069
15070 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15071 {
15072         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15073         return 1;
15074 }
15075
15076 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15077         {
15078                 .dmi_id_list = &(const struct dmi_system_id[]) {
15079                         {
15080                                 .callback = intel_dmi_reverse_brightness,
15081                                 .ident = "NCR Corporation",
15082                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15083                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15084                                 },
15085                         },
15086                         { }  /* terminating entry */
15087                 },
15088                 .hook = quirk_invert_brightness,
15089         },
15090 };
15091
15092 static struct intel_quirk intel_quirks[] = {
15093         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15094         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15095
15096         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15097         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15098
15099         /* 830 needs to leave pipe A & dpll A up */
15100         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15101
15102         /* 830 needs to leave pipe B & dpll B up */
15103         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15104
15105         /* Lenovo U160 cannot use SSC on LVDS */
15106         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15107
15108         /* Sony Vaio Y cannot use SSC on LVDS */
15109         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15110
15111         /* Acer Aspire 5734Z must invert backlight brightness */
15112         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15113
15114         /* Acer/eMachines G725 */
15115         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15116
15117         /* Acer/eMachines e725 */
15118         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15119
15120         /* Acer/Packard Bell NCL20 */
15121         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15122
15123         /* Acer Aspire 4736Z */
15124         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15125
15126         /* Acer Aspire 5336 */
15127         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15128
15129         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15130         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15131
15132         /* Acer C720 Chromebook (Core i3 4005U) */
15133         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15134
15135         /* Apple Macbook 2,1 (Core 2 T7400) */
15136         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15137
15138         /* Apple Macbook 4,1 */
15139         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15140
15141         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15142         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15143
15144         /* HP Chromebook 14 (Celeron 2955U) */
15145         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15146
15147         /* Dell Chromebook 11 */
15148         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15149
15150         /* Dell Chromebook 11 (2015 version) */
15151         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15152 };
15153
15154 static void intel_init_quirks(struct drm_device *dev)
15155 {
15156         struct pci_dev *d = dev->pdev;
15157         int i;
15158
15159         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15160                 struct intel_quirk *q = &intel_quirks[i];
15161
15162                 if (d->device == q->device &&
15163                     (d->subsystem_vendor == q->subsystem_vendor ||
15164                      q->subsystem_vendor == PCI_ANY_ID) &&
15165                     (d->subsystem_device == q->subsystem_device ||
15166                      q->subsystem_device == PCI_ANY_ID))
15167                         q->hook(dev);
15168         }
15169         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15170                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15171                         intel_dmi_quirks[i].hook(dev);
15172         }
15173 }
15174
15175 /* Disable the VGA plane that we never use */
15176 static void i915_disable_vga(struct drm_device *dev)
15177 {
15178         struct drm_i915_private *dev_priv = dev->dev_private;
15179         u8 sr1;
15180         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15181
15182         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15183         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15184         outb(SR01, VGA_SR_INDEX);
15185         sr1 = inb(VGA_SR_DATA);
15186         outb(sr1 | 1<<5, VGA_SR_DATA);
15187         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15188         udelay(300);
15189
15190         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15191         POSTING_READ(vga_reg);
15192 }
15193
15194 void intel_modeset_init_hw(struct drm_device *dev)
15195 {
15196         struct drm_i915_private *dev_priv = dev->dev_private;
15197
15198         intel_update_cdclk(dev);
15199
15200         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
15201
15202         intel_init_clock_gating(dev);
15203         intel_enable_gt_powersave(dev);
15204 }
15205
15206 /*
15207  * Calculate what we think the watermarks should be for the state we've read
15208  * out of the hardware and then immediately program those watermarks so that
15209  * we ensure the hardware settings match our internal state.
15210  *
15211  * We can calculate what we think WM's should be by creating a duplicate of the
15212  * current state (which was constructed during hardware readout) and running it
15213  * through the atomic check code to calculate new watermark values in the
15214  * state object.
15215  */
15216 static void sanitize_watermarks(struct drm_device *dev)
15217 {
15218         struct drm_i915_private *dev_priv = to_i915(dev);
15219         struct drm_atomic_state *state;
15220         struct drm_crtc *crtc;
15221         struct drm_crtc_state *cstate;
15222         struct drm_modeset_acquire_ctx ctx;
15223         int ret;
15224         int i;
15225
15226         /* Only supported on platforms that use atomic watermark design */
15227         if (!dev_priv->display.optimize_watermarks)
15228                 return;
15229
15230         /*
15231          * We need to hold connection_mutex before calling duplicate_state so
15232          * that the connector loop is protected.
15233          */
15234         drm_modeset_acquire_init(&ctx, 0);
15235 retry:
15236         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15237         if (ret == -EDEADLK) {
15238                 drm_modeset_backoff(&ctx);
15239                 goto retry;
15240         } else if (WARN_ON(ret)) {
15241                 goto fail;
15242         }
15243
15244         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15245         if (WARN_ON(IS_ERR(state)))
15246                 goto fail;
15247
15248         /*
15249          * Hardware readout is the only time we don't want to calculate
15250          * intermediate watermarks (since we don't trust the current
15251          * watermarks).
15252          */
15253         to_intel_atomic_state(state)->skip_intermediate_wm = true;
15254
15255         ret = intel_atomic_check(dev, state);
15256         if (ret) {
15257                 /*
15258                  * If we fail here, it means that the hardware appears to be
15259                  * programmed in a way that shouldn't be possible, given our
15260                  * understanding of watermark requirements.  This might mean a
15261                  * mistake in the hardware readout code or a mistake in the
15262                  * watermark calculations for a given platform.  Raise a WARN
15263                  * so that this is noticeable.
15264                  *
15265                  * If this actually happens, we'll have to just leave the
15266                  * BIOS-programmed watermarks untouched and hope for the best.
15267                  */
15268                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15269                 goto fail;
15270         }
15271
15272         /* Write calculated watermark values back */
15273         to_i915(dev)->wm.config = to_intel_atomic_state(state)->wm_config;
15274         for_each_crtc_in_state(state, crtc, cstate, i) {
15275                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15276
15277                 cs->wm.need_postvbl_update = true;
15278                 dev_priv->display.optimize_watermarks(cs);
15279         }
15280
15281         drm_atomic_state_free(state);
15282 fail:
15283         drm_modeset_drop_locks(&ctx);
15284         drm_modeset_acquire_fini(&ctx);
15285 }
15286
15287 void intel_modeset_init(struct drm_device *dev)
15288 {
15289         struct drm_i915_private *dev_priv = to_i915(dev);
15290         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15291         int sprite, ret;
15292         enum pipe pipe;
15293         struct intel_crtc *crtc;
15294
15295         drm_mode_config_init(dev);
15296
15297         dev->mode_config.min_width = 0;
15298         dev->mode_config.min_height = 0;
15299
15300         dev->mode_config.preferred_depth = 24;
15301         dev->mode_config.prefer_shadow = 1;
15302
15303         dev->mode_config.allow_fb_modifiers = true;
15304
15305         dev->mode_config.funcs = &intel_mode_funcs;
15306
15307         intel_init_quirks(dev);
15308
15309         intel_init_pm(dev);
15310
15311         if (INTEL_INFO(dev)->num_pipes == 0)
15312                 return;
15313
15314         /*
15315          * There may be no VBT; and if the BIOS enabled SSC we can
15316          * just keep using it to avoid unnecessary flicker.  Whereas if the
15317          * BIOS isn't using it, don't assume it will work even if the VBT
15318          * indicates as much.
15319          */
15320         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
15321                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15322                                             DREF_SSC1_ENABLE);
15323
15324                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15325                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15326                                      bios_lvds_use_ssc ? "en" : "dis",
15327                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15328                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15329                 }
15330         }
15331
15332         if (IS_GEN2(dev)) {
15333                 dev->mode_config.max_width = 2048;
15334                 dev->mode_config.max_height = 2048;
15335         } else if (IS_GEN3(dev)) {
15336                 dev->mode_config.max_width = 4096;
15337                 dev->mode_config.max_height = 4096;
15338         } else {
15339                 dev->mode_config.max_width = 8192;
15340                 dev->mode_config.max_height = 8192;
15341         }
15342
15343         if (IS_845G(dev) || IS_I865G(dev)) {
15344                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15345                 dev->mode_config.cursor_height = 1023;
15346         } else if (IS_GEN2(dev)) {
15347                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15348                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15349         } else {
15350                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15351                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15352         }
15353
15354         dev->mode_config.fb_base = ggtt->mappable_base;
15355
15356         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15357                       INTEL_INFO(dev)->num_pipes,
15358                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15359
15360         for_each_pipe(dev_priv, pipe) {
15361                 intel_crtc_init(dev, pipe);
15362                 for_each_sprite(dev_priv, pipe, sprite) {
15363                         ret = intel_plane_init(dev, pipe, sprite);
15364                         if (ret)
15365                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15366                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15367                 }
15368         }
15369
15370         intel_update_czclk(dev_priv);
15371         intel_update_rawclk(dev_priv);
15372         intel_update_cdclk(dev);
15373
15374         intel_shared_dpll_init(dev);
15375
15376         /* Just disable it once at startup */
15377         i915_disable_vga(dev);
15378         intel_setup_outputs(dev);
15379
15380         drm_modeset_lock_all(dev);
15381         intel_modeset_setup_hw_state(dev);
15382         drm_modeset_unlock_all(dev);
15383
15384         for_each_intel_crtc(dev, crtc) {
15385                 struct intel_initial_plane_config plane_config = {};
15386
15387                 if (!crtc->active)
15388                         continue;
15389
15390                 /*
15391                  * Note that reserving the BIOS fb up front prevents us
15392                  * from stuffing other stolen allocations like the ring
15393                  * on top.  This prevents some ugliness at boot time, and
15394                  * can even allow for smooth boot transitions if the BIOS
15395                  * fb is large enough for the active pipe configuration.
15396                  */
15397                 dev_priv->display.get_initial_plane_config(crtc,
15398                                                            &plane_config);
15399
15400                 /*
15401                  * If the fb is shared between multiple heads, we'll
15402                  * just get the first one.
15403                  */
15404                 intel_find_initial_plane_obj(crtc, &plane_config);
15405         }
15406
15407         /*
15408          * Make sure hardware watermarks really match the state we read out.
15409          * Note that we need to do this after reconstructing the BIOS fb's
15410          * since the watermark calculation done here will use pstate->fb.
15411          */
15412         sanitize_watermarks(dev);
15413 }
15414
15415 static void intel_enable_pipe_a(struct drm_device *dev)
15416 {
15417         struct intel_connector *connector;
15418         struct drm_connector *crt = NULL;
15419         struct intel_load_detect_pipe load_detect_temp;
15420         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15421
15422         /* We can't just switch on the pipe A, we need to set things up with a
15423          * proper mode and output configuration. As a gross hack, enable pipe A
15424          * by enabling the load detect pipe once. */
15425         for_each_intel_connector(dev, connector) {
15426                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15427                         crt = &connector->base;
15428                         break;
15429                 }
15430         }
15431
15432         if (!crt)
15433                 return;
15434
15435         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15436                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15437 }
15438
15439 static bool
15440 intel_check_plane_mapping(struct intel_crtc *crtc)
15441 {
15442         struct drm_device *dev = crtc->base.dev;
15443         struct drm_i915_private *dev_priv = dev->dev_private;
15444         u32 val;
15445
15446         if (INTEL_INFO(dev)->num_pipes == 1)
15447                 return true;
15448
15449         val = I915_READ(DSPCNTR(!crtc->plane));
15450
15451         if ((val & DISPLAY_PLANE_ENABLE) &&
15452             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15453                 return false;
15454
15455         return true;
15456 }
15457
15458 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15459 {
15460         struct drm_device *dev = crtc->base.dev;
15461         struct intel_encoder *encoder;
15462
15463         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15464                 return true;
15465
15466         return false;
15467 }
15468
15469 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
15470 {
15471         struct drm_device *dev = encoder->base.dev;
15472         struct intel_connector *connector;
15473
15474         for_each_connector_on_encoder(dev, &encoder->base, connector)
15475                 return true;
15476
15477         return false;
15478 }
15479
15480 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15481 {
15482         struct drm_device *dev = crtc->base.dev;
15483         struct drm_i915_private *dev_priv = dev->dev_private;
15484         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15485
15486         /* Clear any frame start delays used for debugging left by the BIOS */
15487         if (!transcoder_is_dsi(cpu_transcoder)) {
15488                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15489
15490                 I915_WRITE(reg,
15491                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15492         }
15493
15494         /* restore vblank interrupts to correct state */
15495         drm_crtc_vblank_reset(&crtc->base);
15496         if (crtc->active) {
15497                 struct intel_plane *plane;
15498
15499                 drm_crtc_vblank_on(&crtc->base);
15500
15501                 /* Disable everything but the primary plane */
15502                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15503                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15504                                 continue;
15505
15506                         plane->disable_plane(&plane->base, &crtc->base);
15507                 }
15508         }
15509
15510         /* We need to sanitize the plane -> pipe mapping first because this will
15511          * disable the crtc (and hence change the state) if it is wrong. Note
15512          * that gen4+ has a fixed plane -> pipe mapping.  */
15513         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15514                 bool plane;
15515
15516                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
15517                               crtc->base.base.id);
15518
15519                 /* Pipe has the wrong plane attached and the plane is active.
15520                  * Temporarily change the plane mapping and disable everything
15521                  * ...  */
15522                 plane = crtc->plane;
15523                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15524                 crtc->plane = !plane;
15525                 intel_crtc_disable_noatomic(&crtc->base);
15526                 crtc->plane = plane;
15527         }
15528
15529         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15530             crtc->pipe == PIPE_A && !crtc->active) {
15531                 /* BIOS forgot to enable pipe A, this mostly happens after
15532                  * resume. Force-enable the pipe to fix this, the update_dpms
15533                  * call below we restore the pipe to the right state, but leave
15534                  * the required bits on. */
15535                 intel_enable_pipe_a(dev);
15536         }
15537
15538         /* Adjust the state of the output pipe according to whether we
15539          * have active connectors/encoders. */
15540         if (crtc->active && !intel_crtc_has_encoders(crtc))
15541                 intel_crtc_disable_noatomic(&crtc->base);
15542
15543         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15544                 /*
15545                  * We start out with underrun reporting disabled to avoid races.
15546                  * For correct bookkeeping mark this on active crtcs.
15547                  *
15548                  * Also on gmch platforms we dont have any hardware bits to
15549                  * disable the underrun reporting. Which means we need to start
15550                  * out with underrun reporting disabled also on inactive pipes,
15551                  * since otherwise we'll complain about the garbage we read when
15552                  * e.g. coming up after runtime pm.
15553                  *
15554                  * No protection against concurrent access is required - at
15555                  * worst a fifo underrun happens which also sets this to false.
15556                  */
15557                 crtc->cpu_fifo_underrun_disabled = true;
15558                 crtc->pch_fifo_underrun_disabled = true;
15559         }
15560 }
15561
15562 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15563 {
15564         struct intel_connector *connector;
15565         struct drm_device *dev = encoder->base.dev;
15566
15567         /* We need to check both for a crtc link (meaning that the
15568          * encoder is active and trying to read from a pipe) and the
15569          * pipe itself being active. */
15570         bool has_active_crtc = encoder->base.crtc &&
15571                 to_intel_crtc(encoder->base.crtc)->active;
15572
15573         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
15574                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15575                               encoder->base.base.id,
15576                               encoder->base.name);
15577
15578                 /* Connector is active, but has no active pipe. This is
15579                  * fallout from our resume register restoring. Disable
15580                  * the encoder manually again. */
15581                 if (encoder->base.crtc) {
15582                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15583                                       encoder->base.base.id,
15584                                       encoder->base.name);
15585                         encoder->disable(encoder);
15586                         if (encoder->post_disable)
15587                                 encoder->post_disable(encoder);
15588                 }
15589                 encoder->base.crtc = NULL;
15590
15591                 /* Inconsistent output/port/pipe state happens presumably due to
15592                  * a bug in one of the get_hw_state functions. Or someplace else
15593                  * in our code, like the register restore mess on resume. Clamp
15594                  * things to off as a safer default. */
15595                 for_each_intel_connector(dev, connector) {
15596                         if (connector->encoder != encoder)
15597                                 continue;
15598                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15599                         connector->base.encoder = NULL;
15600                 }
15601         }
15602         /* Enabled encoders without active connectors will be fixed in
15603          * the crtc fixup. */
15604 }
15605
15606 void i915_redisable_vga_power_on(struct drm_device *dev)
15607 {
15608         struct drm_i915_private *dev_priv = dev->dev_private;
15609         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15610
15611         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15612                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15613                 i915_disable_vga(dev);
15614         }
15615 }
15616
15617 void i915_redisable_vga(struct drm_device *dev)
15618 {
15619         struct drm_i915_private *dev_priv = dev->dev_private;
15620
15621         /* This function can be called both from intel_modeset_setup_hw_state or
15622          * at a very early point in our resume sequence, where the power well
15623          * structures are not yet restored. Since this function is at a very
15624          * paranoid "someone might have enabled VGA while we were not looking"
15625          * level, just check if the power well is enabled instead of trying to
15626          * follow the "don't touch the power well if we don't need it" policy
15627          * the rest of the driver uses. */
15628         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15629                 return;
15630
15631         i915_redisable_vga_power_on(dev);
15632
15633         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15634 }
15635
15636 static bool primary_get_hw_state(struct intel_plane *plane)
15637 {
15638         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15639
15640         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15641 }
15642
15643 /* FIXME read out full plane state for all planes */
15644 static void readout_plane_state(struct intel_crtc *crtc)
15645 {
15646         struct drm_plane *primary = crtc->base.primary;
15647         struct intel_plane_state *plane_state =
15648                 to_intel_plane_state(primary->state);
15649
15650         plane_state->visible = crtc->active &&
15651                 primary_get_hw_state(to_intel_plane(primary));
15652
15653         if (plane_state->visible)
15654                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
15655 }
15656
15657 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15658 {
15659         struct drm_i915_private *dev_priv = dev->dev_private;
15660         enum pipe pipe;
15661         struct intel_crtc *crtc;
15662         struct intel_encoder *encoder;
15663         struct intel_connector *connector;
15664         int i;
15665
15666         dev_priv->active_crtcs = 0;
15667
15668         for_each_intel_crtc(dev, crtc) {
15669                 struct intel_crtc_state *crtc_state = crtc->config;
15670                 int pixclk = 0;
15671
15672                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, &crtc_state->base);
15673                 memset(crtc_state, 0, sizeof(*crtc_state));
15674                 crtc_state->base.crtc = &crtc->base;
15675
15676                 crtc_state->base.active = crtc_state->base.enable =
15677                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15678
15679                 crtc->base.enabled = crtc_state->base.enable;
15680                 crtc->active = crtc_state->base.active;
15681
15682                 if (crtc_state->base.active) {
15683                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15684
15685                         if (IS_BROADWELL(dev_priv)) {
15686                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
15687
15688                                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15689                                 if (crtc_state->ips_enabled)
15690                                         pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15691                         } else if (IS_VALLEYVIEW(dev_priv) ||
15692                                    IS_CHERRYVIEW(dev_priv) ||
15693                                    IS_BROXTON(dev_priv))
15694                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
15695                         else
15696                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15697                 }
15698
15699                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15700
15701                 readout_plane_state(crtc);
15702
15703                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15704                               crtc->base.base.id,
15705                               crtc->active ? "enabled" : "disabled");
15706         }
15707
15708         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15709                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15710
15711                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15712                                                   &pll->config.hw_state);
15713                 pll->config.crtc_mask = 0;
15714                 for_each_intel_crtc(dev, crtc) {
15715                         if (crtc->active && crtc->config->shared_dpll == pll)
15716                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15717                 }
15718                 pll->active_mask = pll->config.crtc_mask;
15719
15720                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15721                               pll->name, pll->config.crtc_mask, pll->on);
15722         }
15723
15724         for_each_intel_encoder(dev, encoder) {
15725                 pipe = 0;
15726
15727                 if (encoder->get_hw_state(encoder, &pipe)) {
15728                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15729                         encoder->base.crtc = &crtc->base;
15730                         encoder->get_config(encoder, crtc->config);
15731                 } else {
15732                         encoder->base.crtc = NULL;
15733                 }
15734
15735                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15736                               encoder->base.base.id,
15737                               encoder->base.name,
15738                               encoder->base.crtc ? "enabled" : "disabled",
15739                               pipe_name(pipe));
15740         }
15741
15742         for_each_intel_connector(dev, connector) {
15743                 if (connector->get_hw_state(connector)) {
15744                         connector->base.dpms = DRM_MODE_DPMS_ON;
15745
15746                         encoder = connector->encoder;
15747                         connector->base.encoder = &encoder->base;
15748
15749                         if (encoder->base.crtc &&
15750                             encoder->base.crtc->state->active) {
15751                                 /*
15752                                  * This has to be done during hardware readout
15753                                  * because anything calling .crtc_disable may
15754                                  * rely on the connector_mask being accurate.
15755                                  */
15756                                 encoder->base.crtc->state->connector_mask |=
15757                                         1 << drm_connector_index(&connector->base);
15758                                 encoder->base.crtc->state->encoder_mask |=
15759                                         1 << drm_encoder_index(&encoder->base);
15760                         }
15761
15762                 } else {
15763                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15764                         connector->base.encoder = NULL;
15765                 }
15766                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15767                               connector->base.base.id,
15768                               connector->base.name,
15769                               connector->base.encoder ? "enabled" : "disabled");
15770         }
15771
15772         for_each_intel_crtc(dev, crtc) {
15773                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15774
15775                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15776                 if (crtc->base.state->active) {
15777                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15778                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15779                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15780
15781                         /*
15782                          * The initial mode needs to be set in order to keep
15783                          * the atomic core happy. It wants a valid mode if the
15784                          * crtc's enabled, so we do the above call.
15785                          *
15786                          * At this point some state updated by the connectors
15787                          * in their ->detect() callback has not run yet, so
15788                          * no recalculation can be done yet.
15789                          *
15790                          * Even if we could do a recalculation and modeset
15791                          * right now it would cause a double modeset if
15792                          * fbdev or userspace chooses a different initial mode.
15793                          *
15794                          * If that happens, someone indicated they wanted a
15795                          * mode change, which means it's safe to do a full
15796                          * recalculation.
15797                          */
15798                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15799
15800                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
15801                         update_scanline_offset(crtc);
15802                 }
15803
15804                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
15805         }
15806 }
15807
15808 /* Scan out the current hw modeset state,
15809  * and sanitizes it to the current state
15810  */
15811 static void
15812 intel_modeset_setup_hw_state(struct drm_device *dev)
15813 {
15814         struct drm_i915_private *dev_priv = dev->dev_private;
15815         enum pipe pipe;
15816         struct intel_crtc *crtc;
15817         struct intel_encoder *encoder;
15818         int i;
15819
15820         intel_modeset_readout_hw_state(dev);
15821
15822         /* HW state is read out, now we need to sanitize this mess. */
15823         for_each_intel_encoder(dev, encoder) {
15824                 intel_sanitize_encoder(encoder);
15825         }
15826
15827         for_each_pipe(dev_priv, pipe) {
15828                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15829                 intel_sanitize_crtc(crtc);
15830                 intel_dump_pipe_config(crtc, crtc->config,
15831                                        "[setup_hw_state]");
15832         }
15833
15834         intel_modeset_update_connector_atomic_state(dev);
15835
15836         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15837                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15838
15839                 if (!pll->on || pll->active_mask)
15840                         continue;
15841
15842                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15843
15844                 pll->funcs.disable(dev_priv, pll);
15845                 pll->on = false;
15846         }
15847
15848         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
15849                 vlv_wm_get_hw_state(dev);
15850         else if (IS_GEN9(dev))
15851                 skl_wm_get_hw_state(dev);
15852         else if (HAS_PCH_SPLIT(dev))
15853                 ilk_wm_get_hw_state(dev);
15854
15855         for_each_intel_crtc(dev, crtc) {
15856                 unsigned long put_domains;
15857
15858                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15859                 if (WARN_ON(put_domains))
15860                         modeset_put_power_domains(dev_priv, put_domains);
15861         }
15862         intel_display_set_init_power(dev_priv, false);
15863
15864         intel_fbc_init_pipe_state(dev_priv);
15865 }
15866
15867 void intel_display_resume(struct drm_device *dev)
15868 {
15869         struct drm_i915_private *dev_priv = to_i915(dev);
15870         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15871         struct drm_modeset_acquire_ctx ctx;
15872         int ret;
15873         bool setup = false;
15874
15875         dev_priv->modeset_restore_state = NULL;
15876
15877         /*
15878          * This is a cludge because with real atomic modeset mode_config.mutex
15879          * won't be taken. Unfortunately some probed state like
15880          * audio_codec_enable is still protected by mode_config.mutex, so lock
15881          * it here for now.
15882          */
15883         mutex_lock(&dev->mode_config.mutex);
15884         drm_modeset_acquire_init(&ctx, 0);
15885
15886 retry:
15887         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15888
15889         if (ret == 0 && !setup) {
15890                 setup = true;
15891
15892                 intel_modeset_setup_hw_state(dev);
15893                 i915_redisable_vga(dev);
15894         }
15895
15896         if (ret == 0 && state) {
15897                 struct drm_crtc_state *crtc_state;
15898                 struct drm_crtc *crtc;
15899                 int i;
15900
15901                 state->acquire_ctx = &ctx;
15902
15903                 for_each_crtc_in_state(state, crtc, crtc_state, i) {
15904                         /*
15905                          * Force recalculation even if we restore
15906                          * current state. With fast modeset this may not result
15907                          * in a modeset when the state is compatible.
15908                          */
15909                         crtc_state->mode_changed = true;
15910                 }
15911
15912                 ret = drm_atomic_commit(state);
15913         }
15914
15915         if (ret == -EDEADLK) {
15916                 drm_modeset_backoff(&ctx);
15917                 goto retry;
15918         }
15919
15920         drm_modeset_drop_locks(&ctx);
15921         drm_modeset_acquire_fini(&ctx);
15922         mutex_unlock(&dev->mode_config.mutex);
15923
15924         if (ret) {
15925                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15926                 drm_atomic_state_free(state);
15927         }
15928 }
15929
15930 void intel_modeset_gem_init(struct drm_device *dev)
15931 {
15932         struct drm_crtc *c;
15933         struct drm_i915_gem_object *obj;
15934         int ret;
15935
15936         intel_init_gt_powersave(dev);
15937
15938         intel_modeset_init_hw(dev);
15939
15940         intel_setup_overlay(dev);
15941
15942         /*
15943          * Make sure any fbs we allocated at startup are properly
15944          * pinned & fenced.  When we do the allocation it's too early
15945          * for this.
15946          */
15947         for_each_crtc(dev, c) {
15948                 obj = intel_fb_obj(c->primary->fb);
15949                 if (obj == NULL)
15950                         continue;
15951
15952                 mutex_lock(&dev->struct_mutex);
15953                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
15954                                                  c->primary->state->rotation);
15955                 mutex_unlock(&dev->struct_mutex);
15956                 if (ret) {
15957                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15958                                   to_intel_crtc(c)->pipe);
15959                         drm_framebuffer_unreference(c->primary->fb);
15960                         c->primary->fb = NULL;
15961                         c->primary->crtc = c->primary->state->crtc = NULL;
15962                         update_state_fb(c->primary);
15963                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15964                 }
15965         }
15966
15967         intel_backlight_register(dev);
15968 }
15969
15970 void intel_connector_unregister(struct intel_connector *intel_connector)
15971 {
15972         struct drm_connector *connector = &intel_connector->base;
15973
15974         intel_panel_destroy_backlight(connector);
15975         drm_connector_unregister(connector);
15976 }
15977
15978 void intel_modeset_cleanup(struct drm_device *dev)
15979 {
15980         struct drm_i915_private *dev_priv = dev->dev_private;
15981         struct intel_connector *connector;
15982
15983         intel_disable_gt_powersave(dev);
15984
15985         intel_backlight_unregister(dev);
15986
15987         /*
15988          * Interrupts and polling as the first thing to avoid creating havoc.
15989          * Too much stuff here (turning of connectors, ...) would
15990          * experience fancy races otherwise.
15991          */
15992         intel_irq_uninstall(dev_priv);
15993
15994         /*
15995          * Due to the hpd irq storm handling the hotplug work can re-arm the
15996          * poll handlers. Hence disable polling after hpd handling is shut down.
15997          */
15998         drm_kms_helper_poll_fini(dev);
15999
16000         intel_unregister_dsm_handler();
16001
16002         intel_fbc_global_disable(dev_priv);
16003
16004         /* flush any delayed tasks or pending work */
16005         flush_scheduled_work();
16006
16007         /* destroy the backlight and sysfs files before encoders/connectors */
16008         for_each_intel_connector(dev, connector)
16009                 connector->unregister(connector);
16010
16011         drm_mode_config_cleanup(dev);
16012
16013         intel_cleanup_overlay(dev);
16014
16015         intel_cleanup_gt_powersave(dev);
16016
16017         intel_teardown_gmbus(dev);
16018 }
16019
16020 /*
16021  * Return which encoder is currently attached for connector.
16022  */
16023 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
16024 {
16025         return &intel_attached_encoder(connector)->base;
16026 }
16027
16028 void intel_connector_attach_encoder(struct intel_connector *connector,
16029                                     struct intel_encoder *encoder)
16030 {
16031         connector->encoder = encoder;
16032         drm_mode_connector_attach_encoder(&connector->base,
16033                                           &encoder->base);
16034 }
16035
16036 /*
16037  * set vga decode state - true == enable VGA decode
16038  */
16039 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
16040 {
16041         struct drm_i915_private *dev_priv = dev->dev_private;
16042         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16043         u16 gmch_ctrl;
16044
16045         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16046                 DRM_ERROR("failed to read control word\n");
16047                 return -EIO;
16048         }
16049
16050         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16051                 return 0;
16052
16053         if (state)
16054                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16055         else
16056                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16057
16058         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16059                 DRM_ERROR("failed to write control word\n");
16060                 return -EIO;
16061         }
16062
16063         return 0;
16064 }
16065
16066 struct intel_display_error_state {
16067
16068         u32 power_well_driver;
16069
16070         int num_transcoders;
16071
16072         struct intel_cursor_error_state {
16073                 u32 control;
16074                 u32 position;
16075                 u32 base;
16076                 u32 size;
16077         } cursor[I915_MAX_PIPES];
16078
16079         struct intel_pipe_error_state {
16080                 bool power_domain_on;
16081                 u32 source;
16082                 u32 stat;
16083         } pipe[I915_MAX_PIPES];
16084
16085         struct intel_plane_error_state {
16086                 u32 control;
16087                 u32 stride;
16088                 u32 size;
16089                 u32 pos;
16090                 u32 addr;
16091                 u32 surface;
16092                 u32 tile_offset;
16093         } plane[I915_MAX_PIPES];
16094
16095         struct intel_transcoder_error_state {
16096                 bool power_domain_on;
16097                 enum transcoder cpu_transcoder;
16098
16099                 u32 conf;
16100
16101                 u32 htotal;
16102                 u32 hblank;
16103                 u32 hsync;
16104                 u32 vtotal;
16105                 u32 vblank;
16106                 u32 vsync;
16107         } transcoder[4];
16108 };
16109
16110 struct intel_display_error_state *
16111 intel_display_capture_error_state(struct drm_device *dev)
16112 {
16113         struct drm_i915_private *dev_priv = dev->dev_private;
16114         struct intel_display_error_state *error;
16115         int transcoders[] = {
16116                 TRANSCODER_A,
16117                 TRANSCODER_B,
16118                 TRANSCODER_C,
16119                 TRANSCODER_EDP,
16120         };
16121         int i;
16122
16123         if (INTEL_INFO(dev)->num_pipes == 0)
16124                 return NULL;
16125
16126         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16127         if (error == NULL)
16128                 return NULL;
16129
16130         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16131                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
16132
16133         for_each_pipe(dev_priv, i) {
16134                 error->pipe[i].power_domain_on =
16135                         __intel_display_power_is_enabled(dev_priv,
16136                                                          POWER_DOMAIN_PIPE(i));
16137                 if (!error->pipe[i].power_domain_on)
16138                         continue;
16139
16140                 error->cursor[i].control = I915_READ(CURCNTR(i));
16141                 error->cursor[i].position = I915_READ(CURPOS(i));
16142                 error->cursor[i].base = I915_READ(CURBASE(i));
16143
16144                 error->plane[i].control = I915_READ(DSPCNTR(i));
16145                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16146                 if (INTEL_INFO(dev)->gen <= 3) {
16147                         error->plane[i].size = I915_READ(DSPSIZE(i));
16148                         error->plane[i].pos = I915_READ(DSPPOS(i));
16149                 }
16150                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16151                         error->plane[i].addr = I915_READ(DSPADDR(i));
16152                 if (INTEL_INFO(dev)->gen >= 4) {
16153                         error->plane[i].surface = I915_READ(DSPSURF(i));
16154                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16155                 }
16156
16157                 error->pipe[i].source = I915_READ(PIPESRC(i));
16158
16159                 if (HAS_GMCH_DISPLAY(dev))
16160                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16161         }
16162
16163         /* Note: this does not include DSI transcoders. */
16164         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
16165         if (HAS_DDI(dev_priv->dev))
16166                 error->num_transcoders++; /* Account for eDP. */
16167
16168         for (i = 0; i < error->num_transcoders; i++) {
16169                 enum transcoder cpu_transcoder = transcoders[i];
16170
16171                 error->transcoder[i].power_domain_on =
16172                         __intel_display_power_is_enabled(dev_priv,
16173                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16174                 if (!error->transcoder[i].power_domain_on)
16175                         continue;
16176
16177                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16178
16179                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16180                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16181                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16182                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16183                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16184                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16185                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16186         }
16187
16188         return error;
16189 }
16190
16191 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16192
16193 void
16194 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16195                                 struct drm_device *dev,
16196                                 struct intel_display_error_state *error)
16197 {
16198         struct drm_i915_private *dev_priv = dev->dev_private;
16199         int i;
16200
16201         if (!error)
16202                 return;
16203
16204         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16205         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16206                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16207                            error->power_well_driver);
16208         for_each_pipe(dev_priv, i) {
16209                 err_printf(m, "Pipe [%d]:\n", i);
16210                 err_printf(m, "  Power: %s\n",
16211                            onoff(error->pipe[i].power_domain_on));
16212                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16213                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16214
16215                 err_printf(m, "Plane [%d]:\n", i);
16216                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16217                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16218                 if (INTEL_INFO(dev)->gen <= 3) {
16219                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16220                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16221                 }
16222                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16223                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16224                 if (INTEL_INFO(dev)->gen >= 4) {
16225                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16226                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16227                 }
16228
16229                 err_printf(m, "Cursor [%d]:\n", i);
16230                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16231                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16232                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16233         }
16234
16235         for (i = 0; i < error->num_transcoders; i++) {
16236                 err_printf(m, "CPU transcoder: %s\n",
16237                            transcoder_name(error->transcoder[i].cpu_transcoder));
16238                 err_printf(m, "  Power: %s\n",
16239                            onoff(error->transcoder[i].power_domain_on));
16240                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16241                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16242                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16243                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16244                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16245                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16246                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16247         }
16248 }