drm/i915/bxt: Fix DSI HW state readout
[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         i915_reg_t reg = DPLL(crtc->pipe);
1532         u32 dpll = pipe_config->dpll_hw_state.dpll;
1533
1534         assert_pipe_disabled(dev_priv, crtc->pipe);
1535
1536         /* PLL is protected by panel, make sure we can write it */
1537         if (IS_MOBILE(dev_priv->dev))
1538                 assert_panel_unlocked(dev_priv, crtc->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", crtc->pipe);
1546
1547         I915_WRITE(DPLL_MD(crtc->pipe), pipe_config->dpll_hw_state.dpll_md);
1548         POSTING_READ(DPLL_MD(crtc->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         int pipe = crtc->pipe;
1568         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1569         u32 tmp;
1570
1571         assert_pipe_disabled(dev_priv, crtc->pipe);
1572
1573         mutex_lock(&dev_priv->sb_lock);
1574
1575         /* Enable back the 10bit clock to display controller */
1576         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1577         tmp |= DPIO_DCLKP_EN;
1578         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1579
1580         mutex_unlock(&dev_priv->sb_lock);
1581
1582         /*
1583          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1584          */
1585         udelay(1);
1586
1587         /* Enable PLL */
1588         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1589
1590         /* Check PLL is locked */
1591         if (wait_for(((I915_READ(DPLL(pipe)) & DPLL_LOCK_VLV) == DPLL_LOCK_VLV), 1))
1592                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1593
1594         /* not sure when this should be written */
1595         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1596         POSTING_READ(DPLL_MD(pipe));
1597 }
1598
1599 static int intel_num_dvo_pipes(struct drm_device *dev)
1600 {
1601         struct intel_crtc *crtc;
1602         int count = 0;
1603
1604         for_each_intel_crtc(dev, crtc)
1605                 count += crtc->base.state->active &&
1606                         intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO);
1607
1608         return count;
1609 }
1610
1611 static void i9xx_enable_pll(struct intel_crtc *crtc)
1612 {
1613         struct drm_device *dev = crtc->base.dev;
1614         struct drm_i915_private *dev_priv = dev->dev_private;
1615         i915_reg_t reg = DPLL(crtc->pipe);
1616         u32 dpll = crtc->config->dpll_hw_state.dpll;
1617
1618         assert_pipe_disabled(dev_priv, crtc->pipe);
1619
1620         /* No really, not for ILK+ */
1621         BUG_ON(INTEL_INFO(dev)->gen >= 5);
1622
1623         /* PLL is protected by panel, make sure we can write it */
1624         if (IS_MOBILE(dev) && !IS_I830(dev))
1625                 assert_panel_unlocked(dev_priv, crtc->pipe);
1626
1627         /* Enable DVO 2x clock on both PLLs if necessary */
1628         if (IS_I830(dev) && intel_num_dvo_pipes(dev) > 0) {
1629                 /*
1630                  * It appears to be important that we don't enable this
1631                  * for the current pipe before otherwise configuring the
1632                  * PLL. No idea how this should be handled if multiple
1633                  * DVO outputs are enabled simultaneosly.
1634                  */
1635                 dpll |= DPLL_DVO_2X_MODE;
1636                 I915_WRITE(DPLL(!crtc->pipe),
1637                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1638         }
1639
1640         /*
1641          * Apparently we need to have VGA mode enabled prior to changing
1642          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1643          * dividers, even though the register value does change.
1644          */
1645         I915_WRITE(reg, 0);
1646
1647         I915_WRITE(reg, dpll);
1648
1649         /* Wait for the clocks to stabilize. */
1650         POSTING_READ(reg);
1651         udelay(150);
1652
1653         if (INTEL_INFO(dev)->gen >= 4) {
1654                 I915_WRITE(DPLL_MD(crtc->pipe),
1655                            crtc->config->dpll_hw_state.dpll_md);
1656         } else {
1657                 /* The pixel multiplier can only be updated once the
1658                  * DPLL is enabled and the clocks are stable.
1659                  *
1660                  * So write it again.
1661                  */
1662                 I915_WRITE(reg, dpll);
1663         }
1664
1665         /* We do this three times for luck */
1666         I915_WRITE(reg, dpll);
1667         POSTING_READ(reg);
1668         udelay(150); /* wait for warmup */
1669         I915_WRITE(reg, dpll);
1670         POSTING_READ(reg);
1671         udelay(150); /* wait for warmup */
1672         I915_WRITE(reg, dpll);
1673         POSTING_READ(reg);
1674         udelay(150); /* wait for warmup */
1675 }
1676
1677 /**
1678  * i9xx_disable_pll - disable a PLL
1679  * @dev_priv: i915 private structure
1680  * @pipe: pipe PLL to disable
1681  *
1682  * Disable the PLL for @pipe, making sure the pipe is off first.
1683  *
1684  * Note!  This is for pre-ILK only.
1685  */
1686 static void i9xx_disable_pll(struct intel_crtc *crtc)
1687 {
1688         struct drm_device *dev = crtc->base.dev;
1689         struct drm_i915_private *dev_priv = dev->dev_private;
1690         enum pipe pipe = crtc->pipe;
1691
1692         /* Disable DVO 2x clock on both PLLs if necessary */
1693         if (IS_I830(dev) &&
1694             intel_pipe_has_type(crtc, INTEL_OUTPUT_DVO) &&
1695             !intel_num_dvo_pipes(dev)) {
1696                 I915_WRITE(DPLL(PIPE_B),
1697                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1698                 I915_WRITE(DPLL(PIPE_A),
1699                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1700         }
1701
1702         /* Don't disable pipe or pipe PLLs if needed */
1703         if ((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1704             (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
1705                 return;
1706
1707         /* Make sure the pipe isn't still relying on us */
1708         assert_pipe_disabled(dev_priv, pipe);
1709
1710         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1711         POSTING_READ(DPLL(pipe));
1712 }
1713
1714 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1715 {
1716         u32 val;
1717
1718         /* Make sure the pipe isn't still relying on us */
1719         assert_pipe_disabled(dev_priv, pipe);
1720
1721         /*
1722          * Leave integrated clock source and reference clock enabled for pipe B.
1723          * The latter is needed for VGA hotplug / manual detection.
1724          */
1725         val = DPLL_VGA_MODE_DIS;
1726         if (pipe == PIPE_B)
1727                 val = DPLL_INTEGRATED_CRI_CLK_VLV | DPLL_REF_CLK_ENABLE_VLV;
1728         I915_WRITE(DPLL(pipe), val);
1729         POSTING_READ(DPLL(pipe));
1730
1731 }
1732
1733 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1734 {
1735         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1736         u32 val;
1737
1738         /* Make sure the pipe isn't still relying on us */
1739         assert_pipe_disabled(dev_priv, pipe);
1740
1741         /* Set PLL en = 0 */
1742         val = DPLL_SSC_REF_CLK_CHV |
1743                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1744         if (pipe != PIPE_A)
1745                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1746         I915_WRITE(DPLL(pipe), val);
1747         POSTING_READ(DPLL(pipe));
1748
1749         mutex_lock(&dev_priv->sb_lock);
1750
1751         /* Disable 10bit clock to display controller */
1752         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1753         val &= ~DPIO_DCLKP_EN;
1754         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1755
1756         mutex_unlock(&dev_priv->sb_lock);
1757 }
1758
1759 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1760                          struct intel_digital_port *dport,
1761                          unsigned int expected_mask)
1762 {
1763         u32 port_mask;
1764         i915_reg_t dpll_reg;
1765
1766         switch (dport->port) {
1767         case PORT_B:
1768                 port_mask = DPLL_PORTB_READY_MASK;
1769                 dpll_reg = DPLL(0);
1770                 break;
1771         case PORT_C:
1772                 port_mask = DPLL_PORTC_READY_MASK;
1773                 dpll_reg = DPLL(0);
1774                 expected_mask <<= 4;
1775                 break;
1776         case PORT_D:
1777                 port_mask = DPLL_PORTD_READY_MASK;
1778                 dpll_reg = DPIO_PHY_STATUS;
1779                 break;
1780         default:
1781                 BUG();
1782         }
1783
1784         if (wait_for((I915_READ(dpll_reg) & port_mask) == expected_mask, 1000))
1785                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1786                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1787 }
1788
1789 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1790                                            enum pipe pipe)
1791 {
1792         struct drm_device *dev = dev_priv->dev;
1793         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
1794         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
1795         i915_reg_t reg;
1796         uint32_t val, pipeconf_val;
1797
1798         /* PCH only available on ILK+ */
1799         BUG_ON(!HAS_PCH_SPLIT(dev));
1800
1801         /* Make sure PCH DPLL is enabled */
1802         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1803
1804         /* FDI must be feeding us bits for PCH ports */
1805         assert_fdi_tx_enabled(dev_priv, pipe);
1806         assert_fdi_rx_enabled(dev_priv, pipe);
1807
1808         if (HAS_PCH_CPT(dev)) {
1809                 /* Workaround: Set the timing override bit before enabling the
1810                  * pch transcoder. */
1811                 reg = TRANS_CHICKEN2(pipe);
1812                 val = I915_READ(reg);
1813                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1814                 I915_WRITE(reg, val);
1815         }
1816
1817         reg = PCH_TRANSCONF(pipe);
1818         val = I915_READ(reg);
1819         pipeconf_val = I915_READ(PIPECONF(pipe));
1820
1821         if (HAS_PCH_IBX(dev_priv->dev)) {
1822                 /*
1823                  * Make the BPC in transcoder be consistent with
1824                  * that in pipeconf reg. For HDMI we must use 8bpc
1825                  * here for both 8bpc and 12bpc.
1826                  */
1827                 val &= ~PIPECONF_BPC_MASK;
1828                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_HDMI))
1829                         val |= PIPECONF_8BPC;
1830                 else
1831                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1832         }
1833
1834         val &= ~TRANS_INTERLACE_MASK;
1835         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1836                 if (HAS_PCH_IBX(dev_priv->dev) &&
1837                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
1838                         val |= TRANS_LEGACY_INTERLACED_ILK;
1839                 else
1840                         val |= TRANS_INTERLACED;
1841         else
1842                 val |= TRANS_PROGRESSIVE;
1843
1844         I915_WRITE(reg, val | TRANS_ENABLE);
1845         if (wait_for(I915_READ(reg) & TRANS_STATE_ENABLE, 100))
1846                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1847 }
1848
1849 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1850                                       enum transcoder cpu_transcoder)
1851 {
1852         u32 val, pipeconf_val;
1853
1854         /* PCH only available on ILK+ */
1855         BUG_ON(!HAS_PCH_SPLIT(dev_priv->dev));
1856
1857         /* FDI must be feeding us bits for PCH ports */
1858         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1859         assert_fdi_rx_enabled(dev_priv, TRANSCODER_A);
1860
1861         /* Workaround: set timing override bit. */
1862         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1863         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1864         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1865
1866         val = TRANS_ENABLE;
1867         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1868
1869         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1870             PIPECONF_INTERLACED_ILK)
1871                 val |= TRANS_INTERLACED;
1872         else
1873                 val |= TRANS_PROGRESSIVE;
1874
1875         I915_WRITE(LPT_TRANSCONF, val);
1876         if (wait_for(I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE, 100))
1877                 DRM_ERROR("Failed to enable PCH transcoder\n");
1878 }
1879
1880 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1881                                             enum pipe pipe)
1882 {
1883         struct drm_device *dev = dev_priv->dev;
1884         i915_reg_t reg;
1885         uint32_t val;
1886
1887         /* FDI relies on the transcoder */
1888         assert_fdi_tx_disabled(dev_priv, pipe);
1889         assert_fdi_rx_disabled(dev_priv, pipe);
1890
1891         /* Ports must be off as well */
1892         assert_pch_ports_disabled(dev_priv, pipe);
1893
1894         reg = PCH_TRANSCONF(pipe);
1895         val = I915_READ(reg);
1896         val &= ~TRANS_ENABLE;
1897         I915_WRITE(reg, val);
1898         /* wait for PCH transcoder off, transcoder state */
1899         if (wait_for((I915_READ(reg) & TRANS_STATE_ENABLE) == 0, 50))
1900                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1901
1902         if (HAS_PCH_CPT(dev)) {
1903                 /* Workaround: Clear the timing override chicken bit again. */
1904                 reg = TRANS_CHICKEN2(pipe);
1905                 val = I915_READ(reg);
1906                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1907                 I915_WRITE(reg, val);
1908         }
1909 }
1910
1911 static void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1912 {
1913         u32 val;
1914
1915         val = I915_READ(LPT_TRANSCONF);
1916         val &= ~TRANS_ENABLE;
1917         I915_WRITE(LPT_TRANSCONF, val);
1918         /* wait for PCH transcoder off, transcoder state */
1919         if (wait_for((I915_READ(LPT_TRANSCONF) & TRANS_STATE_ENABLE) == 0, 50))
1920                 DRM_ERROR("Failed to disable PCH transcoder\n");
1921
1922         /* Workaround: clear timing override bit. */
1923         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1924         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1925         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1926 }
1927
1928 /**
1929  * intel_enable_pipe - enable a pipe, asserting requirements
1930  * @crtc: crtc responsible for the pipe
1931  *
1932  * Enable @crtc's pipe, making sure that various hardware specific requirements
1933  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1934  */
1935 static void intel_enable_pipe(struct intel_crtc *crtc)
1936 {
1937         struct drm_device *dev = crtc->base.dev;
1938         struct drm_i915_private *dev_priv = dev->dev_private;
1939         enum pipe pipe = crtc->pipe;
1940         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1941         enum pipe pch_transcoder;
1942         i915_reg_t reg;
1943         u32 val;
1944
1945         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1946
1947         assert_planes_disabled(dev_priv, pipe);
1948         assert_cursor_disabled(dev_priv, pipe);
1949         assert_sprites_disabled(dev_priv, pipe);
1950
1951         if (HAS_PCH_LPT(dev_priv->dev))
1952                 pch_transcoder = TRANSCODER_A;
1953         else
1954                 pch_transcoder = pipe;
1955
1956         /*
1957          * A pipe without a PLL won't actually be able to drive bits from
1958          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1959          * need the check.
1960          */
1961         if (HAS_GMCH_DISPLAY(dev_priv->dev))
1962                 if (crtc->config->has_dsi_encoder)
1963                         assert_dsi_pll_enabled(dev_priv);
1964                 else
1965                         assert_pll_enabled(dev_priv, pipe);
1966         else {
1967                 if (crtc->config->has_pch_encoder) {
1968                         /* if driving the PCH, we need FDI enabled */
1969                         assert_fdi_rx_pll_enabled(dev_priv, pch_transcoder);
1970                         assert_fdi_tx_pll_enabled(dev_priv,
1971                                                   (enum pipe) cpu_transcoder);
1972                 }
1973                 /* FIXME: assert CPU port conditions for SNB+ */
1974         }
1975
1976         reg = PIPECONF(cpu_transcoder);
1977         val = I915_READ(reg);
1978         if (val & PIPECONF_ENABLE) {
1979                 WARN_ON(!((pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
1980                           (pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE)));
1981                 return;
1982         }
1983
1984         I915_WRITE(reg, val | PIPECONF_ENABLE);
1985         POSTING_READ(reg);
1986
1987         /*
1988          * Until the pipe starts DSL will read as 0, which would cause
1989          * an apparent vblank timestamp jump, which messes up also the
1990          * frame count when it's derived from the timestamps. So let's
1991          * wait for the pipe to start properly before we call
1992          * drm_crtc_vblank_on()
1993          */
1994         if (dev->max_vblank_count == 0 &&
1995             wait_for(intel_get_crtc_scanline(crtc) != crtc->scanline_offset, 50))
1996                 DRM_ERROR("pipe %c didn't start\n", pipe_name(pipe));
1997 }
1998
1999 /**
2000  * intel_disable_pipe - disable a pipe, asserting requirements
2001  * @crtc: crtc whose pipes is to be disabled
2002  *
2003  * Disable the pipe of @crtc, making sure that various hardware
2004  * specific requirements are met, if applicable, e.g. plane
2005  * disabled, panel fitter off, etc.
2006  *
2007  * Will wait until the pipe has shut down before returning.
2008  */
2009 static void intel_disable_pipe(struct intel_crtc *crtc)
2010 {
2011         struct drm_i915_private *dev_priv = crtc->base.dev->dev_private;
2012         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
2013         enum pipe pipe = crtc->pipe;
2014         i915_reg_t reg;
2015         u32 val;
2016
2017         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
2018
2019         /*
2020          * Make sure planes won't keep trying to pump pixels to us,
2021          * or we might hang the display.
2022          */
2023         assert_planes_disabled(dev_priv, pipe);
2024         assert_cursor_disabled(dev_priv, pipe);
2025         assert_sprites_disabled(dev_priv, pipe);
2026
2027         reg = PIPECONF(cpu_transcoder);
2028         val = I915_READ(reg);
2029         if ((val & PIPECONF_ENABLE) == 0)
2030                 return;
2031
2032         /*
2033          * Double wide has implications for planes
2034          * so best keep it disabled when not needed.
2035          */
2036         if (crtc->config->double_wide)
2037                 val &= ~PIPECONF_DOUBLE_WIDE;
2038
2039         /* Don't disable pipe or pipe PLLs if needed */
2040         if (!(pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) &&
2041             !(pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
2042                 val &= ~PIPECONF_ENABLE;
2043
2044         I915_WRITE(reg, val);
2045         if ((val & PIPECONF_ENABLE) == 0)
2046                 intel_wait_for_pipe_off(crtc);
2047 }
2048
2049 static bool need_vtd_wa(struct drm_device *dev)
2050 {
2051 #ifdef CONFIG_INTEL_IOMMU
2052         if (INTEL_INFO(dev)->gen >= 6 && intel_iommu_gfx_mapped)
2053                 return true;
2054 #endif
2055         return false;
2056 }
2057
2058 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
2059 {
2060         return IS_GEN2(dev_priv) ? 2048 : 4096;
2061 }
2062
2063 static unsigned int intel_tile_width_bytes(const struct drm_i915_private *dev_priv,
2064                                            uint64_t fb_modifier, unsigned int cpp)
2065 {
2066         switch (fb_modifier) {
2067         case DRM_FORMAT_MOD_NONE:
2068                 return cpp;
2069         case I915_FORMAT_MOD_X_TILED:
2070                 if (IS_GEN2(dev_priv))
2071                         return 128;
2072                 else
2073                         return 512;
2074         case I915_FORMAT_MOD_Y_TILED:
2075                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
2076                         return 128;
2077                 else
2078                         return 512;
2079         case I915_FORMAT_MOD_Yf_TILED:
2080                 switch (cpp) {
2081                 case 1:
2082                         return 64;
2083                 case 2:
2084                 case 4:
2085                         return 128;
2086                 case 8:
2087                 case 16:
2088                         return 256;
2089                 default:
2090                         MISSING_CASE(cpp);
2091                         return cpp;
2092                 }
2093                 break;
2094         default:
2095                 MISSING_CASE(fb_modifier);
2096                 return cpp;
2097         }
2098 }
2099
2100 unsigned int intel_tile_height(const struct drm_i915_private *dev_priv,
2101                                uint64_t fb_modifier, unsigned int cpp)
2102 {
2103         if (fb_modifier == DRM_FORMAT_MOD_NONE)
2104                 return 1;
2105         else
2106                 return intel_tile_size(dev_priv) /
2107                         intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2108 }
2109
2110 /* Return the tile dimensions in pixel units */
2111 static void intel_tile_dims(const struct drm_i915_private *dev_priv,
2112                             unsigned int *tile_width,
2113                             unsigned int *tile_height,
2114                             uint64_t fb_modifier,
2115                             unsigned int cpp)
2116 {
2117         unsigned int tile_width_bytes =
2118                 intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2119
2120         *tile_width = tile_width_bytes / cpp;
2121         *tile_height = intel_tile_size(dev_priv) / tile_width_bytes;
2122 }
2123
2124 unsigned int
2125 intel_fb_align_height(struct drm_device *dev, unsigned int height,
2126                       uint32_t pixel_format, uint64_t fb_modifier)
2127 {
2128         unsigned int cpp = drm_format_plane_cpp(pixel_format, 0);
2129         unsigned int tile_height = intel_tile_height(to_i915(dev), fb_modifier, cpp);
2130
2131         return ALIGN(height, tile_height);
2132 }
2133
2134 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2135 {
2136         unsigned int size = 0;
2137         int i;
2138
2139         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2140                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2141
2142         return size;
2143 }
2144
2145 static void
2146 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2147                         const struct drm_framebuffer *fb,
2148                         unsigned int rotation)
2149 {
2150         if (intel_rotation_90_or_270(rotation)) {
2151                 *view = i915_ggtt_view_rotated;
2152                 view->params.rotated = to_intel_framebuffer(fb)->rot_info;
2153         } else {
2154                 *view = i915_ggtt_view_normal;
2155         }
2156 }
2157
2158 static void
2159 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2160                    struct drm_framebuffer *fb)
2161 {
2162         struct intel_rotation_info *info = &to_intel_framebuffer(fb)->rot_info;
2163         unsigned int tile_size, tile_width, tile_height, cpp;
2164
2165         tile_size = intel_tile_size(dev_priv);
2166
2167         cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2168         intel_tile_dims(dev_priv, &tile_width, &tile_height,
2169                         fb->modifier[0], cpp);
2170
2171         info->plane[0].width = DIV_ROUND_UP(fb->pitches[0], tile_width * cpp);
2172         info->plane[0].height = DIV_ROUND_UP(fb->height, tile_height);
2173
2174         if (info->pixel_format == DRM_FORMAT_NV12) {
2175                 cpp = drm_format_plane_cpp(fb->pixel_format, 1);
2176                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2177                                 fb->modifier[1], cpp);
2178
2179                 info->uv_offset = fb->offsets[1];
2180                 info->plane[1].width = DIV_ROUND_UP(fb->pitches[1], tile_width * cpp);
2181                 info->plane[1].height = DIV_ROUND_UP(fb->height / 2, tile_height);
2182         }
2183 }
2184
2185 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2186 {
2187         if (INTEL_INFO(dev_priv)->gen >= 9)
2188                 return 256 * 1024;
2189         else if (IS_BROADWATER(dev_priv) || IS_CRESTLINE(dev_priv) ||
2190                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2191                 return 128 * 1024;
2192         else if (INTEL_INFO(dev_priv)->gen >= 4)
2193                 return 4 * 1024;
2194         else
2195                 return 0;
2196 }
2197
2198 static unsigned int intel_surf_alignment(const struct drm_i915_private *dev_priv,
2199                                          uint64_t fb_modifier)
2200 {
2201         switch (fb_modifier) {
2202         case DRM_FORMAT_MOD_NONE:
2203                 return intel_linear_alignment(dev_priv);
2204         case I915_FORMAT_MOD_X_TILED:
2205                 if (INTEL_INFO(dev_priv)->gen >= 9)
2206                         return 256 * 1024;
2207                 return 0;
2208         case I915_FORMAT_MOD_Y_TILED:
2209         case I915_FORMAT_MOD_Yf_TILED:
2210                 return 1 * 1024 * 1024;
2211         default:
2212                 MISSING_CASE(fb_modifier);
2213                 return 0;
2214         }
2215 }
2216
2217 int
2218 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2219                            unsigned int rotation)
2220 {
2221         struct drm_device *dev = fb->dev;
2222         struct drm_i915_private *dev_priv = dev->dev_private;
2223         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2224         struct i915_ggtt_view view;
2225         u32 alignment;
2226         int ret;
2227
2228         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2229
2230         alignment = intel_surf_alignment(dev_priv, fb->modifier[0]);
2231
2232         intel_fill_fb_ggtt_view(&view, fb, rotation);
2233
2234         /* Note that the w/a also requires 64 PTE of padding following the
2235          * bo. We currently fill all unused PTE with the shadow page and so
2236          * we should always have valid PTE following the scanout preventing
2237          * the VT-d warning.
2238          */
2239         if (need_vtd_wa(dev) && alignment < 256 * 1024)
2240                 alignment = 256 * 1024;
2241
2242         /*
2243          * Global gtt pte registers are special registers which actually forward
2244          * writes to a chunk of system memory. Which means that there is no risk
2245          * that the register values disappear as soon as we call
2246          * intel_runtime_pm_put(), so it is correct to wrap only the
2247          * pin/unpin/fence and not more.
2248          */
2249         intel_runtime_pm_get(dev_priv);
2250
2251         ret = i915_gem_object_pin_to_display_plane(obj, alignment,
2252                                                    &view);
2253         if (ret)
2254                 goto err_pm;
2255
2256         /* Install a fence for tiled scan-out. Pre-i965 always needs a
2257          * fence, whereas 965+ only requires a fence if using
2258          * framebuffer compression.  For simplicity, we always install
2259          * a fence as the cost is not that onerous.
2260          */
2261         if (view.type == I915_GGTT_VIEW_NORMAL) {
2262                 ret = i915_gem_object_get_fence(obj);
2263                 if (ret == -EDEADLK) {
2264                         /*
2265                          * -EDEADLK means there are no free fences
2266                          * no pending flips.
2267                          *
2268                          * This is propagated to atomic, but it uses
2269                          * -EDEADLK to force a locking recovery, so
2270                          * change the returned error to -EBUSY.
2271                          */
2272                         ret = -EBUSY;
2273                         goto err_unpin;
2274                 } else if (ret)
2275                         goto err_unpin;
2276
2277                 i915_gem_object_pin_fence(obj);
2278         }
2279
2280         intel_runtime_pm_put(dev_priv);
2281         return 0;
2282
2283 err_unpin:
2284         i915_gem_object_unpin_from_display_plane(obj, &view);
2285 err_pm:
2286         intel_runtime_pm_put(dev_priv);
2287         return ret;
2288 }
2289
2290 static void intel_unpin_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2291 {
2292         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2293         struct i915_ggtt_view view;
2294
2295         WARN_ON(!mutex_is_locked(&obj->base.dev->struct_mutex));
2296
2297         intel_fill_fb_ggtt_view(&view, fb, rotation);
2298
2299         if (view.type == I915_GGTT_VIEW_NORMAL)
2300                 i915_gem_object_unpin_fence(obj);
2301
2302         i915_gem_object_unpin_from_display_plane(obj, &view);
2303 }
2304
2305 /*
2306  * Adjust the tile offset by moving the difference into
2307  * the x/y offsets.
2308  *
2309  * Input tile dimensions and pitch must already be
2310  * rotated to match x and y, and in pixel units.
2311  */
2312 static u32 intel_adjust_tile_offset(int *x, int *y,
2313                                     unsigned int tile_width,
2314                                     unsigned int tile_height,
2315                                     unsigned int tile_size,
2316                                     unsigned int pitch_tiles,
2317                                     u32 old_offset,
2318                                     u32 new_offset)
2319 {
2320         unsigned int tiles;
2321
2322         WARN_ON(old_offset & (tile_size - 1));
2323         WARN_ON(new_offset & (tile_size - 1));
2324         WARN_ON(new_offset > old_offset);
2325
2326         tiles = (old_offset - new_offset) / tile_size;
2327
2328         *y += tiles / pitch_tiles * tile_height;
2329         *x += tiles % pitch_tiles * tile_width;
2330
2331         return new_offset;
2332 }
2333
2334 /*
2335  * Computes the linear offset to the base tile and adjusts
2336  * x, y. bytes per pixel is assumed to be a power-of-two.
2337  *
2338  * In the 90/270 rotated case, x and y are assumed
2339  * to be already rotated to match the rotated GTT view, and
2340  * pitch is the tile_height aligned framebuffer height.
2341  */
2342 u32 intel_compute_tile_offset(int *x, int *y,
2343                               const struct drm_framebuffer *fb, int plane,
2344                               unsigned int pitch,
2345                               unsigned int rotation)
2346 {
2347         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2348         uint64_t fb_modifier = fb->modifier[plane];
2349         unsigned int cpp = drm_format_plane_cpp(fb->pixel_format, plane);
2350         u32 offset, offset_aligned, alignment;
2351
2352         alignment = intel_surf_alignment(dev_priv, fb_modifier);
2353         if (alignment)
2354                 alignment--;
2355
2356         if (fb_modifier != DRM_FORMAT_MOD_NONE) {
2357                 unsigned int tile_size, tile_width, tile_height;
2358                 unsigned int tile_rows, tiles, pitch_tiles;
2359
2360                 tile_size = intel_tile_size(dev_priv);
2361                 intel_tile_dims(dev_priv, &tile_width, &tile_height,
2362                                 fb_modifier, cpp);
2363
2364                 if (intel_rotation_90_or_270(rotation)) {
2365                         pitch_tiles = pitch / tile_height;
2366                         swap(tile_width, tile_height);
2367                 } else {
2368                         pitch_tiles = pitch / (tile_width * cpp);
2369                 }
2370
2371                 tile_rows = *y / tile_height;
2372                 *y %= tile_height;
2373
2374                 tiles = *x / tile_width;
2375                 *x %= tile_width;
2376
2377                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2378                 offset_aligned = offset & ~alignment;
2379
2380                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2381                                          tile_size, pitch_tiles,
2382                                          offset, offset_aligned);
2383         } else {
2384                 offset = *y * pitch + *x * cpp;
2385                 offset_aligned = offset & ~alignment;
2386
2387                 *y = (offset & alignment) / pitch;
2388                 *x = ((offset & alignment) - *y * pitch) / cpp;
2389         }
2390
2391         return offset_aligned;
2392 }
2393
2394 static int i9xx_format_to_fourcc(int format)
2395 {
2396         switch (format) {
2397         case DISPPLANE_8BPP:
2398                 return DRM_FORMAT_C8;
2399         case DISPPLANE_BGRX555:
2400                 return DRM_FORMAT_XRGB1555;
2401         case DISPPLANE_BGRX565:
2402                 return DRM_FORMAT_RGB565;
2403         default:
2404         case DISPPLANE_BGRX888:
2405                 return DRM_FORMAT_XRGB8888;
2406         case DISPPLANE_RGBX888:
2407                 return DRM_FORMAT_XBGR8888;
2408         case DISPPLANE_BGRX101010:
2409                 return DRM_FORMAT_XRGB2101010;
2410         case DISPPLANE_RGBX101010:
2411                 return DRM_FORMAT_XBGR2101010;
2412         }
2413 }
2414
2415 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2416 {
2417         switch (format) {
2418         case PLANE_CTL_FORMAT_RGB_565:
2419                 return DRM_FORMAT_RGB565;
2420         default:
2421         case PLANE_CTL_FORMAT_XRGB_8888:
2422                 if (rgb_order) {
2423                         if (alpha)
2424                                 return DRM_FORMAT_ABGR8888;
2425                         else
2426                                 return DRM_FORMAT_XBGR8888;
2427                 } else {
2428                         if (alpha)
2429                                 return DRM_FORMAT_ARGB8888;
2430                         else
2431                                 return DRM_FORMAT_XRGB8888;
2432                 }
2433         case PLANE_CTL_FORMAT_XRGB_2101010:
2434                 if (rgb_order)
2435                         return DRM_FORMAT_XBGR2101010;
2436                 else
2437                         return DRM_FORMAT_XRGB2101010;
2438         }
2439 }
2440
2441 static bool
2442 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2443                               struct intel_initial_plane_config *plane_config)
2444 {
2445         struct drm_device *dev = crtc->base.dev;
2446         struct drm_i915_private *dev_priv = to_i915(dev);
2447         struct drm_i915_gem_object *obj = NULL;
2448         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2449         struct drm_framebuffer *fb = &plane_config->fb->base;
2450         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2451         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2452                                     PAGE_SIZE);
2453
2454         size_aligned -= base_aligned;
2455
2456         if (plane_config->size == 0)
2457                 return false;
2458
2459         /* If the FB is too big, just don't use it since fbdev is not very
2460          * important and we should probably use that space with FBC or other
2461          * features. */
2462         if (size_aligned * 2 > dev_priv->ggtt.stolen_usable_size)
2463                 return false;
2464
2465         mutex_lock(&dev->struct_mutex);
2466
2467         obj = i915_gem_object_create_stolen_for_preallocated(dev,
2468                                                              base_aligned,
2469                                                              base_aligned,
2470                                                              size_aligned);
2471         if (!obj) {
2472                 mutex_unlock(&dev->struct_mutex);
2473                 return false;
2474         }
2475
2476         obj->tiling_mode = plane_config->tiling;
2477         if (obj->tiling_mode == I915_TILING_X)
2478                 obj->stride = fb->pitches[0];
2479
2480         mode_cmd.pixel_format = fb->pixel_format;
2481         mode_cmd.width = fb->width;
2482         mode_cmd.height = fb->height;
2483         mode_cmd.pitches[0] = fb->pitches[0];
2484         mode_cmd.modifier[0] = fb->modifier[0];
2485         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2486
2487         if (intel_framebuffer_init(dev, to_intel_framebuffer(fb),
2488                                    &mode_cmd, obj)) {
2489                 DRM_DEBUG_KMS("intel fb init failed\n");
2490                 goto out_unref_obj;
2491         }
2492
2493         mutex_unlock(&dev->struct_mutex);
2494
2495         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2496         return true;
2497
2498 out_unref_obj:
2499         drm_gem_object_unreference(&obj->base);
2500         mutex_unlock(&dev->struct_mutex);
2501         return false;
2502 }
2503
2504 /* Update plane->state->fb to match plane->fb after driver-internal updates */
2505 static void
2506 update_state_fb(struct drm_plane *plane)
2507 {
2508         if (plane->fb == plane->state->fb)
2509                 return;
2510
2511         if (plane->state->fb)
2512                 drm_framebuffer_unreference(plane->state->fb);
2513         plane->state->fb = plane->fb;
2514         if (plane->state->fb)
2515                 drm_framebuffer_reference(plane->state->fb);
2516 }
2517
2518 static void
2519 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2520                              struct intel_initial_plane_config *plane_config)
2521 {
2522         struct drm_device *dev = intel_crtc->base.dev;
2523         struct drm_i915_private *dev_priv = dev->dev_private;
2524         struct drm_crtc *c;
2525         struct intel_crtc *i;
2526         struct drm_i915_gem_object *obj;
2527         struct drm_plane *primary = intel_crtc->base.primary;
2528         struct drm_plane_state *plane_state = primary->state;
2529         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2530         struct intel_plane *intel_plane = to_intel_plane(primary);
2531         struct intel_plane_state *intel_state =
2532                 to_intel_plane_state(plane_state);
2533         struct drm_framebuffer *fb;
2534
2535         if (!plane_config->fb)
2536                 return;
2537
2538         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2539                 fb = &plane_config->fb->base;
2540                 goto valid_fb;
2541         }
2542
2543         kfree(plane_config->fb);
2544
2545         /*
2546          * Failed to alloc the obj, check to see if we should share
2547          * an fb with another CRTC instead
2548          */
2549         for_each_crtc(dev, c) {
2550                 i = to_intel_crtc(c);
2551
2552                 if (c == &intel_crtc->base)
2553                         continue;
2554
2555                 if (!i->active)
2556                         continue;
2557
2558                 fb = c->primary->fb;
2559                 if (!fb)
2560                         continue;
2561
2562                 obj = intel_fb_obj(fb);
2563                 if (i915_gem_obj_ggtt_offset(obj) == plane_config->base) {
2564                         drm_framebuffer_reference(fb);
2565                         goto valid_fb;
2566                 }
2567         }
2568
2569         /*
2570          * We've failed to reconstruct the BIOS FB.  Current display state
2571          * indicates that the primary plane is visible, but has a NULL FB,
2572          * which will lead to problems later if we don't fix it up.  The
2573          * simplest solution is to just disable the primary plane now and
2574          * pretend the BIOS never had it enabled.
2575          */
2576         to_intel_plane_state(plane_state)->visible = false;
2577         crtc_state->plane_mask &= ~(1 << drm_plane_index(primary));
2578         intel_pre_disable_primary_noatomic(&intel_crtc->base);
2579         intel_plane->disable_plane(primary, &intel_crtc->base);
2580
2581         return;
2582
2583 valid_fb:
2584         plane_state->src_x = 0;
2585         plane_state->src_y = 0;
2586         plane_state->src_w = fb->width << 16;
2587         plane_state->src_h = fb->height << 16;
2588
2589         plane_state->crtc_x = 0;
2590         plane_state->crtc_y = 0;
2591         plane_state->crtc_w = fb->width;
2592         plane_state->crtc_h = fb->height;
2593
2594         intel_state->src.x1 = plane_state->src_x;
2595         intel_state->src.y1 = plane_state->src_y;
2596         intel_state->src.x2 = plane_state->src_x + plane_state->src_w;
2597         intel_state->src.y2 = plane_state->src_y + plane_state->src_h;
2598         intel_state->dst.x1 = plane_state->crtc_x;
2599         intel_state->dst.y1 = plane_state->crtc_y;
2600         intel_state->dst.x2 = plane_state->crtc_x + plane_state->crtc_w;
2601         intel_state->dst.y2 = plane_state->crtc_y + plane_state->crtc_h;
2602
2603         obj = intel_fb_obj(fb);
2604         if (obj->tiling_mode != I915_TILING_NONE)
2605                 dev_priv->preserve_bios_swizzle = true;
2606
2607         drm_framebuffer_reference(fb);
2608         primary->fb = primary->state->fb = fb;
2609         primary->crtc = primary->state->crtc = &intel_crtc->base;
2610         intel_crtc->base.state->plane_mask |= (1 << drm_plane_index(primary));
2611         obj->frontbuffer_bits |= to_intel_plane(primary)->frontbuffer_bit;
2612 }
2613
2614 static void i9xx_update_primary_plane(struct drm_plane *primary,
2615                                       const struct intel_crtc_state *crtc_state,
2616                                       const struct intel_plane_state *plane_state)
2617 {
2618         struct drm_device *dev = primary->dev;
2619         struct drm_i915_private *dev_priv = dev->dev_private;
2620         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2621         struct drm_framebuffer *fb = plane_state->base.fb;
2622         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2623         int plane = intel_crtc->plane;
2624         u32 linear_offset;
2625         u32 dspcntr;
2626         i915_reg_t reg = DSPCNTR(plane);
2627         unsigned int rotation = plane_state->base.rotation;
2628         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2629         int x = plane_state->src.x1 >> 16;
2630         int y = plane_state->src.y1 >> 16;
2631
2632         dspcntr = DISPPLANE_GAMMA_ENABLE;
2633
2634         dspcntr |= DISPLAY_PLANE_ENABLE;
2635
2636         if (INTEL_INFO(dev)->gen < 4) {
2637                 if (intel_crtc->pipe == PIPE_B)
2638                         dspcntr |= DISPPLANE_SEL_PIPE_B;
2639
2640                 /* pipesrc and dspsize control the size that is scaled from,
2641                  * which should always be the user's requested size.
2642                  */
2643                 I915_WRITE(DSPSIZE(plane),
2644                            ((crtc_state->pipe_src_h - 1) << 16) |
2645                            (crtc_state->pipe_src_w - 1));
2646                 I915_WRITE(DSPPOS(plane), 0);
2647         } else if (IS_CHERRYVIEW(dev) && plane == PLANE_B) {
2648                 I915_WRITE(PRIMSIZE(plane),
2649                            ((crtc_state->pipe_src_h - 1) << 16) |
2650                            (crtc_state->pipe_src_w - 1));
2651                 I915_WRITE(PRIMPOS(plane), 0);
2652                 I915_WRITE(PRIMCNSTALPHA(plane), 0);
2653         }
2654
2655         switch (fb->pixel_format) {
2656         case DRM_FORMAT_C8:
2657                 dspcntr |= DISPPLANE_8BPP;
2658                 break;
2659         case DRM_FORMAT_XRGB1555:
2660                 dspcntr |= DISPPLANE_BGRX555;
2661                 break;
2662         case DRM_FORMAT_RGB565:
2663                 dspcntr |= DISPPLANE_BGRX565;
2664                 break;
2665         case DRM_FORMAT_XRGB8888:
2666                 dspcntr |= DISPPLANE_BGRX888;
2667                 break;
2668         case DRM_FORMAT_XBGR8888:
2669                 dspcntr |= DISPPLANE_RGBX888;
2670                 break;
2671         case DRM_FORMAT_XRGB2101010:
2672                 dspcntr |= DISPPLANE_BGRX101010;
2673                 break;
2674         case DRM_FORMAT_XBGR2101010:
2675                 dspcntr |= DISPPLANE_RGBX101010;
2676                 break;
2677         default:
2678                 BUG();
2679         }
2680
2681         if (INTEL_INFO(dev)->gen >= 4 &&
2682             obj->tiling_mode != I915_TILING_NONE)
2683                 dspcntr |= DISPPLANE_TILED;
2684
2685         if (IS_G4X(dev))
2686                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2687
2688         linear_offset = y * fb->pitches[0] + x * cpp;
2689
2690         if (INTEL_INFO(dev)->gen >= 4) {
2691                 intel_crtc->dspaddr_offset =
2692                         intel_compute_tile_offset(&x, &y, fb, 0,
2693                                                   fb->pitches[0], rotation);
2694                 linear_offset -= intel_crtc->dspaddr_offset;
2695         } else {
2696                 intel_crtc->dspaddr_offset = linear_offset;
2697         }
2698
2699         if (rotation == BIT(DRM_ROTATE_180)) {
2700                 dspcntr |= DISPPLANE_ROTATE_180;
2701
2702                 x += (crtc_state->pipe_src_w - 1);
2703                 y += (crtc_state->pipe_src_h - 1);
2704
2705                 /* Finding the last pixel of the last line of the display
2706                 data and adding to linear_offset*/
2707                 linear_offset +=
2708                         (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2709                         (crtc_state->pipe_src_w - 1) * cpp;
2710         }
2711
2712         intel_crtc->adjusted_x = x;
2713         intel_crtc->adjusted_y = y;
2714
2715         I915_WRITE(reg, dspcntr);
2716
2717         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2718         if (INTEL_INFO(dev)->gen >= 4) {
2719                 I915_WRITE(DSPSURF(plane),
2720                            i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2721                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2722                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2723         } else
2724                 I915_WRITE(DSPADDR(plane), i915_gem_obj_ggtt_offset(obj) + linear_offset);
2725         POSTING_READ(reg);
2726 }
2727
2728 static void i9xx_disable_primary_plane(struct drm_plane *primary,
2729                                        struct drm_crtc *crtc)
2730 {
2731         struct drm_device *dev = crtc->dev;
2732         struct drm_i915_private *dev_priv = dev->dev_private;
2733         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
2734         int plane = intel_crtc->plane;
2735
2736         I915_WRITE(DSPCNTR(plane), 0);
2737         if (INTEL_INFO(dev_priv)->gen >= 4)
2738                 I915_WRITE(DSPSURF(plane), 0);
2739         else
2740                 I915_WRITE(DSPADDR(plane), 0);
2741         POSTING_READ(DSPCNTR(plane));
2742 }
2743
2744 static void ironlake_update_primary_plane(struct drm_plane *primary,
2745                                           const struct intel_crtc_state *crtc_state,
2746                                           const struct intel_plane_state *plane_state)
2747 {
2748         struct drm_device *dev = primary->dev;
2749         struct drm_i915_private *dev_priv = dev->dev_private;
2750         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2751         struct drm_framebuffer *fb = plane_state->base.fb;
2752         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2753         int plane = intel_crtc->plane;
2754         u32 linear_offset;
2755         u32 dspcntr;
2756         i915_reg_t reg = DSPCNTR(plane);
2757         unsigned int rotation = plane_state->base.rotation;
2758         int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
2759         int x = plane_state->src.x1 >> 16;
2760         int y = plane_state->src.y1 >> 16;
2761
2762         dspcntr = DISPPLANE_GAMMA_ENABLE;
2763         dspcntr |= DISPLAY_PLANE_ENABLE;
2764
2765         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
2766                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
2767
2768         switch (fb->pixel_format) {
2769         case DRM_FORMAT_C8:
2770                 dspcntr |= DISPPLANE_8BPP;
2771                 break;
2772         case DRM_FORMAT_RGB565:
2773                 dspcntr |= DISPPLANE_BGRX565;
2774                 break;
2775         case DRM_FORMAT_XRGB8888:
2776                 dspcntr |= DISPPLANE_BGRX888;
2777                 break;
2778         case DRM_FORMAT_XBGR8888:
2779                 dspcntr |= DISPPLANE_RGBX888;
2780                 break;
2781         case DRM_FORMAT_XRGB2101010:
2782                 dspcntr |= DISPPLANE_BGRX101010;
2783                 break;
2784         case DRM_FORMAT_XBGR2101010:
2785                 dspcntr |= DISPPLANE_RGBX101010;
2786                 break;
2787         default:
2788                 BUG();
2789         }
2790
2791         if (obj->tiling_mode != I915_TILING_NONE)
2792                 dspcntr |= DISPPLANE_TILED;
2793
2794         if (!IS_HASWELL(dev) && !IS_BROADWELL(dev))
2795                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
2796
2797         linear_offset = y * fb->pitches[0] + x * cpp;
2798         intel_crtc->dspaddr_offset =
2799                 intel_compute_tile_offset(&x, &y, fb, 0,
2800                                           fb->pitches[0], rotation);
2801         linear_offset -= intel_crtc->dspaddr_offset;
2802         if (rotation == BIT(DRM_ROTATE_180)) {
2803                 dspcntr |= DISPPLANE_ROTATE_180;
2804
2805                 if (!IS_HASWELL(dev) && !IS_BROADWELL(dev)) {
2806                         x += (crtc_state->pipe_src_w - 1);
2807                         y += (crtc_state->pipe_src_h - 1);
2808
2809                         /* Finding the last pixel of the last line of the display
2810                         data and adding to linear_offset*/
2811                         linear_offset +=
2812                                 (crtc_state->pipe_src_h - 1) * fb->pitches[0] +
2813                                 (crtc_state->pipe_src_w - 1) * cpp;
2814                 }
2815         }
2816
2817         intel_crtc->adjusted_x = x;
2818         intel_crtc->adjusted_y = y;
2819
2820         I915_WRITE(reg, dspcntr);
2821
2822         I915_WRITE(DSPSTRIDE(plane), fb->pitches[0]);
2823         I915_WRITE(DSPSURF(plane),
2824                    i915_gem_obj_ggtt_offset(obj) + intel_crtc->dspaddr_offset);
2825         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
2826                 I915_WRITE(DSPOFFSET(plane), (y << 16) | x);
2827         } else {
2828                 I915_WRITE(DSPTILEOFF(plane), (y << 16) | x);
2829                 I915_WRITE(DSPLINOFF(plane), linear_offset);
2830         }
2831         POSTING_READ(reg);
2832 }
2833
2834 u32 intel_fb_stride_alignment(const struct drm_i915_private *dev_priv,
2835                               uint64_t fb_modifier, uint32_t pixel_format)
2836 {
2837         if (fb_modifier == DRM_FORMAT_MOD_NONE) {
2838                 return 64;
2839         } else {
2840                 int cpp = drm_format_plane_cpp(pixel_format, 0);
2841
2842                 return intel_tile_width_bytes(dev_priv, fb_modifier, cpp);
2843         }
2844 }
2845
2846 u32 intel_plane_obj_offset(struct intel_plane *intel_plane,
2847                            struct drm_i915_gem_object *obj,
2848                            unsigned int plane)
2849 {
2850         struct i915_ggtt_view view;
2851         struct i915_vma *vma;
2852         u64 offset;
2853
2854         intel_fill_fb_ggtt_view(&view, intel_plane->base.state->fb,
2855                                 intel_plane->base.state->rotation);
2856
2857         vma = i915_gem_obj_to_ggtt_view(obj, &view);
2858         if (WARN(!vma, "ggtt vma for display object not found! (view=%u)\n",
2859                 view.type))
2860                 return -1;
2861
2862         offset = vma->node.start;
2863
2864         if (plane == 1) {
2865                 offset += vma->ggtt_view.params.rotated.uv_start_page *
2866                           PAGE_SIZE;
2867         }
2868
2869         WARN_ON(upper_32_bits(offset));
2870
2871         return lower_32_bits(offset);
2872 }
2873
2874 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
2875 {
2876         struct drm_device *dev = intel_crtc->base.dev;
2877         struct drm_i915_private *dev_priv = dev->dev_private;
2878
2879         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
2880         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
2881         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
2882 }
2883
2884 /*
2885  * This function detaches (aka. unbinds) unused scalers in hardware
2886  */
2887 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
2888 {
2889         struct intel_crtc_scaler_state *scaler_state;
2890         int i;
2891
2892         scaler_state = &intel_crtc->config->scaler_state;
2893
2894         /* loop through and disable scalers that aren't in use */
2895         for (i = 0; i < intel_crtc->num_scalers; i++) {
2896                 if (!scaler_state->scalers[i].in_use)
2897                         skl_detach_scaler(intel_crtc, i);
2898         }
2899 }
2900
2901 u32 skl_plane_ctl_format(uint32_t pixel_format)
2902 {
2903         switch (pixel_format) {
2904         case DRM_FORMAT_C8:
2905                 return PLANE_CTL_FORMAT_INDEXED;
2906         case DRM_FORMAT_RGB565:
2907                 return PLANE_CTL_FORMAT_RGB_565;
2908         case DRM_FORMAT_XBGR8888:
2909                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
2910         case DRM_FORMAT_XRGB8888:
2911                 return PLANE_CTL_FORMAT_XRGB_8888;
2912         /*
2913          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
2914          * to be already pre-multiplied. We need to add a knob (or a different
2915          * DRM_FORMAT) for user-space to configure that.
2916          */
2917         case DRM_FORMAT_ABGR8888:
2918                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
2919                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2920         case DRM_FORMAT_ARGB8888:
2921                 return PLANE_CTL_FORMAT_XRGB_8888 |
2922                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
2923         case DRM_FORMAT_XRGB2101010:
2924                 return PLANE_CTL_FORMAT_XRGB_2101010;
2925         case DRM_FORMAT_XBGR2101010:
2926                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
2927         case DRM_FORMAT_YUYV:
2928                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
2929         case DRM_FORMAT_YVYU:
2930                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
2931         case DRM_FORMAT_UYVY:
2932                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
2933         case DRM_FORMAT_VYUY:
2934                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
2935         default:
2936                 MISSING_CASE(pixel_format);
2937         }
2938
2939         return 0;
2940 }
2941
2942 u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
2943 {
2944         switch (fb_modifier) {
2945         case DRM_FORMAT_MOD_NONE:
2946                 break;
2947         case I915_FORMAT_MOD_X_TILED:
2948                 return PLANE_CTL_TILED_X;
2949         case I915_FORMAT_MOD_Y_TILED:
2950                 return PLANE_CTL_TILED_Y;
2951         case I915_FORMAT_MOD_Yf_TILED:
2952                 return PLANE_CTL_TILED_YF;
2953         default:
2954                 MISSING_CASE(fb_modifier);
2955         }
2956
2957         return 0;
2958 }
2959
2960 u32 skl_plane_ctl_rotation(unsigned int rotation)
2961 {
2962         switch (rotation) {
2963         case BIT(DRM_ROTATE_0):
2964                 break;
2965         /*
2966          * DRM_ROTATE_ is counter clockwise to stay compatible with Xrandr
2967          * while i915 HW rotation is clockwise, thats why this swapping.
2968          */
2969         case BIT(DRM_ROTATE_90):
2970                 return PLANE_CTL_ROTATE_270;
2971         case BIT(DRM_ROTATE_180):
2972                 return PLANE_CTL_ROTATE_180;
2973         case BIT(DRM_ROTATE_270):
2974                 return PLANE_CTL_ROTATE_90;
2975         default:
2976                 MISSING_CASE(rotation);
2977         }
2978
2979         return 0;
2980 }
2981
2982 static void skylake_update_primary_plane(struct drm_plane *plane,
2983                                          const struct intel_crtc_state *crtc_state,
2984                                          const struct intel_plane_state *plane_state)
2985 {
2986         struct drm_device *dev = plane->dev;
2987         struct drm_i915_private *dev_priv = dev->dev_private;
2988         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
2989         struct drm_framebuffer *fb = plane_state->base.fb;
2990         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2991         int pipe = intel_crtc->pipe;
2992         u32 plane_ctl, stride_div, stride;
2993         u32 tile_height, plane_offset, plane_size;
2994         unsigned int rotation = plane_state->base.rotation;
2995         int x_offset, y_offset;
2996         u32 surf_addr;
2997         int scaler_id = plane_state->scaler_id;
2998         int src_x = plane_state->src.x1 >> 16;
2999         int src_y = plane_state->src.y1 >> 16;
3000         int src_w = drm_rect_width(&plane_state->src) >> 16;
3001         int src_h = drm_rect_height(&plane_state->src) >> 16;
3002         int dst_x = plane_state->dst.x1;
3003         int dst_y = plane_state->dst.y1;
3004         int dst_w = drm_rect_width(&plane_state->dst);
3005         int dst_h = drm_rect_height(&plane_state->dst);
3006
3007         plane_ctl = PLANE_CTL_ENABLE |
3008                     PLANE_CTL_PIPE_GAMMA_ENABLE |
3009                     PLANE_CTL_PIPE_CSC_ENABLE;
3010
3011         plane_ctl |= skl_plane_ctl_format(fb->pixel_format);
3012         plane_ctl |= skl_plane_ctl_tiling(fb->modifier[0]);
3013         plane_ctl |= PLANE_CTL_PLANE_GAMMA_DISABLE;
3014         plane_ctl |= skl_plane_ctl_rotation(rotation);
3015
3016         stride_div = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
3017                                                fb->pixel_format);
3018         surf_addr = intel_plane_obj_offset(to_intel_plane(plane), obj, 0);
3019
3020         WARN_ON(drm_rect_width(&plane_state->src) == 0);
3021
3022         if (intel_rotation_90_or_270(rotation)) {
3023                 int cpp = drm_format_plane_cpp(fb->pixel_format, 0);
3024
3025                 /* stride = Surface height in tiles */
3026                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], cpp);
3027                 stride = DIV_ROUND_UP(fb->height, tile_height);
3028                 x_offset = stride * tile_height - src_y - src_h;
3029                 y_offset = src_x;
3030                 plane_size = (src_w - 1) << 16 | (src_h - 1);
3031         } else {
3032                 stride = fb->pitches[0] / stride_div;
3033                 x_offset = src_x;
3034                 y_offset = src_y;
3035                 plane_size = (src_h - 1) << 16 | (src_w - 1);
3036         }
3037         plane_offset = y_offset << 16 | x_offset;
3038
3039         intel_crtc->adjusted_x = x_offset;
3040         intel_crtc->adjusted_y = y_offset;
3041
3042         I915_WRITE(PLANE_CTL(pipe, 0), plane_ctl);
3043         I915_WRITE(PLANE_OFFSET(pipe, 0), plane_offset);
3044         I915_WRITE(PLANE_SIZE(pipe, 0), plane_size);
3045         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
3046
3047         if (scaler_id >= 0) {
3048                 uint32_t ps_ctrl = 0;
3049
3050                 WARN_ON(!dst_w || !dst_h);
3051                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(0) |
3052                         crtc_state->scaler_state.scalers[scaler_id].mode;
3053                 I915_WRITE(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3054                 I915_WRITE(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3055                 I915_WRITE(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3056                 I915_WRITE(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3057                 I915_WRITE(PLANE_POS(pipe, 0), 0);
3058         } else {
3059                 I915_WRITE(PLANE_POS(pipe, 0), (dst_y << 16) | dst_x);
3060         }
3061
3062         I915_WRITE(PLANE_SURF(pipe, 0), surf_addr);
3063
3064         POSTING_READ(PLANE_SURF(pipe, 0));
3065 }
3066
3067 static void skylake_disable_primary_plane(struct drm_plane *primary,
3068                                           struct drm_crtc *crtc)
3069 {
3070         struct drm_device *dev = crtc->dev;
3071         struct drm_i915_private *dev_priv = dev->dev_private;
3072         int pipe = to_intel_crtc(crtc)->pipe;
3073
3074         I915_WRITE(PLANE_CTL(pipe, 0), 0);
3075         I915_WRITE(PLANE_SURF(pipe, 0), 0);
3076         POSTING_READ(PLANE_SURF(pipe, 0));
3077 }
3078
3079 /* Assume fb object is pinned & idle & fenced and just update base pointers */
3080 static int
3081 intel_pipe_set_base_atomic(struct drm_crtc *crtc, struct drm_framebuffer *fb,
3082                            int x, int y, enum mode_set_atomic state)
3083 {
3084         /* Support for kgdboc is disabled, this needs a major rework. */
3085         DRM_ERROR("legacy panic handler not supported any more.\n");
3086
3087         return -ENODEV;
3088 }
3089
3090 static void intel_complete_page_flips(struct drm_device *dev)
3091 {
3092         struct drm_crtc *crtc;
3093
3094         for_each_crtc(dev, crtc) {
3095                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3096                 enum plane plane = intel_crtc->plane;
3097
3098                 intel_prepare_page_flip(dev, plane);
3099                 intel_finish_page_flip_plane(dev, plane);
3100         }
3101 }
3102
3103 static void intel_update_primary_planes(struct drm_device *dev)
3104 {
3105         struct drm_crtc *crtc;
3106
3107         for_each_crtc(dev, crtc) {
3108                 struct intel_plane *plane = to_intel_plane(crtc->primary);
3109                 struct intel_plane_state *plane_state;
3110
3111                 drm_modeset_lock_crtc(crtc, &plane->base);
3112                 plane_state = to_intel_plane_state(plane->base.state);
3113
3114                 if (plane_state->visible)
3115                         plane->update_plane(&plane->base,
3116                                             to_intel_crtc_state(crtc->state),
3117                                             plane_state);
3118
3119                 drm_modeset_unlock_crtc(crtc);
3120         }
3121 }
3122
3123 void intel_prepare_reset(struct drm_device *dev)
3124 {
3125         /* no reset support for gen2 */
3126         if (IS_GEN2(dev))
3127                 return;
3128
3129         /* reset doesn't touch the display */
3130         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
3131                 return;
3132
3133         drm_modeset_lock_all(dev);
3134         /*
3135          * Disabling the crtcs gracefully seems nicer. Also the
3136          * g33 docs say we should at least disable all the planes.
3137          */
3138         intel_display_suspend(dev);
3139 }
3140
3141 void intel_finish_reset(struct drm_device *dev)
3142 {
3143         struct drm_i915_private *dev_priv = to_i915(dev);
3144
3145         /*
3146          * Flips in the rings will be nuked by the reset,
3147          * so complete all pending flips so that user space
3148          * will get its events and not get stuck.
3149          */
3150         intel_complete_page_flips(dev);
3151
3152         /* no reset support for gen2 */
3153         if (IS_GEN2(dev))
3154                 return;
3155
3156         /* reset doesn't touch the display */
3157         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) {
3158                 /*
3159                  * Flips in the rings have been nuked by the reset,
3160                  * so update the base address of all primary
3161                  * planes to the the last fb to make sure we're
3162                  * showing the correct fb after a reset.
3163                  *
3164                  * FIXME: Atomic will make this obsolete since we won't schedule
3165                  * CS-based flips (which might get lost in gpu resets) any more.
3166                  */
3167                 intel_update_primary_planes(dev);
3168                 return;
3169         }
3170
3171         /*
3172          * The display has been reset as well,
3173          * so need a full re-initialization.
3174          */
3175         intel_runtime_pm_disable_interrupts(dev_priv);
3176         intel_runtime_pm_enable_interrupts(dev_priv);
3177
3178         intel_modeset_init_hw(dev);
3179
3180         spin_lock_irq(&dev_priv->irq_lock);
3181         if (dev_priv->display.hpd_irq_setup)
3182                 dev_priv->display.hpd_irq_setup(dev);
3183         spin_unlock_irq(&dev_priv->irq_lock);
3184
3185         intel_display_resume(dev);
3186
3187         intel_hpd_init(dev_priv);
3188
3189         drm_modeset_unlock_all(dev);
3190 }
3191
3192 static bool intel_crtc_has_pending_flip(struct drm_crtc *crtc)
3193 {
3194         struct drm_device *dev = crtc->dev;
3195         struct drm_i915_private *dev_priv = dev->dev_private;
3196         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3197         bool pending;
3198
3199         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
3200             intel_crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
3201                 return false;
3202
3203         spin_lock_irq(&dev->event_lock);
3204         pending = to_intel_crtc(crtc)->unpin_work != NULL;
3205         spin_unlock_irq(&dev->event_lock);
3206
3207         return pending;
3208 }
3209
3210 static void intel_update_pipe_config(struct intel_crtc *crtc,
3211                                      struct intel_crtc_state *old_crtc_state)
3212 {
3213         struct drm_device *dev = crtc->base.dev;
3214         struct drm_i915_private *dev_priv = dev->dev_private;
3215         struct intel_crtc_state *pipe_config =
3216                 to_intel_crtc_state(crtc->base.state);
3217
3218         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3219         crtc->base.mode = crtc->base.state->mode;
3220
3221         DRM_DEBUG_KMS("Updating pipe size %ix%i -> %ix%i\n",
3222                       old_crtc_state->pipe_src_w, old_crtc_state->pipe_src_h,
3223                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
3224
3225         if (HAS_DDI(dev))
3226                 intel_color_set_csc(&crtc->base);
3227
3228         /*
3229          * Update pipe size and adjust fitter if needed: the reason for this is
3230          * that in compute_mode_changes we check the native mode (not the pfit
3231          * mode) to see if we can flip rather than do a full mode set. In the
3232          * fastboot case, we'll flip, but if we don't update the pipesrc and
3233          * pfit state, we'll end up with a big fb scanned out into the wrong
3234          * sized surface.
3235          */
3236
3237         I915_WRITE(PIPESRC(crtc->pipe),
3238                    ((pipe_config->pipe_src_w - 1) << 16) |
3239                    (pipe_config->pipe_src_h - 1));
3240
3241         /* on skylake this is done by detaching scalers */
3242         if (INTEL_INFO(dev)->gen >= 9) {
3243                 skl_detach_scalers(crtc);
3244
3245                 if (pipe_config->pch_pfit.enabled)
3246                         skylake_pfit_enable(crtc);
3247         } else if (HAS_PCH_SPLIT(dev)) {
3248                 if (pipe_config->pch_pfit.enabled)
3249                         ironlake_pfit_enable(crtc);
3250                 else if (old_crtc_state->pch_pfit.enabled)
3251                         ironlake_pfit_disable(crtc, true);
3252         }
3253 }
3254
3255 static void intel_fdi_normal_train(struct drm_crtc *crtc)
3256 {
3257         struct drm_device *dev = crtc->dev;
3258         struct drm_i915_private *dev_priv = dev->dev_private;
3259         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3260         int pipe = intel_crtc->pipe;
3261         i915_reg_t reg;
3262         u32 temp;
3263
3264         /* enable normal train */
3265         reg = FDI_TX_CTL(pipe);
3266         temp = I915_READ(reg);
3267         if (IS_IVYBRIDGE(dev)) {
3268                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3269                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3270         } else {
3271                 temp &= ~FDI_LINK_TRAIN_NONE;
3272                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3273         }
3274         I915_WRITE(reg, temp);
3275
3276         reg = FDI_RX_CTL(pipe);
3277         temp = I915_READ(reg);
3278         if (HAS_PCH_CPT(dev)) {
3279                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3280                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3281         } else {
3282                 temp &= ~FDI_LINK_TRAIN_NONE;
3283                 temp |= FDI_LINK_TRAIN_NONE;
3284         }
3285         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3286
3287         /* wait one idle pattern time */
3288         POSTING_READ(reg);
3289         udelay(1000);
3290
3291         /* IVB wants error correction enabled */
3292         if (IS_IVYBRIDGE(dev))
3293                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3294                            FDI_FE_ERRC_ENABLE);
3295 }
3296
3297 /* The FDI link training functions for ILK/Ibexpeak. */
3298 static void ironlake_fdi_link_train(struct drm_crtc *crtc)
3299 {
3300         struct drm_device *dev = crtc->dev;
3301         struct drm_i915_private *dev_priv = dev->dev_private;
3302         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3303         int pipe = intel_crtc->pipe;
3304         i915_reg_t reg;
3305         u32 temp, tries;
3306
3307         /* FDI needs bits from pipe first */
3308         assert_pipe_enabled(dev_priv, pipe);
3309
3310         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3311            for train result */
3312         reg = FDI_RX_IMR(pipe);
3313         temp = I915_READ(reg);
3314         temp &= ~FDI_RX_SYMBOL_LOCK;
3315         temp &= ~FDI_RX_BIT_LOCK;
3316         I915_WRITE(reg, temp);
3317         I915_READ(reg);
3318         udelay(150);
3319
3320         /* enable CPU FDI TX and PCH FDI RX */
3321         reg = FDI_TX_CTL(pipe);
3322         temp = I915_READ(reg);
3323         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3324         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3325         temp &= ~FDI_LINK_TRAIN_NONE;
3326         temp |= FDI_LINK_TRAIN_PATTERN_1;
3327         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3328
3329         reg = FDI_RX_CTL(pipe);
3330         temp = I915_READ(reg);
3331         temp &= ~FDI_LINK_TRAIN_NONE;
3332         temp |= FDI_LINK_TRAIN_PATTERN_1;
3333         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3334
3335         POSTING_READ(reg);
3336         udelay(150);
3337
3338         /* Ironlake workaround, enable clock pointer after FDI enable*/
3339         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3340         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3341                    FDI_RX_PHASE_SYNC_POINTER_EN);
3342
3343         reg = FDI_RX_IIR(pipe);
3344         for (tries = 0; tries < 5; tries++) {
3345                 temp = I915_READ(reg);
3346                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3347
3348                 if ((temp & FDI_RX_BIT_LOCK)) {
3349                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3350                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3351                         break;
3352                 }
3353         }
3354         if (tries == 5)
3355                 DRM_ERROR("FDI train 1 fail!\n");
3356
3357         /* Train 2 */
3358         reg = FDI_TX_CTL(pipe);
3359         temp = I915_READ(reg);
3360         temp &= ~FDI_LINK_TRAIN_NONE;
3361         temp |= FDI_LINK_TRAIN_PATTERN_2;
3362         I915_WRITE(reg, temp);
3363
3364         reg = FDI_RX_CTL(pipe);
3365         temp = I915_READ(reg);
3366         temp &= ~FDI_LINK_TRAIN_NONE;
3367         temp |= FDI_LINK_TRAIN_PATTERN_2;
3368         I915_WRITE(reg, temp);
3369
3370         POSTING_READ(reg);
3371         udelay(150);
3372
3373         reg = FDI_RX_IIR(pipe);
3374         for (tries = 0; tries < 5; tries++) {
3375                 temp = I915_READ(reg);
3376                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3377
3378                 if (temp & FDI_RX_SYMBOL_LOCK) {
3379                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3380                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3381                         break;
3382                 }
3383         }
3384         if (tries == 5)
3385                 DRM_ERROR("FDI train 2 fail!\n");
3386
3387         DRM_DEBUG_KMS("FDI train done\n");
3388
3389 }
3390
3391 static const int snb_b_fdi_train_param[] = {
3392         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3393         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3394         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3395         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3396 };
3397
3398 /* The FDI link training functions for SNB/Cougarpoint. */
3399 static void gen6_fdi_link_train(struct drm_crtc *crtc)
3400 {
3401         struct drm_device *dev = crtc->dev;
3402         struct drm_i915_private *dev_priv = dev->dev_private;
3403         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3404         int pipe = intel_crtc->pipe;
3405         i915_reg_t reg;
3406         u32 temp, i, retry;
3407
3408         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3409            for train result */
3410         reg = FDI_RX_IMR(pipe);
3411         temp = I915_READ(reg);
3412         temp &= ~FDI_RX_SYMBOL_LOCK;
3413         temp &= ~FDI_RX_BIT_LOCK;
3414         I915_WRITE(reg, temp);
3415
3416         POSTING_READ(reg);
3417         udelay(150);
3418
3419         /* enable CPU FDI TX and PCH FDI RX */
3420         reg = FDI_TX_CTL(pipe);
3421         temp = I915_READ(reg);
3422         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3423         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3424         temp &= ~FDI_LINK_TRAIN_NONE;
3425         temp |= FDI_LINK_TRAIN_PATTERN_1;
3426         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3427         /* SNB-B */
3428         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3429         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3430
3431         I915_WRITE(FDI_RX_MISC(pipe),
3432                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3433
3434         reg = FDI_RX_CTL(pipe);
3435         temp = I915_READ(reg);
3436         if (HAS_PCH_CPT(dev)) {
3437                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3438                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3439         } else {
3440                 temp &= ~FDI_LINK_TRAIN_NONE;
3441                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3442         }
3443         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3444
3445         POSTING_READ(reg);
3446         udelay(150);
3447
3448         for (i = 0; i < 4; i++) {
3449                 reg = FDI_TX_CTL(pipe);
3450                 temp = I915_READ(reg);
3451                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3452                 temp |= snb_b_fdi_train_param[i];
3453                 I915_WRITE(reg, temp);
3454
3455                 POSTING_READ(reg);
3456                 udelay(500);
3457
3458                 for (retry = 0; retry < 5; retry++) {
3459                         reg = FDI_RX_IIR(pipe);
3460                         temp = I915_READ(reg);
3461                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3462                         if (temp & FDI_RX_BIT_LOCK) {
3463                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3464                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3465                                 break;
3466                         }
3467                         udelay(50);
3468                 }
3469                 if (retry < 5)
3470                         break;
3471         }
3472         if (i == 4)
3473                 DRM_ERROR("FDI train 1 fail!\n");
3474
3475         /* Train 2 */
3476         reg = FDI_TX_CTL(pipe);
3477         temp = I915_READ(reg);
3478         temp &= ~FDI_LINK_TRAIN_NONE;
3479         temp |= FDI_LINK_TRAIN_PATTERN_2;
3480         if (IS_GEN6(dev)) {
3481                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3482                 /* SNB-B */
3483                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3484         }
3485         I915_WRITE(reg, temp);
3486
3487         reg = FDI_RX_CTL(pipe);
3488         temp = I915_READ(reg);
3489         if (HAS_PCH_CPT(dev)) {
3490                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3491                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3492         } else {
3493                 temp &= ~FDI_LINK_TRAIN_NONE;
3494                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3495         }
3496         I915_WRITE(reg, temp);
3497
3498         POSTING_READ(reg);
3499         udelay(150);
3500
3501         for (i = 0; i < 4; i++) {
3502                 reg = FDI_TX_CTL(pipe);
3503                 temp = I915_READ(reg);
3504                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3505                 temp |= snb_b_fdi_train_param[i];
3506                 I915_WRITE(reg, temp);
3507
3508                 POSTING_READ(reg);
3509                 udelay(500);
3510
3511                 for (retry = 0; retry < 5; retry++) {
3512                         reg = FDI_RX_IIR(pipe);
3513                         temp = I915_READ(reg);
3514                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3515                         if (temp & FDI_RX_SYMBOL_LOCK) {
3516                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3517                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
3518                                 break;
3519                         }
3520                         udelay(50);
3521                 }
3522                 if (retry < 5)
3523                         break;
3524         }
3525         if (i == 4)
3526                 DRM_ERROR("FDI train 2 fail!\n");
3527
3528         DRM_DEBUG_KMS("FDI train done.\n");
3529 }
3530
3531 /* Manual link training for Ivy Bridge A0 parts */
3532 static void ivb_manual_fdi_link_train(struct drm_crtc *crtc)
3533 {
3534         struct drm_device *dev = crtc->dev;
3535         struct drm_i915_private *dev_priv = dev->dev_private;
3536         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3537         int pipe = intel_crtc->pipe;
3538         i915_reg_t reg;
3539         u32 temp, i, j;
3540
3541         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3542            for train result */
3543         reg = FDI_RX_IMR(pipe);
3544         temp = I915_READ(reg);
3545         temp &= ~FDI_RX_SYMBOL_LOCK;
3546         temp &= ~FDI_RX_BIT_LOCK;
3547         I915_WRITE(reg, temp);
3548
3549         POSTING_READ(reg);
3550         udelay(150);
3551
3552         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
3553                       I915_READ(FDI_RX_IIR(pipe)));
3554
3555         /* Try each vswing and preemphasis setting twice before moving on */
3556         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
3557                 /* disable first in case we need to retry */
3558                 reg = FDI_TX_CTL(pipe);
3559                 temp = I915_READ(reg);
3560                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
3561                 temp &= ~FDI_TX_ENABLE;
3562                 I915_WRITE(reg, temp);
3563
3564                 reg = FDI_RX_CTL(pipe);
3565                 temp = I915_READ(reg);
3566                 temp &= ~FDI_LINK_TRAIN_AUTO;
3567                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3568                 temp &= ~FDI_RX_ENABLE;
3569                 I915_WRITE(reg, temp);
3570
3571                 /* enable CPU FDI TX and PCH FDI RX */
3572                 reg = FDI_TX_CTL(pipe);
3573                 temp = I915_READ(reg);
3574                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
3575                 temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3576                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
3577                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3578                 temp |= snb_b_fdi_train_param[j/2];
3579                 temp |= FDI_COMPOSITE_SYNC;
3580                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
3581
3582                 I915_WRITE(FDI_RX_MISC(pipe),
3583                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3584
3585                 reg = FDI_RX_CTL(pipe);
3586                 temp = I915_READ(reg);
3587                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3588                 temp |= FDI_COMPOSITE_SYNC;
3589                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
3590
3591                 POSTING_READ(reg);
3592                 udelay(1); /* should be 0.5us */
3593
3594                 for (i = 0; i < 4; i++) {
3595                         reg = FDI_RX_IIR(pipe);
3596                         temp = I915_READ(reg);
3597                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3598
3599                         if (temp & FDI_RX_BIT_LOCK ||
3600                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
3601                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3602                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
3603                                               i);
3604                                 break;
3605                         }
3606                         udelay(1); /* should be 0.5us */
3607                 }
3608                 if (i == 4) {
3609                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
3610                         continue;
3611                 }
3612
3613                 /* Train 2 */
3614                 reg = FDI_TX_CTL(pipe);
3615                 temp = I915_READ(reg);
3616                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3617                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
3618                 I915_WRITE(reg, temp);
3619
3620                 reg = FDI_RX_CTL(pipe);
3621                 temp = I915_READ(reg);
3622                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3623                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3624                 I915_WRITE(reg, temp);
3625
3626                 POSTING_READ(reg);
3627                 udelay(2); /* should be 1.5us */
3628
3629                 for (i = 0; i < 4; i++) {
3630                         reg = FDI_RX_IIR(pipe);
3631                         temp = I915_READ(reg);
3632                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3633
3634                         if (temp & FDI_RX_SYMBOL_LOCK ||
3635                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
3636                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3637                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
3638                                               i);
3639                                 goto train_done;
3640                         }
3641                         udelay(2); /* should be 1.5us */
3642                 }
3643                 if (i == 4)
3644                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
3645         }
3646
3647 train_done:
3648         DRM_DEBUG_KMS("FDI train done.\n");
3649 }
3650
3651 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
3652 {
3653         struct drm_device *dev = intel_crtc->base.dev;
3654         struct drm_i915_private *dev_priv = dev->dev_private;
3655         int pipe = intel_crtc->pipe;
3656         i915_reg_t reg;
3657         u32 temp;
3658
3659         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
3660         reg = FDI_RX_CTL(pipe);
3661         temp = I915_READ(reg);
3662         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
3663         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
3664         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3665         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
3666
3667         POSTING_READ(reg);
3668         udelay(200);
3669
3670         /* Switch from Rawclk to PCDclk */
3671         temp = I915_READ(reg);
3672         I915_WRITE(reg, temp | FDI_PCDCLK);
3673
3674         POSTING_READ(reg);
3675         udelay(200);
3676
3677         /* Enable CPU FDI TX PLL, always on for Ironlake */
3678         reg = FDI_TX_CTL(pipe);
3679         temp = I915_READ(reg);
3680         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
3681                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
3682
3683                 POSTING_READ(reg);
3684                 udelay(100);
3685         }
3686 }
3687
3688 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
3689 {
3690         struct drm_device *dev = intel_crtc->base.dev;
3691         struct drm_i915_private *dev_priv = dev->dev_private;
3692         int pipe = intel_crtc->pipe;
3693         i915_reg_t reg;
3694         u32 temp;
3695
3696         /* Switch from PCDclk to Rawclk */
3697         reg = FDI_RX_CTL(pipe);
3698         temp = I915_READ(reg);
3699         I915_WRITE(reg, temp & ~FDI_PCDCLK);
3700
3701         /* Disable CPU FDI TX PLL */
3702         reg = FDI_TX_CTL(pipe);
3703         temp = I915_READ(reg);
3704         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
3705
3706         POSTING_READ(reg);
3707         udelay(100);
3708
3709         reg = FDI_RX_CTL(pipe);
3710         temp = I915_READ(reg);
3711         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
3712
3713         /* Wait for the clocks to turn off. */
3714         POSTING_READ(reg);
3715         udelay(100);
3716 }
3717
3718 static void ironlake_fdi_disable(struct drm_crtc *crtc)
3719 {
3720         struct drm_device *dev = crtc->dev;
3721         struct drm_i915_private *dev_priv = dev->dev_private;
3722         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3723         int pipe = intel_crtc->pipe;
3724         i915_reg_t reg;
3725         u32 temp;
3726
3727         /* disable CPU FDI tx and PCH FDI rx */
3728         reg = FDI_TX_CTL(pipe);
3729         temp = I915_READ(reg);
3730         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
3731         POSTING_READ(reg);
3732
3733         reg = FDI_RX_CTL(pipe);
3734         temp = I915_READ(reg);
3735         temp &= ~(0x7 << 16);
3736         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3737         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
3738
3739         POSTING_READ(reg);
3740         udelay(100);
3741
3742         /* Ironlake workaround, disable clock pointer after downing FDI */
3743         if (HAS_PCH_IBX(dev))
3744                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3745
3746         /* still set train pattern 1 */
3747         reg = FDI_TX_CTL(pipe);
3748         temp = I915_READ(reg);
3749         temp &= ~FDI_LINK_TRAIN_NONE;
3750         temp |= FDI_LINK_TRAIN_PATTERN_1;
3751         I915_WRITE(reg, temp);
3752
3753         reg = FDI_RX_CTL(pipe);
3754         temp = I915_READ(reg);
3755         if (HAS_PCH_CPT(dev)) {
3756                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3757                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3758         } else {
3759                 temp &= ~FDI_LINK_TRAIN_NONE;
3760                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3761         }
3762         /* BPC in FDI rx is consistent with that in PIPECONF */
3763         temp &= ~(0x07 << 16);
3764         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
3765         I915_WRITE(reg, temp);
3766
3767         POSTING_READ(reg);
3768         udelay(100);
3769 }
3770
3771 bool intel_has_pending_fb_unpin(struct drm_device *dev)
3772 {
3773         struct intel_crtc *crtc;
3774
3775         /* Note that we don't need to be called with mode_config.lock here
3776          * as our list of CRTC objects is static for the lifetime of the
3777          * device and so cannot disappear as we iterate. Similarly, we can
3778          * happily treat the predicates as racy, atomic checks as userspace
3779          * cannot claim and pin a new fb without at least acquring the
3780          * struct_mutex and so serialising with us.
3781          */
3782         for_each_intel_crtc(dev, crtc) {
3783                 if (atomic_read(&crtc->unpin_work_count) == 0)
3784                         continue;
3785
3786                 if (crtc->unpin_work)
3787                         intel_wait_for_vblank(dev, crtc->pipe);
3788
3789                 return true;
3790         }
3791
3792         return false;
3793 }
3794
3795 static void page_flip_completed(struct intel_crtc *intel_crtc)
3796 {
3797         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
3798         struct intel_unpin_work *work = intel_crtc->unpin_work;
3799
3800         /* ensure that the unpin work is consistent wrt ->pending. */
3801         smp_rmb();
3802         intel_crtc->unpin_work = NULL;
3803
3804         if (work->event)
3805                 drm_send_vblank_event(intel_crtc->base.dev,
3806                                       intel_crtc->pipe,
3807                                       work->event);
3808
3809         drm_crtc_vblank_put(&intel_crtc->base);
3810
3811         wake_up_all(&dev_priv->pending_flip_queue);
3812         queue_work(dev_priv->wq, &work->work);
3813
3814         trace_i915_flip_complete(intel_crtc->plane,
3815                                  work->pending_flip_obj);
3816 }
3817
3818 static int intel_crtc_wait_for_pending_flips(struct drm_crtc *crtc)
3819 {
3820         struct drm_device *dev = crtc->dev;
3821         struct drm_i915_private *dev_priv = dev->dev_private;
3822         long ret;
3823
3824         WARN_ON(waitqueue_active(&dev_priv->pending_flip_queue));
3825
3826         ret = wait_event_interruptible_timeout(
3827                                         dev_priv->pending_flip_queue,
3828                                         !intel_crtc_has_pending_flip(crtc),
3829                                         60*HZ);
3830
3831         if (ret < 0)
3832                 return ret;
3833
3834         if (ret == 0) {
3835                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
3836
3837                 spin_lock_irq(&dev->event_lock);
3838                 if (intel_crtc->unpin_work) {
3839                         WARN_ONCE(1, "Removing stuck page flip\n");
3840                         page_flip_completed(intel_crtc);
3841                 }
3842                 spin_unlock_irq(&dev->event_lock);
3843         }
3844
3845         return 0;
3846 }
3847
3848 static void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
3849 {
3850         u32 temp;
3851
3852         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
3853
3854         mutex_lock(&dev_priv->sb_lock);
3855
3856         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3857         temp |= SBI_SSCCTL_DISABLE;
3858         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3859
3860         mutex_unlock(&dev_priv->sb_lock);
3861 }
3862
3863 /* Program iCLKIP clock to the desired frequency */
3864 static void lpt_program_iclkip(struct drm_crtc *crtc)
3865 {
3866         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
3867         int clock = to_intel_crtc(crtc)->config->base.adjusted_mode.crtc_clock;
3868         u32 divsel, phaseinc, auxdiv, phasedir = 0;
3869         u32 temp;
3870
3871         lpt_disable_iclkip(dev_priv);
3872
3873         /* The iCLK virtual clock root frequency is in MHz,
3874          * but the adjusted_mode->crtc_clock in in KHz. To get the
3875          * divisors, it is necessary to divide one by another, so we
3876          * convert the virtual clock precision to KHz here for higher
3877          * precision.
3878          */
3879         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
3880                 u32 iclk_virtual_root_freq = 172800 * 1000;
3881                 u32 iclk_pi_range = 64;
3882                 u32 desired_divisor;
3883
3884                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3885                                                     clock << auxdiv);
3886                 divsel = (desired_divisor / iclk_pi_range) - 2;
3887                 phaseinc = desired_divisor % iclk_pi_range;
3888
3889                 /*
3890                  * Near 20MHz is a corner case which is
3891                  * out of range for the 7-bit divisor
3892                  */
3893                 if (divsel <= 0x7f)
3894                         break;
3895         }
3896
3897         /* This should not happen with any sane values */
3898         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
3899                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
3900         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
3901                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
3902
3903         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
3904                         clock,
3905                         auxdiv,
3906                         divsel,
3907                         phasedir,
3908                         phaseinc);
3909
3910         mutex_lock(&dev_priv->sb_lock);
3911
3912         /* Program SSCDIVINTPHASE6 */
3913         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3914         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
3915         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
3916         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
3917         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
3918         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
3919         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
3920         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
3921
3922         /* Program SSCAUXDIV */
3923         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3924         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
3925         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
3926         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
3927
3928         /* Enable modulator and associated divider */
3929         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3930         temp &= ~SBI_SSCCTL_DISABLE;
3931         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
3932
3933         mutex_unlock(&dev_priv->sb_lock);
3934
3935         /* Wait for initialization time */
3936         udelay(24);
3937
3938         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
3939 }
3940
3941 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
3942 {
3943         u32 divsel, phaseinc, auxdiv;
3944         u32 iclk_virtual_root_freq = 172800 * 1000;
3945         u32 iclk_pi_range = 64;
3946         u32 desired_divisor;
3947         u32 temp;
3948
3949         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
3950                 return 0;
3951
3952         mutex_lock(&dev_priv->sb_lock);
3953
3954         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
3955         if (temp & SBI_SSCCTL_DISABLE) {
3956                 mutex_unlock(&dev_priv->sb_lock);
3957                 return 0;
3958         }
3959
3960         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
3961         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
3962                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
3963         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
3964                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
3965
3966         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
3967         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
3968                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
3969
3970         mutex_unlock(&dev_priv->sb_lock);
3971
3972         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
3973
3974         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
3975                                  desired_divisor << auxdiv);
3976 }
3977
3978 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
3979                                                 enum pipe pch_transcoder)
3980 {
3981         struct drm_device *dev = crtc->base.dev;
3982         struct drm_i915_private *dev_priv = dev->dev_private;
3983         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
3984
3985         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
3986                    I915_READ(HTOTAL(cpu_transcoder)));
3987         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
3988                    I915_READ(HBLANK(cpu_transcoder)));
3989         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
3990                    I915_READ(HSYNC(cpu_transcoder)));
3991
3992         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
3993                    I915_READ(VTOTAL(cpu_transcoder)));
3994         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
3995                    I915_READ(VBLANK(cpu_transcoder)));
3996         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
3997                    I915_READ(VSYNC(cpu_transcoder)));
3998         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
3999                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4000 }
4001
4002 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4003 {
4004         struct drm_i915_private *dev_priv = dev->dev_private;
4005         uint32_t temp;
4006
4007         temp = I915_READ(SOUTH_CHICKEN1);
4008         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4009                 return;
4010
4011         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4012         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4013
4014         temp &= ~FDI_BC_BIFURCATION_SELECT;
4015         if (enable)
4016                 temp |= FDI_BC_BIFURCATION_SELECT;
4017
4018         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4019         I915_WRITE(SOUTH_CHICKEN1, temp);
4020         POSTING_READ(SOUTH_CHICKEN1);
4021 }
4022
4023 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4024 {
4025         struct drm_device *dev = intel_crtc->base.dev;
4026
4027         switch (intel_crtc->pipe) {
4028         case PIPE_A:
4029                 break;
4030         case PIPE_B:
4031                 if (intel_crtc->config->fdi_lanes > 2)
4032                         cpt_set_fdi_bc_bifurcation(dev, false);
4033                 else
4034                         cpt_set_fdi_bc_bifurcation(dev, true);
4035
4036                 break;
4037         case PIPE_C:
4038                 cpt_set_fdi_bc_bifurcation(dev, true);
4039
4040                 break;
4041         default:
4042                 BUG();
4043         }
4044 }
4045
4046 /* Return which DP Port should be selected for Transcoder DP control */
4047 static enum port
4048 intel_trans_dp_port_sel(struct drm_crtc *crtc)
4049 {
4050         struct drm_device *dev = crtc->dev;
4051         struct intel_encoder *encoder;
4052
4053         for_each_encoder_on_crtc(dev, crtc, encoder) {
4054                 if (encoder->type == INTEL_OUTPUT_DISPLAYPORT ||
4055                     encoder->type == INTEL_OUTPUT_EDP)
4056                         return enc_to_dig_port(&encoder->base)->port;
4057         }
4058
4059         return -1;
4060 }
4061
4062 /*
4063  * Enable PCH resources required for PCH ports:
4064  *   - PCH PLLs
4065  *   - FDI training & RX/TX
4066  *   - update transcoder timings
4067  *   - DP transcoding bits
4068  *   - transcoder
4069  */
4070 static void ironlake_pch_enable(struct drm_crtc *crtc)
4071 {
4072         struct drm_device *dev = crtc->dev;
4073         struct drm_i915_private *dev_priv = dev->dev_private;
4074         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4075         int pipe = intel_crtc->pipe;
4076         u32 temp;
4077
4078         assert_pch_transcoder_disabled(dev_priv, pipe);
4079
4080         if (IS_IVYBRIDGE(dev))
4081                 ivybridge_update_fdi_bc_bifurcation(intel_crtc);
4082
4083         /* Write the TU size bits before fdi link training, so that error
4084          * detection works. */
4085         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4086                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4087
4088         /*
4089          * Sometimes spurious CPU pipe underruns happen during FDI
4090          * training, at least with VGA+HDMI cloning. Suppress them.
4091          */
4092         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4093
4094         /* For PCH output, training FDI link */
4095         dev_priv->display.fdi_link_train(crtc);
4096
4097         /* We need to program the right clock selection before writing the pixel
4098          * mutliplier into the DPLL. */
4099         if (HAS_PCH_CPT(dev)) {
4100                 u32 sel;
4101
4102                 temp = I915_READ(PCH_DPLL_SEL);
4103                 temp |= TRANS_DPLL_ENABLE(pipe);
4104                 sel = TRANS_DPLLB_SEL(pipe);
4105                 if (intel_crtc->config->shared_dpll ==
4106                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4107                         temp |= sel;
4108                 else
4109                         temp &= ~sel;
4110                 I915_WRITE(PCH_DPLL_SEL, temp);
4111         }
4112
4113         /* XXX: pch pll's can be enabled any time before we enable the PCH
4114          * transcoder, and we actually should do this to not upset any PCH
4115          * transcoder that already use the clock when we share it.
4116          *
4117          * Note that enable_shared_dpll tries to do the right thing, but
4118          * get_shared_dpll unconditionally resets the pll - we need that to have
4119          * the right LVDS enable sequence. */
4120         intel_enable_shared_dpll(intel_crtc);
4121
4122         /* set transcoder timing, panel must allow it */
4123         assert_panel_unlocked(dev_priv, pipe);
4124         ironlake_pch_transcoder_set_timings(intel_crtc, pipe);
4125
4126         intel_fdi_normal_train(crtc);
4127
4128         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4129
4130         /* For PCH DP, enable TRANS_DP_CTL */
4131         if (HAS_PCH_CPT(dev) && intel_crtc->config->has_dp_encoder) {
4132                 const struct drm_display_mode *adjusted_mode =
4133                         &intel_crtc->config->base.adjusted_mode;
4134                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4135                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4136                 temp = I915_READ(reg);
4137                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4138                           TRANS_DP_SYNC_MASK |
4139                           TRANS_DP_BPC_MASK);
4140                 temp |= TRANS_DP_OUTPUT_ENABLE;
4141                 temp |= bpc << 9; /* same format but at 11:9 */
4142
4143                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4144                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4145                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4146                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4147
4148                 switch (intel_trans_dp_port_sel(crtc)) {
4149                 case PORT_B:
4150                         temp |= TRANS_DP_PORT_SEL_B;
4151                         break;
4152                 case PORT_C:
4153                         temp |= TRANS_DP_PORT_SEL_C;
4154                         break;
4155                 case PORT_D:
4156                         temp |= TRANS_DP_PORT_SEL_D;
4157                         break;
4158                 default:
4159                         BUG();
4160                 }
4161
4162                 I915_WRITE(reg, temp);
4163         }
4164
4165         ironlake_enable_pch_transcoder(dev_priv, pipe);
4166 }
4167
4168 static void lpt_pch_enable(struct drm_crtc *crtc)
4169 {
4170         struct drm_device *dev = crtc->dev;
4171         struct drm_i915_private *dev_priv = dev->dev_private;
4172         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4173         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4174
4175         assert_pch_transcoder_disabled(dev_priv, TRANSCODER_A);
4176
4177         lpt_program_iclkip(crtc);
4178
4179         /* Set transcoder timing. */
4180         ironlake_pch_transcoder_set_timings(intel_crtc, PIPE_A);
4181
4182         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4183 }
4184
4185 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4186 {
4187         struct drm_i915_private *dev_priv = dev->dev_private;
4188         i915_reg_t dslreg = PIPEDSL(pipe);
4189         u32 temp;
4190
4191         temp = I915_READ(dslreg);
4192         udelay(500);
4193         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4194                 if (wait_for(I915_READ(dslreg) != temp, 5))
4195                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4196         }
4197 }
4198
4199 static int
4200 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4201                   unsigned scaler_user, int *scaler_id, unsigned int rotation,
4202                   int src_w, int src_h, int dst_w, int dst_h)
4203 {
4204         struct intel_crtc_scaler_state *scaler_state =
4205                 &crtc_state->scaler_state;
4206         struct intel_crtc *intel_crtc =
4207                 to_intel_crtc(crtc_state->base.crtc);
4208         int need_scaling;
4209
4210         need_scaling = intel_rotation_90_or_270(rotation) ?
4211                 (src_h != dst_w || src_w != dst_h):
4212                 (src_w != dst_w || src_h != dst_h);
4213
4214         /*
4215          * if plane is being disabled or scaler is no more required or force detach
4216          *  - free scaler binded to this plane/crtc
4217          *  - in order to do this, update crtc->scaler_usage
4218          *
4219          * Here scaler state in crtc_state is set free so that
4220          * scaler can be assigned to other user. Actual register
4221          * update to free the scaler is done in plane/panel-fit programming.
4222          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4223          */
4224         if (force_detach || !need_scaling) {
4225                 if (*scaler_id >= 0) {
4226                         scaler_state->scaler_users &= ~(1 << scaler_user);
4227                         scaler_state->scalers[*scaler_id].in_use = 0;
4228
4229                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4230                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4231                                 intel_crtc->pipe, scaler_user, *scaler_id,
4232                                 scaler_state->scaler_users);
4233                         *scaler_id = -1;
4234                 }
4235                 return 0;
4236         }
4237
4238         /* range checks */
4239         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4240                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4241
4242                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4243                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4244                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4245                         "size is out of scaler range\n",
4246                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4247                 return -EINVAL;
4248         }
4249
4250         /* mark this plane as a scaler user in crtc_state */
4251         scaler_state->scaler_users |= (1 << scaler_user);
4252         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4253                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4254                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4255                 scaler_state->scaler_users);
4256
4257         return 0;
4258 }
4259
4260 /**
4261  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4262  *
4263  * @state: crtc's scaler state
4264  *
4265  * Return
4266  *     0 - scaler_usage updated successfully
4267  *    error - requested scaling cannot be supported or other error condition
4268  */
4269 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4270 {
4271         struct intel_crtc *intel_crtc = to_intel_crtc(state->base.crtc);
4272         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4273
4274         DRM_DEBUG_KMS("Updating scaler for [CRTC:%i] scaler_user index %u.%u\n",
4275                       intel_crtc->base.base.id, intel_crtc->pipe, SKL_CRTC_INDEX);
4276
4277         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4278                 &state->scaler_state.scaler_id, BIT(DRM_ROTATE_0),
4279                 state->pipe_src_w, state->pipe_src_h,
4280                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4281 }
4282
4283 /**
4284  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4285  *
4286  * @state: crtc's scaler state
4287  * @plane_state: atomic plane state to update
4288  *
4289  * Return
4290  *     0 - scaler_usage updated successfully
4291  *    error - requested scaling cannot be supported or other error condition
4292  */
4293 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4294                                    struct intel_plane_state *plane_state)
4295 {
4296
4297         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4298         struct intel_plane *intel_plane =
4299                 to_intel_plane(plane_state->base.plane);
4300         struct drm_framebuffer *fb = plane_state->base.fb;
4301         int ret;
4302
4303         bool force_detach = !fb || !plane_state->visible;
4304
4305         DRM_DEBUG_KMS("Updating scaler for [PLANE:%d] scaler_user index %u.%u\n",
4306                       intel_plane->base.base.id, intel_crtc->pipe,
4307                       drm_plane_index(&intel_plane->base));
4308
4309         ret = skl_update_scaler(crtc_state, force_detach,
4310                                 drm_plane_index(&intel_plane->base),
4311                                 &plane_state->scaler_id,
4312                                 plane_state->base.rotation,
4313                                 drm_rect_width(&plane_state->src) >> 16,
4314                                 drm_rect_height(&plane_state->src) >> 16,
4315                                 drm_rect_width(&plane_state->dst),
4316                                 drm_rect_height(&plane_state->dst));
4317
4318         if (ret || plane_state->scaler_id < 0)
4319                 return ret;
4320
4321         /* check colorkey */
4322         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4323                 DRM_DEBUG_KMS("[PLANE:%d] scaling with color key not allowed",
4324                               intel_plane->base.base.id);
4325                 return -EINVAL;
4326         }
4327
4328         /* Check src format */
4329         switch (fb->pixel_format) {
4330         case DRM_FORMAT_RGB565:
4331         case DRM_FORMAT_XBGR8888:
4332         case DRM_FORMAT_XRGB8888:
4333         case DRM_FORMAT_ABGR8888:
4334         case DRM_FORMAT_ARGB8888:
4335         case DRM_FORMAT_XRGB2101010:
4336         case DRM_FORMAT_XBGR2101010:
4337         case DRM_FORMAT_YUYV:
4338         case DRM_FORMAT_YVYU:
4339         case DRM_FORMAT_UYVY:
4340         case DRM_FORMAT_VYUY:
4341                 break;
4342         default:
4343                 DRM_DEBUG_KMS("[PLANE:%d] FB:%d unsupported scaling format 0x%x\n",
4344                         intel_plane->base.base.id, fb->base.id, fb->pixel_format);
4345                 return -EINVAL;
4346         }
4347
4348         return 0;
4349 }
4350
4351 static void skylake_scaler_disable(struct intel_crtc *crtc)
4352 {
4353         int i;
4354
4355         for (i = 0; i < crtc->num_scalers; i++)
4356                 skl_detach_scaler(crtc, i);
4357 }
4358
4359 static void skylake_pfit_enable(struct intel_crtc *crtc)
4360 {
4361         struct drm_device *dev = crtc->base.dev;
4362         struct drm_i915_private *dev_priv = dev->dev_private;
4363         int pipe = crtc->pipe;
4364         struct intel_crtc_scaler_state *scaler_state =
4365                 &crtc->config->scaler_state;
4366
4367         DRM_DEBUG_KMS("for crtc_state = %p\n", crtc->config);
4368
4369         if (crtc->config->pch_pfit.enabled) {
4370                 int id;
4371
4372                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0)) {
4373                         DRM_ERROR("Requesting pfit without getting a scaler first\n");
4374                         return;
4375                 }
4376
4377                 id = scaler_state->scaler_id;
4378                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4379                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4380                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4381                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4382
4383                 DRM_DEBUG_KMS("for crtc_state = %p scaler_id = %d\n", crtc->config, id);
4384         }
4385 }
4386
4387 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4388 {
4389         struct drm_device *dev = crtc->base.dev;
4390         struct drm_i915_private *dev_priv = dev->dev_private;
4391         int pipe = crtc->pipe;
4392
4393         if (crtc->config->pch_pfit.enabled) {
4394                 /* Force use of hard-coded filter coefficients
4395                  * as some pre-programmed values are broken,
4396                  * e.g. x201.
4397                  */
4398                 if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev))
4399                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4400                                                  PF_PIPE_SEL_IVB(pipe));
4401                 else
4402                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4403                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4404                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4405         }
4406 }
4407
4408 void hsw_enable_ips(struct intel_crtc *crtc)
4409 {
4410         struct drm_device *dev = crtc->base.dev;
4411         struct drm_i915_private *dev_priv = dev->dev_private;
4412
4413         if (!crtc->config->ips_enabled)
4414                 return;
4415
4416         /*
4417          * We can only enable IPS after we enable a plane and wait for a vblank
4418          * This function is called from post_plane_update, which is run after
4419          * a vblank wait.
4420          */
4421
4422         assert_plane_enabled(dev_priv, crtc->plane);
4423         if (IS_BROADWELL(dev)) {
4424                 mutex_lock(&dev_priv->rps.hw_lock);
4425                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4426                 mutex_unlock(&dev_priv->rps.hw_lock);
4427                 /* Quoting Art Runyan: "its not safe to expect any particular
4428                  * value in IPS_CTL bit 31 after enabling IPS through the
4429                  * mailbox." Moreover, the mailbox may return a bogus state,
4430                  * so we need to just enable it and continue on.
4431                  */
4432         } else {
4433                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4434                 /* The bit only becomes 1 in the next vblank, so this wait here
4435                  * is essentially intel_wait_for_vblank. If we don't have this
4436                  * and don't wait for vblanks until the end of crtc_enable, then
4437                  * the HW state readout code will complain that the expected
4438                  * IPS_CTL value is not the one we read. */
4439                 if (wait_for(I915_READ_NOTRACE(IPS_CTL) & IPS_ENABLE, 50))
4440                         DRM_ERROR("Timed out waiting for IPS enable\n");
4441         }
4442 }
4443
4444 void hsw_disable_ips(struct intel_crtc *crtc)
4445 {
4446         struct drm_device *dev = crtc->base.dev;
4447         struct drm_i915_private *dev_priv = dev->dev_private;
4448
4449         if (!crtc->config->ips_enabled)
4450                 return;
4451
4452         assert_plane_enabled(dev_priv, crtc->plane);
4453         if (IS_BROADWELL(dev)) {
4454                 mutex_lock(&dev_priv->rps.hw_lock);
4455                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4456                 mutex_unlock(&dev_priv->rps.hw_lock);
4457                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4458                 if (wait_for((I915_READ(IPS_CTL) & IPS_ENABLE) == 0, 42))
4459                         DRM_ERROR("Timed out waiting for IPS disable\n");
4460         } else {
4461                 I915_WRITE(IPS_CTL, 0);
4462                 POSTING_READ(IPS_CTL);
4463         }
4464
4465         /* We need to wait for a vblank before we can disable the plane. */
4466         intel_wait_for_vblank(dev, crtc->pipe);
4467 }
4468
4469 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4470 {
4471         if (intel_crtc->overlay) {
4472                 struct drm_device *dev = intel_crtc->base.dev;
4473                 struct drm_i915_private *dev_priv = dev->dev_private;
4474
4475                 mutex_lock(&dev->struct_mutex);
4476                 dev_priv->mm.interruptible = false;
4477                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4478                 dev_priv->mm.interruptible = true;
4479                 mutex_unlock(&dev->struct_mutex);
4480         }
4481
4482         /* Let userspace switch the overlay on again. In most cases userspace
4483          * has to recompute where to put it anyway.
4484          */
4485 }
4486
4487 /**
4488  * intel_post_enable_primary - Perform operations after enabling primary plane
4489  * @crtc: the CRTC whose primary plane was just enabled
4490  *
4491  * Performs potentially sleeping operations that must be done after the primary
4492  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4493  * called due to an explicit primary plane update, or due to an implicit
4494  * re-enable that is caused when a sprite plane is updated to no longer
4495  * completely hide the primary plane.
4496  */
4497 static void
4498 intel_post_enable_primary(struct drm_crtc *crtc)
4499 {
4500         struct drm_device *dev = crtc->dev;
4501         struct drm_i915_private *dev_priv = dev->dev_private;
4502         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4503         int pipe = intel_crtc->pipe;
4504
4505         /*
4506          * FIXME IPS should be fine as long as one plane is
4507          * enabled, but in practice it seems to have problems
4508          * when going from primary only to sprite only and vice
4509          * versa.
4510          */
4511         hsw_enable_ips(intel_crtc);
4512
4513         /*
4514          * Gen2 reports pipe underruns whenever all planes are disabled.
4515          * So don't enable underrun reporting before at least some planes
4516          * are enabled.
4517          * FIXME: Need to fix the logic to work when we turn off all planes
4518          * but leave the pipe running.
4519          */
4520         if (IS_GEN2(dev))
4521                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4522
4523         /* Underruns don't always raise interrupts, so check manually. */
4524         intel_check_cpu_fifo_underruns(dev_priv);
4525         intel_check_pch_fifo_underruns(dev_priv);
4526 }
4527
4528 /* FIXME move all this to pre_plane_update() with proper state tracking */
4529 static void
4530 intel_pre_disable_primary(struct drm_crtc *crtc)
4531 {
4532         struct drm_device *dev = crtc->dev;
4533         struct drm_i915_private *dev_priv = dev->dev_private;
4534         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4535         int pipe = intel_crtc->pipe;
4536
4537         /*
4538          * Gen2 reports pipe underruns whenever all planes are disabled.
4539          * So diasble underrun reporting before all the planes get disabled.
4540          * FIXME: Need to fix the logic to work when we turn off all planes
4541          * but leave the pipe running.
4542          */
4543         if (IS_GEN2(dev))
4544                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4545
4546         /*
4547          * FIXME IPS should be fine as long as one plane is
4548          * enabled, but in practice it seems to have problems
4549          * when going from primary only to sprite only and vice
4550          * versa.
4551          */
4552         hsw_disable_ips(intel_crtc);
4553 }
4554
4555 /* FIXME get rid of this and use pre_plane_update */
4556 static void
4557 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4558 {
4559         struct drm_device *dev = crtc->dev;
4560         struct drm_i915_private *dev_priv = dev->dev_private;
4561         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4562         int pipe = intel_crtc->pipe;
4563
4564         intel_pre_disable_primary(crtc);
4565
4566         /*
4567          * Vblank time updates from the shadow to live plane control register
4568          * are blocked if the memory self-refresh mode is active at that
4569          * moment. So to make sure the plane gets truly disabled, disable
4570          * first the self-refresh mode. The self-refresh enable bit in turn
4571          * will be checked/applied by the HW only at the next frame start
4572          * event which is after the vblank start event, so we need to have a
4573          * wait-for-vblank between disabling the plane and the pipe.
4574          */
4575         if (HAS_GMCH_DISPLAY(dev)) {
4576                 intel_set_memory_cxsr(dev_priv, false);
4577                 dev_priv->wm.vlv.cxsr = false;
4578                 intel_wait_for_vblank(dev, pipe);
4579         }
4580 }
4581
4582 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
4583 {
4584         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4585         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4586         struct intel_crtc_state *pipe_config =
4587                 to_intel_crtc_state(crtc->base.state);
4588         struct drm_device *dev = crtc->base.dev;
4589         struct drm_plane *primary = crtc->base.primary;
4590         struct drm_plane_state *old_pri_state =
4591                 drm_atomic_get_existing_plane_state(old_state, primary);
4592
4593         intel_frontbuffer_flip(dev, pipe_config->fb_bits);
4594
4595         crtc->wm.cxsr_allowed = true;
4596
4597         if (pipe_config->update_wm_post && pipe_config->base.active)
4598                 intel_update_watermarks(&crtc->base);
4599
4600         if (old_pri_state) {
4601                 struct intel_plane_state *primary_state =
4602                         to_intel_plane_state(primary->state);
4603                 struct intel_plane_state *old_primary_state =
4604                         to_intel_plane_state(old_pri_state);
4605
4606                 intel_fbc_post_update(crtc);
4607
4608                 if (primary_state->visible &&
4609                     (needs_modeset(&pipe_config->base) ||
4610                      !old_primary_state->visible))
4611                         intel_post_enable_primary(&crtc->base);
4612         }
4613 }
4614
4615 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state)
4616 {
4617         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
4618         struct drm_device *dev = crtc->base.dev;
4619         struct drm_i915_private *dev_priv = dev->dev_private;
4620         struct intel_crtc_state *pipe_config =
4621                 to_intel_crtc_state(crtc->base.state);
4622         struct drm_atomic_state *old_state = old_crtc_state->base.state;
4623         struct drm_plane *primary = crtc->base.primary;
4624         struct drm_plane_state *old_pri_state =
4625                 drm_atomic_get_existing_plane_state(old_state, primary);
4626         bool modeset = needs_modeset(&pipe_config->base);
4627
4628         if (old_pri_state) {
4629                 struct intel_plane_state *primary_state =
4630                         to_intel_plane_state(primary->state);
4631                 struct intel_plane_state *old_primary_state =
4632                         to_intel_plane_state(old_pri_state);
4633
4634                 intel_fbc_pre_update(crtc);
4635
4636                 if (old_primary_state->visible &&
4637                     (modeset || !primary_state->visible))
4638                         intel_pre_disable_primary(&crtc->base);
4639         }
4640
4641         if (pipe_config->disable_cxsr) {
4642                 crtc->wm.cxsr_allowed = false;
4643
4644                 /*
4645                  * Vblank time updates from the shadow to live plane control register
4646                  * are blocked if the memory self-refresh mode is active at that
4647                  * moment. So to make sure the plane gets truly disabled, disable
4648                  * first the self-refresh mode. The self-refresh enable bit in turn
4649                  * will be checked/applied by the HW only at the next frame start
4650                  * event which is after the vblank start event, so we need to have a
4651                  * wait-for-vblank between disabling the plane and the pipe.
4652                  */
4653                 if (old_crtc_state->base.active) {
4654                         intel_set_memory_cxsr(dev_priv, false);
4655                         dev_priv->wm.vlv.cxsr = false;
4656                         intel_wait_for_vblank(dev, crtc->pipe);
4657                 }
4658         }
4659
4660         /*
4661          * IVB workaround: must disable low power watermarks for at least
4662          * one frame before enabling scaling.  LP watermarks can be re-enabled
4663          * when scaling is disabled.
4664          *
4665          * WaCxSRDisabledForSpriteScaling:ivb
4666          */
4667         if (pipe_config->disable_lp_wm) {
4668                 ilk_disable_lp_wm(dev);
4669                 intel_wait_for_vblank(dev, crtc->pipe);
4670         }
4671
4672         /*
4673          * If we're doing a modeset, we're done.  No need to do any pre-vblank
4674          * watermark programming here.
4675          */
4676         if (needs_modeset(&pipe_config->base))
4677                 return;
4678
4679         /*
4680          * For platforms that support atomic watermarks, program the
4681          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
4682          * will be the intermediate values that are safe for both pre- and
4683          * post- vblank; when vblank happens, the 'active' values will be set
4684          * to the final 'target' values and we'll do this again to get the
4685          * optimal watermarks.  For gen9+ platforms, the values we program here
4686          * will be the final target values which will get automatically latched
4687          * at vblank time; no further programming will be necessary.
4688          *
4689          * If a platform hasn't been transitioned to atomic watermarks yet,
4690          * we'll continue to update watermarks the old way, if flags tell
4691          * us to.
4692          */
4693         if (dev_priv->display.initial_watermarks != NULL)
4694                 dev_priv->display.initial_watermarks(pipe_config);
4695         else if (pipe_config->update_wm_pre)
4696                 intel_update_watermarks(&crtc->base);
4697 }
4698
4699 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
4700 {
4701         struct drm_device *dev = crtc->dev;
4702         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4703         struct drm_plane *p;
4704         int pipe = intel_crtc->pipe;
4705
4706         intel_crtc_dpms_overlay_disable(intel_crtc);
4707
4708         drm_for_each_plane_mask(p, dev, plane_mask)
4709                 to_intel_plane(p)->disable_plane(p, crtc);
4710
4711         /*
4712          * FIXME: Once we grow proper nuclear flip support out of this we need
4713          * to compute the mask of flip planes precisely. For the time being
4714          * consider this a flip to a NULL plane.
4715          */
4716         intel_frontbuffer_flip(dev, INTEL_FRONTBUFFER_ALL_MASK(pipe));
4717 }
4718
4719 static void ironlake_crtc_enable(struct drm_crtc *crtc)
4720 {
4721         struct drm_device *dev = crtc->dev;
4722         struct drm_i915_private *dev_priv = dev->dev_private;
4723         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4724         struct intel_encoder *encoder;
4725         int pipe = intel_crtc->pipe;
4726
4727         if (WARN_ON(intel_crtc->active))
4728                 return;
4729
4730         if (intel_crtc->config->has_pch_encoder)
4731                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4732
4733         if (intel_crtc->config->has_pch_encoder)
4734                 intel_prepare_shared_dpll(intel_crtc);
4735
4736         if (intel_crtc->config->has_dp_encoder)
4737                 intel_dp_set_m_n(intel_crtc, M1_N1);
4738
4739         intel_set_pipe_timings(intel_crtc);
4740         intel_set_pipe_src_size(intel_crtc);
4741
4742         if (intel_crtc->config->has_pch_encoder) {
4743                 intel_cpu_transcoder_set_m_n(intel_crtc,
4744                                      &intel_crtc->config->fdi_m_n, NULL);
4745         }
4746
4747         ironlake_set_pipeconf(crtc);
4748
4749         intel_crtc->active = true;
4750
4751         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4752
4753         for_each_encoder_on_crtc(dev, crtc, encoder)
4754                 if (encoder->pre_enable)
4755                         encoder->pre_enable(encoder);
4756
4757         if (intel_crtc->config->has_pch_encoder) {
4758                 /* Note: FDI PLL enabling _must_ be done before we enable the
4759                  * cpu pipes, hence this is separate from all the other fdi/pch
4760                  * enabling. */
4761                 ironlake_fdi_pll_enable(intel_crtc);
4762         } else {
4763                 assert_fdi_tx_disabled(dev_priv, pipe);
4764                 assert_fdi_rx_disabled(dev_priv, pipe);
4765         }
4766
4767         ironlake_pfit_enable(intel_crtc);
4768
4769         /*
4770          * On ILK+ LUT must be loaded before the pipe is running but with
4771          * clocks enabled
4772          */
4773         intel_color_load_luts(crtc);
4774
4775         if (dev_priv->display.initial_watermarks != NULL)
4776                 dev_priv->display.initial_watermarks(intel_crtc->config);
4777         intel_enable_pipe(intel_crtc);
4778
4779         if (intel_crtc->config->has_pch_encoder)
4780                 ironlake_pch_enable(crtc);
4781
4782         assert_vblank_disabled(crtc);
4783         drm_crtc_vblank_on(crtc);
4784
4785         for_each_encoder_on_crtc(dev, crtc, encoder)
4786                 encoder->enable(encoder);
4787
4788         if (HAS_PCH_CPT(dev))
4789                 cpt_verify_modeset(dev, intel_crtc->pipe);
4790
4791         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
4792         if (intel_crtc->config->has_pch_encoder)
4793                 intel_wait_for_vblank(dev, pipe);
4794         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
4795 }
4796
4797 /* IPS only exists on ULT machines and is tied to pipe A. */
4798 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
4799 {
4800         return HAS_IPS(crtc->base.dev) && crtc->pipe == PIPE_A;
4801 }
4802
4803 static void haswell_crtc_enable(struct drm_crtc *crtc)
4804 {
4805         struct drm_device *dev = crtc->dev;
4806         struct drm_i915_private *dev_priv = dev->dev_private;
4807         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4808         struct intel_encoder *encoder;
4809         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
4810         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
4811         struct intel_crtc_state *pipe_config =
4812                 to_intel_crtc_state(crtc->state);
4813
4814         if (WARN_ON(intel_crtc->active))
4815                 return;
4816
4817         if (intel_crtc->config->has_pch_encoder)
4818                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4819                                                       false);
4820
4821         if (intel_crtc->config->shared_dpll)
4822                 intel_enable_shared_dpll(intel_crtc);
4823
4824         if (intel_crtc->config->has_dp_encoder)
4825                 intel_dp_set_m_n(intel_crtc, M1_N1);
4826
4827         if (!intel_crtc->config->has_dsi_encoder)
4828                 intel_set_pipe_timings(intel_crtc);
4829
4830         intel_set_pipe_src_size(intel_crtc);
4831
4832         if (cpu_transcoder != TRANSCODER_EDP &&
4833             !transcoder_is_dsi(cpu_transcoder)) {
4834                 I915_WRITE(PIPE_MULT(cpu_transcoder),
4835                            intel_crtc->config->pixel_multiplier - 1);
4836         }
4837
4838         if (intel_crtc->config->has_pch_encoder) {
4839                 intel_cpu_transcoder_set_m_n(intel_crtc,
4840                                      &intel_crtc->config->fdi_m_n, NULL);
4841         }
4842
4843         if (!intel_crtc->config->has_dsi_encoder)
4844                 haswell_set_pipeconf(crtc);
4845
4846         haswell_set_pipemisc(crtc);
4847
4848         intel_color_set_csc(crtc);
4849
4850         intel_crtc->active = true;
4851
4852         if (intel_crtc->config->has_pch_encoder)
4853                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4854         else
4855                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4856
4857         for_each_encoder_on_crtc(dev, crtc, encoder) {
4858                 if (encoder->pre_enable)
4859                         encoder->pre_enable(encoder);
4860         }
4861
4862         if (intel_crtc->config->has_pch_encoder)
4863                 dev_priv->display.fdi_link_train(crtc);
4864
4865         if (!intel_crtc->config->has_dsi_encoder)
4866                 intel_ddi_enable_pipe_clock(intel_crtc);
4867
4868         if (INTEL_INFO(dev)->gen >= 9)
4869                 skylake_pfit_enable(intel_crtc);
4870         else
4871                 ironlake_pfit_enable(intel_crtc);
4872
4873         /*
4874          * On ILK+ LUT must be loaded before the pipe is running but with
4875          * clocks enabled
4876          */
4877         intel_color_load_luts(crtc);
4878
4879         intel_ddi_set_pipe_settings(crtc);
4880         if (!intel_crtc->config->has_dsi_encoder)
4881                 intel_ddi_enable_transcoder_func(crtc);
4882
4883         if (dev_priv->display.initial_watermarks != NULL)
4884                 dev_priv->display.initial_watermarks(pipe_config);
4885         else
4886                 intel_update_watermarks(crtc);
4887
4888         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
4889         if (!intel_crtc->config->has_dsi_encoder)
4890                 intel_enable_pipe(intel_crtc);
4891
4892         if (intel_crtc->config->has_pch_encoder)
4893                 lpt_pch_enable(crtc);
4894
4895         if (intel_crtc->config->dp_encoder_is_mst)
4896                 intel_ddi_set_vc_payload_alloc(crtc, true);
4897
4898         assert_vblank_disabled(crtc);
4899         drm_crtc_vblank_on(crtc);
4900
4901         for_each_encoder_on_crtc(dev, crtc, encoder) {
4902                 encoder->enable(encoder);
4903                 intel_opregion_notify_encoder(encoder, true);
4904         }
4905
4906         if (intel_crtc->config->has_pch_encoder) {
4907                 intel_wait_for_vblank(dev, pipe);
4908                 intel_wait_for_vblank(dev, pipe);
4909                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4910                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
4911                                                       true);
4912         }
4913
4914         /* If we change the relative order between pipe/planes enabling, we need
4915          * to change the workaround. */
4916         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
4917         if (IS_HASWELL(dev) && hsw_workaround_pipe != INVALID_PIPE) {
4918                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4919                 intel_wait_for_vblank(dev, hsw_workaround_pipe);
4920         }
4921 }
4922
4923 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
4924 {
4925         struct drm_device *dev = crtc->base.dev;
4926         struct drm_i915_private *dev_priv = dev->dev_private;
4927         int pipe = crtc->pipe;
4928
4929         /* To avoid upsetting the power well on haswell only disable the pfit if
4930          * it's in use. The hw state code will make sure we get this right. */
4931         if (force || crtc->config->pch_pfit.enabled) {
4932                 I915_WRITE(PF_CTL(pipe), 0);
4933                 I915_WRITE(PF_WIN_POS(pipe), 0);
4934                 I915_WRITE(PF_WIN_SZ(pipe), 0);
4935         }
4936 }
4937
4938 static void ironlake_crtc_disable(struct drm_crtc *crtc)
4939 {
4940         struct drm_device *dev = crtc->dev;
4941         struct drm_i915_private *dev_priv = dev->dev_private;
4942         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4943         struct intel_encoder *encoder;
4944         int pipe = intel_crtc->pipe;
4945
4946         if (intel_crtc->config->has_pch_encoder)
4947                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
4948
4949         for_each_encoder_on_crtc(dev, crtc, encoder)
4950                 encoder->disable(encoder);
4951
4952         drm_crtc_vblank_off(crtc);
4953         assert_vblank_disabled(crtc);
4954
4955         /*
4956          * Sometimes spurious CPU pipe underruns happen when the
4957          * pipe is already disabled, but FDI RX/TX is still enabled.
4958          * Happens at least with VGA+HDMI cloning. Suppress them.
4959          */
4960         if (intel_crtc->config->has_pch_encoder)
4961                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4962
4963         intel_disable_pipe(intel_crtc);
4964
4965         ironlake_pfit_disable(intel_crtc, false);
4966
4967         if (intel_crtc->config->has_pch_encoder) {
4968                 ironlake_fdi_disable(crtc);
4969                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4970         }
4971
4972         for_each_encoder_on_crtc(dev, crtc, encoder)
4973                 if (encoder->post_disable)
4974                         encoder->post_disable(encoder);
4975
4976         if (intel_crtc->config->has_pch_encoder) {
4977                 ironlake_disable_pch_transcoder(dev_priv, pipe);
4978
4979                 if (HAS_PCH_CPT(dev)) {
4980                         i915_reg_t reg;
4981                         u32 temp;
4982
4983                         /* disable TRANS_DP_CTL */
4984                         reg = TRANS_DP_CTL(pipe);
4985                         temp = I915_READ(reg);
4986                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
4987                                   TRANS_DP_PORT_SEL_MASK);
4988                         temp |= TRANS_DP_PORT_SEL_NONE;
4989                         I915_WRITE(reg, temp);
4990
4991                         /* disable DPLL_SEL */
4992                         temp = I915_READ(PCH_DPLL_SEL);
4993                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
4994                         I915_WRITE(PCH_DPLL_SEL, temp);
4995                 }
4996
4997                 ironlake_fdi_pll_disable(intel_crtc);
4998         }
4999
5000         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5001 }
5002
5003 static void haswell_crtc_disable(struct drm_crtc *crtc)
5004 {
5005         struct drm_device *dev = crtc->dev;
5006         struct drm_i915_private *dev_priv = dev->dev_private;
5007         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5008         struct intel_encoder *encoder;
5009         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5010
5011         if (intel_crtc->config->has_pch_encoder)
5012                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5013                                                       false);
5014
5015         for_each_encoder_on_crtc(dev, crtc, encoder) {
5016                 intel_opregion_notify_encoder(encoder, false);
5017                 encoder->disable(encoder);
5018         }
5019
5020         drm_crtc_vblank_off(crtc);
5021         assert_vblank_disabled(crtc);
5022
5023         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5024         if (!intel_crtc->config->has_dsi_encoder)
5025                 intel_disable_pipe(intel_crtc);
5026
5027         if (intel_crtc->config->dp_encoder_is_mst)
5028                 intel_ddi_set_vc_payload_alloc(crtc, false);
5029
5030         if (!intel_crtc->config->has_dsi_encoder)
5031                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5032
5033         if (INTEL_INFO(dev)->gen >= 9)
5034                 skylake_scaler_disable(intel_crtc);
5035         else
5036                 ironlake_pfit_disable(intel_crtc, false);
5037
5038         if (!intel_crtc->config->has_dsi_encoder)
5039                 intel_ddi_disable_pipe_clock(intel_crtc);
5040
5041         for_each_encoder_on_crtc(dev, crtc, encoder)
5042                 if (encoder->post_disable)
5043                         encoder->post_disable(encoder);
5044
5045         if (intel_crtc->config->has_pch_encoder) {
5046                 lpt_disable_pch_transcoder(dev_priv);
5047                 lpt_disable_iclkip(dev_priv);
5048                 intel_ddi_fdi_disable(crtc);
5049
5050                 intel_set_pch_fifo_underrun_reporting(dev_priv, TRANSCODER_A,
5051                                                       true);
5052         }
5053 }
5054
5055 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5056 {
5057         struct drm_device *dev = crtc->base.dev;
5058         struct drm_i915_private *dev_priv = dev->dev_private;
5059         struct intel_crtc_state *pipe_config = crtc->config;
5060
5061         if (!pipe_config->gmch_pfit.control)
5062                 return;
5063
5064         /*
5065          * The panel fitter should only be adjusted whilst the pipe is disabled,
5066          * according to register description and PRM.
5067          */
5068         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5069         assert_pipe_disabled(dev_priv, crtc->pipe);
5070
5071         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5072         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5073
5074         /* Border color in case we don't scale up to the full screen. Black by
5075          * default, change to something else for debugging. */
5076         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5077 }
5078
5079 static enum intel_display_power_domain port_to_power_domain(enum port port)
5080 {
5081         switch (port) {
5082         case PORT_A:
5083                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5084         case PORT_B:
5085                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5086         case PORT_C:
5087                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5088         case PORT_D:
5089                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5090         case PORT_E:
5091                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5092         default:
5093                 MISSING_CASE(port);
5094                 return POWER_DOMAIN_PORT_OTHER;
5095         }
5096 }
5097
5098 static enum intel_display_power_domain port_to_aux_power_domain(enum port port)
5099 {
5100         switch (port) {
5101         case PORT_A:
5102                 return POWER_DOMAIN_AUX_A;
5103         case PORT_B:
5104                 return POWER_DOMAIN_AUX_B;
5105         case PORT_C:
5106                 return POWER_DOMAIN_AUX_C;
5107         case PORT_D:
5108                 return POWER_DOMAIN_AUX_D;
5109         case PORT_E:
5110                 /* FIXME: Check VBT for actual wiring of PORT E */
5111                 return POWER_DOMAIN_AUX_D;
5112         default:
5113                 MISSING_CASE(port);
5114                 return POWER_DOMAIN_AUX_A;
5115         }
5116 }
5117
5118 enum intel_display_power_domain
5119 intel_display_port_power_domain(struct intel_encoder *intel_encoder)
5120 {
5121         struct drm_device *dev = intel_encoder->base.dev;
5122         struct intel_digital_port *intel_dig_port;
5123
5124         switch (intel_encoder->type) {
5125         case INTEL_OUTPUT_UNKNOWN:
5126                 /* Only DDI platforms should ever use this output type */
5127                 WARN_ON_ONCE(!HAS_DDI(dev));
5128         case INTEL_OUTPUT_DISPLAYPORT:
5129         case INTEL_OUTPUT_HDMI:
5130         case INTEL_OUTPUT_EDP:
5131                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5132                 return port_to_power_domain(intel_dig_port->port);
5133         case INTEL_OUTPUT_DP_MST:
5134                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5135                 return port_to_power_domain(intel_dig_port->port);
5136         case INTEL_OUTPUT_ANALOG:
5137                 return POWER_DOMAIN_PORT_CRT;
5138         case INTEL_OUTPUT_DSI:
5139                 return POWER_DOMAIN_PORT_DSI;
5140         default:
5141                 return POWER_DOMAIN_PORT_OTHER;
5142         }
5143 }
5144
5145 enum intel_display_power_domain
5146 intel_display_port_aux_power_domain(struct intel_encoder *intel_encoder)
5147 {
5148         struct drm_device *dev = intel_encoder->base.dev;
5149         struct intel_digital_port *intel_dig_port;
5150
5151         switch (intel_encoder->type) {
5152         case INTEL_OUTPUT_UNKNOWN:
5153         case INTEL_OUTPUT_HDMI:
5154                 /*
5155                  * Only DDI platforms should ever use these output types.
5156                  * We can get here after the HDMI detect code has already set
5157                  * the type of the shared encoder. Since we can't be sure
5158                  * what's the status of the given connectors, play safe and
5159                  * run the DP detection too.
5160                  */
5161                 WARN_ON_ONCE(!HAS_DDI(dev));
5162         case INTEL_OUTPUT_DISPLAYPORT:
5163         case INTEL_OUTPUT_EDP:
5164                 intel_dig_port = enc_to_dig_port(&intel_encoder->base);
5165                 return port_to_aux_power_domain(intel_dig_port->port);
5166         case INTEL_OUTPUT_DP_MST:
5167                 intel_dig_port = enc_to_mst(&intel_encoder->base)->primary;
5168                 return port_to_aux_power_domain(intel_dig_port->port);
5169         default:
5170                 MISSING_CASE(intel_encoder->type);
5171                 return POWER_DOMAIN_AUX_A;
5172         }
5173 }
5174
5175 static unsigned long get_crtc_power_domains(struct drm_crtc *crtc,
5176                                             struct intel_crtc_state *crtc_state)
5177 {
5178         struct drm_device *dev = crtc->dev;
5179         struct drm_encoder *encoder;
5180         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5181         enum pipe pipe = intel_crtc->pipe;
5182         unsigned long mask;
5183         enum transcoder transcoder = crtc_state->cpu_transcoder;
5184
5185         if (!crtc_state->base.active)
5186                 return 0;
5187
5188         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5189         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5190         if (crtc_state->pch_pfit.enabled ||
5191             crtc_state->pch_pfit.force_thru)
5192                 mask |= BIT(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5193
5194         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5195                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5196
5197                 mask |= BIT(intel_display_port_power_domain(intel_encoder));
5198         }
5199
5200         if (crtc_state->shared_dpll)
5201                 mask |= BIT(POWER_DOMAIN_PLLS);
5202
5203         return mask;
5204 }
5205
5206 static unsigned long
5207 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5208                                struct intel_crtc_state *crtc_state)
5209 {
5210         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
5211         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5212         enum intel_display_power_domain domain;
5213         unsigned long domains, new_domains, old_domains;
5214
5215         old_domains = intel_crtc->enabled_power_domains;
5216         intel_crtc->enabled_power_domains = new_domains =
5217                 get_crtc_power_domains(crtc, crtc_state);
5218
5219         domains = new_domains & ~old_domains;
5220
5221         for_each_power_domain(domain, domains)
5222                 intel_display_power_get(dev_priv, domain);
5223
5224         return old_domains & ~new_domains;
5225 }
5226
5227 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5228                                       unsigned long domains)
5229 {
5230         enum intel_display_power_domain domain;
5231
5232         for_each_power_domain(domain, domains)
5233                 intel_display_power_put(dev_priv, domain);
5234 }
5235
5236 static int intel_compute_max_dotclk(struct drm_i915_private *dev_priv)
5237 {
5238         int max_cdclk_freq = dev_priv->max_cdclk_freq;
5239
5240         if (INTEL_INFO(dev_priv)->gen >= 9 ||
5241             IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
5242                 return max_cdclk_freq;
5243         else if (IS_CHERRYVIEW(dev_priv))
5244                 return max_cdclk_freq*95/100;
5245         else if (INTEL_INFO(dev_priv)->gen < 4)
5246                 return 2*max_cdclk_freq*90/100;
5247         else
5248                 return max_cdclk_freq*90/100;
5249 }
5250
5251 static void intel_update_max_cdclk(struct drm_device *dev)
5252 {
5253         struct drm_i915_private *dev_priv = dev->dev_private;
5254
5255         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
5256                 u32 limit = I915_READ(SKL_DFSM) & SKL_DFSM_CDCLK_LIMIT_MASK;
5257
5258                 if (limit == SKL_DFSM_CDCLK_LIMIT_675)
5259                         dev_priv->max_cdclk_freq = 675000;
5260                 else if (limit == SKL_DFSM_CDCLK_LIMIT_540)
5261                         dev_priv->max_cdclk_freq = 540000;
5262                 else if (limit == SKL_DFSM_CDCLK_LIMIT_450)
5263                         dev_priv->max_cdclk_freq = 450000;
5264                 else
5265                         dev_priv->max_cdclk_freq = 337500;
5266         } else if (IS_BROADWELL(dev))  {
5267                 /*
5268                  * FIXME with extra cooling we can allow
5269                  * 540 MHz for ULX and 675 Mhz for ULT.
5270                  * How can we know if extra cooling is
5271                  * available? PCI ID, VTB, something else?
5272                  */
5273                 if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
5274                         dev_priv->max_cdclk_freq = 450000;
5275                 else if (IS_BDW_ULX(dev))
5276                         dev_priv->max_cdclk_freq = 450000;
5277                 else if (IS_BDW_ULT(dev))
5278                         dev_priv->max_cdclk_freq = 540000;
5279                 else
5280                         dev_priv->max_cdclk_freq = 675000;
5281         } else if (IS_CHERRYVIEW(dev)) {
5282                 dev_priv->max_cdclk_freq = 320000;
5283         } else if (IS_VALLEYVIEW(dev)) {
5284                 dev_priv->max_cdclk_freq = 400000;
5285         } else {
5286                 /* otherwise assume cdclk is fixed */
5287                 dev_priv->max_cdclk_freq = dev_priv->cdclk_freq;
5288         }
5289
5290         dev_priv->max_dotclk_freq = intel_compute_max_dotclk(dev_priv);
5291
5292         DRM_DEBUG_DRIVER("Max CD clock rate: %d kHz\n",
5293                          dev_priv->max_cdclk_freq);
5294
5295         DRM_DEBUG_DRIVER("Max dotclock rate: %d kHz\n",
5296                          dev_priv->max_dotclk_freq);
5297 }
5298
5299 static void intel_update_cdclk(struct drm_device *dev)
5300 {
5301         struct drm_i915_private *dev_priv = dev->dev_private;
5302
5303         dev_priv->cdclk_freq = dev_priv->display.get_display_clock_speed(dev);
5304         DRM_DEBUG_DRIVER("Current CD clock rate: %d kHz\n",
5305                          dev_priv->cdclk_freq);
5306
5307         /*
5308          * Program the gmbus_freq based on the cdclk frequency.
5309          * BSpec erroneously claims we should aim for 4MHz, but
5310          * in fact 1MHz is the correct frequency.
5311          */
5312         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
5313                 /*
5314                  * Program the gmbus_freq based on the cdclk frequency.
5315                  * BSpec erroneously claims we should aim for 4MHz, but
5316                  * in fact 1MHz is the correct frequency.
5317                  */
5318                 I915_WRITE(GMBUSFREQ_VLV, DIV_ROUND_UP(dev_priv->cdclk_freq, 1000));
5319         }
5320
5321         if (dev_priv->max_cdclk_freq == 0)
5322                 intel_update_max_cdclk(dev);
5323 }
5324
5325 static void broxton_set_cdclk(struct drm_device *dev, int frequency)
5326 {
5327         struct drm_i915_private *dev_priv = dev->dev_private;
5328         uint32_t divider;
5329         uint32_t ratio;
5330         uint32_t current_freq;
5331         int ret;
5332
5333         /* frequency = 19.2MHz * ratio / 2 / div{1,1.5,2,4} */
5334         switch (frequency) {
5335         case 144000:
5336                 divider = BXT_CDCLK_CD2X_DIV_SEL_4;
5337                 ratio = BXT_DE_PLL_RATIO(60);
5338                 break;
5339         case 288000:
5340                 divider = BXT_CDCLK_CD2X_DIV_SEL_2;
5341                 ratio = BXT_DE_PLL_RATIO(60);
5342                 break;
5343         case 384000:
5344                 divider = BXT_CDCLK_CD2X_DIV_SEL_1_5;
5345                 ratio = BXT_DE_PLL_RATIO(60);
5346                 break;
5347         case 576000:
5348                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5349                 ratio = BXT_DE_PLL_RATIO(60);
5350                 break;
5351         case 624000:
5352                 divider = BXT_CDCLK_CD2X_DIV_SEL_1;
5353                 ratio = BXT_DE_PLL_RATIO(65);
5354                 break;
5355         case 19200:
5356                 /*
5357                  * Bypass frequency with DE PLL disabled. Init ratio, divider
5358                  * to suppress GCC warning.
5359                  */
5360                 ratio = 0;
5361                 divider = 0;
5362                 break;
5363         default:
5364                 DRM_ERROR("unsupported CDCLK freq %d", frequency);
5365
5366                 return;
5367         }
5368
5369         mutex_lock(&dev_priv->rps.hw_lock);
5370         /* Inform power controller of upcoming frequency change */
5371         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5372                                       0x80000000);
5373         mutex_unlock(&dev_priv->rps.hw_lock);
5374
5375         if (ret) {
5376                 DRM_ERROR("PCode CDCLK freq change notify failed (err %d, freq %d)\n",
5377                           ret, frequency);
5378                 return;
5379         }
5380
5381         current_freq = I915_READ(CDCLK_CTL) & CDCLK_FREQ_DECIMAL_MASK;
5382         /* convert from .1 fixpoint MHz with -1MHz offset to kHz */
5383         current_freq = current_freq * 500 + 1000;
5384
5385         /*
5386          * DE PLL has to be disabled when
5387          * - setting to 19.2MHz (bypass, PLL isn't used)
5388          * - before setting to 624MHz (PLL needs toggling)
5389          * - before setting to any frequency from 624MHz (PLL needs toggling)
5390          */
5391         if (frequency == 19200 || frequency == 624000 ||
5392             current_freq == 624000) {
5393                 I915_WRITE(BXT_DE_PLL_ENABLE, ~BXT_DE_PLL_PLL_ENABLE);
5394                 /* Timeout 200us */
5395                 if (wait_for(!(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK),
5396                              1))
5397                         DRM_ERROR("timout waiting for DE PLL unlock\n");
5398         }
5399
5400         if (frequency != 19200) {
5401                 uint32_t val;
5402
5403                 val = I915_READ(BXT_DE_PLL_CTL);
5404                 val &= ~BXT_DE_PLL_RATIO_MASK;
5405                 val |= ratio;
5406                 I915_WRITE(BXT_DE_PLL_CTL, val);
5407
5408                 I915_WRITE(BXT_DE_PLL_ENABLE, BXT_DE_PLL_PLL_ENABLE);
5409                 /* Timeout 200us */
5410                 if (wait_for(I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_LOCK, 1))
5411                         DRM_ERROR("timeout waiting for DE PLL lock\n");
5412
5413                 val = I915_READ(CDCLK_CTL);
5414                 val &= ~BXT_CDCLK_CD2X_DIV_SEL_MASK;
5415                 val |= divider;
5416                 /*
5417                  * Disable SSA Precharge when CD clock frequency < 500 MHz,
5418                  * enable otherwise.
5419                  */
5420                 val &= ~BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5421                 if (frequency >= 500000)
5422                         val |= BXT_CDCLK_SSA_PRECHARGE_ENABLE;
5423
5424                 val &= ~CDCLK_FREQ_DECIMAL_MASK;
5425                 /* convert from kHz to .1 fixpoint MHz with -1MHz offset */
5426                 val |= (frequency - 1000) / 500;
5427                 I915_WRITE(CDCLK_CTL, val);
5428         }
5429
5430         mutex_lock(&dev_priv->rps.hw_lock);
5431         ret = sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ,
5432                                       DIV_ROUND_UP(frequency, 25000));
5433         mutex_unlock(&dev_priv->rps.hw_lock);
5434
5435         if (ret) {
5436                 DRM_ERROR("PCode CDCLK freq set failed, (err %d, freq %d)\n",
5437                           ret, frequency);
5438                 return;
5439         }
5440
5441         intel_update_cdclk(dev);
5442 }
5443
5444 void broxton_init_cdclk(struct drm_device *dev)
5445 {
5446         struct drm_i915_private *dev_priv = dev->dev_private;
5447         uint32_t val;
5448
5449         /*
5450          * NDE_RSTWRN_OPT RST PCH Handshake En must always be 0b on BXT
5451          * or else the reset will hang because there is no PCH to respond.
5452          * Move the handshake programming to initialization sequence.
5453          * Previously was left up to BIOS.
5454          */
5455         val = I915_READ(HSW_NDE_RSTWRN_OPT);
5456         val &= ~RESET_PCH_HANDSHAKE_ENABLE;
5457         I915_WRITE(HSW_NDE_RSTWRN_OPT, val);
5458
5459         /* Enable PG1 for cdclk */
5460         intel_display_power_get(dev_priv, POWER_DOMAIN_PLLS);
5461
5462         /* check if cd clock is enabled */
5463         if (I915_READ(BXT_DE_PLL_ENABLE) & BXT_DE_PLL_PLL_ENABLE) {
5464                 DRM_DEBUG_KMS("Display already initialized\n");
5465                 return;
5466         }
5467
5468         /*
5469          * FIXME:
5470          * - The initial CDCLK needs to be read from VBT.
5471          *   Need to make this change after VBT has changes for BXT.
5472          * - check if setting the max (or any) cdclk freq is really necessary
5473          *   here, it belongs to modeset time
5474          */
5475         broxton_set_cdclk(dev, 624000);
5476
5477         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5478         POSTING_READ(DBUF_CTL);
5479
5480         udelay(10);
5481
5482         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5483                 DRM_ERROR("DBuf power enable timeout!\n");
5484 }
5485
5486 void broxton_uninit_cdclk(struct drm_device *dev)
5487 {
5488         struct drm_i915_private *dev_priv = dev->dev_private;
5489
5490         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5491         POSTING_READ(DBUF_CTL);
5492
5493         udelay(10);
5494
5495         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5496                 DRM_ERROR("DBuf power disable timeout!\n");
5497
5498         /* Set minimum (bypass) frequency, in effect turning off the DE PLL */
5499         broxton_set_cdclk(dev, 19200);
5500
5501         intel_display_power_put(dev_priv, POWER_DOMAIN_PLLS);
5502 }
5503
5504 static const struct skl_cdclk_entry {
5505         unsigned int freq;
5506         unsigned int vco;
5507 } skl_cdclk_frequencies[] = {
5508         { .freq = 308570, .vco = 8640 },
5509         { .freq = 337500, .vco = 8100 },
5510         { .freq = 432000, .vco = 8640 },
5511         { .freq = 450000, .vco = 8100 },
5512         { .freq = 540000, .vco = 8100 },
5513         { .freq = 617140, .vco = 8640 },
5514         { .freq = 675000, .vco = 8100 },
5515 };
5516
5517 static unsigned int skl_cdclk_decimal(unsigned int freq)
5518 {
5519         return (freq - 1000) / 500;
5520 }
5521
5522 static unsigned int skl_cdclk_get_vco(unsigned int freq)
5523 {
5524         unsigned int i;
5525
5526         for (i = 0; i < ARRAY_SIZE(skl_cdclk_frequencies); i++) {
5527                 const struct skl_cdclk_entry *e = &skl_cdclk_frequencies[i];
5528
5529                 if (e->freq == freq)
5530                         return e->vco;
5531         }
5532
5533         return 8100;
5534 }
5535
5536 static void
5537 skl_dpll0_enable(struct drm_i915_private *dev_priv, unsigned int required_vco)
5538 {
5539         unsigned int min_freq;
5540         u32 val;
5541
5542         /* select the minimum CDCLK before enabling DPLL 0 */
5543         val = I915_READ(CDCLK_CTL);
5544         val &= ~CDCLK_FREQ_SEL_MASK | ~CDCLK_FREQ_DECIMAL_MASK;
5545         val |= CDCLK_FREQ_337_308;
5546
5547         if (required_vco == 8640)
5548                 min_freq = 308570;
5549         else
5550                 min_freq = 337500;
5551
5552         val = CDCLK_FREQ_337_308 | skl_cdclk_decimal(min_freq);
5553
5554         I915_WRITE(CDCLK_CTL, val);
5555         POSTING_READ(CDCLK_CTL);
5556
5557         /*
5558          * We always enable DPLL0 with the lowest link rate possible, but still
5559          * taking into account the VCO required to operate the eDP panel at the
5560          * desired frequency. The usual DP link rates operate with a VCO of
5561          * 8100 while the eDP 1.4 alternate link rates need a VCO of 8640.
5562          * The modeset code is responsible for the selection of the exact link
5563          * rate later on, with the constraint of choosing a frequency that
5564          * works with required_vco.
5565          */
5566         val = I915_READ(DPLL_CTRL1);
5567
5568         val &= ~(DPLL_CTRL1_HDMI_MODE(SKL_DPLL0) | DPLL_CTRL1_SSC(SKL_DPLL0) |
5569                  DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0));
5570         val |= DPLL_CTRL1_OVERRIDE(SKL_DPLL0);
5571         if (required_vco == 8640)
5572                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_1080,
5573                                             SKL_DPLL0);
5574         else
5575                 val |= DPLL_CTRL1_LINK_RATE(DPLL_CTRL1_LINK_RATE_810,
5576                                             SKL_DPLL0);
5577
5578         I915_WRITE(DPLL_CTRL1, val);
5579         POSTING_READ(DPLL_CTRL1);
5580
5581         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) | LCPLL_PLL_ENABLE);
5582
5583         if (wait_for(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK, 5))
5584                 DRM_ERROR("DPLL0 not locked\n");
5585 }
5586
5587 static bool skl_cdclk_pcu_ready(struct drm_i915_private *dev_priv)
5588 {
5589         int ret;
5590         u32 val;
5591
5592         /* inform PCU we want to change CDCLK */
5593         val = SKL_CDCLK_PREPARE_FOR_CHANGE;
5594         mutex_lock(&dev_priv->rps.hw_lock);
5595         ret = sandybridge_pcode_read(dev_priv, SKL_PCODE_CDCLK_CONTROL, &val);
5596         mutex_unlock(&dev_priv->rps.hw_lock);
5597
5598         return ret == 0 && (val & SKL_CDCLK_READY_FOR_CHANGE);
5599 }
5600
5601 static bool skl_cdclk_wait_for_pcu_ready(struct drm_i915_private *dev_priv)
5602 {
5603         unsigned int i;
5604
5605         for (i = 0; i < 15; i++) {
5606                 if (skl_cdclk_pcu_ready(dev_priv))
5607                         return true;
5608                 udelay(10);
5609         }
5610
5611         return false;
5612 }
5613
5614 static void skl_set_cdclk(struct drm_i915_private *dev_priv, unsigned int freq)
5615 {
5616         struct drm_device *dev = dev_priv->dev;
5617         u32 freq_select, pcu_ack;
5618
5619         DRM_DEBUG_DRIVER("Changing CDCLK to %dKHz\n", freq);
5620
5621         if (!skl_cdclk_wait_for_pcu_ready(dev_priv)) {
5622                 DRM_ERROR("failed to inform PCU about cdclk change\n");
5623                 return;
5624         }
5625
5626         /* set CDCLK_CTL */
5627         switch(freq) {
5628         case 450000:
5629         case 432000:
5630                 freq_select = CDCLK_FREQ_450_432;
5631                 pcu_ack = 1;
5632                 break;
5633         case 540000:
5634                 freq_select = CDCLK_FREQ_540;
5635                 pcu_ack = 2;
5636                 break;
5637         case 308570:
5638         case 337500:
5639         default:
5640                 freq_select = CDCLK_FREQ_337_308;
5641                 pcu_ack = 0;
5642                 break;
5643         case 617140:
5644         case 675000:
5645                 freq_select = CDCLK_FREQ_675_617;
5646                 pcu_ack = 3;
5647                 break;
5648         }
5649
5650         I915_WRITE(CDCLK_CTL, freq_select | skl_cdclk_decimal(freq));
5651         POSTING_READ(CDCLK_CTL);
5652
5653         /* inform PCU of the change */
5654         mutex_lock(&dev_priv->rps.hw_lock);
5655         sandybridge_pcode_write(dev_priv, SKL_PCODE_CDCLK_CONTROL, pcu_ack);
5656         mutex_unlock(&dev_priv->rps.hw_lock);
5657
5658         intel_update_cdclk(dev);
5659 }
5660
5661 void skl_uninit_cdclk(struct drm_i915_private *dev_priv)
5662 {
5663         /* disable DBUF power */
5664         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) & ~DBUF_POWER_REQUEST);
5665         POSTING_READ(DBUF_CTL);
5666
5667         udelay(10);
5668
5669         if (I915_READ(DBUF_CTL) & DBUF_POWER_STATE)
5670                 DRM_ERROR("DBuf power disable timeout\n");
5671
5672         /* disable DPLL0 */
5673         I915_WRITE(LCPLL1_CTL, I915_READ(LCPLL1_CTL) & ~LCPLL_PLL_ENABLE);
5674         if (wait_for(!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_LOCK), 1))
5675                 DRM_ERROR("Couldn't disable DPLL0\n");
5676 }
5677
5678 void skl_init_cdclk(struct drm_i915_private *dev_priv)
5679 {
5680         unsigned int required_vco;
5681
5682         /* DPLL0 not enabled (happens on early BIOS versions) */
5683         if (!(I915_READ(LCPLL1_CTL) & LCPLL_PLL_ENABLE)) {
5684                 /* enable DPLL0 */
5685                 required_vco = skl_cdclk_get_vco(dev_priv->skl_boot_cdclk);
5686                 skl_dpll0_enable(dev_priv, required_vco);
5687         }
5688
5689         /* set CDCLK to the frequency the BIOS chose */
5690         skl_set_cdclk(dev_priv, dev_priv->skl_boot_cdclk);
5691
5692         /* enable DBUF power */
5693         I915_WRITE(DBUF_CTL, I915_READ(DBUF_CTL) | DBUF_POWER_REQUEST);
5694         POSTING_READ(DBUF_CTL);
5695
5696         udelay(10);
5697
5698         if (!(I915_READ(DBUF_CTL) & DBUF_POWER_STATE))
5699                 DRM_ERROR("DBuf power enable timeout\n");
5700 }
5701
5702 int skl_sanitize_cdclk(struct drm_i915_private *dev_priv)
5703 {
5704         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
5705         uint32_t cdctl = I915_READ(CDCLK_CTL);
5706         int freq = dev_priv->skl_boot_cdclk;
5707
5708         /*
5709          * check if the pre-os intialized the display
5710          * There is SWF18 scratchpad register defined which is set by the
5711          * pre-os which can be used by the OS drivers to check the status
5712          */
5713         if ((I915_READ(SWF_ILK(0x18)) & 0x00FFFFFF) == 0)
5714                 goto sanitize;
5715
5716         /* Is PLL enabled and locked ? */
5717         if (!((lcpll1 & LCPLL_PLL_ENABLE) && (lcpll1 & LCPLL_PLL_LOCK)))
5718                 goto sanitize;
5719
5720         /* DPLL okay; verify the cdclock
5721          *
5722          * Noticed in some instances that the freq selection is correct but
5723          * decimal part is programmed wrong from BIOS where pre-os does not
5724          * enable display. Verify the same as well.
5725          */
5726         if (cdctl == ((cdctl & CDCLK_FREQ_SEL_MASK) | skl_cdclk_decimal(freq)))
5727                 /* All well; nothing to sanitize */
5728                 return false;
5729 sanitize:
5730         /*
5731          * As of now initialize with max cdclk till
5732          * we get dynamic cdclk support
5733          * */
5734         dev_priv->skl_boot_cdclk = dev_priv->max_cdclk_freq;
5735         skl_init_cdclk(dev_priv);
5736
5737         /* we did have to sanitize */
5738         return true;
5739 }
5740
5741 /* Adjust CDclk dividers to allow high res or save power if possible */
5742 static void valleyview_set_cdclk(struct drm_device *dev, int cdclk)
5743 {
5744         struct drm_i915_private *dev_priv = dev->dev_private;
5745         u32 val, cmd;
5746
5747         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5748                                         != dev_priv->cdclk_freq);
5749
5750         if (cdclk >= 320000) /* jump to highest voltage for 400MHz too */
5751                 cmd = 2;
5752         else if (cdclk == 266667)
5753                 cmd = 1;
5754         else
5755                 cmd = 0;
5756
5757         mutex_lock(&dev_priv->rps.hw_lock);
5758         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5759         val &= ~DSPFREQGUAR_MASK;
5760         val |= (cmd << DSPFREQGUAR_SHIFT);
5761         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5762         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5763                       DSPFREQSTAT_MASK) == (cmd << DSPFREQSTAT_SHIFT),
5764                      50)) {
5765                 DRM_ERROR("timed out waiting for CDclk change\n");
5766         }
5767         mutex_unlock(&dev_priv->rps.hw_lock);
5768
5769         mutex_lock(&dev_priv->sb_lock);
5770
5771         if (cdclk == 400000) {
5772                 u32 divider;
5773
5774                 divider = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5775
5776                 /* adjust cdclk divider */
5777                 val = vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL);
5778                 val &= ~CCK_FREQUENCY_VALUES;
5779                 val |= divider;
5780                 vlv_cck_write(dev_priv, CCK_DISPLAY_CLOCK_CONTROL, val);
5781
5782                 if (wait_for((vlv_cck_read(dev_priv, CCK_DISPLAY_CLOCK_CONTROL) &
5783                               CCK_FREQUENCY_STATUS) == (divider << CCK_FREQUENCY_STATUS_SHIFT),
5784                              50))
5785                         DRM_ERROR("timed out waiting for CDclk change\n");
5786         }
5787
5788         /* adjust self-refresh exit latency value */
5789         val = vlv_bunit_read(dev_priv, BUNIT_REG_BISOC);
5790         val &= ~0x7f;
5791
5792         /*
5793          * For high bandwidth configs, we set a higher latency in the bunit
5794          * so that the core display fetch happens in time to avoid underruns.
5795          */
5796         if (cdclk == 400000)
5797                 val |= 4500 / 250; /* 4.5 usec */
5798         else
5799                 val |= 3000 / 250; /* 3.0 usec */
5800         vlv_bunit_write(dev_priv, BUNIT_REG_BISOC, val);
5801
5802         mutex_unlock(&dev_priv->sb_lock);
5803
5804         intel_update_cdclk(dev);
5805 }
5806
5807 static void cherryview_set_cdclk(struct drm_device *dev, int cdclk)
5808 {
5809         struct drm_i915_private *dev_priv = dev->dev_private;
5810         u32 val, cmd;
5811
5812         WARN_ON(dev_priv->display.get_display_clock_speed(dev)
5813                                                 != dev_priv->cdclk_freq);
5814
5815         switch (cdclk) {
5816         case 333333:
5817         case 320000:
5818         case 266667:
5819         case 200000:
5820                 break;
5821         default:
5822                 MISSING_CASE(cdclk);
5823                 return;
5824         }
5825
5826         /*
5827          * Specs are full of misinformation, but testing on actual
5828          * hardware has shown that we just need to write the desired
5829          * CCK divider into the Punit register.
5830          */
5831         cmd = DIV_ROUND_CLOSEST(dev_priv->hpll_freq << 1, cdclk) - 1;
5832
5833         mutex_lock(&dev_priv->rps.hw_lock);
5834         val = vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ);
5835         val &= ~DSPFREQGUAR_MASK_CHV;
5836         val |= (cmd << DSPFREQGUAR_SHIFT_CHV);
5837         vlv_punit_write(dev_priv, PUNIT_REG_DSPFREQ, val);
5838         if (wait_for((vlv_punit_read(dev_priv, PUNIT_REG_DSPFREQ) &
5839                       DSPFREQSTAT_MASK_CHV) == (cmd << DSPFREQSTAT_SHIFT_CHV),
5840                      50)) {
5841                 DRM_ERROR("timed out waiting for CDclk change\n");
5842         }
5843         mutex_unlock(&dev_priv->rps.hw_lock);
5844
5845         intel_update_cdclk(dev);
5846 }
5847
5848 static int valleyview_calc_cdclk(struct drm_i915_private *dev_priv,
5849                                  int max_pixclk)
5850 {
5851         int freq_320 = (dev_priv->hpll_freq <<  1) % 320000 != 0 ? 333333 : 320000;
5852         int limit = IS_CHERRYVIEW(dev_priv) ? 95 : 90;
5853
5854         /*
5855          * Really only a few cases to deal with, as only 4 CDclks are supported:
5856          *   200MHz
5857          *   267MHz
5858          *   320/333MHz (depends on HPLL freq)
5859          *   400MHz (VLV only)
5860          * So we check to see whether we're above 90% (VLV) or 95% (CHV)
5861          * of the lower bin and adjust if needed.
5862          *
5863          * We seem to get an unstable or solid color picture at 200MHz.
5864          * Not sure what's wrong. For now use 200MHz only when all pipes
5865          * are off.
5866          */
5867         if (!IS_CHERRYVIEW(dev_priv) &&
5868             max_pixclk > freq_320*limit/100)
5869                 return 400000;
5870         else if (max_pixclk > 266667*limit/100)
5871                 return freq_320;
5872         else if (max_pixclk > 0)
5873                 return 266667;
5874         else
5875                 return 200000;
5876 }
5877
5878 static int broxton_calc_cdclk(struct drm_i915_private *dev_priv,
5879                               int max_pixclk)
5880 {
5881         /*
5882          * FIXME:
5883          * - remove the guardband, it's not needed on BXT
5884          * - set 19.2MHz bypass frequency if there are no active pipes
5885          */
5886         if (max_pixclk > 576000*9/10)
5887                 return 624000;
5888         else if (max_pixclk > 384000*9/10)
5889                 return 576000;
5890         else if (max_pixclk > 288000*9/10)
5891                 return 384000;
5892         else if (max_pixclk > 144000*9/10)
5893                 return 288000;
5894         else
5895                 return 144000;
5896 }
5897
5898 /* Compute the max pixel clock for new configuration. */
5899 static int intel_mode_max_pixclk(struct drm_device *dev,
5900                                  struct drm_atomic_state *state)
5901 {
5902         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
5903         struct drm_i915_private *dev_priv = dev->dev_private;
5904         struct drm_crtc *crtc;
5905         struct drm_crtc_state *crtc_state;
5906         unsigned max_pixclk = 0, i;
5907         enum pipe pipe;
5908
5909         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
5910                sizeof(intel_state->min_pixclk));
5911
5912         for_each_crtc_in_state(state, crtc, crtc_state, i) {
5913                 int pixclk = 0;
5914
5915                 if (crtc_state->enable)
5916                         pixclk = crtc_state->adjusted_mode.crtc_clock;
5917
5918                 intel_state->min_pixclk[i] = pixclk;
5919         }
5920
5921         for_each_pipe(dev_priv, pipe)
5922                 max_pixclk = max(intel_state->min_pixclk[pipe], max_pixclk);
5923
5924         return max_pixclk;
5925 }
5926
5927 static int valleyview_modeset_calc_cdclk(struct drm_atomic_state *state)
5928 {
5929         struct drm_device *dev = state->dev;
5930         struct drm_i915_private *dev_priv = dev->dev_private;
5931         int max_pixclk = intel_mode_max_pixclk(dev, state);
5932         struct intel_atomic_state *intel_state =
5933                 to_intel_atomic_state(state);
5934
5935         if (max_pixclk < 0)
5936                 return max_pixclk;
5937
5938         intel_state->cdclk = intel_state->dev_cdclk =
5939                 valleyview_calc_cdclk(dev_priv, max_pixclk);
5940
5941         if (!intel_state->active_crtcs)
5942                 intel_state->dev_cdclk = valleyview_calc_cdclk(dev_priv, 0);
5943
5944         return 0;
5945 }
5946
5947 static int broxton_modeset_calc_cdclk(struct drm_atomic_state *state)
5948 {
5949         struct drm_device *dev = state->dev;
5950         struct drm_i915_private *dev_priv = dev->dev_private;
5951         int max_pixclk = intel_mode_max_pixclk(dev, state);
5952         struct intel_atomic_state *intel_state =
5953                 to_intel_atomic_state(state);
5954
5955         if (max_pixclk < 0)
5956                 return max_pixclk;
5957
5958         intel_state->cdclk = intel_state->dev_cdclk =
5959                 broxton_calc_cdclk(dev_priv, max_pixclk);
5960
5961         if (!intel_state->active_crtcs)
5962                 intel_state->dev_cdclk = broxton_calc_cdclk(dev_priv, 0);
5963
5964         return 0;
5965 }
5966
5967 static void vlv_program_pfi_credits(struct drm_i915_private *dev_priv)
5968 {
5969         unsigned int credits, default_credits;
5970
5971         if (IS_CHERRYVIEW(dev_priv))
5972                 default_credits = PFI_CREDIT(12);
5973         else
5974                 default_credits = PFI_CREDIT(8);
5975
5976         if (dev_priv->cdclk_freq >= dev_priv->czclk_freq) {
5977                 /* CHV suggested value is 31 or 63 */
5978                 if (IS_CHERRYVIEW(dev_priv))
5979                         credits = PFI_CREDIT_63;
5980                 else
5981                         credits = PFI_CREDIT(15);
5982         } else {
5983                 credits = default_credits;
5984         }
5985
5986         /*
5987          * WA - write default credits before re-programming
5988          * FIXME: should we also set the resend bit here?
5989          */
5990         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5991                    default_credits);
5992
5993         I915_WRITE(GCI_CONTROL, VGA_FAST_MODE_DISABLE |
5994                    credits | PFI_CREDIT_RESEND);
5995
5996         /*
5997          * FIXME is this guaranteed to clear
5998          * immediately or should we poll for it?
5999          */
6000         WARN_ON(I915_READ(GCI_CONTROL) & PFI_CREDIT_RESEND);
6001 }
6002
6003 static void valleyview_modeset_commit_cdclk(struct drm_atomic_state *old_state)
6004 {
6005         struct drm_device *dev = old_state->dev;
6006         struct drm_i915_private *dev_priv = dev->dev_private;
6007         struct intel_atomic_state *old_intel_state =
6008                 to_intel_atomic_state(old_state);
6009         unsigned req_cdclk = old_intel_state->dev_cdclk;
6010
6011         /*
6012          * FIXME: We can end up here with all power domains off, yet
6013          * with a CDCLK frequency other than the minimum. To account
6014          * for this take the PIPE-A power domain, which covers the HW
6015          * blocks needed for the following programming. This can be
6016          * removed once it's guaranteed that we get here either with
6017          * the minimum CDCLK set, or the required power domains
6018          * enabled.
6019          */
6020         intel_display_power_get(dev_priv, POWER_DOMAIN_PIPE_A);
6021
6022         if (IS_CHERRYVIEW(dev))
6023                 cherryview_set_cdclk(dev, req_cdclk);
6024         else
6025                 valleyview_set_cdclk(dev, req_cdclk);
6026
6027         vlv_program_pfi_credits(dev_priv);
6028
6029         intel_display_power_put(dev_priv, POWER_DOMAIN_PIPE_A);
6030 }
6031
6032 static void valleyview_crtc_enable(struct drm_crtc *crtc)
6033 {
6034         struct drm_device *dev = crtc->dev;
6035         struct drm_i915_private *dev_priv = to_i915(dev);
6036         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6037         struct intel_encoder *encoder;
6038         int pipe = intel_crtc->pipe;
6039
6040         if (WARN_ON(intel_crtc->active))
6041                 return;
6042
6043         if (intel_crtc->config->has_dp_encoder)
6044                 intel_dp_set_m_n(intel_crtc, M1_N1);
6045
6046         intel_set_pipe_timings(intel_crtc);
6047         intel_set_pipe_src_size(intel_crtc);
6048
6049         if (IS_CHERRYVIEW(dev) && pipe == PIPE_B) {
6050                 struct drm_i915_private *dev_priv = dev->dev_private;
6051
6052                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6053                 I915_WRITE(CHV_CANVAS(pipe), 0);
6054         }
6055
6056         i9xx_set_pipeconf(intel_crtc);
6057
6058         intel_crtc->active = true;
6059
6060         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6061
6062         for_each_encoder_on_crtc(dev, crtc, encoder)
6063                 if (encoder->pre_pll_enable)
6064                         encoder->pre_pll_enable(encoder);
6065
6066         if (!intel_crtc->config->has_dsi_encoder) {
6067                 if (IS_CHERRYVIEW(dev)) {
6068                         chv_prepare_pll(intel_crtc, intel_crtc->config);
6069                         chv_enable_pll(intel_crtc, intel_crtc->config);
6070                 } else {
6071                         vlv_prepare_pll(intel_crtc, intel_crtc->config);
6072                         vlv_enable_pll(intel_crtc, intel_crtc->config);
6073                 }
6074         }
6075
6076         for_each_encoder_on_crtc(dev, crtc, encoder)
6077                 if (encoder->pre_enable)
6078                         encoder->pre_enable(encoder);
6079
6080         i9xx_pfit_enable(intel_crtc);
6081
6082         intel_color_load_luts(crtc);
6083
6084         intel_update_watermarks(crtc);
6085         intel_enable_pipe(intel_crtc);
6086
6087         assert_vblank_disabled(crtc);
6088         drm_crtc_vblank_on(crtc);
6089
6090         for_each_encoder_on_crtc(dev, crtc, encoder)
6091                 encoder->enable(encoder);
6092 }
6093
6094 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6095 {
6096         struct drm_device *dev = crtc->base.dev;
6097         struct drm_i915_private *dev_priv = dev->dev_private;
6098
6099         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6100         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6101 }
6102
6103 static void i9xx_crtc_enable(struct drm_crtc *crtc)
6104 {
6105         struct drm_device *dev = crtc->dev;
6106         struct drm_i915_private *dev_priv = to_i915(dev);
6107         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6108         struct intel_encoder *encoder;
6109         int pipe = intel_crtc->pipe;
6110
6111         if (WARN_ON(intel_crtc->active))
6112                 return;
6113
6114         i9xx_set_pll_dividers(intel_crtc);
6115
6116         if (intel_crtc->config->has_dp_encoder)
6117                 intel_dp_set_m_n(intel_crtc, M1_N1);
6118
6119         intel_set_pipe_timings(intel_crtc);
6120         intel_set_pipe_src_size(intel_crtc);
6121
6122         i9xx_set_pipeconf(intel_crtc);
6123
6124         intel_crtc->active = true;
6125
6126         if (!IS_GEN2(dev))
6127                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6128
6129         for_each_encoder_on_crtc(dev, crtc, encoder)
6130                 if (encoder->pre_enable)
6131                         encoder->pre_enable(encoder);
6132
6133         i9xx_enable_pll(intel_crtc);
6134
6135         i9xx_pfit_enable(intel_crtc);
6136
6137         intel_color_load_luts(crtc);
6138
6139         intel_update_watermarks(crtc);
6140         intel_enable_pipe(intel_crtc);
6141
6142         assert_vblank_disabled(crtc);
6143         drm_crtc_vblank_on(crtc);
6144
6145         for_each_encoder_on_crtc(dev, crtc, encoder)
6146                 encoder->enable(encoder);
6147 }
6148
6149 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6150 {
6151         struct drm_device *dev = crtc->base.dev;
6152         struct drm_i915_private *dev_priv = dev->dev_private;
6153
6154         if (!crtc->config->gmch_pfit.control)
6155                 return;
6156
6157         assert_pipe_disabled(dev_priv, crtc->pipe);
6158
6159         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6160                          I915_READ(PFIT_CONTROL));
6161         I915_WRITE(PFIT_CONTROL, 0);
6162 }
6163
6164 static void i9xx_crtc_disable(struct drm_crtc *crtc)
6165 {
6166         struct drm_device *dev = crtc->dev;
6167         struct drm_i915_private *dev_priv = dev->dev_private;
6168         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6169         struct intel_encoder *encoder;
6170         int pipe = intel_crtc->pipe;
6171
6172         /*
6173          * On gen2 planes are double buffered but the pipe isn't, so we must
6174          * wait for planes to fully turn off before disabling the pipe.
6175          */
6176         if (IS_GEN2(dev))
6177                 intel_wait_for_vblank(dev, pipe);
6178
6179         for_each_encoder_on_crtc(dev, crtc, encoder)
6180                 encoder->disable(encoder);
6181
6182         drm_crtc_vblank_off(crtc);
6183         assert_vblank_disabled(crtc);
6184
6185         intel_disable_pipe(intel_crtc);
6186
6187         i9xx_pfit_disable(intel_crtc);
6188
6189         for_each_encoder_on_crtc(dev, crtc, encoder)
6190                 if (encoder->post_disable)
6191                         encoder->post_disable(encoder);
6192
6193         if (!intel_crtc->config->has_dsi_encoder) {
6194                 if (IS_CHERRYVIEW(dev))
6195                         chv_disable_pll(dev_priv, pipe);
6196                 else if (IS_VALLEYVIEW(dev))
6197                         vlv_disable_pll(dev_priv, pipe);
6198                 else
6199                         i9xx_disable_pll(intel_crtc);
6200         }
6201
6202         for_each_encoder_on_crtc(dev, crtc, encoder)
6203                 if (encoder->post_pll_disable)
6204                         encoder->post_pll_disable(encoder);
6205
6206         if (!IS_GEN2(dev))
6207                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6208 }
6209
6210 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc)
6211 {
6212         struct intel_encoder *encoder;
6213         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6214         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6215         enum intel_display_power_domain domain;
6216         unsigned long domains;
6217
6218         if (!intel_crtc->active)
6219                 return;
6220
6221         if (to_intel_plane_state(crtc->primary->state)->visible) {
6222                 WARN_ON(intel_crtc->unpin_work);
6223
6224                 intel_pre_disable_primary_noatomic(crtc);
6225
6226                 intel_crtc_disable_planes(crtc, 1 << drm_plane_index(crtc->primary));
6227                 to_intel_plane_state(crtc->primary->state)->visible = false;
6228         }
6229
6230         dev_priv->display.crtc_disable(crtc);
6231
6232         DRM_DEBUG_KMS("[CRTC:%d] hw state adjusted, was enabled, now disabled\n",
6233                       crtc->base.id);
6234
6235         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6236         crtc->state->active = false;
6237         intel_crtc->active = false;
6238         crtc->enabled = false;
6239         crtc->state->connector_mask = 0;
6240         crtc->state->encoder_mask = 0;
6241
6242         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6243                 encoder->base.crtc = NULL;
6244
6245         intel_fbc_disable(intel_crtc);
6246         intel_update_watermarks(crtc);
6247         intel_disable_shared_dpll(intel_crtc);
6248
6249         domains = intel_crtc->enabled_power_domains;
6250         for_each_power_domain(domain, domains)
6251                 intel_display_power_put(dev_priv, domain);
6252         intel_crtc->enabled_power_domains = 0;
6253
6254         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6255         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6256 }
6257
6258 /*
6259  * turn all crtc's off, but do not adjust state
6260  * This has to be paired with a call to intel_modeset_setup_hw_state.
6261  */
6262 int intel_display_suspend(struct drm_device *dev)
6263 {
6264         struct drm_i915_private *dev_priv = to_i915(dev);
6265         struct drm_atomic_state *state;
6266         int ret;
6267
6268         state = drm_atomic_helper_suspend(dev);
6269         ret = PTR_ERR_OR_ZERO(state);
6270         if (ret)
6271                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6272         else
6273                 dev_priv->modeset_restore_state = state;
6274         return ret;
6275 }
6276
6277 void intel_encoder_destroy(struct drm_encoder *encoder)
6278 {
6279         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6280
6281         drm_encoder_cleanup(encoder);
6282         kfree(intel_encoder);
6283 }
6284
6285 /* Cross check the actual hw state with our own modeset state tracking (and it's
6286  * internal consistency). */
6287 static void intel_connector_check_state(struct intel_connector *connector)
6288 {
6289         struct drm_crtc *crtc = connector->base.state->crtc;
6290
6291         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6292                       connector->base.base.id,
6293                       connector->base.name);
6294
6295         if (connector->get_hw_state(connector)) {
6296                 struct intel_encoder *encoder = connector->encoder;
6297                 struct drm_connector_state *conn_state = connector->base.state;
6298
6299                 I915_STATE_WARN(!crtc,
6300                          "connector enabled without attached crtc\n");
6301
6302                 if (!crtc)
6303                         return;
6304
6305                 I915_STATE_WARN(!crtc->state->active,
6306                       "connector is active, but attached crtc isn't\n");
6307
6308                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6309                         return;
6310
6311                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6312                         "atomic encoder doesn't match attached encoder\n");
6313
6314                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6315                         "attached encoder crtc differs from connector crtc\n");
6316         } else {
6317                 I915_STATE_WARN(crtc && crtc->state->active,
6318                         "attached crtc is active, but connector isn't\n");
6319                 I915_STATE_WARN(!crtc && connector->base.state->best_encoder,
6320                         "best encoder set without crtc!\n");
6321         }
6322 }
6323
6324 int intel_connector_init(struct intel_connector *connector)
6325 {
6326         drm_atomic_helper_connector_reset(&connector->base);
6327
6328         if (!connector->base.state)
6329                 return -ENOMEM;
6330
6331         return 0;
6332 }
6333
6334 struct intel_connector *intel_connector_alloc(void)
6335 {
6336         struct intel_connector *connector;
6337
6338         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6339         if (!connector)
6340                 return NULL;
6341
6342         if (intel_connector_init(connector) < 0) {
6343                 kfree(connector);
6344                 return NULL;
6345         }
6346
6347         return connector;
6348 }
6349
6350 /* Simple connector->get_hw_state implementation for encoders that support only
6351  * one connector and no cloning and hence the encoder state determines the state
6352  * of the connector. */
6353 bool intel_connector_get_hw_state(struct intel_connector *connector)
6354 {
6355         enum pipe pipe = 0;
6356         struct intel_encoder *encoder = connector->encoder;
6357
6358         return encoder->get_hw_state(encoder, &pipe);
6359 }
6360
6361 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6362 {
6363         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6364                 return crtc_state->fdi_lanes;
6365
6366         return 0;
6367 }
6368
6369 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6370                                      struct intel_crtc_state *pipe_config)
6371 {
6372         struct drm_atomic_state *state = pipe_config->base.state;
6373         struct intel_crtc *other_crtc;
6374         struct intel_crtc_state *other_crtc_state;
6375
6376         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6377                       pipe_name(pipe), pipe_config->fdi_lanes);
6378         if (pipe_config->fdi_lanes > 4) {
6379                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6380                               pipe_name(pipe), pipe_config->fdi_lanes);
6381                 return -EINVAL;
6382         }
6383
6384         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
6385                 if (pipe_config->fdi_lanes > 2) {
6386                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6387                                       pipe_config->fdi_lanes);
6388                         return -EINVAL;
6389                 } else {
6390                         return 0;
6391                 }
6392         }
6393
6394         if (INTEL_INFO(dev)->num_pipes == 2)
6395                 return 0;
6396
6397         /* Ivybridge 3 pipe is really complicated */
6398         switch (pipe) {
6399         case PIPE_A:
6400                 return 0;
6401         case PIPE_B:
6402                 if (pipe_config->fdi_lanes <= 2)
6403                         return 0;
6404
6405                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_C));
6406                 other_crtc_state =
6407                         intel_atomic_get_crtc_state(state, other_crtc);
6408                 if (IS_ERR(other_crtc_state))
6409                         return PTR_ERR(other_crtc_state);
6410
6411                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6412                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6413                                       pipe_name(pipe), pipe_config->fdi_lanes);
6414                         return -EINVAL;
6415                 }
6416                 return 0;
6417         case PIPE_C:
6418                 if (pipe_config->fdi_lanes > 2) {
6419                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6420                                       pipe_name(pipe), pipe_config->fdi_lanes);
6421                         return -EINVAL;
6422                 }
6423
6424                 other_crtc = to_intel_crtc(intel_get_crtc_for_pipe(dev, PIPE_B));
6425                 other_crtc_state =
6426                         intel_atomic_get_crtc_state(state, other_crtc);
6427                 if (IS_ERR(other_crtc_state))
6428                         return PTR_ERR(other_crtc_state);
6429
6430                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6431                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6432                         return -EINVAL;
6433                 }
6434                 return 0;
6435         default:
6436                 BUG();
6437         }
6438 }
6439
6440 #define RETRY 1
6441 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6442                                        struct intel_crtc_state *pipe_config)
6443 {
6444         struct drm_device *dev = intel_crtc->base.dev;
6445         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6446         int lane, link_bw, fdi_dotclock, ret;
6447         bool needs_recompute = false;
6448
6449 retry:
6450         /* FDI is a binary signal running at ~2.7GHz, encoding
6451          * each output octet as 10 bits. The actual frequency
6452          * is stored as a divider into a 100MHz clock, and the
6453          * mode pixel clock is stored in units of 1KHz.
6454          * Hence the bw of each lane in terms of the mode signal
6455          * is:
6456          */
6457         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6458
6459         fdi_dotclock = adjusted_mode->crtc_clock;
6460
6461         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6462                                            pipe_config->pipe_bpp);
6463
6464         pipe_config->fdi_lanes = lane;
6465
6466         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6467                                link_bw, &pipe_config->fdi_m_n);
6468
6469         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6470         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6471                 pipe_config->pipe_bpp -= 2*3;
6472                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6473                               pipe_config->pipe_bpp);
6474                 needs_recompute = true;
6475                 pipe_config->bw_constrained = true;
6476
6477                 goto retry;
6478         }
6479
6480         if (needs_recompute)
6481                 return RETRY;
6482
6483         return ret;
6484 }
6485
6486 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6487                                      struct intel_crtc_state *pipe_config)
6488 {
6489         if (pipe_config->pipe_bpp > 24)
6490                 return false;
6491
6492         /* HSW can handle pixel rate up to cdclk? */
6493         if (IS_HASWELL(dev_priv->dev))
6494                 return true;
6495
6496         /*
6497          * We compare against max which means we must take
6498          * the increased cdclk requirement into account when
6499          * calculating the new cdclk.
6500          *
6501          * Should measure whether using a lower cdclk w/o IPS
6502          */
6503         return ilk_pipe_pixel_rate(pipe_config) <=
6504                 dev_priv->max_cdclk_freq * 95 / 100;
6505 }
6506
6507 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6508                                    struct intel_crtc_state *pipe_config)
6509 {
6510         struct drm_device *dev = crtc->base.dev;
6511         struct drm_i915_private *dev_priv = dev->dev_private;
6512
6513         pipe_config->ips_enabled = i915.enable_ips &&
6514                 hsw_crtc_supports_ips(crtc) &&
6515                 pipe_config_supports_ips(dev_priv, pipe_config);
6516 }
6517
6518 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6519 {
6520         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6521
6522         /* GDG double wide on either pipe, otherwise pipe A only */
6523         return INTEL_INFO(dev_priv)->gen < 4 &&
6524                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6525 }
6526
6527 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6528                                      struct intel_crtc_state *pipe_config)
6529 {
6530         struct drm_device *dev = crtc->base.dev;
6531         struct drm_i915_private *dev_priv = dev->dev_private;
6532         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6533
6534         /* FIXME should check pixel clock limits on all platforms */
6535         if (INTEL_INFO(dev)->gen < 4) {
6536                 int clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6537
6538                 /*
6539                  * Enable double wide mode when the dot clock
6540                  * is > 90% of the (display) core speed.
6541                  */
6542                 if (intel_crtc_supports_double_wide(crtc) &&
6543                     adjusted_mode->crtc_clock > clock_limit) {
6544                         clock_limit *= 2;
6545                         pipe_config->double_wide = true;
6546                 }
6547
6548                 if (adjusted_mode->crtc_clock > clock_limit) {
6549                         DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6550                                       adjusted_mode->crtc_clock, clock_limit,
6551                                       yesno(pipe_config->double_wide));
6552                         return -EINVAL;
6553                 }
6554         }
6555
6556         /*
6557          * Pipe horizontal size must be even in:
6558          * - DVO ganged mode
6559          * - LVDS dual channel mode
6560          * - Double wide pipe
6561          */
6562         if ((intel_pipe_will_have_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6563              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6564                 pipe_config->pipe_src_w &= ~1;
6565
6566         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6567          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6568          */
6569         if ((INTEL_INFO(dev)->gen > 4 || IS_G4X(dev)) &&
6570                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6571                 return -EINVAL;
6572
6573         if (HAS_IPS(dev))
6574                 hsw_compute_ips_config(crtc, pipe_config);
6575
6576         if (pipe_config->has_pch_encoder)
6577                 return ironlake_fdi_compute_config(crtc, pipe_config);
6578
6579         return 0;
6580 }
6581
6582 static int skylake_get_display_clock_speed(struct drm_device *dev)
6583 {
6584         struct drm_i915_private *dev_priv = to_i915(dev);
6585         uint32_t lcpll1 = I915_READ(LCPLL1_CTL);
6586         uint32_t cdctl = I915_READ(CDCLK_CTL);
6587         uint32_t linkrate;
6588
6589         if (!(lcpll1 & LCPLL_PLL_ENABLE))
6590                 return 24000; /* 24MHz is the cd freq with NSSC ref */
6591
6592         if ((cdctl & CDCLK_FREQ_SEL_MASK) == CDCLK_FREQ_540)
6593                 return 540000;
6594
6595         linkrate = (I915_READ(DPLL_CTRL1) &
6596                     DPLL_CTRL1_LINK_RATE_MASK(SKL_DPLL0)) >> 1;
6597
6598         if (linkrate == DPLL_CTRL1_LINK_RATE_2160 ||
6599             linkrate == DPLL_CTRL1_LINK_RATE_1080) {
6600                 /* vco 8640 */
6601                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6602                 case CDCLK_FREQ_450_432:
6603                         return 432000;
6604                 case CDCLK_FREQ_337_308:
6605                         return 308570;
6606                 case CDCLK_FREQ_675_617:
6607                         return 617140;
6608                 default:
6609                         WARN(1, "Unknown cd freq selection\n");
6610                 }
6611         } else {
6612                 /* vco 8100 */
6613                 switch (cdctl & CDCLK_FREQ_SEL_MASK) {
6614                 case CDCLK_FREQ_450_432:
6615                         return 450000;
6616                 case CDCLK_FREQ_337_308:
6617                         return 337500;
6618                 case CDCLK_FREQ_675_617:
6619                         return 675000;
6620                 default:
6621                         WARN(1, "Unknown cd freq selection\n");
6622                 }
6623         }
6624
6625         /* error case, do as if DPLL0 isn't enabled */
6626         return 24000;
6627 }
6628
6629 static int broxton_get_display_clock_speed(struct drm_device *dev)
6630 {
6631         struct drm_i915_private *dev_priv = to_i915(dev);
6632         uint32_t cdctl = I915_READ(CDCLK_CTL);
6633         uint32_t pll_ratio = I915_READ(BXT_DE_PLL_CTL) & BXT_DE_PLL_RATIO_MASK;
6634         uint32_t pll_enab = I915_READ(BXT_DE_PLL_ENABLE);
6635         int cdclk;
6636
6637         if (!(pll_enab & BXT_DE_PLL_PLL_ENABLE))
6638                 return 19200;
6639
6640         cdclk = 19200 * pll_ratio / 2;
6641
6642         switch (cdctl & BXT_CDCLK_CD2X_DIV_SEL_MASK) {
6643         case BXT_CDCLK_CD2X_DIV_SEL_1:
6644                 return cdclk;  /* 576MHz or 624MHz */
6645         case BXT_CDCLK_CD2X_DIV_SEL_1_5:
6646                 return cdclk * 2 / 3; /* 384MHz */
6647         case BXT_CDCLK_CD2X_DIV_SEL_2:
6648                 return cdclk / 2; /* 288MHz */
6649         case BXT_CDCLK_CD2X_DIV_SEL_4:
6650                 return cdclk / 4; /* 144MHz */
6651         }
6652
6653         /* error case, do as if DE PLL isn't enabled */
6654         return 19200;
6655 }
6656
6657 static int broadwell_get_display_clock_speed(struct drm_device *dev)
6658 {
6659         struct drm_i915_private *dev_priv = dev->dev_private;
6660         uint32_t lcpll = I915_READ(LCPLL_CTL);
6661         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6662
6663         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6664                 return 800000;
6665         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6666                 return 450000;
6667         else if (freq == LCPLL_CLK_FREQ_450)
6668                 return 450000;
6669         else if (freq == LCPLL_CLK_FREQ_54O_BDW)
6670                 return 540000;
6671         else if (freq == LCPLL_CLK_FREQ_337_5_BDW)
6672                 return 337500;
6673         else
6674                 return 675000;
6675 }
6676
6677 static int haswell_get_display_clock_speed(struct drm_device *dev)
6678 {
6679         struct drm_i915_private *dev_priv = dev->dev_private;
6680         uint32_t lcpll = I915_READ(LCPLL_CTL);
6681         uint32_t freq = lcpll & LCPLL_CLK_FREQ_MASK;
6682
6683         if (lcpll & LCPLL_CD_SOURCE_FCLK)
6684                 return 800000;
6685         else if (I915_READ(FUSE_STRAP) & HSW_CDCLK_LIMIT)
6686                 return 450000;
6687         else if (freq == LCPLL_CLK_FREQ_450)
6688                 return 450000;
6689         else if (IS_HSW_ULT(dev))
6690                 return 337500;
6691         else
6692                 return 540000;
6693 }
6694
6695 static int valleyview_get_display_clock_speed(struct drm_device *dev)
6696 {
6697         return vlv_get_cck_clock_hpll(to_i915(dev), "cdclk",
6698                                       CCK_DISPLAY_CLOCK_CONTROL);
6699 }
6700
6701 static int ilk_get_display_clock_speed(struct drm_device *dev)
6702 {
6703         return 450000;
6704 }
6705
6706 static int i945_get_display_clock_speed(struct drm_device *dev)
6707 {
6708         return 400000;
6709 }
6710
6711 static int i915_get_display_clock_speed(struct drm_device *dev)
6712 {
6713         return 333333;
6714 }
6715
6716 static int i9xx_misc_get_display_clock_speed(struct drm_device *dev)
6717 {
6718         return 200000;
6719 }
6720
6721 static int pnv_get_display_clock_speed(struct drm_device *dev)
6722 {
6723         u16 gcfgc = 0;
6724
6725         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6726
6727         switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6728         case GC_DISPLAY_CLOCK_267_MHZ_PNV:
6729                 return 266667;
6730         case GC_DISPLAY_CLOCK_333_MHZ_PNV:
6731                 return 333333;
6732         case GC_DISPLAY_CLOCK_444_MHZ_PNV:
6733                 return 444444;
6734         case GC_DISPLAY_CLOCK_200_MHZ_PNV:
6735                 return 200000;
6736         default:
6737                 DRM_ERROR("Unknown pnv display core clock 0x%04x\n", gcfgc);
6738         case GC_DISPLAY_CLOCK_133_MHZ_PNV:
6739                 return 133333;
6740         case GC_DISPLAY_CLOCK_167_MHZ_PNV:
6741                 return 166667;
6742         }
6743 }
6744
6745 static int i915gm_get_display_clock_speed(struct drm_device *dev)
6746 {
6747         u16 gcfgc = 0;
6748
6749         pci_read_config_word(dev->pdev, GCFGC, &gcfgc);
6750
6751         if (gcfgc & GC_LOW_FREQUENCY_ENABLE)
6752                 return 133333;
6753         else {
6754                 switch (gcfgc & GC_DISPLAY_CLOCK_MASK) {
6755                 case GC_DISPLAY_CLOCK_333_MHZ:
6756                         return 333333;
6757                 default:
6758                 case GC_DISPLAY_CLOCK_190_200_MHZ:
6759                         return 190000;
6760                 }
6761         }
6762 }
6763
6764 static int i865_get_display_clock_speed(struct drm_device *dev)
6765 {
6766         return 266667;
6767 }
6768
6769 static int i85x_get_display_clock_speed(struct drm_device *dev)
6770 {
6771         u16 hpllcc = 0;
6772
6773         /*
6774          * 852GM/852GMV only supports 133 MHz and the HPLLCC
6775          * encoding is different :(
6776          * FIXME is this the right way to detect 852GM/852GMV?
6777          */
6778         if (dev->pdev->revision == 0x1)
6779                 return 133333;
6780
6781         pci_bus_read_config_word(dev->pdev->bus,
6782                                  PCI_DEVFN(0, 3), HPLLCC, &hpllcc);
6783
6784         /* Assume that the hardware is in the high speed state.  This
6785          * should be the default.
6786          */
6787         switch (hpllcc & GC_CLOCK_CONTROL_MASK) {
6788         case GC_CLOCK_133_200:
6789         case GC_CLOCK_133_200_2:
6790         case GC_CLOCK_100_200:
6791                 return 200000;
6792         case GC_CLOCK_166_250:
6793                 return 250000;
6794         case GC_CLOCK_100_133:
6795                 return 133333;
6796         case GC_CLOCK_133_266:
6797         case GC_CLOCK_133_266_2:
6798         case GC_CLOCK_166_266:
6799                 return 266667;
6800         }
6801
6802         /* Shouldn't happen */
6803         return 0;
6804 }
6805
6806 static int i830_get_display_clock_speed(struct drm_device *dev)
6807 {
6808         return 133333;
6809 }
6810
6811 static unsigned int intel_hpll_vco(struct drm_device *dev)
6812 {
6813         struct drm_i915_private *dev_priv = dev->dev_private;
6814         static const unsigned int blb_vco[8] = {
6815                 [0] = 3200000,
6816                 [1] = 4000000,
6817                 [2] = 5333333,
6818                 [3] = 4800000,
6819                 [4] = 6400000,
6820         };
6821         static const unsigned int pnv_vco[8] = {
6822                 [0] = 3200000,
6823                 [1] = 4000000,
6824                 [2] = 5333333,
6825                 [3] = 4800000,
6826                 [4] = 2666667,
6827         };
6828         static const unsigned int cl_vco[8] = {
6829                 [0] = 3200000,
6830                 [1] = 4000000,
6831                 [2] = 5333333,
6832                 [3] = 6400000,
6833                 [4] = 3333333,
6834                 [5] = 3566667,
6835                 [6] = 4266667,
6836         };
6837         static const unsigned int elk_vco[8] = {
6838                 [0] = 3200000,
6839                 [1] = 4000000,
6840                 [2] = 5333333,
6841                 [3] = 4800000,
6842         };
6843         static const unsigned int ctg_vco[8] = {
6844                 [0] = 3200000,
6845                 [1] = 4000000,
6846                 [2] = 5333333,
6847                 [3] = 6400000,
6848                 [4] = 2666667,
6849                 [5] = 4266667,
6850         };
6851         const unsigned int *vco_table;
6852         unsigned int vco;
6853         uint8_t tmp = 0;
6854
6855         /* FIXME other chipsets? */
6856         if (IS_GM45(dev))
6857                 vco_table = ctg_vco;
6858         else if (IS_G4X(dev))
6859                 vco_table = elk_vco;
6860         else if (IS_CRESTLINE(dev))
6861                 vco_table = cl_vco;
6862         else if (IS_PINEVIEW(dev))
6863                 vco_table = pnv_vco;
6864         else if (IS_G33(dev))
6865                 vco_table = blb_vco;
6866         else
6867                 return 0;
6868
6869         tmp = I915_READ(IS_MOBILE(dev) ? HPLLVCO_MOBILE : HPLLVCO);
6870
6871         vco = vco_table[tmp & 0x7];
6872         if (vco == 0)
6873                 DRM_ERROR("Bad HPLL VCO (HPLLVCO=0x%02x)\n", tmp);
6874         else
6875                 DRM_DEBUG_KMS("HPLL VCO %u kHz\n", vco);
6876
6877         return vco;
6878 }
6879
6880 static int gm45_get_display_clock_speed(struct drm_device *dev)
6881 {
6882         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6883         uint16_t tmp = 0;
6884
6885         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6886
6887         cdclk_sel = (tmp >> 12) & 0x1;
6888
6889         switch (vco) {
6890         case 2666667:
6891         case 4000000:
6892         case 5333333:
6893                 return cdclk_sel ? 333333 : 222222;
6894         case 3200000:
6895                 return cdclk_sel ? 320000 : 228571;
6896         default:
6897                 DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u, CFGC=0x%04x\n", vco, tmp);
6898                 return 222222;
6899         }
6900 }
6901
6902 static int i965gm_get_display_clock_speed(struct drm_device *dev)
6903 {
6904         static const uint8_t div_3200[] = { 16, 10,  8 };
6905         static const uint8_t div_4000[] = { 20, 12, 10 };
6906         static const uint8_t div_5333[] = { 24, 16, 14 };
6907         const uint8_t *div_table;
6908         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6909         uint16_t tmp = 0;
6910
6911         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6912
6913         cdclk_sel = ((tmp >> 8) & 0x1f) - 1;
6914
6915         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6916                 goto fail;
6917
6918         switch (vco) {
6919         case 3200000:
6920                 div_table = div_3200;
6921                 break;
6922         case 4000000:
6923                 div_table = div_4000;
6924                 break;
6925         case 5333333:
6926                 div_table = div_5333;
6927                 break;
6928         default:
6929                 goto fail;
6930         }
6931
6932         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6933
6934 fail:
6935         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%04x\n", vco, tmp);
6936         return 200000;
6937 }
6938
6939 static int g33_get_display_clock_speed(struct drm_device *dev)
6940 {
6941         static const uint8_t div_3200[] = { 12, 10,  8,  7, 5, 16 };
6942         static const uint8_t div_4000[] = { 14, 12, 10,  8, 6, 20 };
6943         static const uint8_t div_4800[] = { 20, 14, 12, 10, 8, 24 };
6944         static const uint8_t div_5333[] = { 20, 16, 12, 12, 8, 28 };
6945         const uint8_t *div_table;
6946         unsigned int cdclk_sel, vco = intel_hpll_vco(dev);
6947         uint16_t tmp = 0;
6948
6949         pci_read_config_word(dev->pdev, GCFGC, &tmp);
6950
6951         cdclk_sel = (tmp >> 4) & 0x7;
6952
6953         if (cdclk_sel >= ARRAY_SIZE(div_3200))
6954                 goto fail;
6955
6956         switch (vco) {
6957         case 3200000:
6958                 div_table = div_3200;
6959                 break;
6960         case 4000000:
6961                 div_table = div_4000;
6962                 break;
6963         case 4800000:
6964                 div_table = div_4800;
6965                 break;
6966         case 5333333:
6967                 div_table = div_5333;
6968                 break;
6969         default:
6970                 goto fail;
6971         }
6972
6973         return DIV_ROUND_CLOSEST(vco, div_table[cdclk_sel]);
6974
6975 fail:
6976         DRM_ERROR("Unable to determine CDCLK. HPLL VCO=%u kHz, CFGC=0x%08x\n", vco, tmp);
6977         return 190476;
6978 }
6979
6980 static void
6981 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6982 {
6983         while (*num > DATA_LINK_M_N_MASK ||
6984                *den > DATA_LINK_M_N_MASK) {
6985                 *num >>= 1;
6986                 *den >>= 1;
6987         }
6988 }
6989
6990 static void compute_m_n(unsigned int m, unsigned int n,
6991                         uint32_t *ret_m, uint32_t *ret_n)
6992 {
6993         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6994         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6995         intel_reduce_m_n_ratio(ret_m, ret_n);
6996 }
6997
6998 void
6999 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
7000                        int pixel_clock, int link_clock,
7001                        struct intel_link_m_n *m_n)
7002 {
7003         m_n->tu = 64;
7004
7005         compute_m_n(bits_per_pixel * pixel_clock,
7006                     link_clock * nlanes * 8,
7007                     &m_n->gmch_m, &m_n->gmch_n);
7008
7009         compute_m_n(pixel_clock, link_clock,
7010                     &m_n->link_m, &m_n->link_n);
7011 }
7012
7013 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
7014 {
7015         if (i915.panel_use_ssc >= 0)
7016                 return i915.panel_use_ssc != 0;
7017         return dev_priv->vbt.lvds_use_ssc
7018                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
7019 }
7020
7021 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
7022 {
7023         return (1 << dpll->n) << 16 | dpll->m2;
7024 }
7025
7026 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
7027 {
7028         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
7029 }
7030
7031 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
7032                                      struct intel_crtc_state *crtc_state,
7033                                      intel_clock_t *reduced_clock)
7034 {
7035         struct drm_device *dev = crtc->base.dev;
7036         u32 fp, fp2 = 0;
7037
7038         if (IS_PINEVIEW(dev)) {
7039                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
7040                 if (reduced_clock)
7041                         fp2 = pnv_dpll_compute_fp(reduced_clock);
7042         } else {
7043                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
7044                 if (reduced_clock)
7045                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
7046         }
7047
7048         crtc_state->dpll_hw_state.fp0 = fp;
7049
7050         crtc->lowfreq_avail = false;
7051         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7052             reduced_clock) {
7053                 crtc_state->dpll_hw_state.fp1 = fp2;
7054                 crtc->lowfreq_avail = true;
7055         } else {
7056                 crtc_state->dpll_hw_state.fp1 = fp;
7057         }
7058 }
7059
7060 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
7061                 pipe)
7062 {
7063         u32 reg_val;
7064
7065         /*
7066          * PLLB opamp always calibrates to max value of 0x3f, force enable it
7067          * and set it to a reasonable value instead.
7068          */
7069         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7070         reg_val &= 0xffffff00;
7071         reg_val |= 0x00000030;
7072         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7073
7074         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7075         reg_val &= 0x8cffffff;
7076         reg_val = 0x8c000000;
7077         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7078
7079         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
7080         reg_val &= 0xffffff00;
7081         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
7082
7083         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
7084         reg_val &= 0x00ffffff;
7085         reg_val |= 0xb0000000;
7086         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
7087 }
7088
7089 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
7090                                          struct intel_link_m_n *m_n)
7091 {
7092         struct drm_device *dev = crtc->base.dev;
7093         struct drm_i915_private *dev_priv = dev->dev_private;
7094         int pipe = crtc->pipe;
7095
7096         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7097         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
7098         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
7099         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
7100 }
7101
7102 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
7103                                          struct intel_link_m_n *m_n,
7104                                          struct intel_link_m_n *m2_n2)
7105 {
7106         struct drm_device *dev = crtc->base.dev;
7107         struct drm_i915_private *dev_priv = dev->dev_private;
7108         int pipe = crtc->pipe;
7109         enum transcoder transcoder = crtc->config->cpu_transcoder;
7110
7111         if (INTEL_INFO(dev)->gen >= 5) {
7112                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
7113                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
7114                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
7115                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
7116                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
7117                  * for gen < 8) and if DRRS is supported (to make sure the
7118                  * registers are not unnecessarily accessed).
7119                  */
7120                 if (m2_n2 && (IS_CHERRYVIEW(dev) || INTEL_INFO(dev)->gen < 8) &&
7121                         crtc->config->has_drrs) {
7122                         I915_WRITE(PIPE_DATA_M2(transcoder),
7123                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
7124                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
7125                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
7126                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
7127                 }
7128         } else {
7129                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
7130                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
7131                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
7132                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
7133         }
7134 }
7135
7136 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
7137 {
7138         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
7139
7140         if (m_n == M1_N1) {
7141                 dp_m_n = &crtc->config->dp_m_n;
7142                 dp_m2_n2 = &crtc->config->dp_m2_n2;
7143         } else if (m_n == M2_N2) {
7144
7145                 /*
7146                  * M2_N2 registers are not supported. Hence m2_n2 divider value
7147                  * needs to be programmed into M1_N1.
7148                  */
7149                 dp_m_n = &crtc->config->dp_m2_n2;
7150         } else {
7151                 DRM_ERROR("Unsupported divider value\n");
7152                 return;
7153         }
7154
7155         if (crtc->config->has_pch_encoder)
7156                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
7157         else
7158                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
7159 }
7160
7161 static void vlv_compute_dpll(struct intel_crtc *crtc,
7162                              struct intel_crtc_state *pipe_config)
7163 {
7164         u32 dpll, dpll_md;
7165
7166         /*
7167          * Enable DPIO clock input. We should never disable the reference
7168          * clock for pipe B, since VGA hotplug / manual detection depends
7169          * on it.
7170          */
7171         dpll = DPLL_EXT_BUFFER_ENABLE_VLV | DPLL_REF_CLK_ENABLE_VLV |
7172                 DPLL_VGA_MODE_DIS | DPLL_INTEGRATED_REF_CLK_VLV;
7173         /* We should never disable this, set it here for state tracking */
7174         if (crtc->pipe == PIPE_B)
7175                 dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7176         dpll |= DPLL_VCO_ENABLE;
7177         pipe_config->dpll_hw_state.dpll = dpll;
7178
7179         dpll_md = (pipe_config->pixel_multiplier - 1)
7180                 << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7181         pipe_config->dpll_hw_state.dpll_md = dpll_md;
7182 }
7183
7184 static void vlv_prepare_pll(struct intel_crtc *crtc,
7185                             const struct intel_crtc_state *pipe_config)
7186 {
7187         struct drm_device *dev = crtc->base.dev;
7188         struct drm_i915_private *dev_priv = dev->dev_private;
7189         int pipe = crtc->pipe;
7190         u32 mdiv;
7191         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7192         u32 coreclk, reg_val;
7193
7194         mutex_lock(&dev_priv->sb_lock);
7195
7196         bestn = pipe_config->dpll.n;
7197         bestm1 = pipe_config->dpll.m1;
7198         bestm2 = pipe_config->dpll.m2;
7199         bestp1 = pipe_config->dpll.p1;
7200         bestp2 = pipe_config->dpll.p2;
7201
7202         /* See eDP HDMI DPIO driver vbios notes doc */
7203
7204         /* PLL B needs special handling */
7205         if (pipe == PIPE_B)
7206                 vlv_pllb_recal_opamp(dev_priv, pipe);
7207
7208         /* Set up Tx target for periodic Rcomp update */
7209         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7210
7211         /* Disable target IRef on PLL */
7212         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7213         reg_val &= 0x00ffffff;
7214         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7215
7216         /* Disable fast lock */
7217         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7218
7219         /* Set idtafcrecal before PLL is enabled */
7220         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7221         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7222         mdiv |= ((bestn << DPIO_N_SHIFT));
7223         mdiv |= (1 << DPIO_K_SHIFT);
7224
7225         /*
7226          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7227          * but we don't support that).
7228          * Note: don't use the DAC post divider as it seems unstable.
7229          */
7230         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7231         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7232
7233         mdiv |= DPIO_ENABLE_CALIBRATION;
7234         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7235
7236         /* Set HBR and RBR LPF coefficients */
7237         if (pipe_config->port_clock == 162000 ||
7238             intel_pipe_has_type(crtc, INTEL_OUTPUT_ANALOG) ||
7239             intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI))
7240                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7241                                  0x009f0003);
7242         else
7243                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7244                                  0x00d0000f);
7245
7246         if (pipe_config->has_dp_encoder) {
7247                 /* Use SSC source */
7248                 if (pipe == PIPE_A)
7249                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7250                                          0x0df40000);
7251                 else
7252                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7253                                          0x0df70000);
7254         } else { /* HDMI or VGA */
7255                 /* Use bend source */
7256                 if (pipe == PIPE_A)
7257                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7258                                          0x0df70000);
7259                 else
7260                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7261                                          0x0df40000);
7262         }
7263
7264         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7265         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7266         if (intel_pipe_has_type(crtc, INTEL_OUTPUT_DISPLAYPORT) ||
7267             intel_pipe_has_type(crtc, INTEL_OUTPUT_EDP))
7268                 coreclk |= 0x01000000;
7269         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7270
7271         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7272         mutex_unlock(&dev_priv->sb_lock);
7273 }
7274
7275 static void chv_compute_dpll(struct intel_crtc *crtc,
7276                              struct intel_crtc_state *pipe_config)
7277 {
7278         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7279                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS |
7280                 DPLL_VCO_ENABLE;
7281         if (crtc->pipe != PIPE_A)
7282                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7283
7284         pipe_config->dpll_hw_state.dpll_md =
7285                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7286 }
7287
7288 static void chv_prepare_pll(struct intel_crtc *crtc,
7289                             const struct intel_crtc_state *pipe_config)
7290 {
7291         struct drm_device *dev = crtc->base.dev;
7292         struct drm_i915_private *dev_priv = dev->dev_private;
7293         int pipe = crtc->pipe;
7294         i915_reg_t dpll_reg = DPLL(crtc->pipe);
7295         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7296         u32 loopfilter, tribuf_calcntr;
7297         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7298         u32 dpio_val;
7299         int vco;
7300
7301         bestn = pipe_config->dpll.n;
7302         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7303         bestm1 = pipe_config->dpll.m1;
7304         bestm2 = pipe_config->dpll.m2 >> 22;
7305         bestp1 = pipe_config->dpll.p1;
7306         bestp2 = pipe_config->dpll.p2;
7307         vco = pipe_config->dpll.vco;
7308         dpio_val = 0;
7309         loopfilter = 0;
7310
7311         /*
7312          * Enable Refclk and SSC
7313          */
7314         I915_WRITE(dpll_reg,
7315                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7316
7317         mutex_lock(&dev_priv->sb_lock);
7318
7319         /* p1 and p2 divider */
7320         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7321                         5 << DPIO_CHV_S1_DIV_SHIFT |
7322                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7323                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7324                         1 << DPIO_CHV_K_DIV_SHIFT);
7325
7326         /* Feedback post-divider - m2 */
7327         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7328
7329         /* Feedback refclk divider - n and m1 */
7330         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7331                         DPIO_CHV_M1_DIV_BY_2 |
7332                         1 << DPIO_CHV_N_DIV_SHIFT);
7333
7334         /* M2 fraction division */
7335         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7336
7337         /* M2 fraction division enable */
7338         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7339         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7340         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7341         if (bestm2_frac)
7342                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7343         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7344
7345         /* Program digital lock detect threshold */
7346         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7347         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7348                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7349         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7350         if (!bestm2_frac)
7351                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7352         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7353
7354         /* Loop filter */
7355         if (vco == 5400000) {
7356                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7357                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7358                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7359                 tribuf_calcntr = 0x9;
7360         } else if (vco <= 6200000) {
7361                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7362                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7363                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7364                 tribuf_calcntr = 0x9;
7365         } else if (vco <= 6480000) {
7366                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7367                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7368                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7369                 tribuf_calcntr = 0x8;
7370         } else {
7371                 /* Not supported. Apply the same limits as in the max case */
7372                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7373                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7374                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7375                 tribuf_calcntr = 0;
7376         }
7377         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7378
7379         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7380         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7381         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7382         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7383
7384         /* AFC Recal */
7385         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7386                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7387                         DPIO_AFC_RECAL);
7388
7389         mutex_unlock(&dev_priv->sb_lock);
7390 }
7391
7392 /**
7393  * vlv_force_pll_on - forcibly enable just the PLL
7394  * @dev_priv: i915 private structure
7395  * @pipe: pipe PLL to enable
7396  * @dpll: PLL configuration
7397  *
7398  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7399  * in cases where we need the PLL enabled even when @pipe is not going to
7400  * be enabled.
7401  */
7402 int vlv_force_pll_on(struct drm_device *dev, enum pipe pipe,
7403                      const struct dpll *dpll)
7404 {
7405         struct intel_crtc *crtc =
7406                 to_intel_crtc(intel_get_crtc_for_pipe(dev, pipe));
7407         struct intel_crtc_state *pipe_config;
7408
7409         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7410         if (!pipe_config)
7411                 return -ENOMEM;
7412
7413         pipe_config->base.crtc = &crtc->base;
7414         pipe_config->pixel_multiplier = 1;
7415         pipe_config->dpll = *dpll;
7416
7417         if (IS_CHERRYVIEW(dev)) {
7418                 chv_compute_dpll(crtc, pipe_config);
7419                 chv_prepare_pll(crtc, pipe_config);
7420                 chv_enable_pll(crtc, pipe_config);
7421         } else {
7422                 vlv_compute_dpll(crtc, pipe_config);
7423                 vlv_prepare_pll(crtc, pipe_config);
7424                 vlv_enable_pll(crtc, pipe_config);
7425         }
7426
7427         kfree(pipe_config);
7428
7429         return 0;
7430 }
7431
7432 /**
7433  * vlv_force_pll_off - forcibly disable just the PLL
7434  * @dev_priv: i915 private structure
7435  * @pipe: pipe PLL to disable
7436  *
7437  * Disable the PLL for @pipe. To be used in cases where we need
7438  * the PLL enabled even when @pipe is not going to be enabled.
7439  */
7440 void vlv_force_pll_off(struct drm_device *dev, enum pipe pipe)
7441 {
7442         if (IS_CHERRYVIEW(dev))
7443                 chv_disable_pll(to_i915(dev), pipe);
7444         else
7445                 vlv_disable_pll(to_i915(dev), pipe);
7446 }
7447
7448 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7449                               struct intel_crtc_state *crtc_state,
7450                               intel_clock_t *reduced_clock)
7451 {
7452         struct drm_device *dev = crtc->base.dev;
7453         struct drm_i915_private *dev_priv = dev->dev_private;
7454         u32 dpll;
7455         bool is_sdvo;
7456         struct dpll *clock = &crtc_state->dpll;
7457
7458         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7459
7460         is_sdvo = intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7461                 intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI);
7462
7463         dpll = DPLL_VGA_MODE_DIS;
7464
7465         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS))
7466                 dpll |= DPLLB_MODE_LVDS;
7467         else
7468                 dpll |= DPLLB_MODE_DAC_SERIAL;
7469
7470         if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
7471                 dpll |= (crtc_state->pixel_multiplier - 1)
7472                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7473         }
7474
7475         if (is_sdvo)
7476                 dpll |= DPLL_SDVO_HIGH_SPEED;
7477
7478         if (crtc_state->has_dp_encoder)
7479                 dpll |= DPLL_SDVO_HIGH_SPEED;
7480
7481         /* compute bitmask from p1 value */
7482         if (IS_PINEVIEW(dev))
7483                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7484         else {
7485                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7486                 if (IS_G4X(dev) && reduced_clock)
7487                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7488         }
7489         switch (clock->p2) {
7490         case 5:
7491                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7492                 break;
7493         case 7:
7494                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7495                 break;
7496         case 10:
7497                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7498                 break;
7499         case 14:
7500                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7501                 break;
7502         }
7503         if (INTEL_INFO(dev)->gen >= 4)
7504                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7505
7506         if (crtc_state->sdvo_tv_clock)
7507                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7508         else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7509                  intel_panel_use_ssc(dev_priv))
7510                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7511         else
7512                 dpll |= PLL_REF_INPUT_DREFCLK;
7513
7514         dpll |= DPLL_VCO_ENABLE;
7515         crtc_state->dpll_hw_state.dpll = dpll;
7516
7517         if (INTEL_INFO(dev)->gen >= 4) {
7518                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7519                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7520                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7521         }
7522 }
7523
7524 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7525                               struct intel_crtc_state *crtc_state,
7526                               intel_clock_t *reduced_clock)
7527 {
7528         struct drm_device *dev = crtc->base.dev;
7529         struct drm_i915_private *dev_priv = dev->dev_private;
7530         u32 dpll;
7531         struct dpll *clock = &crtc_state->dpll;
7532
7533         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7534
7535         dpll = DPLL_VGA_MODE_DIS;
7536
7537         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7538                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7539         } else {
7540                 if (clock->p1 == 2)
7541                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7542                 else
7543                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7544                 if (clock->p2 == 4)
7545                         dpll |= PLL_P2_DIVIDE_BY_4;
7546         }
7547
7548         if (!IS_I830(dev) && intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO))
7549                 dpll |= DPLL_DVO_2X_MODE;
7550
7551         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7552             intel_panel_use_ssc(dev_priv))
7553                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7554         else
7555                 dpll |= PLL_REF_INPUT_DREFCLK;
7556
7557         dpll |= DPLL_VCO_ENABLE;
7558         crtc_state->dpll_hw_state.dpll = dpll;
7559 }
7560
7561 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7562 {
7563         struct drm_device *dev = intel_crtc->base.dev;
7564         struct drm_i915_private *dev_priv = dev->dev_private;
7565         enum pipe pipe = intel_crtc->pipe;
7566         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7567         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7568         uint32_t crtc_vtotal, crtc_vblank_end;
7569         int vsyncshift = 0;
7570
7571         /* We need to be careful not to changed the adjusted mode, for otherwise
7572          * the hw state checker will get angry at the mismatch. */
7573         crtc_vtotal = adjusted_mode->crtc_vtotal;
7574         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7575
7576         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7577                 /* the chip adds 2 halflines automatically */
7578                 crtc_vtotal -= 1;
7579                 crtc_vblank_end -= 1;
7580
7581                 if (intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7582                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7583                 else
7584                         vsyncshift = adjusted_mode->crtc_hsync_start -
7585                                 adjusted_mode->crtc_htotal / 2;
7586                 if (vsyncshift < 0)
7587                         vsyncshift += adjusted_mode->crtc_htotal;
7588         }
7589
7590         if (INTEL_INFO(dev)->gen > 3)
7591                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7592
7593         I915_WRITE(HTOTAL(cpu_transcoder),
7594                    (adjusted_mode->crtc_hdisplay - 1) |
7595                    ((adjusted_mode->crtc_htotal - 1) << 16));
7596         I915_WRITE(HBLANK(cpu_transcoder),
7597                    (adjusted_mode->crtc_hblank_start - 1) |
7598                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7599         I915_WRITE(HSYNC(cpu_transcoder),
7600                    (adjusted_mode->crtc_hsync_start - 1) |
7601                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7602
7603         I915_WRITE(VTOTAL(cpu_transcoder),
7604                    (adjusted_mode->crtc_vdisplay - 1) |
7605                    ((crtc_vtotal - 1) << 16));
7606         I915_WRITE(VBLANK(cpu_transcoder),
7607                    (adjusted_mode->crtc_vblank_start - 1) |
7608                    ((crtc_vblank_end - 1) << 16));
7609         I915_WRITE(VSYNC(cpu_transcoder),
7610                    (adjusted_mode->crtc_vsync_start - 1) |
7611                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7612
7613         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7614          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7615          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7616          * bits. */
7617         if (IS_HASWELL(dev) && cpu_transcoder == TRANSCODER_EDP &&
7618             (pipe == PIPE_B || pipe == PIPE_C))
7619                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7620
7621 }
7622
7623 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7624 {
7625         struct drm_device *dev = intel_crtc->base.dev;
7626         struct drm_i915_private *dev_priv = dev->dev_private;
7627         enum pipe pipe = intel_crtc->pipe;
7628
7629         /* pipesrc controls the size that is scaled from, which should
7630          * always be the user's requested size.
7631          */
7632         I915_WRITE(PIPESRC(pipe),
7633                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7634                    (intel_crtc->config->pipe_src_h - 1));
7635 }
7636
7637 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7638                                    struct intel_crtc_state *pipe_config)
7639 {
7640         struct drm_device *dev = crtc->base.dev;
7641         struct drm_i915_private *dev_priv = dev->dev_private;
7642         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7643         uint32_t tmp;
7644
7645         tmp = I915_READ(HTOTAL(cpu_transcoder));
7646         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7647         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7648         tmp = I915_READ(HBLANK(cpu_transcoder));
7649         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7650         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7651         tmp = I915_READ(HSYNC(cpu_transcoder));
7652         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7653         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7654
7655         tmp = I915_READ(VTOTAL(cpu_transcoder));
7656         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7657         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7658         tmp = I915_READ(VBLANK(cpu_transcoder));
7659         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7660         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7661         tmp = I915_READ(VSYNC(cpu_transcoder));
7662         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7663         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7664
7665         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7666                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7667                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7668                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7669         }
7670 }
7671
7672 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7673                                     struct intel_crtc_state *pipe_config)
7674 {
7675         struct drm_device *dev = crtc->base.dev;
7676         struct drm_i915_private *dev_priv = dev->dev_private;
7677         u32 tmp;
7678
7679         tmp = I915_READ(PIPESRC(crtc->pipe));
7680         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7681         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7682
7683         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7684         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7685 }
7686
7687 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7688                                  struct intel_crtc_state *pipe_config)
7689 {
7690         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7691         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7692         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7693         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7694
7695         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7696         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7697         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7698         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7699
7700         mode->flags = pipe_config->base.adjusted_mode.flags;
7701         mode->type = DRM_MODE_TYPE_DRIVER;
7702
7703         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7704         mode->flags |= pipe_config->base.adjusted_mode.flags;
7705
7706         mode->hsync = drm_mode_hsync(mode);
7707         mode->vrefresh = drm_mode_vrefresh(mode);
7708         drm_mode_set_name(mode);
7709 }
7710
7711 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7712 {
7713         struct drm_device *dev = intel_crtc->base.dev;
7714         struct drm_i915_private *dev_priv = dev->dev_private;
7715         uint32_t pipeconf;
7716
7717         pipeconf = 0;
7718
7719         if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
7720             (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
7721                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7722
7723         if (intel_crtc->config->double_wide)
7724                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7725
7726         /* only g4x and later have fancy bpc/dither controls */
7727         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
7728                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7729                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7730                         pipeconf |= PIPECONF_DITHER_EN |
7731                                     PIPECONF_DITHER_TYPE_SP;
7732
7733                 switch (intel_crtc->config->pipe_bpp) {
7734                 case 18:
7735                         pipeconf |= PIPECONF_6BPC;
7736                         break;
7737                 case 24:
7738                         pipeconf |= PIPECONF_8BPC;
7739                         break;
7740                 case 30:
7741                         pipeconf |= PIPECONF_10BPC;
7742                         break;
7743                 default:
7744                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7745                         BUG();
7746                 }
7747         }
7748
7749         if (HAS_PIPE_CXSR(dev)) {
7750                 if (intel_crtc->lowfreq_avail) {
7751                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7752                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7753                 } else {
7754                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7755                 }
7756         }
7757
7758         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7759                 if (INTEL_INFO(dev)->gen < 4 ||
7760                     intel_pipe_has_type(intel_crtc, INTEL_OUTPUT_SDVO))
7761                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7762                 else
7763                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7764         } else
7765                 pipeconf |= PIPECONF_PROGRESSIVE;
7766
7767         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
7768              intel_crtc->config->limited_color_range)
7769                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7770
7771         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7772         POSTING_READ(PIPECONF(intel_crtc->pipe));
7773 }
7774
7775 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7776                                    struct intel_crtc_state *crtc_state)
7777 {
7778         struct drm_device *dev = crtc->base.dev;
7779         struct drm_i915_private *dev_priv = dev->dev_private;
7780         const intel_limit_t *limit;
7781         int refclk = 48000;
7782
7783         memset(&crtc_state->dpll_hw_state, 0,
7784                sizeof(crtc_state->dpll_hw_state));
7785
7786         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7787                 if (intel_panel_use_ssc(dev_priv)) {
7788                         refclk = dev_priv->vbt.lvds_ssc_freq;
7789                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7790                 }
7791
7792                 limit = &intel_limits_i8xx_lvds;
7793         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_DVO)) {
7794                 limit = &intel_limits_i8xx_dvo;
7795         } else {
7796                 limit = &intel_limits_i8xx_dac;
7797         }
7798
7799         if (!crtc_state->clock_set &&
7800             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7801                                  refclk, NULL, &crtc_state->dpll)) {
7802                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7803                 return -EINVAL;
7804         }
7805
7806         i8xx_compute_dpll(crtc, crtc_state, NULL);
7807
7808         return 0;
7809 }
7810
7811 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7812                                   struct intel_crtc_state *crtc_state)
7813 {
7814         struct drm_device *dev = crtc->base.dev;
7815         struct drm_i915_private *dev_priv = dev->dev_private;
7816         const intel_limit_t *limit;
7817         int refclk = 96000;
7818
7819         memset(&crtc_state->dpll_hw_state, 0,
7820                sizeof(crtc_state->dpll_hw_state));
7821
7822         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7823                 if (intel_panel_use_ssc(dev_priv)) {
7824                         refclk = dev_priv->vbt.lvds_ssc_freq;
7825                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7826                 }
7827
7828                 if (intel_is_dual_link_lvds(dev))
7829                         limit = &intel_limits_g4x_dual_channel_lvds;
7830                 else
7831                         limit = &intel_limits_g4x_single_channel_lvds;
7832         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7833                    intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7834                 limit = &intel_limits_g4x_hdmi;
7835         } else if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7836                 limit = &intel_limits_g4x_sdvo;
7837         } else {
7838                 /* The option is for other outputs */
7839                 limit = &intel_limits_i9xx_sdvo;
7840         }
7841
7842         if (!crtc_state->clock_set &&
7843             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7844                                 refclk, NULL, &crtc_state->dpll)) {
7845                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7846                 return -EINVAL;
7847         }
7848
7849         i9xx_compute_dpll(crtc, crtc_state, NULL);
7850
7851         return 0;
7852 }
7853
7854 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7855                                   struct intel_crtc_state *crtc_state)
7856 {
7857         struct drm_device *dev = crtc->base.dev;
7858         struct drm_i915_private *dev_priv = dev->dev_private;
7859         const intel_limit_t *limit;
7860         int refclk = 96000;
7861
7862         memset(&crtc_state->dpll_hw_state, 0,
7863                sizeof(crtc_state->dpll_hw_state));
7864
7865         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7866                 if (intel_panel_use_ssc(dev_priv)) {
7867                         refclk = dev_priv->vbt.lvds_ssc_freq;
7868                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7869                 }
7870
7871                 limit = &intel_limits_pineview_lvds;
7872         } else {
7873                 limit = &intel_limits_pineview_sdvo;
7874         }
7875
7876         if (!crtc_state->clock_set &&
7877             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7878                                 refclk, NULL, &crtc_state->dpll)) {
7879                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7880                 return -EINVAL;
7881         }
7882
7883         i9xx_compute_dpll(crtc, crtc_state, NULL);
7884
7885         return 0;
7886 }
7887
7888 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7889                                    struct intel_crtc_state *crtc_state)
7890 {
7891         struct drm_device *dev = crtc->base.dev;
7892         struct drm_i915_private *dev_priv = dev->dev_private;
7893         const intel_limit_t *limit;
7894         int refclk = 96000;
7895
7896         memset(&crtc_state->dpll_hw_state, 0,
7897                sizeof(crtc_state->dpll_hw_state));
7898
7899         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7900                 if (intel_panel_use_ssc(dev_priv)) {
7901                         refclk = dev_priv->vbt.lvds_ssc_freq;
7902                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7903                 }
7904
7905                 limit = &intel_limits_i9xx_lvds;
7906         } else {
7907                 limit = &intel_limits_i9xx_sdvo;
7908         }
7909
7910         if (!crtc_state->clock_set &&
7911             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7912                                  refclk, NULL, &crtc_state->dpll)) {
7913                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7914                 return -EINVAL;
7915         }
7916
7917         i9xx_compute_dpll(crtc, crtc_state, NULL);
7918
7919         return 0;
7920 }
7921
7922 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7923                                   struct intel_crtc_state *crtc_state)
7924 {
7925         int refclk = 100000;
7926         const intel_limit_t *limit = &intel_limits_chv;
7927
7928         memset(&crtc_state->dpll_hw_state, 0,
7929                sizeof(crtc_state->dpll_hw_state));
7930
7931         if (crtc_state->has_dsi_encoder)
7932                 return 0;
7933
7934         if (!crtc_state->clock_set &&
7935             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7936                                 refclk, NULL, &crtc_state->dpll)) {
7937                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7938                 return -EINVAL;
7939         }
7940
7941         chv_compute_dpll(crtc, crtc_state);
7942
7943         return 0;
7944 }
7945
7946 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7947                                   struct intel_crtc_state *crtc_state)
7948 {
7949         int refclk = 100000;
7950         const intel_limit_t *limit = &intel_limits_vlv;
7951
7952         memset(&crtc_state->dpll_hw_state, 0,
7953                sizeof(crtc_state->dpll_hw_state));
7954
7955         if (crtc_state->has_dsi_encoder)
7956                 return 0;
7957
7958         if (!crtc_state->clock_set &&
7959             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7960                                 refclk, NULL, &crtc_state->dpll)) {
7961                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7962                 return -EINVAL;
7963         }
7964
7965         vlv_compute_dpll(crtc, crtc_state);
7966
7967         return 0;
7968 }
7969
7970 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7971                                  struct intel_crtc_state *pipe_config)
7972 {
7973         struct drm_device *dev = crtc->base.dev;
7974         struct drm_i915_private *dev_priv = dev->dev_private;
7975         uint32_t tmp;
7976
7977         if (INTEL_INFO(dev)->gen <= 3 && (IS_I830(dev) || !IS_MOBILE(dev)))
7978                 return;
7979
7980         tmp = I915_READ(PFIT_CONTROL);
7981         if (!(tmp & PFIT_ENABLE))
7982                 return;
7983
7984         /* Check whether the pfit is attached to our pipe. */
7985         if (INTEL_INFO(dev)->gen < 4) {
7986                 if (crtc->pipe != PIPE_B)
7987                         return;
7988         } else {
7989                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7990                         return;
7991         }
7992
7993         pipe_config->gmch_pfit.control = tmp;
7994         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7995         if (INTEL_INFO(dev)->gen < 5)
7996                 pipe_config->gmch_pfit.lvds_border_bits =
7997                         I915_READ(LVDS) & LVDS_BORDER_ENABLE;
7998 }
7999
8000 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
8001                                struct intel_crtc_state *pipe_config)
8002 {
8003         struct drm_device *dev = crtc->base.dev;
8004         struct drm_i915_private *dev_priv = dev->dev_private;
8005         int pipe = pipe_config->cpu_transcoder;
8006         intel_clock_t clock;
8007         u32 mdiv;
8008         int refclk = 100000;
8009
8010         /* In case of MIPI DPLL will not even be used */
8011         if (!(pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE))
8012                 return;
8013
8014         mutex_lock(&dev_priv->sb_lock);
8015         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
8016         mutex_unlock(&dev_priv->sb_lock);
8017
8018         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
8019         clock.m2 = mdiv & DPIO_M2DIV_MASK;
8020         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
8021         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
8022         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
8023
8024         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
8025 }
8026
8027 static void
8028 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
8029                               struct intel_initial_plane_config *plane_config)
8030 {
8031         struct drm_device *dev = crtc->base.dev;
8032         struct drm_i915_private *dev_priv = dev->dev_private;
8033         u32 val, base, offset;
8034         int pipe = crtc->pipe, plane = crtc->plane;
8035         int fourcc, pixel_format;
8036         unsigned int aligned_height;
8037         struct drm_framebuffer *fb;
8038         struct intel_framebuffer *intel_fb;
8039
8040         val = I915_READ(DSPCNTR(plane));
8041         if (!(val & DISPLAY_PLANE_ENABLE))
8042                 return;
8043
8044         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8045         if (!intel_fb) {
8046                 DRM_DEBUG_KMS("failed to alloc fb\n");
8047                 return;
8048         }
8049
8050         fb = &intel_fb->base;
8051
8052         if (INTEL_INFO(dev)->gen >= 4) {
8053                 if (val & DISPPLANE_TILED) {
8054                         plane_config->tiling = I915_TILING_X;
8055                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
8056                 }
8057         }
8058
8059         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8060         fourcc = i9xx_format_to_fourcc(pixel_format);
8061         fb->pixel_format = fourcc;
8062         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
8063
8064         if (INTEL_INFO(dev)->gen >= 4) {
8065                 if (plane_config->tiling)
8066                         offset = I915_READ(DSPTILEOFF(plane));
8067                 else
8068                         offset = I915_READ(DSPLINOFF(plane));
8069                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
8070         } else {
8071                 base = I915_READ(DSPADDR(plane));
8072         }
8073         plane_config->base = base;
8074
8075         val = I915_READ(PIPESRC(pipe));
8076         fb->width = ((val >> 16) & 0xfff) + 1;
8077         fb->height = ((val >> 0) & 0xfff) + 1;
8078
8079         val = I915_READ(DSPSTRIDE(pipe));
8080         fb->pitches[0] = val & 0xffffffc0;
8081
8082         aligned_height = intel_fb_align_height(dev, fb->height,
8083                                                fb->pixel_format,
8084                                                fb->modifier[0]);
8085
8086         plane_config->size = fb->pitches[0] * aligned_height;
8087
8088         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8089                       pipe_name(pipe), plane, fb->width, fb->height,
8090                       fb->bits_per_pixel, base, fb->pitches[0],
8091                       plane_config->size);
8092
8093         plane_config->fb = intel_fb;
8094 }
8095
8096 static void chv_crtc_clock_get(struct intel_crtc *crtc,
8097                                struct intel_crtc_state *pipe_config)
8098 {
8099         struct drm_device *dev = crtc->base.dev;
8100         struct drm_i915_private *dev_priv = dev->dev_private;
8101         int pipe = pipe_config->cpu_transcoder;
8102         enum dpio_channel port = vlv_pipe_to_channel(pipe);
8103         intel_clock_t clock;
8104         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
8105         int refclk = 100000;
8106
8107         mutex_lock(&dev_priv->sb_lock);
8108         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
8109         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
8110         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
8111         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
8112         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
8113         mutex_unlock(&dev_priv->sb_lock);
8114
8115         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
8116         clock.m2 = (pll_dw0 & 0xff) << 22;
8117         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
8118                 clock.m2 |= pll_dw2 & 0x3fffff;
8119         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
8120         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
8121         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
8122
8123         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
8124 }
8125
8126 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8127                                  struct intel_crtc_state *pipe_config)
8128 {
8129         struct drm_device *dev = crtc->base.dev;
8130         struct drm_i915_private *dev_priv = dev->dev_private;
8131         enum intel_display_power_domain power_domain;
8132         uint32_t tmp;
8133         bool ret;
8134
8135         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8136         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8137                 return false;
8138
8139         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8140         pipe_config->shared_dpll = NULL;
8141
8142         ret = false;
8143
8144         tmp = I915_READ(PIPECONF(crtc->pipe));
8145         if (!(tmp & PIPECONF_ENABLE))
8146                 goto out;
8147
8148         if (IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
8149                 switch (tmp & PIPECONF_BPC_MASK) {
8150                 case PIPECONF_6BPC:
8151                         pipe_config->pipe_bpp = 18;
8152                         break;
8153                 case PIPECONF_8BPC:
8154                         pipe_config->pipe_bpp = 24;
8155                         break;
8156                 case PIPECONF_10BPC:
8157                         pipe_config->pipe_bpp = 30;
8158                         break;
8159                 default:
8160                         break;
8161                 }
8162         }
8163
8164         if ((IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) &&
8165             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8166                 pipe_config->limited_color_range = true;
8167
8168         if (INTEL_INFO(dev)->gen < 4)
8169                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8170
8171         intel_get_pipe_timings(crtc, pipe_config);
8172         intel_get_pipe_src_size(crtc, pipe_config);
8173
8174         i9xx_get_pfit_config(crtc, pipe_config);
8175
8176         if (INTEL_INFO(dev)->gen >= 4) {
8177                 tmp = I915_READ(DPLL_MD(crtc->pipe));
8178                 pipe_config->pixel_multiplier =
8179                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8180                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8181                 pipe_config->dpll_hw_state.dpll_md = tmp;
8182         } else if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) {
8183                 tmp = I915_READ(DPLL(crtc->pipe));
8184                 pipe_config->pixel_multiplier =
8185                         ((tmp & SDVO_MULTIPLIER_MASK)
8186                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8187         } else {
8188                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8189                  * port and will be fixed up in the encoder->get_config
8190                  * function. */
8191                 pipe_config->pixel_multiplier = 1;
8192         }
8193         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8194         if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
8195                 /*
8196                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8197                  * on 830. Filter it out here so that we don't
8198                  * report errors due to that.
8199                  */
8200                 if (IS_I830(dev))
8201                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8202
8203                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8204                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8205         } else {
8206                 /* Mask out read-only status bits. */
8207                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8208                                                      DPLL_PORTC_READY_MASK |
8209                                                      DPLL_PORTB_READY_MASK);
8210         }
8211
8212         if (IS_CHERRYVIEW(dev))
8213                 chv_crtc_clock_get(crtc, pipe_config);
8214         else if (IS_VALLEYVIEW(dev))
8215                 vlv_crtc_clock_get(crtc, pipe_config);
8216         else
8217                 i9xx_crtc_clock_get(crtc, pipe_config);
8218
8219         /*
8220          * Normally the dotclock is filled in by the encoder .get_config()
8221          * but in case the pipe is enabled w/o any ports we need a sane
8222          * default.
8223          */
8224         pipe_config->base.adjusted_mode.crtc_clock =
8225                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8226
8227         ret = true;
8228
8229 out:
8230         intel_display_power_put(dev_priv, power_domain);
8231
8232         return ret;
8233 }
8234
8235 static void ironlake_init_pch_refclk(struct drm_device *dev)
8236 {
8237         struct drm_i915_private *dev_priv = dev->dev_private;
8238         struct intel_encoder *encoder;
8239         u32 val, final;
8240         bool has_lvds = false;
8241         bool has_cpu_edp = false;
8242         bool has_panel = false;
8243         bool has_ck505 = false;
8244         bool can_ssc = false;
8245
8246         /* We need to take the global config into account */
8247         for_each_intel_encoder(dev, encoder) {
8248                 switch (encoder->type) {
8249                 case INTEL_OUTPUT_LVDS:
8250                         has_panel = true;
8251                         has_lvds = true;
8252                         break;
8253                 case INTEL_OUTPUT_EDP:
8254                         has_panel = true;
8255                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
8256                                 has_cpu_edp = true;
8257                         break;
8258                 default:
8259                         break;
8260                 }
8261         }
8262
8263         if (HAS_PCH_IBX(dev)) {
8264                 has_ck505 = dev_priv->vbt.display_clock_mode;
8265                 can_ssc = has_ck505;
8266         } else {
8267                 has_ck505 = false;
8268                 can_ssc = true;
8269         }
8270
8271         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d\n",
8272                       has_panel, has_lvds, has_ck505);
8273
8274         /* Ironlake: try to setup display ref clock before DPLL
8275          * enabling. This is only under driver's control after
8276          * PCH B stepping, previous chipset stepping should be
8277          * ignoring this setting.
8278          */
8279         val = I915_READ(PCH_DREF_CONTROL);
8280
8281         /* As we must carefully and slowly disable/enable each source in turn,
8282          * compute the final state we want first and check if we need to
8283          * make any changes at all.
8284          */
8285         final = val;
8286         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8287         if (has_ck505)
8288                 final |= DREF_NONSPREAD_CK505_ENABLE;
8289         else
8290                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8291
8292         final &= ~DREF_SSC_SOURCE_MASK;
8293         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8294         final &= ~DREF_SSC1_ENABLE;
8295
8296         if (has_panel) {
8297                 final |= DREF_SSC_SOURCE_ENABLE;
8298
8299                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8300                         final |= DREF_SSC1_ENABLE;
8301
8302                 if (has_cpu_edp) {
8303                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8304                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8305                         else
8306                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8307                 } else
8308                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8309         } else {
8310                 final |= DREF_SSC_SOURCE_DISABLE;
8311                 final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8312         }
8313
8314         if (final == val)
8315                 return;
8316
8317         /* Always enable nonspread source */
8318         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8319
8320         if (has_ck505)
8321                 val |= DREF_NONSPREAD_CK505_ENABLE;
8322         else
8323                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8324
8325         if (has_panel) {
8326                 val &= ~DREF_SSC_SOURCE_MASK;
8327                 val |= DREF_SSC_SOURCE_ENABLE;
8328
8329                 /* SSC must be turned on before enabling the CPU output  */
8330                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8331                         DRM_DEBUG_KMS("Using SSC on panel\n");
8332                         val |= DREF_SSC1_ENABLE;
8333                 } else
8334                         val &= ~DREF_SSC1_ENABLE;
8335
8336                 /* Get SSC going before enabling the outputs */
8337                 I915_WRITE(PCH_DREF_CONTROL, val);
8338                 POSTING_READ(PCH_DREF_CONTROL);
8339                 udelay(200);
8340
8341                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8342
8343                 /* Enable CPU source on CPU attached eDP */
8344                 if (has_cpu_edp) {
8345                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8346                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8347                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8348                         } else
8349                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8350                 } else
8351                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8352
8353                 I915_WRITE(PCH_DREF_CONTROL, val);
8354                 POSTING_READ(PCH_DREF_CONTROL);
8355                 udelay(200);
8356         } else {
8357                 DRM_DEBUG_KMS("Disabling SSC entirely\n");
8358
8359                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8360
8361                 /* Turn off CPU output */
8362                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8363
8364                 I915_WRITE(PCH_DREF_CONTROL, val);
8365                 POSTING_READ(PCH_DREF_CONTROL);
8366                 udelay(200);
8367
8368                 /* Turn off the SSC source */
8369                 val &= ~DREF_SSC_SOURCE_MASK;
8370                 val |= DREF_SSC_SOURCE_DISABLE;
8371
8372                 /* Turn off SSC1 */
8373                 val &= ~DREF_SSC1_ENABLE;
8374
8375                 I915_WRITE(PCH_DREF_CONTROL, val);
8376                 POSTING_READ(PCH_DREF_CONTROL);
8377                 udelay(200);
8378         }
8379
8380         BUG_ON(val != final);
8381 }
8382
8383 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8384 {
8385         uint32_t tmp;
8386
8387         tmp = I915_READ(SOUTH_CHICKEN2);
8388         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8389         I915_WRITE(SOUTH_CHICKEN2, tmp);
8390
8391         if (wait_for_atomic_us(I915_READ(SOUTH_CHICKEN2) &
8392                                FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8393                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8394
8395         tmp = I915_READ(SOUTH_CHICKEN2);
8396         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8397         I915_WRITE(SOUTH_CHICKEN2, tmp);
8398
8399         if (wait_for_atomic_us((I915_READ(SOUTH_CHICKEN2) &
8400                                 FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8401                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8402 }
8403
8404 /* WaMPhyProgramming:hsw */
8405 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8406 {
8407         uint32_t tmp;
8408
8409         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8410         tmp &= ~(0xFF << 24);
8411         tmp |= (0x12 << 24);
8412         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8413
8414         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8415         tmp |= (1 << 11);
8416         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8417
8418         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8419         tmp |= (1 << 11);
8420         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8421
8422         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8423         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8424         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8425
8426         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8427         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8428         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8429
8430         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8431         tmp &= ~(7 << 13);
8432         tmp |= (5 << 13);
8433         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8434
8435         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8436         tmp &= ~(7 << 13);
8437         tmp |= (5 << 13);
8438         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8439
8440         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8441         tmp &= ~0xFF;
8442         tmp |= 0x1C;
8443         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8444
8445         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8446         tmp &= ~0xFF;
8447         tmp |= 0x1C;
8448         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8449
8450         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8451         tmp &= ~(0xFF << 16);
8452         tmp |= (0x1C << 16);
8453         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8454
8455         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8456         tmp &= ~(0xFF << 16);
8457         tmp |= (0x1C << 16);
8458         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8459
8460         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8461         tmp |= (1 << 27);
8462         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8463
8464         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8465         tmp |= (1 << 27);
8466         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8467
8468         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8469         tmp &= ~(0xF << 28);
8470         tmp |= (4 << 28);
8471         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8472
8473         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8474         tmp &= ~(0xF << 28);
8475         tmp |= (4 << 28);
8476         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8477 }
8478
8479 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8480  * Programming" based on the parameters passed:
8481  * - Sequence to enable CLKOUT_DP
8482  * - Sequence to enable CLKOUT_DP without spread
8483  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8484  */
8485 static void lpt_enable_clkout_dp(struct drm_device *dev, bool with_spread,
8486                                  bool with_fdi)
8487 {
8488         struct drm_i915_private *dev_priv = dev->dev_private;
8489         uint32_t reg, tmp;
8490
8491         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8492                 with_spread = true;
8493         if (WARN(HAS_PCH_LPT_LP(dev) && with_fdi, "LP PCH doesn't have FDI\n"))
8494                 with_fdi = false;
8495
8496         mutex_lock(&dev_priv->sb_lock);
8497
8498         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8499         tmp &= ~SBI_SSCCTL_DISABLE;
8500         tmp |= SBI_SSCCTL_PATHALT;
8501         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8502
8503         udelay(24);
8504
8505         if (with_spread) {
8506                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8507                 tmp &= ~SBI_SSCCTL_PATHALT;
8508                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8509
8510                 if (with_fdi) {
8511                         lpt_reset_fdi_mphy(dev_priv);
8512                         lpt_program_fdi_mphy(dev_priv);
8513                 }
8514         }
8515
8516         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8517         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8518         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8519         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8520
8521         mutex_unlock(&dev_priv->sb_lock);
8522 }
8523
8524 /* Sequence to disable CLKOUT_DP */
8525 static void lpt_disable_clkout_dp(struct drm_device *dev)
8526 {
8527         struct drm_i915_private *dev_priv = dev->dev_private;
8528         uint32_t reg, tmp;
8529
8530         mutex_lock(&dev_priv->sb_lock);
8531
8532         reg = HAS_PCH_LPT_LP(dev) ? SBI_GEN0 : SBI_DBUFF0;
8533         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8534         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8535         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8536
8537         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8538         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8539                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8540                         tmp |= SBI_SSCCTL_PATHALT;
8541                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8542                         udelay(32);
8543                 }
8544                 tmp |= SBI_SSCCTL_DISABLE;
8545                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8546         }
8547
8548         mutex_unlock(&dev_priv->sb_lock);
8549 }
8550
8551 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8552
8553 static const uint16_t sscdivintphase[] = {
8554         [BEND_IDX( 50)] = 0x3B23,
8555         [BEND_IDX( 45)] = 0x3B23,
8556         [BEND_IDX( 40)] = 0x3C23,
8557         [BEND_IDX( 35)] = 0x3C23,
8558         [BEND_IDX( 30)] = 0x3D23,
8559         [BEND_IDX( 25)] = 0x3D23,
8560         [BEND_IDX( 20)] = 0x3E23,
8561         [BEND_IDX( 15)] = 0x3E23,
8562         [BEND_IDX( 10)] = 0x3F23,
8563         [BEND_IDX(  5)] = 0x3F23,
8564         [BEND_IDX(  0)] = 0x0025,
8565         [BEND_IDX( -5)] = 0x0025,
8566         [BEND_IDX(-10)] = 0x0125,
8567         [BEND_IDX(-15)] = 0x0125,
8568         [BEND_IDX(-20)] = 0x0225,
8569         [BEND_IDX(-25)] = 0x0225,
8570         [BEND_IDX(-30)] = 0x0325,
8571         [BEND_IDX(-35)] = 0x0325,
8572         [BEND_IDX(-40)] = 0x0425,
8573         [BEND_IDX(-45)] = 0x0425,
8574         [BEND_IDX(-50)] = 0x0525,
8575 };
8576
8577 /*
8578  * Bend CLKOUT_DP
8579  * steps -50 to 50 inclusive, in steps of 5
8580  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8581  * change in clock period = -(steps / 10) * 5.787 ps
8582  */
8583 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8584 {
8585         uint32_t tmp;
8586         int idx = BEND_IDX(steps);
8587
8588         if (WARN_ON(steps % 5 != 0))
8589                 return;
8590
8591         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8592                 return;
8593
8594         mutex_lock(&dev_priv->sb_lock);
8595
8596         if (steps % 10 != 0)
8597                 tmp = 0xAAAAAAAB;
8598         else
8599                 tmp = 0x00000000;
8600         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8601
8602         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8603         tmp &= 0xffff0000;
8604         tmp |= sscdivintphase[idx];
8605         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8606
8607         mutex_unlock(&dev_priv->sb_lock);
8608 }
8609
8610 #undef BEND_IDX
8611
8612 static void lpt_init_pch_refclk(struct drm_device *dev)
8613 {
8614         struct intel_encoder *encoder;
8615         bool has_vga = false;
8616
8617         for_each_intel_encoder(dev, encoder) {
8618                 switch (encoder->type) {
8619                 case INTEL_OUTPUT_ANALOG:
8620                         has_vga = true;
8621                         break;
8622                 default:
8623                         break;
8624                 }
8625         }
8626
8627         if (has_vga) {
8628                 lpt_bend_clkout_dp(to_i915(dev), 0);
8629                 lpt_enable_clkout_dp(dev, true, true);
8630         } else {
8631                 lpt_disable_clkout_dp(dev);
8632         }
8633 }
8634
8635 /*
8636  * Initialize reference clocks when the driver loads
8637  */
8638 void intel_init_pch_refclk(struct drm_device *dev)
8639 {
8640         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev))
8641                 ironlake_init_pch_refclk(dev);
8642         else if (HAS_PCH_LPT(dev))
8643                 lpt_init_pch_refclk(dev);
8644 }
8645
8646 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8647 {
8648         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8649         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8650         int pipe = intel_crtc->pipe;
8651         uint32_t val;
8652
8653         val = 0;
8654
8655         switch (intel_crtc->config->pipe_bpp) {
8656         case 18:
8657                 val |= PIPECONF_6BPC;
8658                 break;
8659         case 24:
8660                 val |= PIPECONF_8BPC;
8661                 break;
8662         case 30:
8663                 val |= PIPECONF_10BPC;
8664                 break;
8665         case 36:
8666                 val |= PIPECONF_12BPC;
8667                 break;
8668         default:
8669                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8670                 BUG();
8671         }
8672
8673         if (intel_crtc->config->dither)
8674                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8675
8676         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8677                 val |= PIPECONF_INTERLACED_ILK;
8678         else
8679                 val |= PIPECONF_PROGRESSIVE;
8680
8681         if (intel_crtc->config->limited_color_range)
8682                 val |= PIPECONF_COLOR_RANGE_SELECT;
8683
8684         I915_WRITE(PIPECONF(pipe), val);
8685         POSTING_READ(PIPECONF(pipe));
8686 }
8687
8688 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8689 {
8690         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8691         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8692         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8693         u32 val = 0;
8694
8695         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8696                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8697
8698         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8699                 val |= PIPECONF_INTERLACED_ILK;
8700         else
8701                 val |= PIPECONF_PROGRESSIVE;
8702
8703         I915_WRITE(PIPECONF(cpu_transcoder), val);
8704         POSTING_READ(PIPECONF(cpu_transcoder));
8705 }
8706
8707 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8708 {
8709         struct drm_i915_private *dev_priv = crtc->dev->dev_private;
8710         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8711
8712         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8713                 u32 val = 0;
8714
8715                 switch (intel_crtc->config->pipe_bpp) {
8716                 case 18:
8717                         val |= PIPEMISC_DITHER_6_BPC;
8718                         break;
8719                 case 24:
8720                         val |= PIPEMISC_DITHER_8_BPC;
8721                         break;
8722                 case 30:
8723                         val |= PIPEMISC_DITHER_10_BPC;
8724                         break;
8725                 case 36:
8726                         val |= PIPEMISC_DITHER_12_BPC;
8727                         break;
8728                 default:
8729                         /* Case prevented by pipe_config_set_bpp. */
8730                         BUG();
8731                 }
8732
8733                 if (intel_crtc->config->dither)
8734                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8735
8736                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8737         }
8738 }
8739
8740 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8741 {
8742         /*
8743          * Account for spread spectrum to avoid
8744          * oversubscribing the link. Max center spread
8745          * is 2.5%; use 5% for safety's sake.
8746          */
8747         u32 bps = target_clock * bpp * 21 / 20;
8748         return DIV_ROUND_UP(bps, link_bw * 8);
8749 }
8750
8751 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8752 {
8753         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8754 }
8755
8756 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8757                                   struct intel_crtc_state *crtc_state,
8758                                   intel_clock_t *reduced_clock)
8759 {
8760         struct drm_crtc *crtc = &intel_crtc->base;
8761         struct drm_device *dev = crtc->dev;
8762         struct drm_i915_private *dev_priv = dev->dev_private;
8763         struct drm_atomic_state *state = crtc_state->base.state;
8764         struct drm_connector *connector;
8765         struct drm_connector_state *connector_state;
8766         struct intel_encoder *encoder;
8767         u32 dpll, fp, fp2;
8768         int factor, i;
8769         bool is_lvds = false, is_sdvo = false;
8770
8771         for_each_connector_in_state(state, connector, connector_state, i) {
8772                 if (connector_state->crtc != crtc_state->base.crtc)
8773                         continue;
8774
8775                 encoder = to_intel_encoder(connector_state->best_encoder);
8776
8777                 switch (encoder->type) {
8778                 case INTEL_OUTPUT_LVDS:
8779                         is_lvds = true;
8780                         break;
8781                 case INTEL_OUTPUT_SDVO:
8782                 case INTEL_OUTPUT_HDMI:
8783                         is_sdvo = true;
8784                         break;
8785                 default:
8786                         break;
8787                 }
8788         }
8789
8790         /* Enable autotuning of the PLL clock (if permissible) */
8791         factor = 21;
8792         if (is_lvds) {
8793                 if ((intel_panel_use_ssc(dev_priv) &&
8794                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8795                     (HAS_PCH_IBX(dev) && intel_is_dual_link_lvds(dev)))
8796                         factor = 25;
8797         } else if (crtc_state->sdvo_tv_clock)
8798                 factor = 20;
8799
8800         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8801
8802         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8803                 fp |= FP_CB_TUNE;
8804
8805         if (reduced_clock) {
8806                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8807
8808                 if (reduced_clock->m < factor * reduced_clock->n)
8809                         fp2 |= FP_CB_TUNE;
8810         } else {
8811                 fp2 = fp;
8812         }
8813
8814         dpll = 0;
8815
8816         if (is_lvds)
8817                 dpll |= DPLLB_MODE_LVDS;
8818         else
8819                 dpll |= DPLLB_MODE_DAC_SERIAL;
8820
8821         dpll |= (crtc_state->pixel_multiplier - 1)
8822                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8823
8824         if (is_sdvo)
8825                 dpll |= DPLL_SDVO_HIGH_SPEED;
8826         if (crtc_state->has_dp_encoder)
8827                 dpll |= DPLL_SDVO_HIGH_SPEED;
8828
8829         /* compute bitmask from p1 value */
8830         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8831         /* also FPA1 */
8832         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8833
8834         switch (crtc_state->dpll.p2) {
8835         case 5:
8836                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8837                 break;
8838         case 7:
8839                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8840                 break;
8841         case 10:
8842                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8843                 break;
8844         case 14:
8845                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8846                 break;
8847         }
8848
8849         if (is_lvds && intel_panel_use_ssc(dev_priv))
8850                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8851         else
8852                 dpll |= PLL_REF_INPUT_DREFCLK;
8853
8854         dpll |= DPLL_VCO_ENABLE;
8855
8856         crtc_state->dpll_hw_state.dpll = dpll;
8857         crtc_state->dpll_hw_state.fp0 = fp;
8858         crtc_state->dpll_hw_state.fp1 = fp2;
8859 }
8860
8861 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8862                                        struct intel_crtc_state *crtc_state)
8863 {
8864         struct drm_device *dev = crtc->base.dev;
8865         struct drm_i915_private *dev_priv = dev->dev_private;
8866         intel_clock_t reduced_clock;
8867         bool has_reduced_clock = false;
8868         struct intel_shared_dpll *pll;
8869         const intel_limit_t *limit;
8870         int refclk = 120000;
8871
8872         memset(&crtc_state->dpll_hw_state, 0,
8873                sizeof(crtc_state->dpll_hw_state));
8874
8875         crtc->lowfreq_avail = false;
8876
8877         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8878         if (!crtc_state->has_pch_encoder)
8879                 return 0;
8880
8881         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8882                 if (intel_panel_use_ssc(dev_priv)) {
8883                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8884                                       dev_priv->vbt.lvds_ssc_freq);
8885                         refclk = dev_priv->vbt.lvds_ssc_freq;
8886                 }
8887
8888                 if (intel_is_dual_link_lvds(dev)) {
8889                         if (refclk == 100000)
8890                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8891                         else
8892                                 limit = &intel_limits_ironlake_dual_lvds;
8893                 } else {
8894                         if (refclk == 100000)
8895                                 limit = &intel_limits_ironlake_single_lvds_100m;
8896                         else
8897                                 limit = &intel_limits_ironlake_single_lvds;
8898                 }
8899         } else {
8900                 limit = &intel_limits_ironlake_dac;
8901         }
8902
8903         if (!crtc_state->clock_set &&
8904             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8905                                 refclk, NULL, &crtc_state->dpll)) {
8906                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8907                 return -EINVAL;
8908         }
8909
8910         ironlake_compute_dpll(crtc, crtc_state,
8911                               has_reduced_clock ? &reduced_clock : NULL);
8912
8913         pll = intel_get_shared_dpll(crtc, crtc_state, NULL);
8914         if (pll == NULL) {
8915                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8916                                  pipe_name(crtc->pipe));
8917                 return -EINVAL;
8918         }
8919
8920         if (intel_pipe_will_have_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8921             has_reduced_clock)
8922                 crtc->lowfreq_avail = true;
8923
8924         return 0;
8925 }
8926
8927 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8928                                          struct intel_link_m_n *m_n)
8929 {
8930         struct drm_device *dev = crtc->base.dev;
8931         struct drm_i915_private *dev_priv = dev->dev_private;
8932         enum pipe pipe = crtc->pipe;
8933
8934         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8935         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8936         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8937                 & ~TU_SIZE_MASK;
8938         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8939         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8940                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8941 }
8942
8943 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8944                                          enum transcoder transcoder,
8945                                          struct intel_link_m_n *m_n,
8946                                          struct intel_link_m_n *m2_n2)
8947 {
8948         struct drm_device *dev = crtc->base.dev;
8949         struct drm_i915_private *dev_priv = dev->dev_private;
8950         enum pipe pipe = crtc->pipe;
8951
8952         if (INTEL_INFO(dev)->gen >= 5) {
8953                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8954                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8955                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8956                         & ~TU_SIZE_MASK;
8957                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8958                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8959                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8960                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8961                  * gen < 8) and if DRRS is supported (to make sure the
8962                  * registers are not unnecessarily read).
8963                  */
8964                 if (m2_n2 && INTEL_INFO(dev)->gen < 8 &&
8965                         crtc->config->has_drrs) {
8966                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8967                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8968                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8969                                         & ~TU_SIZE_MASK;
8970                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8971                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8972                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8973                 }
8974         } else {
8975                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8976                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8977                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8978                         & ~TU_SIZE_MASK;
8979                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8980                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8981                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8982         }
8983 }
8984
8985 void intel_dp_get_m_n(struct intel_crtc *crtc,
8986                       struct intel_crtc_state *pipe_config)
8987 {
8988         if (pipe_config->has_pch_encoder)
8989                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8990         else
8991                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8992                                              &pipe_config->dp_m_n,
8993                                              &pipe_config->dp_m2_n2);
8994 }
8995
8996 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8997                                         struct intel_crtc_state *pipe_config)
8998 {
8999         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
9000                                      &pipe_config->fdi_m_n, NULL);
9001 }
9002
9003 static void skylake_get_pfit_config(struct intel_crtc *crtc,
9004                                     struct intel_crtc_state *pipe_config)
9005 {
9006         struct drm_device *dev = crtc->base.dev;
9007         struct drm_i915_private *dev_priv = dev->dev_private;
9008         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
9009         uint32_t ps_ctrl = 0;
9010         int id = -1;
9011         int i;
9012
9013         /* find scaler attached to this pipe */
9014         for (i = 0; i < crtc->num_scalers; i++) {
9015                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
9016                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
9017                         id = i;
9018                         pipe_config->pch_pfit.enabled = true;
9019                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
9020                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
9021                         break;
9022                 }
9023         }
9024
9025         scaler_state->scaler_id = id;
9026         if (id >= 0) {
9027                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
9028         } else {
9029                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
9030         }
9031 }
9032
9033 static void
9034 skylake_get_initial_plane_config(struct intel_crtc *crtc,
9035                                  struct intel_initial_plane_config *plane_config)
9036 {
9037         struct drm_device *dev = crtc->base.dev;
9038         struct drm_i915_private *dev_priv = dev->dev_private;
9039         u32 val, base, offset, stride_mult, tiling;
9040         int pipe = crtc->pipe;
9041         int fourcc, pixel_format;
9042         unsigned int aligned_height;
9043         struct drm_framebuffer *fb;
9044         struct intel_framebuffer *intel_fb;
9045
9046         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9047         if (!intel_fb) {
9048                 DRM_DEBUG_KMS("failed to alloc fb\n");
9049                 return;
9050         }
9051
9052         fb = &intel_fb->base;
9053
9054         val = I915_READ(PLANE_CTL(pipe, 0));
9055         if (!(val & PLANE_CTL_ENABLE))
9056                 goto error;
9057
9058         pixel_format = val & PLANE_CTL_FORMAT_MASK;
9059         fourcc = skl_format_to_fourcc(pixel_format,
9060                                       val & PLANE_CTL_ORDER_RGBX,
9061                                       val & PLANE_CTL_ALPHA_MASK);
9062         fb->pixel_format = fourcc;
9063         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9064
9065         tiling = val & PLANE_CTL_TILED_MASK;
9066         switch (tiling) {
9067         case PLANE_CTL_TILED_LINEAR:
9068                 fb->modifier[0] = DRM_FORMAT_MOD_NONE;
9069                 break;
9070         case PLANE_CTL_TILED_X:
9071                 plane_config->tiling = I915_TILING_X;
9072                 fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9073                 break;
9074         case PLANE_CTL_TILED_Y:
9075                 fb->modifier[0] = I915_FORMAT_MOD_Y_TILED;
9076                 break;
9077         case PLANE_CTL_TILED_YF:
9078                 fb->modifier[0] = I915_FORMAT_MOD_Yf_TILED;
9079                 break;
9080         default:
9081                 MISSING_CASE(tiling);
9082                 goto error;
9083         }
9084
9085         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
9086         plane_config->base = base;
9087
9088         offset = I915_READ(PLANE_OFFSET(pipe, 0));
9089
9090         val = I915_READ(PLANE_SIZE(pipe, 0));
9091         fb->height = ((val >> 16) & 0xfff) + 1;
9092         fb->width = ((val >> 0) & 0x1fff) + 1;
9093
9094         val = I915_READ(PLANE_STRIDE(pipe, 0));
9095         stride_mult = intel_fb_stride_alignment(dev_priv, fb->modifier[0],
9096                                                 fb->pixel_format);
9097         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9098
9099         aligned_height = intel_fb_align_height(dev, fb->height,
9100                                                fb->pixel_format,
9101                                                fb->modifier[0]);
9102
9103         plane_config->size = fb->pitches[0] * aligned_height;
9104
9105         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9106                       pipe_name(pipe), fb->width, fb->height,
9107                       fb->bits_per_pixel, base, fb->pitches[0],
9108                       plane_config->size);
9109
9110         plane_config->fb = intel_fb;
9111         return;
9112
9113 error:
9114         kfree(fb);
9115 }
9116
9117 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9118                                      struct intel_crtc_state *pipe_config)
9119 {
9120         struct drm_device *dev = crtc->base.dev;
9121         struct drm_i915_private *dev_priv = dev->dev_private;
9122         uint32_t tmp;
9123
9124         tmp = I915_READ(PF_CTL(crtc->pipe));
9125
9126         if (tmp & PF_ENABLE) {
9127                 pipe_config->pch_pfit.enabled = true;
9128                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9129                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9130
9131                 /* We currently do not free assignements of panel fitters on
9132                  * ivb/hsw (since we don't use the higher upscaling modes which
9133                  * differentiates them) so just WARN about this case for now. */
9134                 if (IS_GEN7(dev)) {
9135                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9136                                 PF_PIPE_SEL_IVB(crtc->pipe));
9137                 }
9138         }
9139 }
9140
9141 static void
9142 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
9143                                   struct intel_initial_plane_config *plane_config)
9144 {
9145         struct drm_device *dev = crtc->base.dev;
9146         struct drm_i915_private *dev_priv = dev->dev_private;
9147         u32 val, base, offset;
9148         int pipe = crtc->pipe;
9149         int fourcc, pixel_format;
9150         unsigned int aligned_height;
9151         struct drm_framebuffer *fb;
9152         struct intel_framebuffer *intel_fb;
9153
9154         val = I915_READ(DSPCNTR(pipe));
9155         if (!(val & DISPLAY_PLANE_ENABLE))
9156                 return;
9157
9158         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9159         if (!intel_fb) {
9160                 DRM_DEBUG_KMS("failed to alloc fb\n");
9161                 return;
9162         }
9163
9164         fb = &intel_fb->base;
9165
9166         if (INTEL_INFO(dev)->gen >= 4) {
9167                 if (val & DISPPLANE_TILED) {
9168                         plane_config->tiling = I915_TILING_X;
9169                         fb->modifier[0] = I915_FORMAT_MOD_X_TILED;
9170                 }
9171         }
9172
9173         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
9174         fourcc = i9xx_format_to_fourcc(pixel_format);
9175         fb->pixel_format = fourcc;
9176         fb->bits_per_pixel = drm_format_plane_cpp(fourcc, 0) * 8;
9177
9178         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
9179         if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
9180                 offset = I915_READ(DSPOFFSET(pipe));
9181         } else {
9182                 if (plane_config->tiling)
9183                         offset = I915_READ(DSPTILEOFF(pipe));
9184                 else
9185                         offset = I915_READ(DSPLINOFF(pipe));
9186         }
9187         plane_config->base = base;
9188
9189         val = I915_READ(PIPESRC(pipe));
9190         fb->width = ((val >> 16) & 0xfff) + 1;
9191         fb->height = ((val >> 0) & 0xfff) + 1;
9192
9193         val = I915_READ(DSPSTRIDE(pipe));
9194         fb->pitches[0] = val & 0xffffffc0;
9195
9196         aligned_height = intel_fb_align_height(dev, fb->height,
9197                                                fb->pixel_format,
9198                                                fb->modifier[0]);
9199
9200         plane_config->size = fb->pitches[0] * aligned_height;
9201
9202         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9203                       pipe_name(pipe), fb->width, fb->height,
9204                       fb->bits_per_pixel, base, fb->pitches[0],
9205                       plane_config->size);
9206
9207         plane_config->fb = intel_fb;
9208 }
9209
9210 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9211                                      struct intel_crtc_state *pipe_config)
9212 {
9213         struct drm_device *dev = crtc->base.dev;
9214         struct drm_i915_private *dev_priv = dev->dev_private;
9215         enum intel_display_power_domain power_domain;
9216         uint32_t tmp;
9217         bool ret;
9218
9219         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9220         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9221                 return false;
9222
9223         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9224         pipe_config->shared_dpll = NULL;
9225
9226         ret = false;
9227         tmp = I915_READ(PIPECONF(crtc->pipe));
9228         if (!(tmp & PIPECONF_ENABLE))
9229                 goto out;
9230
9231         switch (tmp & PIPECONF_BPC_MASK) {
9232         case PIPECONF_6BPC:
9233                 pipe_config->pipe_bpp = 18;
9234                 break;
9235         case PIPECONF_8BPC:
9236                 pipe_config->pipe_bpp = 24;
9237                 break;
9238         case PIPECONF_10BPC:
9239                 pipe_config->pipe_bpp = 30;
9240                 break;
9241         case PIPECONF_12BPC:
9242                 pipe_config->pipe_bpp = 36;
9243                 break;
9244         default:
9245                 break;
9246         }
9247
9248         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9249                 pipe_config->limited_color_range = true;
9250
9251         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9252                 struct intel_shared_dpll *pll;
9253                 enum intel_dpll_id pll_id;
9254
9255                 pipe_config->has_pch_encoder = true;
9256
9257                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9258                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9259                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9260
9261                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9262
9263                 if (HAS_PCH_IBX(dev_priv->dev)) {
9264                         pll_id = (enum intel_dpll_id) crtc->pipe;
9265                 } else {
9266                         tmp = I915_READ(PCH_DPLL_SEL);
9267                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9268                                 pll_id = DPLL_ID_PCH_PLL_B;
9269                         else
9270                                 pll_id= DPLL_ID_PCH_PLL_A;
9271                 }
9272
9273                 pipe_config->shared_dpll =
9274                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9275                 pll = pipe_config->shared_dpll;
9276
9277                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9278                                                  &pipe_config->dpll_hw_state));
9279
9280                 tmp = pipe_config->dpll_hw_state.dpll;
9281                 pipe_config->pixel_multiplier =
9282                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9283                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9284
9285                 ironlake_pch_clock_get(crtc, pipe_config);
9286         } else {
9287                 pipe_config->pixel_multiplier = 1;
9288         }
9289
9290         intel_get_pipe_timings(crtc, pipe_config);
9291         intel_get_pipe_src_size(crtc, pipe_config);
9292
9293         ironlake_get_pfit_config(crtc, pipe_config);
9294
9295         ret = true;
9296
9297 out:
9298         intel_display_power_put(dev_priv, power_domain);
9299
9300         return ret;
9301 }
9302
9303 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9304 {
9305         struct drm_device *dev = dev_priv->dev;
9306         struct intel_crtc *crtc;
9307
9308         for_each_intel_crtc(dev, crtc)
9309                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9310                      pipe_name(crtc->pipe));
9311
9312         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_DRIVER), "Power well on\n");
9313         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9314         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9315         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9316         I915_STATE_WARN(I915_READ(PCH_PP_STATUS) & PP_ON, "Panel power on\n");
9317         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9318              "CPU PWM1 enabled\n");
9319         if (IS_HASWELL(dev))
9320                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9321                      "CPU PWM2 enabled\n");
9322         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9323              "PCH PWM1 enabled\n");
9324         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9325              "Utility pin enabled\n");
9326         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9327
9328         /*
9329          * In theory we can still leave IRQs enabled, as long as only the HPD
9330          * interrupts remain enabled. We used to check for that, but since it's
9331          * gen-specific and since we only disable LCPLL after we fully disable
9332          * the interrupts, the check below should be enough.
9333          */
9334         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9335 }
9336
9337 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9338 {
9339         struct drm_device *dev = dev_priv->dev;
9340
9341         if (IS_HASWELL(dev))
9342                 return I915_READ(D_COMP_HSW);
9343         else
9344                 return I915_READ(D_COMP_BDW);
9345 }
9346
9347 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9348 {
9349         struct drm_device *dev = dev_priv->dev;
9350
9351         if (IS_HASWELL(dev)) {
9352                 mutex_lock(&dev_priv->rps.hw_lock);
9353                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9354                                             val))
9355                         DRM_ERROR("Failed to write to D_COMP\n");
9356                 mutex_unlock(&dev_priv->rps.hw_lock);
9357         } else {
9358                 I915_WRITE(D_COMP_BDW, val);
9359                 POSTING_READ(D_COMP_BDW);
9360         }
9361 }
9362
9363 /*
9364  * This function implements pieces of two sequences from BSpec:
9365  * - Sequence for display software to disable LCPLL
9366  * - Sequence for display software to allow package C8+
9367  * The steps implemented here are just the steps that actually touch the LCPLL
9368  * register. Callers should take care of disabling all the display engine
9369  * functions, doing the mode unset, fixing interrupts, etc.
9370  */
9371 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9372                               bool switch_to_fclk, bool allow_power_down)
9373 {
9374         uint32_t val;
9375
9376         assert_can_disable_lcpll(dev_priv);
9377
9378         val = I915_READ(LCPLL_CTL);
9379
9380         if (switch_to_fclk) {
9381                 val |= LCPLL_CD_SOURCE_FCLK;
9382                 I915_WRITE(LCPLL_CTL, val);
9383
9384                 if (wait_for_atomic_us(I915_READ(LCPLL_CTL) &
9385                                        LCPLL_CD_SOURCE_FCLK_DONE, 1))
9386                         DRM_ERROR("Switching to FCLK failed\n");
9387
9388                 val = I915_READ(LCPLL_CTL);
9389         }
9390
9391         val |= LCPLL_PLL_DISABLE;
9392         I915_WRITE(LCPLL_CTL, val);
9393         POSTING_READ(LCPLL_CTL);
9394
9395         if (wait_for((I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK) == 0, 1))
9396                 DRM_ERROR("LCPLL still locked\n");
9397
9398         val = hsw_read_dcomp(dev_priv);
9399         val |= D_COMP_COMP_DISABLE;
9400         hsw_write_dcomp(dev_priv, val);
9401         ndelay(100);
9402
9403         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9404                      1))
9405                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9406
9407         if (allow_power_down) {
9408                 val = I915_READ(LCPLL_CTL);
9409                 val |= LCPLL_POWER_DOWN_ALLOW;
9410                 I915_WRITE(LCPLL_CTL, val);
9411                 POSTING_READ(LCPLL_CTL);
9412         }
9413 }
9414
9415 /*
9416  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9417  * source.
9418  */
9419 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9420 {
9421         uint32_t val;
9422
9423         val = I915_READ(LCPLL_CTL);
9424
9425         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9426                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9427                 return;
9428
9429         /*
9430          * Make sure we're not on PC8 state before disabling PC8, otherwise
9431          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9432          */
9433         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9434
9435         if (val & LCPLL_POWER_DOWN_ALLOW) {
9436                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9437                 I915_WRITE(LCPLL_CTL, val);
9438                 POSTING_READ(LCPLL_CTL);
9439         }
9440
9441         val = hsw_read_dcomp(dev_priv);
9442         val |= D_COMP_COMP_FORCE;
9443         val &= ~D_COMP_COMP_DISABLE;
9444         hsw_write_dcomp(dev_priv, val);
9445
9446         val = I915_READ(LCPLL_CTL);
9447         val &= ~LCPLL_PLL_DISABLE;
9448         I915_WRITE(LCPLL_CTL, val);
9449
9450         if (wait_for(I915_READ(LCPLL_CTL) & LCPLL_PLL_LOCK, 5))
9451                 DRM_ERROR("LCPLL not locked yet\n");
9452
9453         if (val & LCPLL_CD_SOURCE_FCLK) {
9454                 val = I915_READ(LCPLL_CTL);
9455                 val &= ~LCPLL_CD_SOURCE_FCLK;
9456                 I915_WRITE(LCPLL_CTL, val);
9457
9458                 if (wait_for_atomic_us((I915_READ(LCPLL_CTL) &
9459                                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9460                         DRM_ERROR("Switching back to LCPLL failed\n");
9461         }
9462
9463         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9464         intel_update_cdclk(dev_priv->dev);
9465 }
9466
9467 /*
9468  * Package states C8 and deeper are really deep PC states that can only be
9469  * reached when all the devices on the system allow it, so even if the graphics
9470  * device allows PC8+, it doesn't mean the system will actually get to these
9471  * states. Our driver only allows PC8+ when going into runtime PM.
9472  *
9473  * The requirements for PC8+ are that all the outputs are disabled, the power
9474  * well is disabled and most interrupts are disabled, and these are also
9475  * requirements for runtime PM. When these conditions are met, we manually do
9476  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9477  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9478  * hang the machine.
9479  *
9480  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9481  * the state of some registers, so when we come back from PC8+ we need to
9482  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9483  * need to take care of the registers kept by RC6. Notice that this happens even
9484  * if we don't put the device in PCI D3 state (which is what currently happens
9485  * because of the runtime PM support).
9486  *
9487  * For more, read "Display Sequences for Package C8" on the hardware
9488  * documentation.
9489  */
9490 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9491 {
9492         struct drm_device *dev = dev_priv->dev;
9493         uint32_t val;
9494
9495         DRM_DEBUG_KMS("Enabling package C8+\n");
9496
9497         if (HAS_PCH_LPT_LP(dev)) {
9498                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9499                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9500                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9501         }
9502
9503         lpt_disable_clkout_dp(dev);
9504         hsw_disable_lcpll(dev_priv, true, true);
9505 }
9506
9507 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9508 {
9509         struct drm_device *dev = dev_priv->dev;
9510         uint32_t val;
9511
9512         DRM_DEBUG_KMS("Disabling package C8+\n");
9513
9514         hsw_restore_lcpll(dev_priv);
9515         lpt_init_pch_refclk(dev);
9516
9517         if (HAS_PCH_LPT_LP(dev)) {
9518                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9519                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9520                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9521         }
9522 }
9523
9524 static void broxton_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9525 {
9526         struct drm_device *dev = old_state->dev;
9527         struct intel_atomic_state *old_intel_state =
9528                 to_intel_atomic_state(old_state);
9529         unsigned int req_cdclk = old_intel_state->dev_cdclk;
9530
9531         broxton_set_cdclk(dev, req_cdclk);
9532 }
9533
9534 /* compute the max rate for new configuration */
9535 static int ilk_max_pixel_rate(struct drm_atomic_state *state)
9536 {
9537         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9538         struct drm_i915_private *dev_priv = state->dev->dev_private;
9539         struct drm_crtc *crtc;
9540         struct drm_crtc_state *cstate;
9541         struct intel_crtc_state *crtc_state;
9542         unsigned max_pixel_rate = 0, i;
9543         enum pipe pipe;
9544
9545         memcpy(intel_state->min_pixclk, dev_priv->min_pixclk,
9546                sizeof(intel_state->min_pixclk));
9547
9548         for_each_crtc_in_state(state, crtc, cstate, i) {
9549                 int pixel_rate;
9550
9551                 crtc_state = to_intel_crtc_state(cstate);
9552                 if (!crtc_state->base.enable) {
9553                         intel_state->min_pixclk[i] = 0;
9554                         continue;
9555                 }
9556
9557                 pixel_rate = ilk_pipe_pixel_rate(crtc_state);
9558
9559                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
9560                 if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
9561                         pixel_rate = DIV_ROUND_UP(pixel_rate * 100, 95);
9562
9563                 intel_state->min_pixclk[i] = pixel_rate;
9564         }
9565
9566         for_each_pipe(dev_priv, pipe)
9567                 max_pixel_rate = max(intel_state->min_pixclk[pipe], max_pixel_rate);
9568
9569         return max_pixel_rate;
9570 }
9571
9572 static void broadwell_set_cdclk(struct drm_device *dev, int cdclk)
9573 {
9574         struct drm_i915_private *dev_priv = dev->dev_private;
9575         uint32_t val, data;
9576         int ret;
9577
9578         if (WARN((I915_READ(LCPLL_CTL) &
9579                   (LCPLL_PLL_DISABLE | LCPLL_PLL_LOCK |
9580                    LCPLL_CD_CLOCK_DISABLE | LCPLL_ROOT_CD_CLOCK_DISABLE |
9581                    LCPLL_CD2X_CLOCK_DISABLE | LCPLL_POWER_DOWN_ALLOW |
9582                    LCPLL_CD_SOURCE_FCLK)) != LCPLL_PLL_LOCK,
9583                  "trying to change cdclk frequency with cdclk not enabled\n"))
9584                 return;
9585
9586         mutex_lock(&dev_priv->rps.hw_lock);
9587         ret = sandybridge_pcode_write(dev_priv,
9588                                       BDW_PCODE_DISPLAY_FREQ_CHANGE_REQ, 0x0);
9589         mutex_unlock(&dev_priv->rps.hw_lock);
9590         if (ret) {
9591                 DRM_ERROR("failed to inform pcode about cdclk change\n");
9592                 return;
9593         }
9594
9595         val = I915_READ(LCPLL_CTL);
9596         val |= LCPLL_CD_SOURCE_FCLK;
9597         I915_WRITE(LCPLL_CTL, val);
9598
9599         if (wait_for_us(I915_READ(LCPLL_CTL) &
9600                         LCPLL_CD_SOURCE_FCLK_DONE, 1))
9601                 DRM_ERROR("Switching to FCLK failed\n");
9602
9603         val = I915_READ(LCPLL_CTL);
9604         val &= ~LCPLL_CLK_FREQ_MASK;
9605
9606         switch (cdclk) {
9607         case 450000:
9608                 val |= LCPLL_CLK_FREQ_450;
9609                 data = 0;
9610                 break;
9611         case 540000:
9612                 val |= LCPLL_CLK_FREQ_54O_BDW;
9613                 data = 1;
9614                 break;
9615         case 337500:
9616                 val |= LCPLL_CLK_FREQ_337_5_BDW;
9617                 data = 2;
9618                 break;
9619         case 675000:
9620                 val |= LCPLL_CLK_FREQ_675_BDW;
9621                 data = 3;
9622                 break;
9623         default:
9624                 WARN(1, "invalid cdclk frequency\n");
9625                 return;
9626         }
9627
9628         I915_WRITE(LCPLL_CTL, val);
9629
9630         val = I915_READ(LCPLL_CTL);
9631         val &= ~LCPLL_CD_SOURCE_FCLK;
9632         I915_WRITE(LCPLL_CTL, val);
9633
9634         if (wait_for_us((I915_READ(LCPLL_CTL) &
9635                         LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9636                 DRM_ERROR("Switching back to LCPLL failed\n");
9637
9638         mutex_lock(&dev_priv->rps.hw_lock);
9639         sandybridge_pcode_write(dev_priv, HSW_PCODE_DE_WRITE_FREQ_REQ, data);
9640         mutex_unlock(&dev_priv->rps.hw_lock);
9641
9642         intel_update_cdclk(dev);
9643
9644         WARN(cdclk != dev_priv->cdclk_freq,
9645              "cdclk requested %d kHz but got %d kHz\n",
9646              cdclk, dev_priv->cdclk_freq);
9647 }
9648
9649 static int broadwell_modeset_calc_cdclk(struct drm_atomic_state *state)
9650 {
9651         struct drm_i915_private *dev_priv = to_i915(state->dev);
9652         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
9653         int max_pixclk = ilk_max_pixel_rate(state);
9654         int cdclk;
9655
9656         /*
9657          * FIXME should also account for plane ratio
9658          * once 64bpp pixel formats are supported.
9659          */
9660         if (max_pixclk > 540000)
9661                 cdclk = 675000;
9662         else if (max_pixclk > 450000)
9663                 cdclk = 540000;
9664         else if (max_pixclk > 337500)
9665                 cdclk = 450000;
9666         else
9667                 cdclk = 337500;
9668
9669         if (cdclk > dev_priv->max_cdclk_freq) {
9670                 DRM_DEBUG_KMS("requested cdclk (%d kHz) exceeds max (%d kHz)\n",
9671                               cdclk, dev_priv->max_cdclk_freq);
9672                 return -EINVAL;
9673         }
9674
9675         intel_state->cdclk = intel_state->dev_cdclk = cdclk;
9676         if (!intel_state->active_crtcs)
9677                 intel_state->dev_cdclk = 337500;
9678
9679         return 0;
9680 }
9681
9682 static void broadwell_modeset_commit_cdclk(struct drm_atomic_state *old_state)
9683 {
9684         struct drm_device *dev = old_state->dev;
9685         struct intel_atomic_state *old_intel_state =
9686                 to_intel_atomic_state(old_state);
9687         unsigned req_cdclk = old_intel_state->dev_cdclk;
9688
9689         broadwell_set_cdclk(dev, req_cdclk);
9690 }
9691
9692 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9693                                       struct intel_crtc_state *crtc_state)
9694 {
9695         struct intel_encoder *intel_encoder =
9696                 intel_ddi_get_crtc_new_encoder(crtc_state);
9697
9698         if (intel_encoder->type != INTEL_OUTPUT_DSI) {
9699                 if (!intel_ddi_pll_select(crtc, crtc_state))
9700                         return -EINVAL;
9701         }
9702
9703         crtc->lowfreq_avail = false;
9704
9705         return 0;
9706 }
9707
9708 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9709                                 enum port port,
9710                                 struct intel_crtc_state *pipe_config)
9711 {
9712         enum intel_dpll_id id;
9713
9714         switch (port) {
9715         case PORT_A:
9716                 pipe_config->ddi_pll_sel = SKL_DPLL0;
9717                 id = DPLL_ID_SKL_DPLL0;
9718                 break;
9719         case PORT_B:
9720                 pipe_config->ddi_pll_sel = SKL_DPLL1;
9721                 id = DPLL_ID_SKL_DPLL1;
9722                 break;
9723         case PORT_C:
9724                 pipe_config->ddi_pll_sel = SKL_DPLL2;
9725                 id = DPLL_ID_SKL_DPLL2;
9726                 break;
9727         default:
9728                 DRM_ERROR("Incorrect port type\n");
9729                 return;
9730         }
9731
9732         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9733 }
9734
9735 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9736                                 enum port port,
9737                                 struct intel_crtc_state *pipe_config)
9738 {
9739         enum intel_dpll_id id;
9740         u32 temp;
9741
9742         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9743         pipe_config->ddi_pll_sel = temp >> (port * 3 + 1);
9744
9745         switch (pipe_config->ddi_pll_sel) {
9746         case SKL_DPLL0:
9747                 id = DPLL_ID_SKL_DPLL0;
9748                 break;
9749         case SKL_DPLL1:
9750                 id = DPLL_ID_SKL_DPLL1;
9751                 break;
9752         case SKL_DPLL2:
9753                 id = DPLL_ID_SKL_DPLL2;
9754                 break;
9755         case SKL_DPLL3:
9756                 id = DPLL_ID_SKL_DPLL3;
9757                 break;
9758         default:
9759                 MISSING_CASE(pipe_config->ddi_pll_sel);
9760                 return;
9761         }
9762
9763         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9764 }
9765
9766 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9767                                 enum port port,
9768                                 struct intel_crtc_state *pipe_config)
9769 {
9770         enum intel_dpll_id id;
9771
9772         pipe_config->ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9773
9774         switch (pipe_config->ddi_pll_sel) {
9775         case PORT_CLK_SEL_WRPLL1:
9776                 id = DPLL_ID_WRPLL1;
9777                 break;
9778         case PORT_CLK_SEL_WRPLL2:
9779                 id = DPLL_ID_WRPLL2;
9780                 break;
9781         case PORT_CLK_SEL_SPLL:
9782                 id = DPLL_ID_SPLL;
9783                 break;
9784         case PORT_CLK_SEL_LCPLL_810:
9785                 id = DPLL_ID_LCPLL_810;
9786                 break;
9787         case PORT_CLK_SEL_LCPLL_1350:
9788                 id = DPLL_ID_LCPLL_1350;
9789                 break;
9790         case PORT_CLK_SEL_LCPLL_2700:
9791                 id = DPLL_ID_LCPLL_2700;
9792                 break;
9793         default:
9794                 MISSING_CASE(pipe_config->ddi_pll_sel);
9795                 /* fall through */
9796         case PORT_CLK_SEL_NONE:
9797                 return;
9798         }
9799
9800         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9801 }
9802
9803 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9804                                      struct intel_crtc_state *pipe_config,
9805                                      unsigned long *power_domain_mask)
9806 {
9807         struct drm_device *dev = crtc->base.dev;
9808         struct drm_i915_private *dev_priv = dev->dev_private;
9809         enum intel_display_power_domain power_domain;
9810         u32 tmp;
9811
9812         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9813
9814         /*
9815          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9816          * consistency and less surprising code; it's in always on power).
9817          */
9818         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9819         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9820                 enum pipe trans_edp_pipe;
9821                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9822                 default:
9823                         WARN(1, "unknown pipe linked to edp transcoder\n");
9824                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9825                 case TRANS_DDI_EDP_INPUT_A_ON:
9826                         trans_edp_pipe = PIPE_A;
9827                         break;
9828                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9829                         trans_edp_pipe = PIPE_B;
9830                         break;
9831                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9832                         trans_edp_pipe = PIPE_C;
9833                         break;
9834                 }
9835
9836                 if (trans_edp_pipe == crtc->pipe)
9837                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9838         }
9839
9840         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9841         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9842                 return false;
9843         *power_domain_mask |= BIT(power_domain);
9844
9845         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9846
9847         return tmp & PIPECONF_ENABLE;
9848 }
9849
9850 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9851                                          struct intel_crtc_state *pipe_config,
9852                                          unsigned long *power_domain_mask)
9853 {
9854         struct drm_device *dev = crtc->base.dev;
9855         struct drm_i915_private *dev_priv = dev->dev_private;
9856         enum intel_display_power_domain power_domain;
9857         enum port port;
9858         enum transcoder cpu_transcoder;
9859         u32 tmp;
9860
9861         pipe_config->has_dsi_encoder = false;
9862
9863         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9864                 if (port == PORT_A)
9865                         cpu_transcoder = TRANSCODER_DSI_A;
9866                 else
9867                         cpu_transcoder = TRANSCODER_DSI_C;
9868
9869                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9870                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9871                         continue;
9872                 *power_domain_mask |= BIT(power_domain);
9873
9874                 /*
9875                  * The PLL needs to be enabled with a valid divider
9876                  * configuration, otherwise accessing DSI registers will hang
9877                  * the machine. See BSpec North Display Engine
9878                  * registers/MIPI[BXT]. We can break out here early, since we
9879                  * need the same DSI PLL to be enabled for both DSI ports.
9880                  */
9881                 if (!intel_dsi_pll_is_enabled(dev_priv))
9882                         break;
9883
9884                 /* XXX: this works for video mode only */
9885                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9886                 if (!(tmp & DPI_ENABLE))
9887                         continue;
9888
9889                 tmp = I915_READ(MIPI_CTRL(port));
9890                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9891                         continue;
9892
9893                 pipe_config->cpu_transcoder = cpu_transcoder;
9894                 pipe_config->has_dsi_encoder = true;
9895                 break;
9896         }
9897
9898         return pipe_config->has_dsi_encoder;
9899 }
9900
9901 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9902                                        struct intel_crtc_state *pipe_config)
9903 {
9904         struct drm_device *dev = crtc->base.dev;
9905         struct drm_i915_private *dev_priv = dev->dev_private;
9906         struct intel_shared_dpll *pll;
9907         enum port port;
9908         uint32_t tmp;
9909
9910         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9911
9912         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9913
9914         if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
9915                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9916         else if (IS_BROXTON(dev))
9917                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9918         else
9919                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9920
9921         pll = pipe_config->shared_dpll;
9922         if (pll) {
9923                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9924                                                  &pipe_config->dpll_hw_state));
9925         }
9926
9927         /*
9928          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9929          * DDI E. So just check whether this pipe is wired to DDI E and whether
9930          * the PCH transcoder is on.
9931          */
9932         if (INTEL_INFO(dev)->gen < 9 &&
9933             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9934                 pipe_config->has_pch_encoder = true;
9935
9936                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9937                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9938                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9939
9940                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9941         }
9942 }
9943
9944 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9945                                     struct intel_crtc_state *pipe_config)
9946 {
9947         struct drm_device *dev = crtc->base.dev;
9948         struct drm_i915_private *dev_priv = dev->dev_private;
9949         enum intel_display_power_domain power_domain;
9950         unsigned long power_domain_mask;
9951         bool active;
9952
9953         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9954         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9955                 return false;
9956         power_domain_mask = BIT(power_domain);
9957
9958         pipe_config->shared_dpll = NULL;
9959
9960         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9961
9962         if (IS_BROXTON(dev_priv)) {
9963                 bxt_get_dsi_transcoder_state(crtc, pipe_config,
9964                                              &power_domain_mask);
9965                 WARN_ON(active && pipe_config->has_dsi_encoder);
9966                 if (pipe_config->has_dsi_encoder)
9967                         active = true;
9968         }
9969
9970         if (!active)
9971                 goto out;
9972
9973         if (!pipe_config->has_dsi_encoder) {
9974                 haswell_get_ddi_port_state(crtc, pipe_config);
9975                 intel_get_pipe_timings(crtc, pipe_config);
9976         }
9977
9978         intel_get_pipe_src_size(crtc, pipe_config);
9979
9980         pipe_config->gamma_mode =
9981                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9982
9983         if (INTEL_INFO(dev)->gen >= 9) {
9984                 skl_init_scalers(dev, crtc, pipe_config);
9985         }
9986
9987         if (INTEL_INFO(dev)->gen >= 9) {
9988                 pipe_config->scaler_state.scaler_id = -1;
9989                 pipe_config->scaler_state.scaler_users &= ~(1 << SKL_CRTC_INDEX);
9990         }
9991
9992         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9993         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9994                 power_domain_mask |= BIT(power_domain);
9995                 if (INTEL_INFO(dev)->gen >= 9)
9996                         skylake_get_pfit_config(crtc, pipe_config);
9997                 else
9998                         ironlake_get_pfit_config(crtc, pipe_config);
9999         }
10000
10001         if (IS_HASWELL(dev))
10002                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
10003                         (I915_READ(IPS_CTL) & IPS_ENABLE);
10004
10005         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
10006             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
10007                 pipe_config->pixel_multiplier =
10008                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
10009         } else {
10010                 pipe_config->pixel_multiplier = 1;
10011         }
10012
10013 out:
10014         for_each_power_domain(power_domain, power_domain_mask)
10015                 intel_display_power_put(dev_priv, power_domain);
10016
10017         return active;
10018 }
10019
10020 static void i845_update_cursor(struct drm_crtc *crtc, u32 base,
10021                                const struct intel_plane_state *plane_state)
10022 {
10023         struct drm_device *dev = crtc->dev;
10024         struct drm_i915_private *dev_priv = dev->dev_private;
10025         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10026         uint32_t cntl = 0, size = 0;
10027
10028         if (plane_state && plane_state->visible) {
10029                 unsigned int width = plane_state->base.crtc_w;
10030                 unsigned int height = plane_state->base.crtc_h;
10031                 unsigned int stride = roundup_pow_of_two(width) * 4;
10032
10033                 switch (stride) {
10034                 default:
10035                         WARN_ONCE(1, "Invalid cursor width/stride, width=%u, stride=%u\n",
10036                                   width, stride);
10037                         stride = 256;
10038                         /* fallthrough */
10039                 case 256:
10040                 case 512:
10041                 case 1024:
10042                 case 2048:
10043                         break;
10044                 }
10045
10046                 cntl |= CURSOR_ENABLE |
10047                         CURSOR_GAMMA_ENABLE |
10048                         CURSOR_FORMAT_ARGB |
10049                         CURSOR_STRIDE(stride);
10050
10051                 size = (height << 12) | width;
10052         }
10053
10054         if (intel_crtc->cursor_cntl != 0 &&
10055             (intel_crtc->cursor_base != base ||
10056              intel_crtc->cursor_size != size ||
10057              intel_crtc->cursor_cntl != cntl)) {
10058                 /* On these chipsets we can only modify the base/size/stride
10059                  * whilst the cursor is disabled.
10060                  */
10061                 I915_WRITE(CURCNTR(PIPE_A), 0);
10062                 POSTING_READ(CURCNTR(PIPE_A));
10063                 intel_crtc->cursor_cntl = 0;
10064         }
10065
10066         if (intel_crtc->cursor_base != base) {
10067                 I915_WRITE(CURBASE(PIPE_A), base);
10068                 intel_crtc->cursor_base = base;
10069         }
10070
10071         if (intel_crtc->cursor_size != size) {
10072                 I915_WRITE(CURSIZE, size);
10073                 intel_crtc->cursor_size = size;
10074         }
10075
10076         if (intel_crtc->cursor_cntl != cntl) {
10077                 I915_WRITE(CURCNTR(PIPE_A), cntl);
10078                 POSTING_READ(CURCNTR(PIPE_A));
10079                 intel_crtc->cursor_cntl = cntl;
10080         }
10081 }
10082
10083 static void i9xx_update_cursor(struct drm_crtc *crtc, u32 base,
10084                                const struct intel_plane_state *plane_state)
10085 {
10086         struct drm_device *dev = crtc->dev;
10087         struct drm_i915_private *dev_priv = dev->dev_private;
10088         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10089         int pipe = intel_crtc->pipe;
10090         uint32_t cntl = 0;
10091
10092         if (plane_state && plane_state->visible) {
10093                 cntl = MCURSOR_GAMMA_ENABLE;
10094                 switch (plane_state->base.crtc_w) {
10095                         case 64:
10096                                 cntl |= CURSOR_MODE_64_ARGB_AX;
10097                                 break;
10098                         case 128:
10099                                 cntl |= CURSOR_MODE_128_ARGB_AX;
10100                                 break;
10101                         case 256:
10102                                 cntl |= CURSOR_MODE_256_ARGB_AX;
10103                                 break;
10104                         default:
10105                                 MISSING_CASE(plane_state->base.crtc_w);
10106                                 return;
10107                 }
10108                 cntl |= pipe << 28; /* Connect to correct pipe */
10109
10110                 if (HAS_DDI(dev))
10111                         cntl |= CURSOR_PIPE_CSC_ENABLE;
10112
10113                 if (plane_state->base.rotation == BIT(DRM_ROTATE_180))
10114                         cntl |= CURSOR_ROTATE_180;
10115         }
10116
10117         if (intel_crtc->cursor_cntl != cntl) {
10118                 I915_WRITE(CURCNTR(pipe), cntl);
10119                 POSTING_READ(CURCNTR(pipe));
10120                 intel_crtc->cursor_cntl = cntl;
10121         }
10122
10123         /* and commit changes on next vblank */
10124         I915_WRITE(CURBASE(pipe), base);
10125         POSTING_READ(CURBASE(pipe));
10126
10127         intel_crtc->cursor_base = base;
10128 }
10129
10130 /* If no-part of the cursor is visible on the framebuffer, then the GPU may hang... */
10131 static void intel_crtc_update_cursor(struct drm_crtc *crtc,
10132                                      const struct intel_plane_state *plane_state)
10133 {
10134         struct drm_device *dev = crtc->dev;
10135         struct drm_i915_private *dev_priv = dev->dev_private;
10136         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10137         int pipe = intel_crtc->pipe;
10138         u32 base = intel_crtc->cursor_addr;
10139         u32 pos = 0;
10140
10141         if (plane_state) {
10142                 int x = plane_state->base.crtc_x;
10143                 int y = plane_state->base.crtc_y;
10144
10145                 if (x < 0) {
10146                         pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
10147                         x = -x;
10148                 }
10149                 pos |= x << CURSOR_X_SHIFT;
10150
10151                 if (y < 0) {
10152                         pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
10153                         y = -y;
10154                 }
10155                 pos |= y << CURSOR_Y_SHIFT;
10156
10157                 /* ILK+ do this automagically */
10158                 if (HAS_GMCH_DISPLAY(dev) &&
10159                     plane_state->base.rotation == BIT(DRM_ROTATE_180)) {
10160                         base += (plane_state->base.crtc_h *
10161                                  plane_state->base.crtc_w - 1) * 4;
10162                 }
10163         }
10164
10165         I915_WRITE(CURPOS(pipe), pos);
10166
10167         if (IS_845G(dev) || IS_I865G(dev))
10168                 i845_update_cursor(crtc, base, plane_state);
10169         else
10170                 i9xx_update_cursor(crtc, base, plane_state);
10171 }
10172
10173 static bool cursor_size_ok(struct drm_device *dev,
10174                            uint32_t width, uint32_t height)
10175 {
10176         if (width == 0 || height == 0)
10177                 return false;
10178
10179         /*
10180          * 845g/865g are special in that they are only limited by
10181          * the width of their cursors, the height is arbitrary up to
10182          * the precision of the register. Everything else requires
10183          * square cursors, limited to a few power-of-two sizes.
10184          */
10185         if (IS_845G(dev) || IS_I865G(dev)) {
10186                 if ((width & 63) != 0)
10187                         return false;
10188
10189                 if (width > (IS_845G(dev) ? 64 : 512))
10190                         return false;
10191
10192                 if (height > 1023)
10193                         return false;
10194         } else {
10195                 switch (width | height) {
10196                 case 256:
10197                 case 128:
10198                         if (IS_GEN2(dev))
10199                                 return false;
10200                 case 64:
10201                         break;
10202                 default:
10203                         return false;
10204                 }
10205         }
10206
10207         return true;
10208 }
10209
10210 /* VESA 640x480x72Hz mode to set on the pipe */
10211 static struct drm_display_mode load_detect_mode = {
10212         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10213                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10214 };
10215
10216 struct drm_framebuffer *
10217 __intel_framebuffer_create(struct drm_device *dev,
10218                            struct drm_mode_fb_cmd2 *mode_cmd,
10219                            struct drm_i915_gem_object *obj)
10220 {
10221         struct intel_framebuffer *intel_fb;
10222         int ret;
10223
10224         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10225         if (!intel_fb)
10226                 return ERR_PTR(-ENOMEM);
10227
10228         ret = intel_framebuffer_init(dev, intel_fb, mode_cmd, obj);
10229         if (ret)
10230                 goto err;
10231
10232         return &intel_fb->base;
10233
10234 err:
10235         kfree(intel_fb);
10236         return ERR_PTR(ret);
10237 }
10238
10239 static struct drm_framebuffer *
10240 intel_framebuffer_create(struct drm_device *dev,
10241                          struct drm_mode_fb_cmd2 *mode_cmd,
10242                          struct drm_i915_gem_object *obj)
10243 {
10244         struct drm_framebuffer *fb;
10245         int ret;
10246
10247         ret = i915_mutex_lock_interruptible(dev);
10248         if (ret)
10249                 return ERR_PTR(ret);
10250         fb = __intel_framebuffer_create(dev, mode_cmd, obj);
10251         mutex_unlock(&dev->struct_mutex);
10252
10253         return fb;
10254 }
10255
10256 static u32
10257 intel_framebuffer_pitch_for_width(int width, int bpp)
10258 {
10259         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
10260         return ALIGN(pitch, 64);
10261 }
10262
10263 static u32
10264 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
10265 {
10266         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
10267         return PAGE_ALIGN(pitch * mode->vdisplay);
10268 }
10269
10270 static struct drm_framebuffer *
10271 intel_framebuffer_create_for_mode(struct drm_device *dev,
10272                                   struct drm_display_mode *mode,
10273                                   int depth, int bpp)
10274 {
10275         struct drm_framebuffer *fb;
10276         struct drm_i915_gem_object *obj;
10277         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
10278
10279         obj = i915_gem_alloc_object(dev,
10280                                     intel_framebuffer_size_for_mode(mode, bpp));
10281         if (obj == NULL)
10282                 return ERR_PTR(-ENOMEM);
10283
10284         mode_cmd.width = mode->hdisplay;
10285         mode_cmd.height = mode->vdisplay;
10286         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
10287                                                                 bpp);
10288         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
10289
10290         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
10291         if (IS_ERR(fb))
10292                 drm_gem_object_unreference_unlocked(&obj->base);
10293
10294         return fb;
10295 }
10296
10297 static struct drm_framebuffer *
10298 mode_fits_in_fbdev(struct drm_device *dev,
10299                    struct drm_display_mode *mode)
10300 {
10301 #ifdef CONFIG_DRM_FBDEV_EMULATION
10302         struct drm_i915_private *dev_priv = dev->dev_private;
10303         struct drm_i915_gem_object *obj;
10304         struct drm_framebuffer *fb;
10305
10306         if (!dev_priv->fbdev)
10307                 return NULL;
10308
10309         if (!dev_priv->fbdev->fb)
10310                 return NULL;
10311
10312         obj = dev_priv->fbdev->fb->obj;
10313         BUG_ON(!obj);
10314
10315         fb = &dev_priv->fbdev->fb->base;
10316         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
10317                                                                fb->bits_per_pixel))
10318                 return NULL;
10319
10320         if (obj->base.size < mode->vdisplay * fb->pitches[0])
10321                 return NULL;
10322
10323         drm_framebuffer_reference(fb);
10324         return fb;
10325 #else
10326         return NULL;
10327 #endif
10328 }
10329
10330 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
10331                                            struct drm_crtc *crtc,
10332                                            struct drm_display_mode *mode,
10333                                            struct drm_framebuffer *fb,
10334                                            int x, int y)
10335 {
10336         struct drm_plane_state *plane_state;
10337         int hdisplay, vdisplay;
10338         int ret;
10339
10340         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
10341         if (IS_ERR(plane_state))
10342                 return PTR_ERR(plane_state);
10343
10344         if (mode)
10345                 drm_crtc_get_hv_timing(mode, &hdisplay, &vdisplay);
10346         else
10347                 hdisplay = vdisplay = 0;
10348
10349         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
10350         if (ret)
10351                 return ret;
10352         drm_atomic_set_fb_for_plane(plane_state, fb);
10353         plane_state->crtc_x = 0;
10354         plane_state->crtc_y = 0;
10355         plane_state->crtc_w = hdisplay;
10356         plane_state->crtc_h = vdisplay;
10357         plane_state->src_x = x << 16;
10358         plane_state->src_y = y << 16;
10359         plane_state->src_w = hdisplay << 16;
10360         plane_state->src_h = vdisplay << 16;
10361
10362         return 0;
10363 }
10364
10365 bool intel_get_load_detect_pipe(struct drm_connector *connector,
10366                                 struct drm_display_mode *mode,
10367                                 struct intel_load_detect_pipe *old,
10368                                 struct drm_modeset_acquire_ctx *ctx)
10369 {
10370         struct intel_crtc *intel_crtc;
10371         struct intel_encoder *intel_encoder =
10372                 intel_attached_encoder(connector);
10373         struct drm_crtc *possible_crtc;
10374         struct drm_encoder *encoder = &intel_encoder->base;
10375         struct drm_crtc *crtc = NULL;
10376         struct drm_device *dev = encoder->dev;
10377         struct drm_framebuffer *fb;
10378         struct drm_mode_config *config = &dev->mode_config;
10379         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10380         struct drm_connector_state *connector_state;
10381         struct intel_crtc_state *crtc_state;
10382         int ret, i = -1;
10383
10384         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10385                       connector->base.id, connector->name,
10386                       encoder->base.id, encoder->name);
10387
10388         old->restore_state = NULL;
10389
10390 retry:
10391         ret = drm_modeset_lock(&config->connection_mutex, ctx);
10392         if (ret)
10393                 goto fail;
10394
10395         /*
10396          * Algorithm gets a little messy:
10397          *
10398          *   - if the connector already has an assigned crtc, use it (but make
10399          *     sure it's on first)
10400          *
10401          *   - try to find the first unused crtc that can drive this connector,
10402          *     and use that if we find one
10403          */
10404
10405         /* See if we already have a CRTC for this connector */
10406         if (connector->state->crtc) {
10407                 crtc = connector->state->crtc;
10408
10409                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10410                 if (ret)
10411                         goto fail;
10412
10413                 /* Make sure the crtc and connector are running */
10414                 goto found;
10415         }
10416
10417         /* Find an unused one (if possible) */
10418         for_each_crtc(dev, possible_crtc) {
10419                 i++;
10420                 if (!(encoder->possible_crtcs & (1 << i)))
10421                         continue;
10422
10423                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10424                 if (ret)
10425                         goto fail;
10426
10427                 if (possible_crtc->state->enable) {
10428                         drm_modeset_unlock(&possible_crtc->mutex);
10429                         continue;
10430                 }
10431
10432                 crtc = possible_crtc;
10433                 break;
10434         }
10435
10436         /*
10437          * If we didn't find an unused CRTC, don't use any.
10438          */
10439         if (!crtc) {
10440                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10441                 goto fail;
10442         }
10443
10444 found:
10445         intel_crtc = to_intel_crtc(crtc);
10446
10447         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10448         if (ret)
10449                 goto fail;
10450
10451         state = drm_atomic_state_alloc(dev);
10452         restore_state = drm_atomic_state_alloc(dev);
10453         if (!state || !restore_state) {
10454                 ret = -ENOMEM;
10455                 goto fail;
10456         }
10457
10458         state->acquire_ctx = ctx;
10459         restore_state->acquire_ctx = ctx;
10460
10461         connector_state = drm_atomic_get_connector_state(state, connector);
10462         if (IS_ERR(connector_state)) {
10463                 ret = PTR_ERR(connector_state);
10464                 goto fail;
10465         }
10466
10467         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10468         if (ret)
10469                 goto fail;
10470
10471         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10472         if (IS_ERR(crtc_state)) {
10473                 ret = PTR_ERR(crtc_state);
10474                 goto fail;
10475         }
10476
10477         crtc_state->base.active = crtc_state->base.enable = true;
10478
10479         if (!mode)
10480                 mode = &load_detect_mode;
10481
10482         /* We need a framebuffer large enough to accommodate all accesses
10483          * that the plane may generate whilst we perform load detection.
10484          * We can not rely on the fbcon either being present (we get called
10485          * during its initialisation to detect all boot displays, or it may
10486          * not even exist) or that it is large enough to satisfy the
10487          * requested mode.
10488          */
10489         fb = mode_fits_in_fbdev(dev, mode);
10490         if (fb == NULL) {
10491                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10492                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10493         } else
10494                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10495         if (IS_ERR(fb)) {
10496                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10497                 goto fail;
10498         }
10499
10500         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10501         if (ret)
10502                 goto fail;
10503
10504         drm_framebuffer_unreference(fb);
10505
10506         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10507         if (ret)
10508                 goto fail;
10509
10510         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10511         if (!ret)
10512                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10513         if (!ret)
10514                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10515         if (ret) {
10516                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10517                 goto fail;
10518         }
10519
10520         ret = drm_atomic_commit(state);
10521         if (ret) {
10522                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10523                 goto fail;
10524         }
10525
10526         old->restore_state = restore_state;
10527
10528         /* let the connector get through one full cycle before testing */
10529         intel_wait_for_vblank(dev, intel_crtc->pipe);
10530         return true;
10531
10532 fail:
10533         drm_atomic_state_free(state);
10534         drm_atomic_state_free(restore_state);
10535         restore_state = state = NULL;
10536
10537         if (ret == -EDEADLK) {
10538                 drm_modeset_backoff(ctx);
10539                 goto retry;
10540         }
10541
10542         return false;
10543 }
10544
10545 void intel_release_load_detect_pipe(struct drm_connector *connector,
10546                                     struct intel_load_detect_pipe *old,
10547                                     struct drm_modeset_acquire_ctx *ctx)
10548 {
10549         struct intel_encoder *intel_encoder =
10550                 intel_attached_encoder(connector);
10551         struct drm_encoder *encoder = &intel_encoder->base;
10552         struct drm_atomic_state *state = old->restore_state;
10553         int ret;
10554
10555         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10556                       connector->base.id, connector->name,
10557                       encoder->base.id, encoder->name);
10558
10559         if (!state)
10560                 return;
10561
10562         ret = drm_atomic_commit(state);
10563         if (ret) {
10564                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10565                 drm_atomic_state_free(state);
10566         }
10567 }
10568
10569 static int i9xx_pll_refclk(struct drm_device *dev,
10570                            const struct intel_crtc_state *pipe_config)
10571 {
10572         struct drm_i915_private *dev_priv = dev->dev_private;
10573         u32 dpll = pipe_config->dpll_hw_state.dpll;
10574
10575         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10576                 return dev_priv->vbt.lvds_ssc_freq;
10577         else if (HAS_PCH_SPLIT(dev))
10578                 return 120000;
10579         else if (!IS_GEN2(dev))
10580                 return 96000;
10581         else
10582                 return 48000;
10583 }
10584
10585 /* Returns the clock of the currently programmed mode of the given pipe. */
10586 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10587                                 struct intel_crtc_state *pipe_config)
10588 {
10589         struct drm_device *dev = crtc->base.dev;
10590         struct drm_i915_private *dev_priv = dev->dev_private;
10591         int pipe = pipe_config->cpu_transcoder;
10592         u32 dpll = pipe_config->dpll_hw_state.dpll;
10593         u32 fp;
10594         intel_clock_t clock;
10595         int port_clock;
10596         int refclk = i9xx_pll_refclk(dev, pipe_config);
10597
10598         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10599                 fp = pipe_config->dpll_hw_state.fp0;
10600         else
10601                 fp = pipe_config->dpll_hw_state.fp1;
10602
10603         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10604         if (IS_PINEVIEW(dev)) {
10605                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10606                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10607         } else {
10608                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10609                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10610         }
10611
10612         if (!IS_GEN2(dev)) {
10613                 if (IS_PINEVIEW(dev))
10614                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10615                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10616                 else
10617                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10618                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10619
10620                 switch (dpll & DPLL_MODE_MASK) {
10621                 case DPLLB_MODE_DAC_SERIAL:
10622                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10623                                 5 : 10;
10624                         break;
10625                 case DPLLB_MODE_LVDS:
10626                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10627                                 7 : 14;
10628                         break;
10629                 default:
10630                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10631                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10632                         return;
10633                 }
10634
10635                 if (IS_PINEVIEW(dev))
10636                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10637                 else
10638                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10639         } else {
10640                 u32 lvds = IS_I830(dev) ? 0 : I915_READ(LVDS);
10641                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10642
10643                 if (is_lvds) {
10644                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10645                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10646
10647                         if (lvds & LVDS_CLKB_POWER_UP)
10648                                 clock.p2 = 7;
10649                         else
10650                                 clock.p2 = 14;
10651                 } else {
10652                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10653                                 clock.p1 = 2;
10654                         else {
10655                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10656                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10657                         }
10658                         if (dpll & PLL_P2_DIVIDE_BY_4)
10659                                 clock.p2 = 4;
10660                         else
10661                                 clock.p2 = 2;
10662                 }
10663
10664                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10665         }
10666
10667         /*
10668          * This value includes pixel_multiplier. We will use
10669          * port_clock to compute adjusted_mode.crtc_clock in the
10670          * encoder's get_config() function.
10671          */
10672         pipe_config->port_clock = port_clock;
10673 }
10674
10675 int intel_dotclock_calculate(int link_freq,
10676                              const struct intel_link_m_n *m_n)
10677 {
10678         /*
10679          * The calculation for the data clock is:
10680          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10681          * But we want to avoid losing precison if possible, so:
10682          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10683          *
10684          * and the link clock is simpler:
10685          * link_clock = (m * link_clock) / n
10686          */
10687
10688         if (!m_n->link_n)
10689                 return 0;
10690
10691         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10692 }
10693
10694 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10695                                    struct intel_crtc_state *pipe_config)
10696 {
10697         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10698
10699         /* read out port_clock from the DPLL */
10700         i9xx_crtc_clock_get(crtc, pipe_config);
10701
10702         /*
10703          * In case there is an active pipe without active ports,
10704          * we may need some idea for the dotclock anyway.
10705          * Calculate one based on the FDI configuration.
10706          */
10707         pipe_config->base.adjusted_mode.crtc_clock =
10708                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10709                                          &pipe_config->fdi_m_n);
10710 }
10711
10712 /** Returns the currently programmed mode of the given pipe. */
10713 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10714                                              struct drm_crtc *crtc)
10715 {
10716         struct drm_i915_private *dev_priv = dev->dev_private;
10717         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10718         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
10719         struct drm_display_mode *mode;
10720         struct intel_crtc_state *pipe_config;
10721         int htot = I915_READ(HTOTAL(cpu_transcoder));
10722         int hsync = I915_READ(HSYNC(cpu_transcoder));
10723         int vtot = I915_READ(VTOTAL(cpu_transcoder));
10724         int vsync = I915_READ(VSYNC(cpu_transcoder));
10725         enum pipe pipe = intel_crtc->pipe;
10726
10727         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10728         if (!mode)
10729                 return NULL;
10730
10731         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10732         if (!pipe_config) {
10733                 kfree(mode);
10734                 return NULL;
10735         }
10736
10737         /*
10738          * Construct a pipe_config sufficient for getting the clock info
10739          * back out of crtc_clock_get.
10740          *
10741          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10742          * to use a real value here instead.
10743          */
10744         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10745         pipe_config->pixel_multiplier = 1;
10746         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10747         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10748         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10749         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10750
10751         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10752         mode->hdisplay = (htot & 0xffff) + 1;
10753         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10754         mode->hsync_start = (hsync & 0xffff) + 1;
10755         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10756         mode->vdisplay = (vtot & 0xffff) + 1;
10757         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10758         mode->vsync_start = (vsync & 0xffff) + 1;
10759         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10760
10761         drm_mode_set_name(mode);
10762
10763         kfree(pipe_config);
10764
10765         return mode;
10766 }
10767
10768 void intel_mark_busy(struct drm_device *dev)
10769 {
10770         struct drm_i915_private *dev_priv = dev->dev_private;
10771
10772         if (dev_priv->mm.busy)
10773                 return;
10774
10775         intel_runtime_pm_get(dev_priv);
10776         i915_update_gfx_val(dev_priv);
10777         if (INTEL_INFO(dev)->gen >= 6)
10778                 gen6_rps_busy(dev_priv);
10779         dev_priv->mm.busy = true;
10780 }
10781
10782 void intel_mark_idle(struct drm_device *dev)
10783 {
10784         struct drm_i915_private *dev_priv = dev->dev_private;
10785
10786         if (!dev_priv->mm.busy)
10787                 return;
10788
10789         dev_priv->mm.busy = false;
10790
10791         if (INTEL_INFO(dev)->gen >= 6)
10792                 gen6_rps_idle(dev->dev_private);
10793
10794         intel_runtime_pm_put(dev_priv);
10795 }
10796
10797 static void intel_crtc_destroy(struct drm_crtc *crtc)
10798 {
10799         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10800         struct drm_device *dev = crtc->dev;
10801         struct intel_unpin_work *work;
10802
10803         spin_lock_irq(&dev->event_lock);
10804         work = intel_crtc->unpin_work;
10805         intel_crtc->unpin_work = NULL;
10806         spin_unlock_irq(&dev->event_lock);
10807
10808         if (work) {
10809                 cancel_work_sync(&work->work);
10810                 kfree(work);
10811         }
10812
10813         drm_crtc_cleanup(crtc);
10814
10815         kfree(intel_crtc);
10816 }
10817
10818 static void intel_unpin_work_fn(struct work_struct *__work)
10819 {
10820         struct intel_unpin_work *work =
10821                 container_of(__work, struct intel_unpin_work, work);
10822         struct intel_crtc *crtc = to_intel_crtc(work->crtc);
10823         struct drm_device *dev = crtc->base.dev;
10824         struct drm_plane *primary = crtc->base.primary;
10825
10826         mutex_lock(&dev->struct_mutex);
10827         intel_unpin_fb_obj(work->old_fb, primary->state->rotation);
10828         drm_gem_object_unreference(&work->pending_flip_obj->base);
10829
10830         if (work->flip_queued_req)
10831                 i915_gem_request_assign(&work->flip_queued_req, NULL);
10832         mutex_unlock(&dev->struct_mutex);
10833
10834         intel_frontbuffer_flip_complete(dev, to_intel_plane(primary)->frontbuffer_bit);
10835         intel_fbc_post_update(crtc);
10836         drm_framebuffer_unreference(work->old_fb);
10837
10838         BUG_ON(atomic_read(&crtc->unpin_work_count) == 0);
10839         atomic_dec(&crtc->unpin_work_count);
10840
10841         kfree(work);
10842 }
10843
10844 static void do_intel_finish_page_flip(struct drm_device *dev,
10845                                       struct drm_crtc *crtc)
10846 {
10847         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10848         struct intel_unpin_work *work;
10849         unsigned long flags;
10850
10851         /* Ignore early vblank irqs */
10852         if (intel_crtc == NULL)
10853                 return;
10854
10855         /*
10856          * This is called both by irq handlers and the reset code (to complete
10857          * lost pageflips) so needs the full irqsave spinlocks.
10858          */
10859         spin_lock_irqsave(&dev->event_lock, flags);
10860         work = intel_crtc->unpin_work;
10861
10862         /* Ensure we don't miss a work->pending update ... */
10863         smp_rmb();
10864
10865         if (work == NULL || atomic_read(&work->pending) < INTEL_FLIP_COMPLETE) {
10866                 spin_unlock_irqrestore(&dev->event_lock, flags);
10867                 return;
10868         }
10869
10870         page_flip_completed(intel_crtc);
10871
10872         spin_unlock_irqrestore(&dev->event_lock, flags);
10873 }
10874
10875 void intel_finish_page_flip(struct drm_device *dev, int pipe)
10876 {
10877         struct drm_i915_private *dev_priv = dev->dev_private;
10878         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
10879
10880         do_intel_finish_page_flip(dev, crtc);
10881 }
10882
10883 void intel_finish_page_flip_plane(struct drm_device *dev, int plane)
10884 {
10885         struct drm_i915_private *dev_priv = dev->dev_private;
10886         struct drm_crtc *crtc = dev_priv->plane_to_crtc_mapping[plane];
10887
10888         do_intel_finish_page_flip(dev, crtc);
10889 }
10890
10891 /* Is 'a' after or equal to 'b'? */
10892 static bool g4x_flip_count_after_eq(u32 a, u32 b)
10893 {
10894         return !((a - b) & 0x80000000);
10895 }
10896
10897 static bool page_flip_finished(struct intel_crtc *crtc)
10898 {
10899         struct drm_device *dev = crtc->base.dev;
10900         struct drm_i915_private *dev_priv = dev->dev_private;
10901
10902         if (i915_reset_in_progress(&dev_priv->gpu_error) ||
10903             crtc->reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter))
10904                 return true;
10905
10906         /*
10907          * The relevant registers doen't exist on pre-ctg.
10908          * As the flip done interrupt doesn't trigger for mmio
10909          * flips on gmch platforms, a flip count check isn't
10910          * really needed there. But since ctg has the registers,
10911          * include it in the check anyway.
10912          */
10913         if (INTEL_INFO(dev)->gen < 5 && !IS_G4X(dev))
10914                 return true;
10915
10916         /*
10917          * BDW signals flip done immediately if the plane
10918          * is disabled, even if the plane enable is already
10919          * armed to occur at the next vblank :(
10920          */
10921
10922         /*
10923          * A DSPSURFLIVE check isn't enough in case the mmio and CS flips
10924          * used the same base address. In that case the mmio flip might
10925          * have completed, but the CS hasn't even executed the flip yet.
10926          *
10927          * A flip count check isn't enough as the CS might have updated
10928          * the base address just after start of vblank, but before we
10929          * managed to process the interrupt. This means we'd complete the
10930          * CS flip too soon.
10931          *
10932          * Combining both checks should get us a good enough result. It may
10933          * still happen that the CS flip has been executed, but has not
10934          * yet actually completed. But in case the base address is the same
10935          * anyway, we don't really care.
10936          */
10937         return (I915_READ(DSPSURFLIVE(crtc->plane)) & ~0xfff) ==
10938                 crtc->unpin_work->gtt_offset &&
10939                 g4x_flip_count_after_eq(I915_READ(PIPE_FLIPCOUNT_G4X(crtc->pipe)),
10940                                     crtc->unpin_work->flip_count);
10941 }
10942
10943 void intel_prepare_page_flip(struct drm_device *dev, int plane)
10944 {
10945         struct drm_i915_private *dev_priv = dev->dev_private;
10946         struct intel_crtc *intel_crtc =
10947                 to_intel_crtc(dev_priv->plane_to_crtc_mapping[plane]);
10948         unsigned long flags;
10949
10950
10951         /*
10952          * This is called both by irq handlers and the reset code (to complete
10953          * lost pageflips) so needs the full irqsave spinlocks.
10954          *
10955          * NB: An MMIO update of the plane base pointer will also
10956          * generate a page-flip completion irq, i.e. every modeset
10957          * is also accompanied by a spurious intel_prepare_page_flip().
10958          */
10959         spin_lock_irqsave(&dev->event_lock, flags);
10960         if (intel_crtc->unpin_work && page_flip_finished(intel_crtc))
10961                 atomic_inc_not_zero(&intel_crtc->unpin_work->pending);
10962         spin_unlock_irqrestore(&dev->event_lock, flags);
10963 }
10964
10965 static inline void intel_mark_page_flip_active(struct intel_unpin_work *work)
10966 {
10967         /* Ensure that the work item is consistent when activating it ... */
10968         smp_wmb();
10969         atomic_set(&work->pending, INTEL_FLIP_PENDING);
10970         /* and that it is marked active as soon as the irq could fire. */
10971         smp_wmb();
10972 }
10973
10974 static int intel_gen2_queue_flip(struct drm_device *dev,
10975                                  struct drm_crtc *crtc,
10976                                  struct drm_framebuffer *fb,
10977                                  struct drm_i915_gem_object *obj,
10978                                  struct drm_i915_gem_request *req,
10979                                  uint32_t flags)
10980 {
10981         struct intel_engine_cs *engine = req->engine;
10982         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10983         u32 flip_mask;
10984         int ret;
10985
10986         ret = intel_ring_begin(req, 6);
10987         if (ret)
10988                 return ret;
10989
10990         /* Can't queue multiple flips, so wait for the previous
10991          * one to finish before executing the next.
10992          */
10993         if (intel_crtc->plane)
10994                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
10995         else
10996                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
10997         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
10998         intel_ring_emit(engine, MI_NOOP);
10999         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11000                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11001         intel_ring_emit(engine, fb->pitches[0]);
11002         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11003         intel_ring_emit(engine, 0); /* aux display base address, unused */
11004
11005         intel_mark_page_flip_active(intel_crtc->unpin_work);
11006         return 0;
11007 }
11008
11009 static int intel_gen3_queue_flip(struct drm_device *dev,
11010                                  struct drm_crtc *crtc,
11011                                  struct drm_framebuffer *fb,
11012                                  struct drm_i915_gem_object *obj,
11013                                  struct drm_i915_gem_request *req,
11014                                  uint32_t flags)
11015 {
11016         struct intel_engine_cs *engine = req->engine;
11017         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11018         u32 flip_mask;
11019         int ret;
11020
11021         ret = intel_ring_begin(req, 6);
11022         if (ret)
11023                 return ret;
11024
11025         if (intel_crtc->plane)
11026                 flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
11027         else
11028                 flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
11029         intel_ring_emit(engine, MI_WAIT_FOR_EVENT | flip_mask);
11030         intel_ring_emit(engine, MI_NOOP);
11031         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 |
11032                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11033         intel_ring_emit(engine, fb->pitches[0]);
11034         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11035         intel_ring_emit(engine, MI_NOOP);
11036
11037         intel_mark_page_flip_active(intel_crtc->unpin_work);
11038         return 0;
11039 }
11040
11041 static int intel_gen4_queue_flip(struct drm_device *dev,
11042                                  struct drm_crtc *crtc,
11043                                  struct drm_framebuffer *fb,
11044                                  struct drm_i915_gem_object *obj,
11045                                  struct drm_i915_gem_request *req,
11046                                  uint32_t flags)
11047 {
11048         struct intel_engine_cs *engine = req->engine;
11049         struct drm_i915_private *dev_priv = dev->dev_private;
11050         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11051         uint32_t pf, pipesrc;
11052         int ret;
11053
11054         ret = intel_ring_begin(req, 4);
11055         if (ret)
11056                 return ret;
11057
11058         /* i965+ uses the linear or tiled offsets from the
11059          * Display Registers (which do not change across a page-flip)
11060          * so we need only reprogram the base address.
11061          */
11062         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11063                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11064         intel_ring_emit(engine, fb->pitches[0]);
11065         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset |
11066                         obj->tiling_mode);
11067
11068         /* XXX Enabling the panel-fitter across page-flip is so far
11069          * untested on non-native modes, so ignore it for now.
11070          * pf = I915_READ(pipe == 0 ? PFA_CTL_1 : PFB_CTL_1) & PF_ENABLE;
11071          */
11072         pf = 0;
11073         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11074         intel_ring_emit(engine, pf | pipesrc);
11075
11076         intel_mark_page_flip_active(intel_crtc->unpin_work);
11077         return 0;
11078 }
11079
11080 static int intel_gen6_queue_flip(struct drm_device *dev,
11081                                  struct drm_crtc *crtc,
11082                                  struct drm_framebuffer *fb,
11083                                  struct drm_i915_gem_object *obj,
11084                                  struct drm_i915_gem_request *req,
11085                                  uint32_t flags)
11086 {
11087         struct intel_engine_cs *engine = req->engine;
11088         struct drm_i915_private *dev_priv = dev->dev_private;
11089         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11090         uint32_t pf, pipesrc;
11091         int ret;
11092
11093         ret = intel_ring_begin(req, 4);
11094         if (ret)
11095                 return ret;
11096
11097         intel_ring_emit(engine, MI_DISPLAY_FLIP |
11098                         MI_DISPLAY_FLIP_PLANE(intel_crtc->plane));
11099         intel_ring_emit(engine, fb->pitches[0] | obj->tiling_mode);
11100         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11101
11102         /* Contrary to the suggestions in the documentation,
11103          * "Enable Panel Fitter" does not seem to be required when page
11104          * flipping with a non-native mode, and worse causes a normal
11105          * modeset to fail.
11106          * pf = I915_READ(PF_CTL(intel_crtc->pipe)) & PF_ENABLE;
11107          */
11108         pf = 0;
11109         pipesrc = I915_READ(PIPESRC(intel_crtc->pipe)) & 0x0fff0fff;
11110         intel_ring_emit(engine, pf | pipesrc);
11111
11112         intel_mark_page_flip_active(intel_crtc->unpin_work);
11113         return 0;
11114 }
11115
11116 static int intel_gen7_queue_flip(struct drm_device *dev,
11117                                  struct drm_crtc *crtc,
11118                                  struct drm_framebuffer *fb,
11119                                  struct drm_i915_gem_object *obj,
11120                                  struct drm_i915_gem_request *req,
11121                                  uint32_t flags)
11122 {
11123         struct intel_engine_cs *engine = req->engine;
11124         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11125         uint32_t plane_bit = 0;
11126         int len, ret;
11127
11128         switch (intel_crtc->plane) {
11129         case PLANE_A:
11130                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_A;
11131                 break;
11132         case PLANE_B:
11133                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_B;
11134                 break;
11135         case PLANE_C:
11136                 plane_bit = MI_DISPLAY_FLIP_IVB_PLANE_C;
11137                 break;
11138         default:
11139                 WARN_ONCE(1, "unknown plane in flip command\n");
11140                 return -ENODEV;
11141         }
11142
11143         len = 4;
11144         if (engine->id == RCS) {
11145                 len += 6;
11146                 /*
11147                  * On Gen 8, SRM is now taking an extra dword to accommodate
11148                  * 48bits addresses, and we need a NOOP for the batch size to
11149                  * stay even.
11150                  */
11151                 if (IS_GEN8(dev))
11152                         len += 2;
11153         }
11154
11155         /*
11156          * BSpec MI_DISPLAY_FLIP for IVB:
11157          * "The full packet must be contained within the same cache line."
11158          *
11159          * Currently the LRI+SRM+MI_DISPLAY_FLIP all fit within the same
11160          * cacheline, if we ever start emitting more commands before
11161          * the MI_DISPLAY_FLIP we may need to first emit everything else,
11162          * then do the cacheline alignment, and finally emit the
11163          * MI_DISPLAY_FLIP.
11164          */
11165         ret = intel_ring_cacheline_align(req);
11166         if (ret)
11167                 return ret;
11168
11169         ret = intel_ring_begin(req, len);
11170         if (ret)
11171                 return ret;
11172
11173         /* Unmask the flip-done completion message. Note that the bspec says that
11174          * we should do this for both the BCS and RCS, and that we must not unmask
11175          * more than one flip event at any time (or ensure that one flip message
11176          * can be sent by waiting for flip-done prior to queueing new flips).
11177          * Experimentation says that BCS works despite DERRMR masking all
11178          * flip-done completion events and that unmasking all planes at once
11179          * for the RCS also doesn't appear to drop events. Setting the DERRMR
11180          * to zero does lead to lockups within MI_DISPLAY_FLIP.
11181          */
11182         if (engine->id == RCS) {
11183                 intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(1));
11184                 intel_ring_emit_reg(engine, DERRMR);
11185                 intel_ring_emit(engine, ~(DERRMR_PIPEA_PRI_FLIP_DONE |
11186                                           DERRMR_PIPEB_PRI_FLIP_DONE |
11187                                           DERRMR_PIPEC_PRI_FLIP_DONE));
11188                 if (IS_GEN8(dev))
11189                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM_GEN8 |
11190                                               MI_SRM_LRM_GLOBAL_GTT);
11191                 else
11192                         intel_ring_emit(engine, MI_STORE_REGISTER_MEM |
11193                                               MI_SRM_LRM_GLOBAL_GTT);
11194                 intel_ring_emit_reg(engine, DERRMR);
11195                 intel_ring_emit(engine, engine->scratch.gtt_offset + 256);
11196                 if (IS_GEN8(dev)) {
11197                         intel_ring_emit(engine, 0);
11198                         intel_ring_emit(engine, MI_NOOP);
11199                 }
11200         }
11201
11202         intel_ring_emit(engine, MI_DISPLAY_FLIP_I915 | plane_bit);
11203         intel_ring_emit(engine, (fb->pitches[0] | obj->tiling_mode));
11204         intel_ring_emit(engine, intel_crtc->unpin_work->gtt_offset);
11205         intel_ring_emit(engine, (MI_NOOP));
11206
11207         intel_mark_page_flip_active(intel_crtc->unpin_work);
11208         return 0;
11209 }
11210
11211 static bool use_mmio_flip(struct intel_engine_cs *engine,
11212                           struct drm_i915_gem_object *obj)
11213 {
11214         /*
11215          * This is not being used for older platforms, because
11216          * non-availability of flip done interrupt forces us to use
11217          * CS flips. Older platforms derive flip done using some clever
11218          * tricks involving the flip_pending status bits and vblank irqs.
11219          * So using MMIO flips there would disrupt this mechanism.
11220          */
11221
11222         if (engine == NULL)
11223                 return true;
11224
11225         if (INTEL_INFO(engine->dev)->gen < 5)
11226                 return false;
11227
11228         if (i915.use_mmio_flip < 0)
11229                 return false;
11230         else if (i915.use_mmio_flip > 0)
11231                 return true;
11232         else if (i915.enable_execlists)
11233                 return true;
11234         else if (obj->base.dma_buf &&
11235                  !reservation_object_test_signaled_rcu(obj->base.dma_buf->resv,
11236                                                        false))
11237                 return true;
11238         else
11239                 return engine != i915_gem_request_get_engine(obj->last_write_req);
11240 }
11241
11242 static void skl_do_mmio_flip(struct intel_crtc *intel_crtc,
11243                              unsigned int rotation,
11244                              struct intel_unpin_work *work)
11245 {
11246         struct drm_device *dev = intel_crtc->base.dev;
11247         struct drm_i915_private *dev_priv = dev->dev_private;
11248         struct drm_framebuffer *fb = intel_crtc->base.primary->fb;
11249         const enum pipe pipe = intel_crtc->pipe;
11250         u32 ctl, stride, tile_height;
11251
11252         ctl = I915_READ(PLANE_CTL(pipe, 0));
11253         ctl &= ~PLANE_CTL_TILED_MASK;
11254         switch (fb->modifier[0]) {
11255         case DRM_FORMAT_MOD_NONE:
11256                 break;
11257         case I915_FORMAT_MOD_X_TILED:
11258                 ctl |= PLANE_CTL_TILED_X;
11259                 break;
11260         case I915_FORMAT_MOD_Y_TILED:
11261                 ctl |= PLANE_CTL_TILED_Y;
11262                 break;
11263         case I915_FORMAT_MOD_Yf_TILED:
11264                 ctl |= PLANE_CTL_TILED_YF;
11265                 break;
11266         default:
11267                 MISSING_CASE(fb->modifier[0]);
11268         }
11269
11270         /*
11271          * The stride is either expressed as a multiple of 64 bytes chunks for
11272          * linear buffers or in number of tiles for tiled buffers.
11273          */
11274         if (intel_rotation_90_or_270(rotation)) {
11275                 /* stride = Surface height in tiles */
11276                 tile_height = intel_tile_height(dev_priv, fb->modifier[0], 0);
11277                 stride = DIV_ROUND_UP(fb->height, tile_height);
11278         } else {
11279                 stride = fb->pitches[0] /
11280                         intel_fb_stride_alignment(dev_priv, fb->modifier[0],
11281                                                   fb->pixel_format);
11282         }
11283
11284         /*
11285          * Both PLANE_CTL and PLANE_STRIDE are not updated on vblank but on
11286          * PLANE_SURF updates, the update is then guaranteed to be atomic.
11287          */
11288         I915_WRITE(PLANE_CTL(pipe, 0), ctl);
11289         I915_WRITE(PLANE_STRIDE(pipe, 0), stride);
11290
11291         I915_WRITE(PLANE_SURF(pipe, 0), work->gtt_offset);
11292         POSTING_READ(PLANE_SURF(pipe, 0));
11293 }
11294
11295 static void ilk_do_mmio_flip(struct intel_crtc *intel_crtc,
11296                              struct intel_unpin_work *work)
11297 {
11298         struct drm_device *dev = intel_crtc->base.dev;
11299         struct drm_i915_private *dev_priv = dev->dev_private;
11300         struct intel_framebuffer *intel_fb =
11301                 to_intel_framebuffer(intel_crtc->base.primary->fb);
11302         struct drm_i915_gem_object *obj = intel_fb->obj;
11303         i915_reg_t reg = DSPCNTR(intel_crtc->plane);
11304         u32 dspcntr;
11305
11306         dspcntr = I915_READ(reg);
11307
11308         if (obj->tiling_mode != I915_TILING_NONE)
11309                 dspcntr |= DISPPLANE_TILED;
11310         else
11311                 dspcntr &= ~DISPPLANE_TILED;
11312
11313         I915_WRITE(reg, dspcntr);
11314
11315         I915_WRITE(DSPSURF(intel_crtc->plane), work->gtt_offset);
11316         POSTING_READ(DSPSURF(intel_crtc->plane));
11317 }
11318
11319 /*
11320  * XXX: This is the temporary way to update the plane registers until we get
11321  * around to using the usual plane update functions for MMIO flips
11322  */
11323 static void intel_do_mmio_flip(struct intel_mmio_flip *mmio_flip)
11324 {
11325         struct intel_crtc *crtc = mmio_flip->crtc;
11326         struct intel_unpin_work *work;
11327
11328         spin_lock_irq(&crtc->base.dev->event_lock);
11329         work = crtc->unpin_work;
11330         spin_unlock_irq(&crtc->base.dev->event_lock);
11331         if (work == NULL)
11332                 return;
11333
11334         intel_mark_page_flip_active(work);
11335
11336         intel_pipe_update_start(crtc);
11337
11338         if (INTEL_INFO(mmio_flip->i915)->gen >= 9)
11339                 skl_do_mmio_flip(crtc, mmio_flip->rotation, work);
11340         else
11341                 /* use_mmio_flip() retricts MMIO flips to ilk+ */
11342                 ilk_do_mmio_flip(crtc, work);
11343
11344         intel_pipe_update_end(crtc);
11345 }
11346
11347 static void intel_mmio_flip_work_func(struct work_struct *work)
11348 {
11349         struct intel_mmio_flip *mmio_flip =
11350                 container_of(work, struct intel_mmio_flip, work);
11351         struct intel_framebuffer *intel_fb =
11352                 to_intel_framebuffer(mmio_flip->crtc->base.primary->fb);
11353         struct drm_i915_gem_object *obj = intel_fb->obj;
11354
11355         if (mmio_flip->req) {
11356                 WARN_ON(__i915_wait_request(mmio_flip->req,
11357                                             mmio_flip->crtc->reset_counter,
11358                                             false, NULL,
11359                                             &mmio_flip->i915->rps.mmioflips));
11360                 i915_gem_request_unreference__unlocked(mmio_flip->req);
11361         }
11362
11363         /* For framebuffer backed by dmabuf, wait for fence */
11364         if (obj->base.dma_buf)
11365                 WARN_ON(reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
11366                                                             false, false,
11367                                                             MAX_SCHEDULE_TIMEOUT) < 0);
11368
11369         intel_do_mmio_flip(mmio_flip);
11370         kfree(mmio_flip);
11371 }
11372
11373 static int intel_queue_mmio_flip(struct drm_device *dev,
11374                                  struct drm_crtc *crtc,
11375                                  struct drm_i915_gem_object *obj)
11376 {
11377         struct intel_mmio_flip *mmio_flip;
11378
11379         mmio_flip = kmalloc(sizeof(*mmio_flip), GFP_KERNEL);
11380         if (mmio_flip == NULL)
11381                 return -ENOMEM;
11382
11383         mmio_flip->i915 = to_i915(dev);
11384         mmio_flip->req = i915_gem_request_reference(obj->last_write_req);
11385         mmio_flip->crtc = to_intel_crtc(crtc);
11386         mmio_flip->rotation = crtc->primary->state->rotation;
11387
11388         INIT_WORK(&mmio_flip->work, intel_mmio_flip_work_func);
11389         schedule_work(&mmio_flip->work);
11390
11391         return 0;
11392 }
11393
11394 static int intel_default_queue_flip(struct drm_device *dev,
11395                                     struct drm_crtc *crtc,
11396                                     struct drm_framebuffer *fb,
11397                                     struct drm_i915_gem_object *obj,
11398                                     struct drm_i915_gem_request *req,
11399                                     uint32_t flags)
11400 {
11401         return -ENODEV;
11402 }
11403
11404 static bool __intel_pageflip_stall_check(struct drm_device *dev,
11405                                          struct drm_crtc *crtc)
11406 {
11407         struct drm_i915_private *dev_priv = dev->dev_private;
11408         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11409         struct intel_unpin_work *work = intel_crtc->unpin_work;
11410         u32 addr;
11411
11412         if (atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE)
11413                 return true;
11414
11415         if (atomic_read(&work->pending) < INTEL_FLIP_PENDING)
11416                 return false;
11417
11418         if (!work->enable_stall_check)
11419                 return false;
11420
11421         if (work->flip_ready_vblank == 0) {
11422                 if (work->flip_queued_req &&
11423                     !i915_gem_request_completed(work->flip_queued_req, true))
11424                         return false;
11425
11426                 work->flip_ready_vblank = drm_crtc_vblank_count(crtc);
11427         }
11428
11429         if (drm_crtc_vblank_count(crtc) - work->flip_ready_vblank < 3)
11430                 return false;
11431
11432         /* Potential stall - if we see that the flip has happened,
11433          * assume a missed interrupt. */
11434         if (INTEL_INFO(dev)->gen >= 4)
11435                 addr = I915_HI_DISPBASE(I915_READ(DSPSURF(intel_crtc->plane)));
11436         else
11437                 addr = I915_READ(DSPADDR(intel_crtc->plane));
11438
11439         /* There is a potential issue here with a false positive after a flip
11440          * to the same address. We could address this by checking for a
11441          * non-incrementing frame counter.
11442          */
11443         return addr == work->gtt_offset;
11444 }
11445
11446 void intel_check_page_flip(struct drm_device *dev, int pipe)
11447 {
11448         struct drm_i915_private *dev_priv = dev->dev_private;
11449         struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
11450         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11451         struct intel_unpin_work *work;
11452
11453         WARN_ON(!in_interrupt());
11454
11455         if (crtc == NULL)
11456                 return;
11457
11458         spin_lock(&dev->event_lock);
11459         work = intel_crtc->unpin_work;
11460         if (work != NULL && __intel_pageflip_stall_check(dev, crtc)) {
11461                 WARN_ONCE(1, "Kicking stuck page flip: queued at %d, now %d\n",
11462                          work->flip_queued_vblank, drm_vblank_count(dev, pipe));
11463                 page_flip_completed(intel_crtc);
11464                 work = NULL;
11465         }
11466         if (work != NULL &&
11467             drm_vblank_count(dev, pipe) - work->flip_queued_vblank > 1)
11468                 intel_queue_rps_boost_for_request(dev, work->flip_queued_req);
11469         spin_unlock(&dev->event_lock);
11470 }
11471
11472 static int intel_crtc_page_flip(struct drm_crtc *crtc,
11473                                 struct drm_framebuffer *fb,
11474                                 struct drm_pending_vblank_event *event,
11475                                 uint32_t page_flip_flags)
11476 {
11477         struct drm_device *dev = crtc->dev;
11478         struct drm_i915_private *dev_priv = dev->dev_private;
11479         struct drm_framebuffer *old_fb = crtc->primary->fb;
11480         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
11481         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11482         struct drm_plane *primary = crtc->primary;
11483         enum pipe pipe = intel_crtc->pipe;
11484         struct intel_unpin_work *work;
11485         struct intel_engine_cs *engine;
11486         bool mmio_flip;
11487         struct drm_i915_gem_request *request = NULL;
11488         int ret;
11489
11490         /*
11491          * drm_mode_page_flip_ioctl() should already catch this, but double
11492          * check to be safe.  In the future we may enable pageflipping from
11493          * a disabled primary plane.
11494          */
11495         if (WARN_ON(intel_fb_obj(old_fb) == NULL))
11496                 return -EBUSY;
11497
11498         /* Can't change pixel format via MI display flips. */
11499         if (fb->pixel_format != crtc->primary->fb->pixel_format)
11500                 return -EINVAL;
11501
11502         /*
11503          * TILEOFF/LINOFF registers can't be changed via MI display flips.
11504          * Note that pitch changes could also affect these register.
11505          */
11506         if (INTEL_INFO(dev)->gen > 3 &&
11507             (fb->offsets[0] != crtc->primary->fb->offsets[0] ||
11508              fb->pitches[0] != crtc->primary->fb->pitches[0]))
11509                 return -EINVAL;
11510
11511         if (i915_terminally_wedged(&dev_priv->gpu_error))
11512                 goto out_hang;
11513
11514         work = kzalloc(sizeof(*work), GFP_KERNEL);
11515         if (work == NULL)
11516                 return -ENOMEM;
11517
11518         work->event = event;
11519         work->crtc = crtc;
11520         work->old_fb = old_fb;
11521         INIT_WORK(&work->work, intel_unpin_work_fn);
11522
11523         ret = drm_crtc_vblank_get(crtc);
11524         if (ret)
11525                 goto free_work;
11526
11527         /* We borrow the event spin lock for protecting unpin_work */
11528         spin_lock_irq(&dev->event_lock);
11529         if (intel_crtc->unpin_work) {
11530                 /* Before declaring the flip queue wedged, check if
11531                  * the hardware completed the operation behind our backs.
11532                  */
11533                 if (__intel_pageflip_stall_check(dev, crtc)) {
11534                         DRM_DEBUG_DRIVER("flip queue: previous flip completed, continuing\n");
11535                         page_flip_completed(intel_crtc);
11536                 } else {
11537                         DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
11538                         spin_unlock_irq(&dev->event_lock);
11539
11540                         drm_crtc_vblank_put(crtc);
11541                         kfree(work);
11542                         return -EBUSY;
11543                 }
11544         }
11545         intel_crtc->unpin_work = work;
11546         spin_unlock_irq(&dev->event_lock);
11547
11548         if (atomic_read(&intel_crtc->unpin_work_count) >= 2)
11549                 flush_workqueue(dev_priv->wq);
11550
11551         /* Reference the objects for the scheduled work. */
11552         drm_framebuffer_reference(work->old_fb);
11553         drm_gem_object_reference(&obj->base);
11554
11555         crtc->primary->fb = fb;
11556         update_state_fb(crtc->primary);
11557         intel_fbc_pre_update(intel_crtc);
11558
11559         work->pending_flip_obj = obj;
11560
11561         ret = i915_mutex_lock_interruptible(dev);
11562         if (ret)
11563                 goto cleanup;
11564
11565         atomic_inc(&intel_crtc->unpin_work_count);
11566         intel_crtc->reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
11567
11568         if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev))
11569                 work->flip_count = I915_READ(PIPE_FLIPCOUNT_G4X(pipe)) + 1;
11570
11571         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
11572                 engine = &dev_priv->engine[BCS];
11573                 if (obj->tiling_mode != intel_fb_obj(work->old_fb)->tiling_mode)
11574                         /* vlv: DISPLAY_FLIP fails to change tiling */
11575                         engine = NULL;
11576         } else if (IS_IVYBRIDGE(dev) || IS_HASWELL(dev)) {
11577                 engine = &dev_priv->engine[BCS];
11578         } else if (INTEL_INFO(dev)->gen >= 7) {
11579                 engine = i915_gem_request_get_engine(obj->last_write_req);
11580                 if (engine == NULL || engine->id != RCS)
11581                         engine = &dev_priv->engine[BCS];
11582         } else {
11583                 engine = &dev_priv->engine[RCS];
11584         }
11585
11586         mmio_flip = use_mmio_flip(engine, obj);
11587
11588         /* When using CS flips, we want to emit semaphores between rings.
11589          * However, when using mmio flips we will create a task to do the
11590          * synchronisation, so all we want here is to pin the framebuffer
11591          * into the display plane and skip any waits.
11592          */
11593         if (!mmio_flip) {
11594                 ret = i915_gem_object_sync(obj, engine, &request);
11595                 if (ret)
11596                         goto cleanup_pending;
11597         }
11598
11599         ret = intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
11600         if (ret)
11601                 goto cleanup_pending;
11602
11603         work->gtt_offset = intel_plane_obj_offset(to_intel_plane(primary),
11604                                                   obj, 0);
11605         work->gtt_offset += intel_crtc->dspaddr_offset;
11606
11607         if (mmio_flip) {
11608                 ret = intel_queue_mmio_flip(dev, crtc, obj);
11609                 if (ret)
11610                         goto cleanup_unpin;
11611
11612                 i915_gem_request_assign(&work->flip_queued_req,
11613                                         obj->last_write_req);
11614         } else {
11615                 if (!request) {
11616                         request = i915_gem_request_alloc(engine, NULL);
11617                         if (IS_ERR(request)) {
11618                                 ret = PTR_ERR(request);
11619                                 goto cleanup_unpin;
11620                         }
11621                 }
11622
11623                 ret = dev_priv->display.queue_flip(dev, crtc, fb, obj, request,
11624                                                    page_flip_flags);
11625                 if (ret)
11626                         goto cleanup_unpin;
11627
11628                 i915_gem_request_assign(&work->flip_queued_req, request);
11629         }
11630
11631         if (request)
11632                 i915_add_request_no_flush(request);
11633
11634         work->flip_queued_vblank = drm_crtc_vblank_count(crtc);
11635         work->enable_stall_check = true;
11636
11637         i915_gem_track_fb(intel_fb_obj(work->old_fb), obj,
11638                           to_intel_plane(primary)->frontbuffer_bit);
11639         mutex_unlock(&dev->struct_mutex);
11640
11641         intel_frontbuffer_flip_prepare(dev,
11642                                        to_intel_plane(primary)->frontbuffer_bit);
11643
11644         trace_i915_flip_request(intel_crtc->plane, obj);
11645
11646         return 0;
11647
11648 cleanup_unpin:
11649         intel_unpin_fb_obj(fb, crtc->primary->state->rotation);
11650 cleanup_pending:
11651         if (!IS_ERR_OR_NULL(request))
11652                 i915_gem_request_cancel(request);
11653         atomic_dec(&intel_crtc->unpin_work_count);
11654         mutex_unlock(&dev->struct_mutex);
11655 cleanup:
11656         crtc->primary->fb = old_fb;
11657         update_state_fb(crtc->primary);
11658
11659         drm_gem_object_unreference_unlocked(&obj->base);
11660         drm_framebuffer_unreference(work->old_fb);
11661
11662         spin_lock_irq(&dev->event_lock);
11663         intel_crtc->unpin_work = NULL;
11664         spin_unlock_irq(&dev->event_lock);
11665
11666         drm_crtc_vblank_put(crtc);
11667 free_work:
11668         kfree(work);
11669
11670         if (ret == -EIO) {
11671                 struct drm_atomic_state *state;
11672                 struct drm_plane_state *plane_state;
11673
11674 out_hang:
11675                 state = drm_atomic_state_alloc(dev);
11676                 if (!state)
11677                         return -ENOMEM;
11678                 state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
11679
11680 retry:
11681                 plane_state = drm_atomic_get_plane_state(state, primary);
11682                 ret = PTR_ERR_OR_ZERO(plane_state);
11683                 if (!ret) {
11684                         drm_atomic_set_fb_for_plane(plane_state, fb);
11685
11686                         ret = drm_atomic_set_crtc_for_plane(plane_state, crtc);
11687                         if (!ret)
11688                                 ret = drm_atomic_commit(state);
11689                 }
11690
11691                 if (ret == -EDEADLK) {
11692                         drm_modeset_backoff(state->acquire_ctx);
11693                         drm_atomic_state_clear(state);
11694                         goto retry;
11695                 }
11696
11697                 if (ret)
11698                         drm_atomic_state_free(state);
11699
11700                 if (ret == 0 && event) {
11701                         spin_lock_irq(&dev->event_lock);
11702                         drm_send_vblank_event(dev, pipe, event);
11703                         spin_unlock_irq(&dev->event_lock);
11704                 }
11705         }
11706         return ret;
11707 }
11708
11709
11710 /**
11711  * intel_wm_need_update - Check whether watermarks need updating
11712  * @plane: drm plane
11713  * @state: new plane state
11714  *
11715  * Check current plane state versus the new one to determine whether
11716  * watermarks need to be recalculated.
11717  *
11718  * Returns true or false.
11719  */
11720 static bool intel_wm_need_update(struct drm_plane *plane,
11721                                  struct drm_plane_state *state)
11722 {
11723         struct intel_plane_state *new = to_intel_plane_state(state);
11724         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
11725
11726         /* Update watermarks on tiling or size changes. */
11727         if (new->visible != cur->visible)
11728                 return true;
11729
11730         if (!cur->base.fb || !new->base.fb)
11731                 return false;
11732
11733         if (cur->base.fb->modifier[0] != new->base.fb->modifier[0] ||
11734             cur->base.rotation != new->base.rotation ||
11735             drm_rect_width(&new->src) != drm_rect_width(&cur->src) ||
11736             drm_rect_height(&new->src) != drm_rect_height(&cur->src) ||
11737             drm_rect_width(&new->dst) != drm_rect_width(&cur->dst) ||
11738             drm_rect_height(&new->dst) != drm_rect_height(&cur->dst))
11739                 return true;
11740
11741         return false;
11742 }
11743
11744 static bool needs_scaling(struct intel_plane_state *state)
11745 {
11746         int src_w = drm_rect_width(&state->src) >> 16;
11747         int src_h = drm_rect_height(&state->src) >> 16;
11748         int dst_w = drm_rect_width(&state->dst);
11749         int dst_h = drm_rect_height(&state->dst);
11750
11751         return (src_w != dst_w || src_h != dst_h);
11752 }
11753
11754 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
11755                                     struct drm_plane_state *plane_state)
11756 {
11757         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
11758         struct drm_crtc *crtc = crtc_state->crtc;
11759         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11760         struct drm_plane *plane = plane_state->plane;
11761         struct drm_device *dev = crtc->dev;
11762         struct drm_i915_private *dev_priv = to_i915(dev);
11763         struct intel_plane_state *old_plane_state =
11764                 to_intel_plane_state(plane->state);
11765         int idx = intel_crtc->base.base.id, ret;
11766         bool mode_changed = needs_modeset(crtc_state);
11767         bool was_crtc_enabled = crtc->state->active;
11768         bool is_crtc_enabled = crtc_state->active;
11769         bool turn_off, turn_on, visible, was_visible;
11770         struct drm_framebuffer *fb = plane_state->fb;
11771
11772         if (crtc_state && INTEL_INFO(dev)->gen >= 9 &&
11773             plane->type != DRM_PLANE_TYPE_CURSOR) {
11774                 ret = skl_update_scaler_plane(
11775                         to_intel_crtc_state(crtc_state),
11776                         to_intel_plane_state(plane_state));
11777                 if (ret)
11778                         return ret;
11779         }
11780
11781         was_visible = old_plane_state->visible;
11782         visible = to_intel_plane_state(plane_state)->visible;
11783
11784         if (!was_crtc_enabled && WARN_ON(was_visible))
11785                 was_visible = false;
11786
11787         /*
11788          * Visibility is calculated as if the crtc was on, but
11789          * after scaler setup everything depends on it being off
11790          * when the crtc isn't active.
11791          */
11792         if (!is_crtc_enabled)
11793                 to_intel_plane_state(plane_state)->visible = visible = false;
11794
11795         if (!was_visible && !visible)
11796                 return 0;
11797
11798         if (fb != old_plane_state->base.fb)
11799                 pipe_config->fb_changed = true;
11800
11801         turn_off = was_visible && (!visible || mode_changed);
11802         turn_on = visible && (!was_visible || mode_changed);
11803
11804         DRM_DEBUG_ATOMIC("[CRTC:%i] has [PLANE:%i] with fb %i\n", idx,
11805                          plane->base.id, fb ? fb->base.id : -1);
11806
11807         DRM_DEBUG_ATOMIC("[PLANE:%i] visible %i -> %i, off %i, on %i, ms %i\n",
11808                          plane->base.id, was_visible, visible,
11809                          turn_off, turn_on, mode_changed);
11810
11811         if (turn_on) {
11812                 pipe_config->update_wm_pre = true;
11813
11814                 /* must disable cxsr around plane enable/disable */
11815                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11816                         pipe_config->disable_cxsr = true;
11817         } else if (turn_off) {
11818                 pipe_config->update_wm_post = true;
11819
11820                 /* must disable cxsr around plane enable/disable */
11821                 if (plane->type != DRM_PLANE_TYPE_CURSOR)
11822                         pipe_config->disable_cxsr = true;
11823         } else if (intel_wm_need_update(plane, plane_state)) {
11824                 /* FIXME bollocks */
11825                 pipe_config->update_wm_pre = true;
11826                 pipe_config->update_wm_post = true;
11827         }
11828
11829         /* Pre-gen9 platforms need two-step watermark updates */
11830         if ((pipe_config->update_wm_pre || pipe_config->update_wm_post) &&
11831             INTEL_INFO(dev)->gen < 9 && dev_priv->display.optimize_watermarks)
11832                 to_intel_crtc_state(crtc_state)->wm.need_postvbl_update = true;
11833
11834         if (visible || was_visible)
11835                 pipe_config->fb_bits |= to_intel_plane(plane)->frontbuffer_bit;
11836
11837         /*
11838          * WaCxSRDisabledForSpriteScaling:ivb
11839          *
11840          * cstate->update_wm was already set above, so this flag will
11841          * take effect when we commit and program watermarks.
11842          */
11843         if (plane->type == DRM_PLANE_TYPE_OVERLAY && IS_IVYBRIDGE(dev) &&
11844             needs_scaling(to_intel_plane_state(plane_state)) &&
11845             !needs_scaling(old_plane_state))
11846                 pipe_config->disable_lp_wm = true;
11847
11848         return 0;
11849 }
11850
11851 static bool encoders_cloneable(const struct intel_encoder *a,
11852                                const struct intel_encoder *b)
11853 {
11854         /* masks could be asymmetric, so check both ways */
11855         return a == b || (a->cloneable & (1 << b->type) &&
11856                           b->cloneable & (1 << a->type));
11857 }
11858
11859 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
11860                                          struct intel_crtc *crtc,
11861                                          struct intel_encoder *encoder)
11862 {
11863         struct intel_encoder *source_encoder;
11864         struct drm_connector *connector;
11865         struct drm_connector_state *connector_state;
11866         int i;
11867
11868         for_each_connector_in_state(state, connector, connector_state, i) {
11869                 if (connector_state->crtc != &crtc->base)
11870                         continue;
11871
11872                 source_encoder =
11873                         to_intel_encoder(connector_state->best_encoder);
11874                 if (!encoders_cloneable(encoder, source_encoder))
11875                         return false;
11876         }
11877
11878         return true;
11879 }
11880
11881 static bool check_encoder_cloning(struct drm_atomic_state *state,
11882                                   struct intel_crtc *crtc)
11883 {
11884         struct intel_encoder *encoder;
11885         struct drm_connector *connector;
11886         struct drm_connector_state *connector_state;
11887         int i;
11888
11889         for_each_connector_in_state(state, connector, connector_state, i) {
11890                 if (connector_state->crtc != &crtc->base)
11891                         continue;
11892
11893                 encoder = to_intel_encoder(connector_state->best_encoder);
11894                 if (!check_single_encoder_cloning(state, crtc, encoder))
11895                         return false;
11896         }
11897
11898         return true;
11899 }
11900
11901 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11902                                    struct drm_crtc_state *crtc_state)
11903 {
11904         struct drm_device *dev = crtc->dev;
11905         struct drm_i915_private *dev_priv = dev->dev_private;
11906         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11907         struct intel_crtc_state *pipe_config =
11908                 to_intel_crtc_state(crtc_state);
11909         struct drm_atomic_state *state = crtc_state->state;
11910         int ret;
11911         bool mode_changed = needs_modeset(crtc_state);
11912
11913         if (mode_changed && !check_encoder_cloning(state, intel_crtc)) {
11914                 DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11915                 return -EINVAL;
11916         }
11917
11918         if (mode_changed && !crtc_state->active)
11919                 pipe_config->update_wm_post = true;
11920
11921         if (mode_changed && crtc_state->enable &&
11922             dev_priv->display.crtc_compute_clock &&
11923             !WARN_ON(pipe_config->shared_dpll)) {
11924                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11925                                                            pipe_config);
11926                 if (ret)
11927                         return ret;
11928         }
11929
11930         if (crtc_state->color_mgmt_changed) {
11931                 ret = intel_color_check(crtc, crtc_state);
11932                 if (ret)
11933                         return ret;
11934         }
11935
11936         ret = 0;
11937         if (dev_priv->display.compute_pipe_wm) {
11938                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11939                 if (ret) {
11940                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11941                         return ret;
11942                 }
11943         }
11944
11945         if (dev_priv->display.compute_intermediate_wm &&
11946             !to_intel_atomic_state(state)->skip_intermediate_wm) {
11947                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11948                         return 0;
11949
11950                 /*
11951                  * Calculate 'intermediate' watermarks that satisfy both the
11952                  * old state and the new state.  We can program these
11953                  * immediately.
11954                  */
11955                 ret = dev_priv->display.compute_intermediate_wm(crtc->dev,
11956                                                                 intel_crtc,
11957                                                                 pipe_config);
11958                 if (ret) {
11959                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11960                         return ret;
11961                 }
11962         }
11963
11964         if (INTEL_INFO(dev)->gen >= 9) {
11965                 if (mode_changed)
11966                         ret = skl_update_scaler_crtc(pipe_config);
11967
11968                 if (!ret)
11969                         ret = intel_atomic_setup_scalers(dev, intel_crtc,
11970                                                          pipe_config);
11971         }
11972
11973         return ret;
11974 }
11975
11976 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11977         .mode_set_base_atomic = intel_pipe_set_base_atomic,
11978         .atomic_begin = intel_begin_crtc_commit,
11979         .atomic_flush = intel_finish_crtc_commit,
11980         .atomic_check = intel_crtc_atomic_check,
11981 };
11982
11983 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11984 {
11985         struct intel_connector *connector;
11986
11987         for_each_intel_connector(dev, connector) {
11988                 if (connector->base.encoder) {
11989                         connector->base.state->best_encoder =
11990                                 connector->base.encoder;
11991                         connector->base.state->crtc =
11992                                 connector->base.encoder->crtc;
11993                 } else {
11994                         connector->base.state->best_encoder = NULL;
11995                         connector->base.state->crtc = NULL;
11996                 }
11997         }
11998 }
11999
12000 static void
12001 connected_sink_compute_bpp(struct intel_connector *connector,
12002                            struct intel_crtc_state *pipe_config)
12003 {
12004         int bpp = pipe_config->pipe_bpp;
12005
12006         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
12007                 connector->base.base.id,
12008                 connector->base.name);
12009
12010         /* Don't use an invalid EDID bpc value */
12011         if (connector->base.display_info.bpc &&
12012             connector->base.display_info.bpc * 3 < bpp) {
12013                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
12014                               bpp, connector->base.display_info.bpc*3);
12015                 pipe_config->pipe_bpp = connector->base.display_info.bpc*3;
12016         }
12017
12018         /* Clamp bpp to default limit on screens without EDID 1.4 */
12019         if (connector->base.display_info.bpc == 0) {
12020                 int type = connector->base.connector_type;
12021                 int clamp_bpp = 24;
12022
12023                 /* Fall back to 18 bpp when DP sink capability is unknown. */
12024                 if (type == DRM_MODE_CONNECTOR_DisplayPort ||
12025                     type == DRM_MODE_CONNECTOR_eDP)
12026                         clamp_bpp = 18;
12027
12028                 if (bpp > clamp_bpp) {
12029                         DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of %d\n",
12030                                       bpp, clamp_bpp);
12031                         pipe_config->pipe_bpp = clamp_bpp;
12032                 }
12033         }
12034 }
12035
12036 static int
12037 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
12038                           struct intel_crtc_state *pipe_config)
12039 {
12040         struct drm_device *dev = crtc->base.dev;
12041         struct drm_atomic_state *state;
12042         struct drm_connector *connector;
12043         struct drm_connector_state *connector_state;
12044         int bpp, i;
12045
12046         if ((IS_G4X(dev) || IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)))
12047                 bpp = 10*3;
12048         else if (INTEL_INFO(dev)->gen >= 5)
12049                 bpp = 12*3;
12050         else
12051                 bpp = 8*3;
12052
12053
12054         pipe_config->pipe_bpp = bpp;
12055
12056         state = pipe_config->base.state;
12057
12058         /* Clamp display bpp to EDID value */
12059         for_each_connector_in_state(state, connector, connector_state, i) {
12060                 if (connector_state->crtc != &crtc->base)
12061                         continue;
12062
12063                 connected_sink_compute_bpp(to_intel_connector(connector),
12064                                            pipe_config);
12065         }
12066
12067         return bpp;
12068 }
12069
12070 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
12071 {
12072         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
12073                         "type: 0x%x flags: 0x%x\n",
12074                 mode->crtc_clock,
12075                 mode->crtc_hdisplay, mode->crtc_hsync_start,
12076                 mode->crtc_hsync_end, mode->crtc_htotal,
12077                 mode->crtc_vdisplay, mode->crtc_vsync_start,
12078                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
12079 }
12080
12081 static void intel_dump_pipe_config(struct intel_crtc *crtc,
12082                                    struct intel_crtc_state *pipe_config,
12083                                    const char *context)
12084 {
12085         struct drm_device *dev = crtc->base.dev;
12086         struct drm_plane *plane;
12087         struct intel_plane *intel_plane;
12088         struct intel_plane_state *state;
12089         struct drm_framebuffer *fb;
12090
12091         DRM_DEBUG_KMS("[CRTC:%d]%s config %p for pipe %c\n", crtc->base.base.id,
12092                       context, pipe_config, pipe_name(crtc->pipe));
12093
12094         DRM_DEBUG_KMS("cpu_transcoder: %s\n", transcoder_name(pipe_config->cpu_transcoder));
12095         DRM_DEBUG_KMS("pipe bpp: %i, dithering: %i\n",
12096                       pipe_config->pipe_bpp, pipe_config->dither);
12097         DRM_DEBUG_KMS("fdi/pch: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12098                       pipe_config->has_pch_encoder,
12099                       pipe_config->fdi_lanes,
12100                       pipe_config->fdi_m_n.gmch_m, pipe_config->fdi_m_n.gmch_n,
12101                       pipe_config->fdi_m_n.link_m, pipe_config->fdi_m_n.link_n,
12102                       pipe_config->fdi_m_n.tu);
12103         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
12104                       pipe_config->has_dp_encoder,
12105                       pipe_config->lane_count,
12106                       pipe_config->dp_m_n.gmch_m, pipe_config->dp_m_n.gmch_n,
12107                       pipe_config->dp_m_n.link_m, pipe_config->dp_m_n.link_n,
12108                       pipe_config->dp_m_n.tu);
12109
12110         DRM_DEBUG_KMS("dp: %i, lanes: %i, gmch_m2: %u, gmch_n2: %u, link_m2: %u, link_n2: %u, tu2: %u\n",
12111                       pipe_config->has_dp_encoder,
12112                       pipe_config->lane_count,
12113                       pipe_config->dp_m2_n2.gmch_m,
12114                       pipe_config->dp_m2_n2.gmch_n,
12115                       pipe_config->dp_m2_n2.link_m,
12116                       pipe_config->dp_m2_n2.link_n,
12117                       pipe_config->dp_m2_n2.tu);
12118
12119         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
12120                       pipe_config->has_audio,
12121                       pipe_config->has_infoframe);
12122
12123         DRM_DEBUG_KMS("requested mode:\n");
12124         drm_mode_debug_printmodeline(&pipe_config->base.mode);
12125         DRM_DEBUG_KMS("adjusted mode:\n");
12126         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
12127         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
12128         DRM_DEBUG_KMS("port clock: %d\n", pipe_config->port_clock);
12129         DRM_DEBUG_KMS("pipe src size: %dx%d\n",
12130                       pipe_config->pipe_src_w, pipe_config->pipe_src_h);
12131         DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
12132                       crtc->num_scalers,
12133                       pipe_config->scaler_state.scaler_users,
12134                       pipe_config->scaler_state.scaler_id);
12135         DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
12136                       pipe_config->gmch_pfit.control,
12137                       pipe_config->gmch_pfit.pgm_ratios,
12138                       pipe_config->gmch_pfit.lvds_border_bits);
12139         DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
12140                       pipe_config->pch_pfit.pos,
12141                       pipe_config->pch_pfit.size,
12142                       pipe_config->pch_pfit.enabled ? "enabled" : "disabled");
12143         DRM_DEBUG_KMS("ips: %i\n", pipe_config->ips_enabled);
12144         DRM_DEBUG_KMS("double wide: %i\n", pipe_config->double_wide);
12145
12146         if (IS_BROXTON(dev)) {
12147                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: ebb0: 0x%x, ebb4: 0x%x,"
12148                               "pll0: 0x%x, pll1: 0x%x, pll2: 0x%x, pll3: 0x%x, "
12149                               "pll6: 0x%x, pll8: 0x%x, pll9: 0x%x, pll10: 0x%x, pcsdw12: 0x%x\n",
12150                               pipe_config->ddi_pll_sel,
12151                               pipe_config->dpll_hw_state.ebb0,
12152                               pipe_config->dpll_hw_state.ebb4,
12153                               pipe_config->dpll_hw_state.pll0,
12154                               pipe_config->dpll_hw_state.pll1,
12155                               pipe_config->dpll_hw_state.pll2,
12156                               pipe_config->dpll_hw_state.pll3,
12157                               pipe_config->dpll_hw_state.pll6,
12158                               pipe_config->dpll_hw_state.pll8,
12159                               pipe_config->dpll_hw_state.pll9,
12160                               pipe_config->dpll_hw_state.pll10,
12161                               pipe_config->dpll_hw_state.pcsdw12);
12162         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
12163                 DRM_DEBUG_KMS("ddi_pll_sel: %u; dpll_hw_state: "
12164                               "ctrl1: 0x%x, cfgcr1: 0x%x, cfgcr2: 0x%x\n",
12165                               pipe_config->ddi_pll_sel,
12166                               pipe_config->dpll_hw_state.ctrl1,
12167                               pipe_config->dpll_hw_state.cfgcr1,
12168                               pipe_config->dpll_hw_state.cfgcr2);
12169         } else if (HAS_DDI(dev)) {
12170                 DRM_DEBUG_KMS("ddi_pll_sel: 0x%x; dpll_hw_state: wrpll: 0x%x spll: 0x%x\n",
12171                               pipe_config->ddi_pll_sel,
12172                               pipe_config->dpll_hw_state.wrpll,
12173                               pipe_config->dpll_hw_state.spll);
12174         } else {
12175                 DRM_DEBUG_KMS("dpll_hw_state: dpll: 0x%x, dpll_md: 0x%x, "
12176                               "fp0: 0x%x, fp1: 0x%x\n",
12177                               pipe_config->dpll_hw_state.dpll,
12178                               pipe_config->dpll_hw_state.dpll_md,
12179                               pipe_config->dpll_hw_state.fp0,
12180                               pipe_config->dpll_hw_state.fp1);
12181         }
12182
12183         DRM_DEBUG_KMS("planes on this crtc\n");
12184         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
12185                 intel_plane = to_intel_plane(plane);
12186                 if (intel_plane->pipe != crtc->pipe)
12187                         continue;
12188
12189                 state = to_intel_plane_state(plane->state);
12190                 fb = state->base.fb;
12191                 if (!fb) {
12192                         DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d "
12193                                 "disabled, scaler_id = %d\n",
12194                                 plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12195                                 plane->base.id, intel_plane->pipe,
12196                                 (crtc->base.primary == plane) ? 0 : intel_plane->plane + 1,
12197                                 drm_plane_index(plane), state->scaler_id);
12198                         continue;
12199                 }
12200
12201                 DRM_DEBUG_KMS("%s PLANE:%d plane: %u.%u idx: %d enabled",
12202                         plane->type == DRM_PLANE_TYPE_CURSOR ? "CURSOR" : "STANDARD",
12203                         plane->base.id, intel_plane->pipe,
12204                         crtc->base.primary == plane ? 0 : intel_plane->plane + 1,
12205                         drm_plane_index(plane));
12206                 DRM_DEBUG_KMS("\tFB:%d, fb = %ux%u format = 0x%x",
12207                         fb->base.id, fb->width, fb->height, fb->pixel_format);
12208                 DRM_DEBUG_KMS("\tscaler:%d src (%u, %u) %ux%u dst (%u, %u) %ux%u\n",
12209                         state->scaler_id,
12210                         state->src.x1 >> 16, state->src.y1 >> 16,
12211                         drm_rect_width(&state->src) >> 16,
12212                         drm_rect_height(&state->src) >> 16,
12213                         state->dst.x1, state->dst.y1,
12214                         drm_rect_width(&state->dst), drm_rect_height(&state->dst));
12215         }
12216 }
12217
12218 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
12219 {
12220         struct drm_device *dev = state->dev;
12221         struct drm_connector *connector;
12222         unsigned int used_ports = 0;
12223
12224         /*
12225          * Walk the connector list instead of the encoder
12226          * list to detect the problem on ddi platforms
12227          * where there's just one encoder per digital port.
12228          */
12229         drm_for_each_connector(connector, dev) {
12230                 struct drm_connector_state *connector_state;
12231                 struct intel_encoder *encoder;
12232
12233                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
12234                 if (!connector_state)
12235                         connector_state = connector->state;
12236
12237                 if (!connector_state->best_encoder)
12238                         continue;
12239
12240                 encoder = to_intel_encoder(connector_state->best_encoder);
12241
12242                 WARN_ON(!connector_state->crtc);
12243
12244                 switch (encoder->type) {
12245                         unsigned int port_mask;
12246                 case INTEL_OUTPUT_UNKNOWN:
12247                         if (WARN_ON(!HAS_DDI(dev)))
12248                                 break;
12249                 case INTEL_OUTPUT_DISPLAYPORT:
12250                 case INTEL_OUTPUT_HDMI:
12251                 case INTEL_OUTPUT_EDP:
12252                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
12253
12254                         /* the same port mustn't appear more than once */
12255                         if (used_ports & port_mask)
12256                                 return false;
12257
12258                         used_ports |= port_mask;
12259                 default:
12260                         break;
12261                 }
12262         }
12263
12264         return true;
12265 }
12266
12267 static void
12268 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
12269 {
12270         struct drm_crtc_state tmp_state;
12271         struct intel_crtc_scaler_state scaler_state;
12272         struct intel_dpll_hw_state dpll_hw_state;
12273         struct intel_shared_dpll *shared_dpll;
12274         uint32_t ddi_pll_sel;
12275         bool force_thru;
12276
12277         /* FIXME: before the switch to atomic started, a new pipe_config was
12278          * kzalloc'd. Code that depends on any field being zero should be
12279          * fixed, so that the crtc_state can be safely duplicated. For now,
12280          * only fields that are know to not cause problems are preserved. */
12281
12282         tmp_state = crtc_state->base;
12283         scaler_state = crtc_state->scaler_state;
12284         shared_dpll = crtc_state->shared_dpll;
12285         dpll_hw_state = crtc_state->dpll_hw_state;
12286         ddi_pll_sel = crtc_state->ddi_pll_sel;
12287         force_thru = crtc_state->pch_pfit.force_thru;
12288
12289         memset(crtc_state, 0, sizeof *crtc_state);
12290
12291         crtc_state->base = tmp_state;
12292         crtc_state->scaler_state = scaler_state;
12293         crtc_state->shared_dpll = shared_dpll;
12294         crtc_state->dpll_hw_state = dpll_hw_state;
12295         crtc_state->ddi_pll_sel = ddi_pll_sel;
12296         crtc_state->pch_pfit.force_thru = force_thru;
12297 }
12298
12299 static int
12300 intel_modeset_pipe_config(struct drm_crtc *crtc,
12301                           struct intel_crtc_state *pipe_config)
12302 {
12303         struct drm_atomic_state *state = pipe_config->base.state;
12304         struct intel_encoder *encoder;
12305         struct drm_connector *connector;
12306         struct drm_connector_state *connector_state;
12307         int base_bpp, ret = -EINVAL;
12308         int i;
12309         bool retry = true;
12310
12311         clear_intel_crtc_state(pipe_config);
12312
12313         pipe_config->cpu_transcoder =
12314                 (enum transcoder) to_intel_crtc(crtc)->pipe;
12315
12316         /*
12317          * Sanitize sync polarity flags based on requested ones. If neither
12318          * positive or negative polarity is requested, treat this as meaning
12319          * negative polarity.
12320          */
12321         if (!(pipe_config->base.adjusted_mode.flags &
12322               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
12323                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
12324
12325         if (!(pipe_config->base.adjusted_mode.flags &
12326               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
12327                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
12328
12329         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
12330                                              pipe_config);
12331         if (base_bpp < 0)
12332                 goto fail;
12333
12334         /*
12335          * Determine the real pipe dimensions. Note that stereo modes can
12336          * increase the actual pipe size due to the frame doubling and
12337          * insertion of additional space for blanks between the frame. This
12338          * is stored in the crtc timings. We use the requested mode to do this
12339          * computation to clearly distinguish it from the adjusted mode, which
12340          * can be changed by the connectors in the below retry loop.
12341          */
12342         drm_crtc_get_hv_timing(&pipe_config->base.mode,
12343                                &pipe_config->pipe_src_w,
12344                                &pipe_config->pipe_src_h);
12345
12346 encoder_retry:
12347         /* Ensure the port clock defaults are reset when retrying. */
12348         pipe_config->port_clock = 0;
12349         pipe_config->pixel_multiplier = 1;
12350
12351         /* Fill in default crtc timings, allow encoders to overwrite them. */
12352         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
12353                               CRTC_STEREO_DOUBLE);
12354
12355         /* Pass our mode to the connectors and the CRTC to give them a chance to
12356          * adjust it according to limitations or connector properties, and also
12357          * a chance to reject the mode entirely.
12358          */
12359         for_each_connector_in_state(state, connector, connector_state, i) {
12360                 if (connector_state->crtc != crtc)
12361                         continue;
12362
12363                 encoder = to_intel_encoder(connector_state->best_encoder);
12364
12365                 if (!(encoder->compute_config(encoder, pipe_config))) {
12366                         DRM_DEBUG_KMS("Encoder config failure\n");
12367                         goto fail;
12368                 }
12369         }
12370
12371         /* Set default port clock if not overwritten by the encoder. Needs to be
12372          * done afterwards in case the encoder adjusts the mode. */
12373         if (!pipe_config->port_clock)
12374                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
12375                         * pipe_config->pixel_multiplier;
12376
12377         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
12378         if (ret < 0) {
12379                 DRM_DEBUG_KMS("CRTC fixup failed\n");
12380                 goto fail;
12381         }
12382
12383         if (ret == RETRY) {
12384                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
12385                         ret = -EINVAL;
12386                         goto fail;
12387                 }
12388
12389                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
12390                 retry = false;
12391                 goto encoder_retry;
12392         }
12393
12394         /* Dithering seems to not pass-through bits correctly when it should, so
12395          * only enable it on 6bpc panels. */
12396         pipe_config->dither = pipe_config->pipe_bpp == 6*3;
12397         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
12398                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
12399
12400 fail:
12401         return ret;
12402 }
12403
12404 static void
12405 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
12406 {
12407         struct drm_crtc *crtc;
12408         struct drm_crtc_state *crtc_state;
12409         int i;
12410
12411         /* Double check state. */
12412         for_each_crtc_in_state(state, crtc, crtc_state, i) {
12413                 to_intel_crtc(crtc)->config = to_intel_crtc_state(crtc->state);
12414
12415                 /* Update hwmode for vblank functions */
12416                 if (crtc->state->active)
12417                         crtc->hwmode = crtc->state->adjusted_mode;
12418                 else
12419                         crtc->hwmode.crtc_clock = 0;
12420
12421                 /*
12422                  * Update legacy state to satisfy fbc code. This can
12423                  * be removed when fbc uses the atomic state.
12424                  */
12425                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12426                         struct drm_plane_state *plane_state = crtc->primary->state;
12427
12428                         crtc->primary->fb = plane_state->fb;
12429                         crtc->x = plane_state->src_x >> 16;
12430                         crtc->y = plane_state->src_y >> 16;
12431                 }
12432         }
12433 }
12434
12435 static bool intel_fuzzy_clock_check(int clock1, int clock2)
12436 {
12437         int diff;
12438
12439         if (clock1 == clock2)
12440                 return true;
12441
12442         if (!clock1 || !clock2)
12443                 return false;
12444
12445         diff = abs(clock1 - clock2);
12446
12447         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
12448                 return true;
12449
12450         return false;
12451 }
12452
12453 #define for_each_intel_crtc_masked(dev, mask, intel_crtc) \
12454         list_for_each_entry((intel_crtc), \
12455                             &(dev)->mode_config.crtc_list, \
12456                             base.head) \
12457                 for_each_if (mask & (1 <<(intel_crtc)->pipe))
12458
12459 static bool
12460 intel_compare_m_n(unsigned int m, unsigned int n,
12461                   unsigned int m2, unsigned int n2,
12462                   bool exact)
12463 {
12464         if (m == m2 && n == n2)
12465                 return true;
12466
12467         if (exact || !m || !n || !m2 || !n2)
12468                 return false;
12469
12470         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
12471
12472         if (n > n2) {
12473                 while (n > n2) {
12474                         m2 <<= 1;
12475                         n2 <<= 1;
12476                 }
12477         } else if (n < n2) {
12478                 while (n < n2) {
12479                         m <<= 1;
12480                         n <<= 1;
12481                 }
12482         }
12483
12484         if (n != n2)
12485                 return false;
12486
12487         return intel_fuzzy_clock_check(m, m2);
12488 }
12489
12490 static bool
12491 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
12492                        struct intel_link_m_n *m2_n2,
12493                        bool adjust)
12494 {
12495         if (m_n->tu == m2_n2->tu &&
12496             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
12497                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
12498             intel_compare_m_n(m_n->link_m, m_n->link_n,
12499                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
12500                 if (adjust)
12501                         *m2_n2 = *m_n;
12502
12503                 return true;
12504         }
12505
12506         return false;
12507 }
12508
12509 static bool
12510 intel_pipe_config_compare(struct drm_device *dev,
12511                           struct intel_crtc_state *current_config,
12512                           struct intel_crtc_state *pipe_config,
12513                           bool adjust)
12514 {
12515         bool ret = true;
12516
12517 #define INTEL_ERR_OR_DBG_KMS(fmt, ...) \
12518         do { \
12519                 if (!adjust) \
12520                         DRM_ERROR(fmt, ##__VA_ARGS__); \
12521                 else \
12522                         DRM_DEBUG_KMS(fmt, ##__VA_ARGS__); \
12523         } while (0)
12524
12525 #define PIPE_CONF_CHECK_X(name) \
12526         if (current_config->name != pipe_config->name) { \
12527                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12528                           "(expected 0x%08x, found 0x%08x)\n", \
12529                           current_config->name, \
12530                           pipe_config->name); \
12531                 ret = false; \
12532         }
12533
12534 #define PIPE_CONF_CHECK_I(name) \
12535         if (current_config->name != pipe_config->name) { \
12536                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12537                           "(expected %i, found %i)\n", \
12538                           current_config->name, \
12539                           pipe_config->name); \
12540                 ret = false; \
12541         }
12542
12543 #define PIPE_CONF_CHECK_P(name) \
12544         if (current_config->name != pipe_config->name) { \
12545                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12546                           "(expected %p, found %p)\n", \
12547                           current_config->name, \
12548                           pipe_config->name); \
12549                 ret = false; \
12550         }
12551
12552 #define PIPE_CONF_CHECK_M_N(name) \
12553         if (!intel_compare_link_m_n(&current_config->name, \
12554                                     &pipe_config->name,\
12555                                     adjust)) { \
12556                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12557                           "(expected tu %i gmch %i/%i link %i/%i, " \
12558                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12559                           current_config->name.tu, \
12560                           current_config->name.gmch_m, \
12561                           current_config->name.gmch_n, \
12562                           current_config->name.link_m, \
12563                           current_config->name.link_n, \
12564                           pipe_config->name.tu, \
12565                           pipe_config->name.gmch_m, \
12566                           pipe_config->name.gmch_n, \
12567                           pipe_config->name.link_m, \
12568                           pipe_config->name.link_n); \
12569                 ret = false; \
12570         }
12571
12572 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
12573         if (!intel_compare_link_m_n(&current_config->name, \
12574                                     &pipe_config->name, adjust) && \
12575             !intel_compare_link_m_n(&current_config->alt_name, \
12576                                     &pipe_config->name, adjust)) { \
12577                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12578                           "(expected tu %i gmch %i/%i link %i/%i, " \
12579                           "or tu %i gmch %i/%i link %i/%i, " \
12580                           "found tu %i, gmch %i/%i link %i/%i)\n", \
12581                           current_config->name.tu, \
12582                           current_config->name.gmch_m, \
12583                           current_config->name.gmch_n, \
12584                           current_config->name.link_m, \
12585                           current_config->name.link_n, \
12586                           current_config->alt_name.tu, \
12587                           current_config->alt_name.gmch_m, \
12588                           current_config->alt_name.gmch_n, \
12589                           current_config->alt_name.link_m, \
12590                           current_config->alt_name.link_n, \
12591                           pipe_config->name.tu, \
12592                           pipe_config->name.gmch_m, \
12593                           pipe_config->name.gmch_n, \
12594                           pipe_config->name.link_m, \
12595                           pipe_config->name.link_n); \
12596                 ret = false; \
12597         }
12598
12599 /* This is required for BDW+ where there is only one set of registers for
12600  * switching between high and low RR.
12601  * This macro can be used whenever a comparison has to be made between one
12602  * hw state and multiple sw state variables.
12603  */
12604 #define PIPE_CONF_CHECK_I_ALT(name, alt_name) \
12605         if ((current_config->name != pipe_config->name) && \
12606                 (current_config->alt_name != pipe_config->name)) { \
12607                         INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12608                                   "(expected %i or %i, found %i)\n", \
12609                                   current_config->name, \
12610                                   current_config->alt_name, \
12611                                   pipe_config->name); \
12612                         ret = false; \
12613         }
12614
12615 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
12616         if ((current_config->name ^ pipe_config->name) & (mask)) { \
12617                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name "(" #mask ") " \
12618                           "(expected %i, found %i)\n", \
12619                           current_config->name & (mask), \
12620                           pipe_config->name & (mask)); \
12621                 ret = false; \
12622         }
12623
12624 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
12625         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
12626                 INTEL_ERR_OR_DBG_KMS("mismatch in " #name " " \
12627                           "(expected %i, found %i)\n", \
12628                           current_config->name, \
12629                           pipe_config->name); \
12630                 ret = false; \
12631         }
12632
12633 #define PIPE_CONF_QUIRK(quirk)  \
12634         ((current_config->quirks | pipe_config->quirks) & (quirk))
12635
12636         PIPE_CONF_CHECK_I(cpu_transcoder);
12637
12638         PIPE_CONF_CHECK_I(has_pch_encoder);
12639         PIPE_CONF_CHECK_I(fdi_lanes);
12640         PIPE_CONF_CHECK_M_N(fdi_m_n);
12641
12642         PIPE_CONF_CHECK_I(has_dp_encoder);
12643         PIPE_CONF_CHECK_I(lane_count);
12644
12645         if (INTEL_INFO(dev)->gen < 8) {
12646                 PIPE_CONF_CHECK_M_N(dp_m_n);
12647
12648                 if (current_config->has_drrs)
12649                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
12650         } else
12651                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
12652
12653         PIPE_CONF_CHECK_I(has_dsi_encoder);
12654
12655         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
12656         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
12657         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
12658         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
12659         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
12660         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
12661
12662         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
12663         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
12664         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
12665         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
12666         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
12667         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
12668
12669         PIPE_CONF_CHECK_I(pixel_multiplier);
12670         PIPE_CONF_CHECK_I(has_hdmi_sink);
12671         if ((INTEL_INFO(dev)->gen < 8 && !IS_HASWELL(dev)) ||
12672             IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
12673                 PIPE_CONF_CHECK_I(limited_color_range);
12674         PIPE_CONF_CHECK_I(has_infoframe);
12675
12676         PIPE_CONF_CHECK_I(has_audio);
12677
12678         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12679                               DRM_MODE_FLAG_INTERLACE);
12680
12681         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
12682                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12683                                       DRM_MODE_FLAG_PHSYNC);
12684                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12685                                       DRM_MODE_FLAG_NHSYNC);
12686                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12687                                       DRM_MODE_FLAG_PVSYNC);
12688                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
12689                                       DRM_MODE_FLAG_NVSYNC);
12690         }
12691
12692         PIPE_CONF_CHECK_X(gmch_pfit.control);
12693         /* pfit ratios are autocomputed by the hw on gen4+ */
12694         if (INTEL_INFO(dev)->gen < 4)
12695                 PIPE_CONF_CHECK_I(gmch_pfit.pgm_ratios);
12696         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
12697
12698         if (!adjust) {
12699                 PIPE_CONF_CHECK_I(pipe_src_w);
12700                 PIPE_CONF_CHECK_I(pipe_src_h);
12701
12702                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
12703                 if (current_config->pch_pfit.enabled) {
12704                         PIPE_CONF_CHECK_X(pch_pfit.pos);
12705                         PIPE_CONF_CHECK_X(pch_pfit.size);
12706                 }
12707
12708                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
12709         }
12710
12711         /* BDW+ don't expose a synchronous way to read the state */
12712         if (IS_HASWELL(dev))
12713                 PIPE_CONF_CHECK_I(ips_enabled);
12714
12715         PIPE_CONF_CHECK_I(double_wide);
12716
12717         PIPE_CONF_CHECK_X(ddi_pll_sel);
12718
12719         PIPE_CONF_CHECK_P(shared_dpll);
12720         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
12721         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
12722         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
12723         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
12724         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
12725         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
12726         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
12727         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
12728         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
12729
12730         if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5)
12731                 PIPE_CONF_CHECK_I(pipe_bpp);
12732
12733         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12734         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12735
12736 #undef PIPE_CONF_CHECK_X
12737 #undef PIPE_CONF_CHECK_I
12738 #undef PIPE_CONF_CHECK_P
12739 #undef PIPE_CONF_CHECK_I_ALT
12740 #undef PIPE_CONF_CHECK_FLAGS
12741 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12742 #undef PIPE_CONF_QUIRK
12743 #undef INTEL_ERR_OR_DBG_KMS
12744
12745         return ret;
12746 }
12747
12748 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12749                                            const struct intel_crtc_state *pipe_config)
12750 {
12751         if (pipe_config->has_pch_encoder) {
12752                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12753                                                             &pipe_config->fdi_m_n);
12754                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12755
12756                 /*
12757                  * FDI already provided one idea for the dotclock.
12758                  * Yell if the encoder disagrees.
12759                  */
12760                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12761                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12762                      fdi_dotclock, dotclock);
12763         }
12764 }
12765
12766 static void check_wm_state(struct drm_device *dev)
12767 {
12768         struct drm_i915_private *dev_priv = dev->dev_private;
12769         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12770         struct intel_crtc *intel_crtc;
12771         int plane;
12772
12773         if (INTEL_INFO(dev)->gen < 9)
12774                 return;
12775
12776         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12777         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12778
12779         for_each_intel_crtc(dev, intel_crtc) {
12780                 struct skl_ddb_entry *hw_entry, *sw_entry;
12781                 const enum pipe pipe = intel_crtc->pipe;
12782
12783                 if (!intel_crtc->active)
12784                         continue;
12785
12786                 /* planes */
12787                 for_each_plane(dev_priv, pipe, plane) {
12788                         hw_entry = &hw_ddb.plane[pipe][plane];
12789                         sw_entry = &sw_ddb->plane[pipe][plane];
12790
12791                         if (skl_ddb_entry_equal(hw_entry, sw_entry))
12792                                 continue;
12793
12794                         DRM_ERROR("mismatch in DDB state pipe %c plane %d "
12795                                   "(expected (%u,%u), found (%u,%u))\n",
12796                                   pipe_name(pipe), plane + 1,
12797                                   sw_entry->start, sw_entry->end,
12798                                   hw_entry->start, hw_entry->end);
12799                 }
12800
12801                 /* cursor */
12802                 hw_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
12803                 sw_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
12804
12805                 if (skl_ddb_entry_equal(hw_entry, sw_entry))
12806                         continue;
12807
12808                 DRM_ERROR("mismatch in DDB state pipe %c cursor "
12809                           "(expected (%u,%u), found (%u,%u))\n",
12810                           pipe_name(pipe),
12811                           sw_entry->start, sw_entry->end,
12812                           hw_entry->start, hw_entry->end);
12813         }
12814 }
12815
12816 static void
12817 check_connector_state(struct drm_device *dev,
12818                       struct drm_atomic_state *old_state)
12819 {
12820         struct drm_connector_state *old_conn_state;
12821         struct drm_connector *connector;
12822         int i;
12823
12824         for_each_connector_in_state(old_state, connector, old_conn_state, i) {
12825                 struct drm_encoder *encoder = connector->encoder;
12826                 struct drm_connector_state *state = connector->state;
12827
12828                 /* This also checks the encoder/connector hw state with the
12829                  * ->get_hw_state callbacks. */
12830                 intel_connector_check_state(to_intel_connector(connector));
12831
12832                 I915_STATE_WARN(state->best_encoder != encoder,
12833                      "connector's atomic encoder doesn't match legacy encoder\n");
12834         }
12835 }
12836
12837 static void
12838 check_encoder_state(struct drm_device *dev)
12839 {
12840         struct intel_encoder *encoder;
12841         struct intel_connector *connector;
12842
12843         for_each_intel_encoder(dev, encoder) {
12844                 bool enabled = false;
12845                 enum pipe pipe;
12846
12847                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12848                               encoder->base.base.id,
12849                               encoder->base.name);
12850
12851                 for_each_intel_connector(dev, connector) {
12852                         if (connector->base.state->best_encoder != &encoder->base)
12853                                 continue;
12854                         enabled = true;
12855
12856                         I915_STATE_WARN(connector->base.state->crtc !=
12857                                         encoder->base.crtc,
12858                              "connector's crtc doesn't match encoder crtc\n");
12859                 }
12860
12861                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12862                      "encoder's enabled state mismatch "
12863                      "(expected %i, found %i)\n",
12864                      !!encoder->base.crtc, enabled);
12865
12866                 if (!encoder->base.crtc) {
12867                         bool active;
12868
12869                         active = encoder->get_hw_state(encoder, &pipe);
12870                         I915_STATE_WARN(active,
12871                              "encoder detached but still enabled on pipe %c.\n",
12872                              pipe_name(pipe));
12873                 }
12874         }
12875 }
12876
12877 static void
12878 check_crtc_state(struct drm_device *dev, struct drm_atomic_state *old_state)
12879 {
12880         struct drm_i915_private *dev_priv = dev->dev_private;
12881         struct intel_encoder *encoder;
12882         struct drm_crtc_state *old_crtc_state;
12883         struct drm_crtc *crtc;
12884         int i;
12885
12886         for_each_crtc_in_state(old_state, crtc, old_crtc_state, i) {
12887                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12888                 struct intel_crtc_state *pipe_config, *sw_config;
12889                 bool active;
12890
12891                 if (!needs_modeset(crtc->state) &&
12892                     !to_intel_crtc_state(crtc->state)->update_pipe)
12893                         continue;
12894
12895                 __drm_atomic_helper_crtc_destroy_state(crtc, old_crtc_state);
12896                 pipe_config = to_intel_crtc_state(old_crtc_state);
12897                 memset(pipe_config, 0, sizeof(*pipe_config));
12898                 pipe_config->base.crtc = crtc;
12899                 pipe_config->base.state = old_state;
12900
12901                 DRM_DEBUG_KMS("[CRTC:%d]\n",
12902                               crtc->base.id);
12903
12904                 active = dev_priv->display.get_pipe_config(intel_crtc,
12905                                                            pipe_config);
12906
12907                 /* hw state is inconsistent with the pipe quirk */
12908                 if ((intel_crtc->pipe == PIPE_A && dev_priv->quirks & QUIRK_PIPEA_FORCE) ||
12909                     (intel_crtc->pipe == PIPE_B && dev_priv->quirks & QUIRK_PIPEB_FORCE))
12910                         active = crtc->state->active;
12911
12912                 I915_STATE_WARN(crtc->state->active != active,
12913                      "crtc active state doesn't match with hw state "
12914                      "(expected %i, found %i)\n", crtc->state->active, active);
12915
12916                 I915_STATE_WARN(intel_crtc->active != crtc->state->active,
12917                      "transitional active state does not match atomic hw state "
12918                      "(expected %i, found %i)\n", crtc->state->active, intel_crtc->active);
12919
12920                 for_each_encoder_on_crtc(dev, crtc, encoder) {
12921                         enum pipe pipe;
12922
12923                         active = encoder->get_hw_state(encoder, &pipe);
12924                         I915_STATE_WARN(active != crtc->state->active,
12925                                 "[ENCODER:%i] active %i with crtc active %i\n",
12926                                 encoder->base.base.id, active, crtc->state->active);
12927
12928                         I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12929                                         "Encoder connected to wrong pipe %c\n",
12930                                         pipe_name(pipe));
12931
12932                         if (active)
12933                                 encoder->get_config(encoder, pipe_config);
12934                 }
12935
12936                 if (!crtc->state->active)
12937                         continue;
12938
12939                 intel_pipe_config_sanity_check(dev_priv, pipe_config);
12940
12941                 sw_config = to_intel_crtc_state(crtc->state);
12942                 if (!intel_pipe_config_compare(dev, sw_config,
12943                                                pipe_config, false)) {
12944                         I915_STATE_WARN(1, "pipe state doesn't match!\n");
12945                         intel_dump_pipe_config(intel_crtc, pipe_config,
12946                                                "[hw state]");
12947                         intel_dump_pipe_config(intel_crtc, sw_config,
12948                                                "[sw state]");
12949                 }
12950         }
12951 }
12952
12953 static void
12954 check_shared_dpll_state(struct drm_device *dev)
12955 {
12956         struct drm_i915_private *dev_priv = dev->dev_private;
12957         struct intel_crtc *crtc;
12958         struct intel_dpll_hw_state dpll_hw_state;
12959         int i;
12960
12961         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
12962                 struct intel_shared_dpll *pll =
12963                         intel_get_shared_dpll_by_id(dev_priv, i);
12964                 unsigned enabled_crtcs = 0, active_crtcs = 0;
12965                 bool active;
12966
12967                 memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12968
12969                 DRM_DEBUG_KMS("%s\n", pll->name);
12970
12971                 active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
12972
12973                 I915_STATE_WARN(pll->active_mask & ~pll->config.crtc_mask,
12974                      "more active pll users than references: %x vs %x\n",
12975                      pll->active_mask, pll->config.crtc_mask);
12976
12977                 if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
12978                         I915_STATE_WARN(!pll->on && pll->active_mask,
12979                              "pll in active use but not on in sw tracking\n");
12980                         I915_STATE_WARN(pll->on && !pll->active_mask,
12981                              "pll is on but not used by any active crtc\n");
12982                         I915_STATE_WARN(pll->on != active,
12983                              "pll on state mismatch (expected %i, found %i)\n",
12984                              pll->on, active);
12985                 }
12986
12987                 for_each_intel_crtc(dev, crtc) {
12988                         if (crtc->base.state->enable && crtc->config->shared_dpll == pll)
12989                                 enabled_crtcs |= 1 << drm_crtc_index(&crtc->base);
12990                         if (crtc->base.state->active && crtc->config->shared_dpll == pll)
12991                                 active_crtcs |= 1 << drm_crtc_index(&crtc->base);
12992                 }
12993
12994                 I915_STATE_WARN(pll->active_mask != active_crtcs,
12995                      "pll active crtcs mismatch (expected %x, found %x)\n",
12996                      pll->active_mask, active_crtcs);
12997                 I915_STATE_WARN(pll->config.crtc_mask != enabled_crtcs,
12998                      "pll enabled crtcs mismatch (expected %x, found %x)\n",
12999                      pll->config.crtc_mask, enabled_crtcs);
13000
13001                 I915_STATE_WARN(pll->on && memcmp(&pll->config.hw_state, &dpll_hw_state,
13002                                        sizeof(dpll_hw_state)),
13003                      "pll hw state mismatch\n");
13004         }
13005 }
13006
13007 static void
13008 intel_modeset_check_state(struct drm_device *dev,
13009                           struct drm_atomic_state *old_state)
13010 {
13011         check_wm_state(dev);
13012         check_connector_state(dev, old_state);
13013         check_encoder_state(dev);
13014         check_crtc_state(dev, old_state);
13015         check_shared_dpll_state(dev);
13016 }
13017
13018 static void update_scanline_offset(struct intel_crtc *crtc)
13019 {
13020         struct drm_device *dev = crtc->base.dev;
13021
13022         /*
13023          * The scanline counter increments at the leading edge of hsync.
13024          *
13025          * On most platforms it starts counting from vtotal-1 on the
13026          * first active line. That means the scanline counter value is
13027          * always one less than what we would expect. Ie. just after
13028          * start of vblank, which also occurs at start of hsync (on the
13029          * last active line), the scanline counter will read vblank_start-1.
13030          *
13031          * On gen2 the scanline counter starts counting from 1 instead
13032          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
13033          * to keep the value positive), instead of adding one.
13034          *
13035          * On HSW+ the behaviour of the scanline counter depends on the output
13036          * type. For DP ports it behaves like most other platforms, but on HDMI
13037          * there's an extra 1 line difference. So we need to add two instead of
13038          * one to the value.
13039          */
13040         if (IS_GEN2(dev)) {
13041                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
13042                 int vtotal;
13043
13044                 vtotal = adjusted_mode->crtc_vtotal;
13045                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
13046                         vtotal /= 2;
13047
13048                 crtc->scanline_offset = vtotal - 1;
13049         } else if (HAS_DDI(dev) &&
13050                    intel_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) {
13051                 crtc->scanline_offset = 2;
13052         } else
13053                 crtc->scanline_offset = 1;
13054 }
13055
13056 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
13057 {
13058         struct drm_device *dev = state->dev;
13059         struct drm_i915_private *dev_priv = to_i915(dev);
13060         struct intel_shared_dpll_config *shared_dpll = NULL;
13061         struct drm_crtc *crtc;
13062         struct drm_crtc_state *crtc_state;
13063         int i;
13064
13065         if (!dev_priv->display.crtc_compute_clock)
13066                 return;
13067
13068         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13069                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13070                 struct intel_shared_dpll *old_dpll =
13071                         to_intel_crtc_state(crtc->state)->shared_dpll;
13072
13073                 if (!needs_modeset(crtc_state))
13074                         continue;
13075
13076                 to_intel_crtc_state(crtc_state)->shared_dpll = NULL;
13077
13078                 if (!old_dpll)
13079                         continue;
13080
13081                 if (!shared_dpll)
13082                         shared_dpll = intel_atomic_get_shared_dpll_state(state);
13083
13084                 intel_shared_dpll_config_put(shared_dpll, old_dpll, intel_crtc);
13085         }
13086 }
13087
13088 /*
13089  * This implements the workaround described in the "notes" section of the mode
13090  * set sequence documentation. When going from no pipes or single pipe to
13091  * multiple pipes, and planes are enabled after the pipe, we need to wait at
13092  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
13093  */
13094 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
13095 {
13096         struct drm_crtc_state *crtc_state;
13097         struct intel_crtc *intel_crtc;
13098         struct drm_crtc *crtc;
13099         struct intel_crtc_state *first_crtc_state = NULL;
13100         struct intel_crtc_state *other_crtc_state = NULL;
13101         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
13102         int i;
13103
13104         /* look at all crtc's that are going to be enabled in during modeset */
13105         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13106                 intel_crtc = to_intel_crtc(crtc);
13107
13108                 if (!crtc_state->active || !needs_modeset(crtc_state))
13109                         continue;
13110
13111                 if (first_crtc_state) {
13112                         other_crtc_state = to_intel_crtc_state(crtc_state);
13113                         break;
13114                 } else {
13115                         first_crtc_state = to_intel_crtc_state(crtc_state);
13116                         first_pipe = intel_crtc->pipe;
13117                 }
13118         }
13119
13120         /* No workaround needed? */
13121         if (!first_crtc_state)
13122                 return 0;
13123
13124         /* w/a possibly needed, check how many crtc's are already enabled. */
13125         for_each_intel_crtc(state->dev, intel_crtc) {
13126                 struct intel_crtc_state *pipe_config;
13127
13128                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
13129                 if (IS_ERR(pipe_config))
13130                         return PTR_ERR(pipe_config);
13131
13132                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
13133
13134                 if (!pipe_config->base.active ||
13135                     needs_modeset(&pipe_config->base))
13136                         continue;
13137
13138                 /* 2 or more enabled crtcs means no need for w/a */
13139                 if (enabled_pipe != INVALID_PIPE)
13140                         return 0;
13141
13142                 enabled_pipe = intel_crtc->pipe;
13143         }
13144
13145         if (enabled_pipe != INVALID_PIPE)
13146                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
13147         else if (other_crtc_state)
13148                 other_crtc_state->hsw_workaround_pipe = first_pipe;
13149
13150         return 0;
13151 }
13152
13153 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
13154 {
13155         struct drm_crtc *crtc;
13156         struct drm_crtc_state *crtc_state;
13157         int ret = 0;
13158
13159         /* add all active pipes to the state */
13160         for_each_crtc(state->dev, crtc) {
13161                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
13162                 if (IS_ERR(crtc_state))
13163                         return PTR_ERR(crtc_state);
13164
13165                 if (!crtc_state->active || needs_modeset(crtc_state))
13166                         continue;
13167
13168                 crtc_state->mode_changed = true;
13169
13170                 ret = drm_atomic_add_affected_connectors(state, crtc);
13171                 if (ret)
13172                         break;
13173
13174                 ret = drm_atomic_add_affected_planes(state, crtc);
13175                 if (ret)
13176                         break;
13177         }
13178
13179         return ret;
13180 }
13181
13182 static int intel_modeset_checks(struct drm_atomic_state *state)
13183 {
13184         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13185         struct drm_i915_private *dev_priv = state->dev->dev_private;
13186         struct drm_crtc *crtc;
13187         struct drm_crtc_state *crtc_state;
13188         int ret = 0, i;
13189
13190         if (!check_digital_port_conflicts(state)) {
13191                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
13192                 return -EINVAL;
13193         }
13194
13195         intel_state->modeset = true;
13196         intel_state->active_crtcs = dev_priv->active_crtcs;
13197
13198         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13199                 if (crtc_state->active)
13200                         intel_state->active_crtcs |= 1 << i;
13201                 else
13202                         intel_state->active_crtcs &= ~(1 << i);
13203         }
13204
13205         /*
13206          * See if the config requires any additional preparation, e.g.
13207          * to adjust global state with pipes off.  We need to do this
13208          * here so we can get the modeset_pipe updated config for the new
13209          * mode set on this crtc.  For other crtcs we need to use the
13210          * adjusted_mode bits in the crtc directly.
13211          */
13212         if (dev_priv->display.modeset_calc_cdclk) {
13213                 ret = dev_priv->display.modeset_calc_cdclk(state);
13214
13215                 if (!ret && intel_state->dev_cdclk != dev_priv->cdclk_freq)
13216                         ret = intel_modeset_all_pipes(state);
13217
13218                 if (ret < 0)
13219                         return ret;
13220
13221                 DRM_DEBUG_KMS("New cdclk calculated to be atomic %u, actual %u\n",
13222                               intel_state->cdclk, intel_state->dev_cdclk);
13223         } else
13224                 to_intel_atomic_state(state)->cdclk = dev_priv->atomic_cdclk_freq;
13225
13226         intel_modeset_clear_plls(state);
13227
13228         if (IS_HASWELL(dev_priv))
13229                 return haswell_mode_set_planes_workaround(state);
13230
13231         return 0;
13232 }
13233
13234 /*
13235  * Handle calculation of various watermark data at the end of the atomic check
13236  * phase.  The code here should be run after the per-crtc and per-plane 'check'
13237  * handlers to ensure that all derived state has been updated.
13238  */
13239 static void calc_watermark_data(struct drm_atomic_state *state)
13240 {
13241         struct drm_device *dev = state->dev;
13242         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13243         struct drm_crtc *crtc;
13244         struct drm_crtc_state *cstate;
13245         struct drm_plane *plane;
13246         struct drm_plane_state *pstate;
13247
13248         /*
13249          * Calculate watermark configuration details now that derived
13250          * plane/crtc state is all properly updated.
13251          */
13252         drm_for_each_crtc(crtc, dev) {
13253                 cstate = drm_atomic_get_existing_crtc_state(state, crtc) ?:
13254                         crtc->state;
13255
13256                 if (cstate->active)
13257                         intel_state->wm_config.num_pipes_active++;
13258         }
13259         drm_for_each_legacy_plane(plane, dev) {
13260                 pstate = drm_atomic_get_existing_plane_state(state, plane) ?:
13261                         plane->state;
13262
13263                 if (!to_intel_plane_state(pstate)->visible)
13264                         continue;
13265
13266                 intel_state->wm_config.sprites_enabled = true;
13267                 if (pstate->crtc_w != pstate->src_w >> 16 ||
13268                     pstate->crtc_h != pstate->src_h >> 16)
13269                         intel_state->wm_config.sprites_scaled = true;
13270         }
13271 }
13272
13273 /**
13274  * intel_atomic_check - validate state object
13275  * @dev: drm device
13276  * @state: state to validate
13277  */
13278 static int intel_atomic_check(struct drm_device *dev,
13279                               struct drm_atomic_state *state)
13280 {
13281         struct drm_i915_private *dev_priv = to_i915(dev);
13282         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13283         struct drm_crtc *crtc;
13284         struct drm_crtc_state *crtc_state;
13285         int ret, i;
13286         bool any_ms = false;
13287
13288         ret = drm_atomic_helper_check_modeset(dev, state);
13289         if (ret)
13290                 return ret;
13291
13292         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13293                 struct intel_crtc_state *pipe_config =
13294                         to_intel_crtc_state(crtc_state);
13295
13296                 /* Catch I915_MODE_FLAG_INHERITED */
13297                 if (crtc_state->mode.private_flags != crtc->state->mode.private_flags)
13298                         crtc_state->mode_changed = true;
13299
13300                 if (!crtc_state->enable) {
13301                         if (needs_modeset(crtc_state))
13302                                 any_ms = true;
13303                         continue;
13304                 }
13305
13306                 if (!needs_modeset(crtc_state))
13307                         continue;
13308
13309                 /* FIXME: For only active_changed we shouldn't need to do any
13310                  * state recomputation at all. */
13311
13312                 ret = drm_atomic_add_affected_connectors(state, crtc);
13313                 if (ret)
13314                         return ret;
13315
13316                 ret = intel_modeset_pipe_config(crtc, pipe_config);
13317                 if (ret)
13318                         return ret;
13319
13320                 if (i915.fastboot &&
13321                     intel_pipe_config_compare(dev,
13322                                         to_intel_crtc_state(crtc->state),
13323                                         pipe_config, true)) {
13324                         crtc_state->mode_changed = false;
13325                         to_intel_crtc_state(crtc_state)->update_pipe = true;
13326                 }
13327
13328                 if (needs_modeset(crtc_state)) {
13329                         any_ms = true;
13330
13331                         ret = drm_atomic_add_affected_planes(state, crtc);
13332                         if (ret)
13333                                 return ret;
13334                 }
13335
13336                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
13337                                        needs_modeset(crtc_state) ?
13338                                        "[modeset]" : "[fastset]");
13339         }
13340
13341         if (any_ms) {
13342                 ret = intel_modeset_checks(state);
13343
13344                 if (ret)
13345                         return ret;
13346         } else
13347                 intel_state->cdclk = dev_priv->cdclk_freq;
13348
13349         ret = drm_atomic_helper_check_planes(dev, state);
13350         if (ret)
13351                 return ret;
13352
13353         intel_fbc_choose_crtc(dev_priv, state);
13354         calc_watermark_data(state);
13355
13356         return 0;
13357 }
13358
13359 static int intel_atomic_prepare_commit(struct drm_device *dev,
13360                                        struct drm_atomic_state *state,
13361                                        bool async)
13362 {
13363         struct drm_i915_private *dev_priv = dev->dev_private;
13364         struct drm_plane_state *plane_state;
13365         struct drm_crtc_state *crtc_state;
13366         struct drm_plane *plane;
13367         struct drm_crtc *crtc;
13368         int i, ret;
13369
13370         if (async) {
13371                 DRM_DEBUG_KMS("i915 does not yet support async commit\n");
13372                 return -EINVAL;
13373         }
13374
13375         for_each_crtc_in_state(state, crtc, crtc_state, i) {
13376                 ret = intel_crtc_wait_for_pending_flips(crtc);
13377                 if (ret)
13378                         return ret;
13379
13380                 if (atomic_read(&to_intel_crtc(crtc)->unpin_work_count) >= 2)
13381                         flush_workqueue(dev_priv->wq);
13382         }
13383
13384         ret = mutex_lock_interruptible(&dev->struct_mutex);
13385         if (ret)
13386                 return ret;
13387
13388         ret = drm_atomic_helper_prepare_planes(dev, state);
13389         if (!ret && !async && !i915_reset_in_progress(&dev_priv->gpu_error)) {
13390                 u32 reset_counter;
13391
13392                 reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
13393                 mutex_unlock(&dev->struct_mutex);
13394
13395                 for_each_plane_in_state(state, plane, plane_state, i) {
13396                         struct intel_plane_state *intel_plane_state =
13397                                 to_intel_plane_state(plane_state);
13398
13399                         if (!intel_plane_state->wait_req)
13400                                 continue;
13401
13402                         ret = __i915_wait_request(intel_plane_state->wait_req,
13403                                                   reset_counter, true,
13404                                                   NULL, NULL);
13405
13406                         /* Swallow -EIO errors to allow updates during hw lockup. */
13407                         if (ret == -EIO)
13408                                 ret = 0;
13409
13410                         if (ret)
13411                                 break;
13412                 }
13413
13414                 if (!ret)
13415                         return 0;
13416
13417                 mutex_lock(&dev->struct_mutex);
13418                 drm_atomic_helper_cleanup_planes(dev, state);
13419         }
13420
13421         mutex_unlock(&dev->struct_mutex);
13422         return ret;
13423 }
13424
13425 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
13426                                           struct drm_i915_private *dev_priv,
13427                                           unsigned crtc_mask)
13428 {
13429         unsigned last_vblank_count[I915_MAX_PIPES];
13430         enum pipe pipe;
13431         int ret;
13432
13433         if (!crtc_mask)
13434                 return;
13435
13436         for_each_pipe(dev_priv, pipe) {
13437                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13438
13439                 if (!((1 << pipe) & crtc_mask))
13440                         continue;
13441
13442                 ret = drm_crtc_vblank_get(crtc);
13443                 if (WARN_ON(ret != 0)) {
13444                         crtc_mask &= ~(1 << pipe);
13445                         continue;
13446                 }
13447
13448                 last_vblank_count[pipe] = drm_crtc_vblank_count(crtc);
13449         }
13450
13451         for_each_pipe(dev_priv, pipe) {
13452                 struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe];
13453                 long lret;
13454
13455                 if (!((1 << pipe) & crtc_mask))
13456                         continue;
13457
13458                 lret = wait_event_timeout(dev->vblank[pipe].queue,
13459                                 last_vblank_count[pipe] !=
13460                                         drm_crtc_vblank_count(crtc),
13461                                 msecs_to_jiffies(50));
13462
13463                 WARN_ON(!lret);
13464
13465                 drm_crtc_vblank_put(crtc);
13466         }
13467 }
13468
13469 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
13470 {
13471         /* fb updated, need to unpin old fb */
13472         if (crtc_state->fb_changed)
13473                 return true;
13474
13475         /* wm changes, need vblank before final wm's */
13476         if (crtc_state->update_wm_post)
13477                 return true;
13478
13479         /*
13480          * cxsr is re-enabled after vblank.
13481          * This is already handled by crtc_state->update_wm_post,
13482          * but added for clarity.
13483          */
13484         if (crtc_state->disable_cxsr)
13485                 return true;
13486
13487         return false;
13488 }
13489
13490 /**
13491  * intel_atomic_commit - commit validated state object
13492  * @dev: DRM device
13493  * @state: the top-level driver state object
13494  * @async: asynchronous commit
13495  *
13496  * This function commits a top-level state object that has been validated
13497  * with drm_atomic_helper_check().
13498  *
13499  * FIXME:  Atomic modeset support for i915 is not yet complete.  At the moment
13500  * we can only handle plane-related operations and do not yet support
13501  * asynchronous commit.
13502  *
13503  * RETURNS
13504  * Zero for success or -errno.
13505  */
13506 static int intel_atomic_commit(struct drm_device *dev,
13507                                struct drm_atomic_state *state,
13508                                bool async)
13509 {
13510         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13511         struct drm_i915_private *dev_priv = dev->dev_private;
13512         struct drm_crtc_state *old_crtc_state;
13513         struct drm_crtc *crtc;
13514         struct intel_crtc_state *intel_cstate;
13515         int ret = 0, i;
13516         bool hw_check = intel_state->modeset;
13517         unsigned long put_domains[I915_MAX_PIPES] = {};
13518         unsigned crtc_vblank_mask = 0;
13519
13520         ret = intel_atomic_prepare_commit(dev, state, async);
13521         if (ret) {
13522                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13523                 return ret;
13524         }
13525
13526         drm_atomic_helper_swap_state(dev, state);
13527         dev_priv->wm.config = intel_state->wm_config;
13528         intel_shared_dpll_commit(state);
13529
13530         if (intel_state->modeset) {
13531                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
13532                        sizeof(intel_state->min_pixclk));
13533                 dev_priv->active_crtcs = intel_state->active_crtcs;
13534                 dev_priv->atomic_cdclk_freq = intel_state->cdclk;
13535
13536                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13537         }
13538
13539         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13540                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13541
13542                 if (needs_modeset(crtc->state) ||
13543                     to_intel_crtc_state(crtc->state)->update_pipe) {
13544                         hw_check = true;
13545
13546                         put_domains[to_intel_crtc(crtc)->pipe] =
13547                                 modeset_get_crtc_power_domains(crtc,
13548                                         to_intel_crtc_state(crtc->state));
13549                 }
13550
13551                 if (!needs_modeset(crtc->state))
13552                         continue;
13553
13554                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13555
13556                 if (old_crtc_state->active) {
13557                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
13558                         dev_priv->display.crtc_disable(crtc);
13559                         intel_crtc->active = false;
13560                         intel_fbc_disable(intel_crtc);
13561                         intel_disable_shared_dpll(intel_crtc);
13562
13563                         /*
13564                          * Underruns don't always raise
13565                          * interrupts, so check manually.
13566                          */
13567                         intel_check_cpu_fifo_underruns(dev_priv);
13568                         intel_check_pch_fifo_underruns(dev_priv);
13569
13570                         if (!crtc->state->active)
13571                                 intel_update_watermarks(crtc);
13572                 }
13573         }
13574
13575         /* Only after disabling all output pipelines that will be changed can we
13576          * update the the output configuration. */
13577         intel_modeset_update_crtc_state(state);
13578
13579         if (intel_state->modeset) {
13580                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13581
13582                 if (dev_priv->display.modeset_commit_cdclk &&
13583                     intel_state->dev_cdclk != dev_priv->cdclk_freq)
13584                         dev_priv->display.modeset_commit_cdclk(state);
13585         }
13586
13587         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13588         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13589                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13590                 bool modeset = needs_modeset(crtc->state);
13591                 struct intel_crtc_state *pipe_config =
13592                         to_intel_crtc_state(crtc->state);
13593                 bool update_pipe = !modeset && pipe_config->update_pipe;
13594
13595                 if (modeset && crtc->state->active) {
13596                         update_scanline_offset(to_intel_crtc(crtc));
13597                         dev_priv->display.crtc_enable(crtc);
13598                 }
13599
13600                 if (!modeset &&
13601                     crtc->state->active &&
13602                     crtc->state->color_mgmt_changed) {
13603                         /*
13604                          * Only update color management when not doing
13605                          * a modeset as this will be done by
13606                          * crtc_enable already.
13607                          */
13608                         intel_color_set_csc(crtc);
13609                         intel_color_load_luts(crtc);
13610                 }
13611
13612                 if (!modeset)
13613                         intel_pre_plane_update(to_intel_crtc_state(old_crtc_state));
13614
13615                 if (crtc->state->active &&
13616                     drm_atomic_get_existing_plane_state(state, crtc->primary))
13617                         intel_fbc_enable(intel_crtc);
13618
13619                 if (crtc->state->active &&
13620                     (crtc->state->planes_changed || update_pipe))
13621                         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
13622
13623                 if (pipe_config->base.active && needs_vblank_wait(pipe_config))
13624                         crtc_vblank_mask |= 1 << i;
13625         }
13626
13627         /* FIXME: add subpixel order */
13628
13629         if (!state->legacy_cursor_update)
13630                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
13631
13632         /*
13633          * Now that the vblank has passed, we can go ahead and program the
13634          * optimal watermarks on platforms that need two-step watermark
13635          * programming.
13636          *
13637          * TODO: Move this (and other cleanup) to an async worker eventually.
13638          */
13639         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13640                 intel_cstate = to_intel_crtc_state(crtc->state);
13641
13642                 if (dev_priv->display.optimize_watermarks)
13643                         dev_priv->display.optimize_watermarks(intel_cstate);
13644         }
13645
13646         for_each_crtc_in_state(state, crtc, old_crtc_state, i) {
13647                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13648
13649                 if (put_domains[i])
13650                         modeset_put_power_domains(dev_priv, put_domains[i]);
13651         }
13652
13653         if (intel_state->modeset)
13654                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
13655
13656         mutex_lock(&dev->struct_mutex);
13657         drm_atomic_helper_cleanup_planes(dev, state);
13658         mutex_unlock(&dev->struct_mutex);
13659
13660         if (hw_check)
13661                 intel_modeset_check_state(dev, state);
13662
13663         drm_atomic_state_free(state);
13664
13665         /* As one of the primary mmio accessors, KMS has a high likelihood
13666          * of triggering bugs in unclaimed access. After we finish
13667          * modesetting, see if an error has been flagged, and if so
13668          * enable debugging for the next modeset - and hope we catch
13669          * the culprit.
13670          *
13671          * XXX note that we assume display power is on at this point.
13672          * This might hold true now but we need to add pm helper to check
13673          * unclaimed only when the hardware is on, as atomic commits
13674          * can happen also when the device is completely off.
13675          */
13676         intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13677
13678         return 0;
13679 }
13680
13681 void intel_crtc_restore_mode(struct drm_crtc *crtc)
13682 {
13683         struct drm_device *dev = crtc->dev;
13684         struct drm_atomic_state *state;
13685         struct drm_crtc_state *crtc_state;
13686         int ret;
13687
13688         state = drm_atomic_state_alloc(dev);
13689         if (!state) {
13690                 DRM_DEBUG_KMS("[CRTC:%d] crtc restore failed, out of memory",
13691                               crtc->base.id);
13692                 return;
13693         }
13694
13695         state->acquire_ctx = drm_modeset_legacy_acquire_ctx(crtc);
13696
13697 retry:
13698         crtc_state = drm_atomic_get_crtc_state(state, crtc);
13699         ret = PTR_ERR_OR_ZERO(crtc_state);
13700         if (!ret) {
13701                 if (!crtc_state->active)
13702                         goto out;
13703
13704                 crtc_state->mode_changed = true;
13705                 ret = drm_atomic_commit(state);
13706         }
13707
13708         if (ret == -EDEADLK) {
13709                 drm_atomic_state_clear(state);
13710                 drm_modeset_backoff(state->acquire_ctx);
13711                 goto retry;
13712         }
13713
13714         if (ret)
13715 out:
13716                 drm_atomic_state_free(state);
13717 }
13718
13719 #undef for_each_intel_crtc_masked
13720
13721 static const struct drm_crtc_funcs intel_crtc_funcs = {
13722         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13723         .set_config = drm_atomic_helper_set_config,
13724         .set_property = drm_atomic_helper_crtc_set_property,
13725         .destroy = intel_crtc_destroy,
13726         .page_flip = intel_crtc_page_flip,
13727         .atomic_duplicate_state = intel_crtc_duplicate_state,
13728         .atomic_destroy_state = intel_crtc_destroy_state,
13729 };
13730
13731 /**
13732  * intel_prepare_plane_fb - Prepare fb for usage on plane
13733  * @plane: drm plane to prepare for
13734  * @fb: framebuffer to prepare for presentation
13735  *
13736  * Prepares a framebuffer for usage on a display plane.  Generally this
13737  * involves pinning the underlying object and updating the frontbuffer tracking
13738  * bits.  Some older platforms need special physical address handling for
13739  * cursor planes.
13740  *
13741  * Must be called with struct_mutex held.
13742  *
13743  * Returns 0 on success, negative error code on failure.
13744  */
13745 int
13746 intel_prepare_plane_fb(struct drm_plane *plane,
13747                        const struct drm_plane_state *new_state)
13748 {
13749         struct drm_device *dev = plane->dev;
13750         struct drm_framebuffer *fb = new_state->fb;
13751         struct intel_plane *intel_plane = to_intel_plane(plane);
13752         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13753         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13754         int ret = 0;
13755
13756         if (!obj && !old_obj)
13757                 return 0;
13758
13759         if (old_obj) {
13760                 struct drm_crtc_state *crtc_state =
13761                         drm_atomic_get_existing_crtc_state(new_state->state, plane->state->crtc);
13762
13763                 /* Big Hammer, we also need to ensure that any pending
13764                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13765                  * current scanout is retired before unpinning the old
13766                  * framebuffer. Note that we rely on userspace rendering
13767                  * into the buffer attached to the pipe they are waiting
13768                  * on. If not, userspace generates a GPU hang with IPEHR
13769                  * point to the MI_WAIT_FOR_EVENT.
13770                  *
13771                  * This should only fail upon a hung GPU, in which case we
13772                  * can safely continue.
13773                  */
13774                 if (needs_modeset(crtc_state))
13775                         ret = i915_gem_object_wait_rendering(old_obj, true);
13776
13777                 /* Swallow -EIO errors to allow updates during hw lockup. */
13778                 if (ret && ret != -EIO)
13779                         return ret;
13780         }
13781
13782         /* For framebuffer backed by dmabuf, wait for fence */
13783         if (obj && obj->base.dma_buf) {
13784                 long lret;
13785
13786                 lret = reservation_object_wait_timeout_rcu(obj->base.dma_buf->resv,
13787                                                            false, true,
13788                                                            MAX_SCHEDULE_TIMEOUT);
13789                 if (lret == -ERESTARTSYS)
13790                         return lret;
13791
13792                 WARN(lret < 0, "waiting returns %li\n", lret);
13793         }
13794
13795         if (!obj) {
13796                 ret = 0;
13797         } else if (plane->type == DRM_PLANE_TYPE_CURSOR &&
13798             INTEL_INFO(dev)->cursor_needs_physical) {
13799                 int align = IS_I830(dev) ? 16 * 1024 : 256;
13800                 ret = i915_gem_object_attach_phys(obj, align);
13801                 if (ret)
13802                         DRM_DEBUG_KMS("failed to attach phys object\n");
13803         } else {
13804                 ret = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
13805         }
13806
13807         if (ret == 0) {
13808                 if (obj) {
13809                         struct intel_plane_state *plane_state =
13810                                 to_intel_plane_state(new_state);
13811
13812                         i915_gem_request_assign(&plane_state->wait_req,
13813                                                 obj->last_write_req);
13814                 }
13815
13816                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13817         }
13818
13819         return ret;
13820 }
13821
13822 /**
13823  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13824  * @plane: drm plane to clean up for
13825  * @fb: old framebuffer that was on plane
13826  *
13827  * Cleans up a framebuffer that has just been removed from a plane.
13828  *
13829  * Must be called with struct_mutex held.
13830  */
13831 void
13832 intel_cleanup_plane_fb(struct drm_plane *plane,
13833                        const struct drm_plane_state *old_state)
13834 {
13835         struct drm_device *dev = plane->dev;
13836         struct intel_plane *intel_plane = to_intel_plane(plane);
13837         struct intel_plane_state *old_intel_state;
13838         struct drm_i915_gem_object *old_obj = intel_fb_obj(old_state->fb);
13839         struct drm_i915_gem_object *obj = intel_fb_obj(plane->state->fb);
13840
13841         old_intel_state = to_intel_plane_state(old_state);
13842
13843         if (!obj && !old_obj)
13844                 return;
13845
13846         if (old_obj && (plane->type != DRM_PLANE_TYPE_CURSOR ||
13847             !INTEL_INFO(dev)->cursor_needs_physical))
13848                 intel_unpin_fb_obj(old_state->fb, old_state->rotation);
13849
13850         /* prepare_fb aborted? */
13851         if ((old_obj && (old_obj->frontbuffer_bits & intel_plane->frontbuffer_bit)) ||
13852             (obj && !(obj->frontbuffer_bits & intel_plane->frontbuffer_bit)))
13853                 i915_gem_track_fb(old_obj, obj, intel_plane->frontbuffer_bit);
13854
13855         i915_gem_request_assign(&old_intel_state->wait_req, NULL);
13856 }
13857
13858 int
13859 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
13860 {
13861         int max_scale;
13862         struct drm_device *dev;
13863         struct drm_i915_private *dev_priv;
13864         int crtc_clock, cdclk;
13865
13866         if (!intel_crtc || !crtc_state->base.enable)
13867                 return DRM_PLANE_HELPER_NO_SCALING;
13868
13869         dev = intel_crtc->base.dev;
13870         dev_priv = dev->dev_private;
13871         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13872         cdclk = to_intel_atomic_state(crtc_state->base.state)->cdclk;
13873
13874         if (WARN_ON_ONCE(!crtc_clock || cdclk < crtc_clock))
13875                 return DRM_PLANE_HELPER_NO_SCALING;
13876
13877         /*
13878          * skl max scale is lower of:
13879          *    close to 3 but not 3, -1 is for that purpose
13880          *            or
13881          *    cdclk/crtc_clock
13882          */
13883         max_scale = min((1 << 16) * 3 - 1, (1 << 8) * ((cdclk << 8) / crtc_clock));
13884
13885         return max_scale;
13886 }
13887
13888 static int
13889 intel_check_primary_plane(struct drm_plane *plane,
13890                           struct intel_crtc_state *crtc_state,
13891                           struct intel_plane_state *state)
13892 {
13893         struct drm_crtc *crtc = state->base.crtc;
13894         struct drm_framebuffer *fb = state->base.fb;
13895         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13896         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13897         bool can_position = false;
13898
13899         if (INTEL_INFO(plane->dev)->gen >= 9) {
13900                 /* use scaler when colorkey is not required */
13901                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
13902                         min_scale = 1;
13903                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
13904                 }
13905                 can_position = true;
13906         }
13907
13908         return drm_plane_helper_check_update(plane, crtc, fb, &state->src,
13909                                              &state->dst, &state->clip,
13910                                              min_scale, max_scale,
13911                                              can_position, true,
13912                                              &state->visible);
13913 }
13914
13915 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13916                                     struct drm_crtc_state *old_crtc_state)
13917 {
13918         struct drm_device *dev = crtc->dev;
13919         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13920         struct intel_crtc_state *old_intel_state =
13921                 to_intel_crtc_state(old_crtc_state);
13922         bool modeset = needs_modeset(crtc->state);
13923
13924         /* Perform vblank evasion around commit operation */
13925         intel_pipe_update_start(intel_crtc);
13926
13927         if (modeset)
13928                 return;
13929
13930         if (to_intel_crtc_state(crtc->state)->update_pipe)
13931                 intel_update_pipe_config(intel_crtc, old_intel_state);
13932         else if (INTEL_INFO(dev)->gen >= 9)
13933                 skl_detach_scalers(intel_crtc);
13934 }
13935
13936 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13937                                      struct drm_crtc_state *old_crtc_state)
13938 {
13939         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13940
13941         intel_pipe_update_end(intel_crtc);
13942 }
13943
13944 /**
13945  * intel_plane_destroy - destroy a plane
13946  * @plane: plane to destroy
13947  *
13948  * Common destruction function for all types of planes (primary, cursor,
13949  * sprite).
13950  */
13951 void intel_plane_destroy(struct drm_plane *plane)
13952 {
13953         struct intel_plane *intel_plane = to_intel_plane(plane);
13954         drm_plane_cleanup(plane);
13955         kfree(intel_plane);
13956 }
13957
13958 const struct drm_plane_funcs intel_plane_funcs = {
13959         .update_plane = drm_atomic_helper_update_plane,
13960         .disable_plane = drm_atomic_helper_disable_plane,
13961         .destroy = intel_plane_destroy,
13962         .set_property = drm_atomic_helper_plane_set_property,
13963         .atomic_get_property = intel_plane_atomic_get_property,
13964         .atomic_set_property = intel_plane_atomic_set_property,
13965         .atomic_duplicate_state = intel_plane_duplicate_state,
13966         .atomic_destroy_state = intel_plane_destroy_state,
13967
13968 };
13969
13970 static struct drm_plane *intel_primary_plane_create(struct drm_device *dev,
13971                                                     int pipe)
13972 {
13973         struct intel_plane *primary;
13974         struct intel_plane_state *state;
13975         const uint32_t *intel_primary_formats;
13976         unsigned int num_formats;
13977
13978         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13979         if (primary == NULL)
13980                 return NULL;
13981
13982         state = intel_create_plane_state(&primary->base);
13983         if (!state) {
13984                 kfree(primary);
13985                 return NULL;
13986         }
13987         primary->base.state = &state->base;
13988
13989         primary->can_scale = false;
13990         primary->max_downscale = 1;
13991         if (INTEL_INFO(dev)->gen >= 9) {
13992                 primary->can_scale = true;
13993                 state->scaler_id = -1;
13994         }
13995         primary->pipe = pipe;
13996         primary->plane = pipe;
13997         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13998         primary->check_plane = intel_check_primary_plane;
13999         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4)
14000                 primary->plane = !pipe;
14001
14002         if (INTEL_INFO(dev)->gen >= 9) {
14003                 intel_primary_formats = skl_primary_formats;
14004                 num_formats = ARRAY_SIZE(skl_primary_formats);
14005
14006                 primary->update_plane = skylake_update_primary_plane;
14007                 primary->disable_plane = skylake_disable_primary_plane;
14008         } else if (HAS_PCH_SPLIT(dev)) {
14009                 intel_primary_formats = i965_primary_formats;
14010                 num_formats = ARRAY_SIZE(i965_primary_formats);
14011
14012                 primary->update_plane = ironlake_update_primary_plane;
14013                 primary->disable_plane = i9xx_disable_primary_plane;
14014         } else if (INTEL_INFO(dev)->gen >= 4) {
14015                 intel_primary_formats = i965_primary_formats;
14016                 num_formats = ARRAY_SIZE(i965_primary_formats);
14017
14018                 primary->update_plane = i9xx_update_primary_plane;
14019                 primary->disable_plane = i9xx_disable_primary_plane;
14020         } else {
14021                 intel_primary_formats = i8xx_primary_formats;
14022                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14023
14024                 primary->update_plane = i9xx_update_primary_plane;
14025                 primary->disable_plane = i9xx_disable_primary_plane;
14026         }
14027
14028         drm_universal_plane_init(dev, &primary->base, 0,
14029                                  &intel_plane_funcs,
14030                                  intel_primary_formats, num_formats,
14031                                  DRM_PLANE_TYPE_PRIMARY, NULL);
14032
14033         if (INTEL_INFO(dev)->gen >= 4)
14034                 intel_create_rotation_property(dev, primary);
14035
14036         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
14037
14038         return &primary->base;
14039 }
14040
14041 void intel_create_rotation_property(struct drm_device *dev, struct intel_plane *plane)
14042 {
14043         if (!dev->mode_config.rotation_property) {
14044                 unsigned long flags = BIT(DRM_ROTATE_0) |
14045                         BIT(DRM_ROTATE_180);
14046
14047                 if (INTEL_INFO(dev)->gen >= 9)
14048                         flags |= BIT(DRM_ROTATE_90) | BIT(DRM_ROTATE_270);
14049
14050                 dev->mode_config.rotation_property =
14051                         drm_mode_create_rotation_property(dev, flags);
14052         }
14053         if (dev->mode_config.rotation_property)
14054                 drm_object_attach_property(&plane->base.base,
14055                                 dev->mode_config.rotation_property,
14056                                 plane->base.state->rotation);
14057 }
14058
14059 static int
14060 intel_check_cursor_plane(struct drm_plane *plane,
14061                          struct intel_crtc_state *crtc_state,
14062                          struct intel_plane_state *state)
14063 {
14064         struct drm_crtc *crtc = crtc_state->base.crtc;
14065         struct drm_framebuffer *fb = state->base.fb;
14066         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14067         enum pipe pipe = to_intel_plane(plane)->pipe;
14068         unsigned stride;
14069         int ret;
14070
14071         ret = drm_plane_helper_check_update(plane, crtc, fb, &state->src,
14072                                             &state->dst, &state->clip,
14073                                             DRM_PLANE_HELPER_NO_SCALING,
14074                                             DRM_PLANE_HELPER_NO_SCALING,
14075                                             true, true, &state->visible);
14076         if (ret)
14077                 return ret;
14078
14079         /* if we want to turn off the cursor ignore width and height */
14080         if (!obj)
14081                 return 0;
14082
14083         /* Check for which cursor types we support */
14084         if (!cursor_size_ok(plane->dev, state->base.crtc_w, state->base.crtc_h)) {
14085                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
14086                           state->base.crtc_w, state->base.crtc_h);
14087                 return -EINVAL;
14088         }
14089
14090         stride = roundup_pow_of_two(state->base.crtc_w) * 4;
14091         if (obj->base.size < stride * state->base.crtc_h) {
14092                 DRM_DEBUG_KMS("buffer is too small\n");
14093                 return -ENOMEM;
14094         }
14095
14096         if (fb->modifier[0] != DRM_FORMAT_MOD_NONE) {
14097                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
14098                 return -EINVAL;
14099         }
14100
14101         /*
14102          * There's something wrong with the cursor on CHV pipe C.
14103          * If it straddles the left edge of the screen then
14104          * moving it away from the edge or disabling it often
14105          * results in a pipe underrun, and often that can lead to
14106          * dead pipe (constant underrun reported, and it scans
14107          * out just a solid color). To recover from that, the
14108          * display power well must be turned off and on again.
14109          * Refuse the put the cursor into that compromised position.
14110          */
14111         if (IS_CHERRYVIEW(plane->dev) && pipe == PIPE_C &&
14112             state->visible && state->base.crtc_x < 0) {
14113                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
14114                 return -EINVAL;
14115         }
14116
14117         return 0;
14118 }
14119
14120 static void
14121 intel_disable_cursor_plane(struct drm_plane *plane,
14122                            struct drm_crtc *crtc)
14123 {
14124         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14125
14126         intel_crtc->cursor_addr = 0;
14127         intel_crtc_update_cursor(crtc, NULL);
14128 }
14129
14130 static void
14131 intel_update_cursor_plane(struct drm_plane *plane,
14132                           const struct intel_crtc_state *crtc_state,
14133                           const struct intel_plane_state *state)
14134 {
14135         struct drm_crtc *crtc = crtc_state->base.crtc;
14136         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
14137         struct drm_device *dev = plane->dev;
14138         struct drm_i915_gem_object *obj = intel_fb_obj(state->base.fb);
14139         uint32_t addr;
14140
14141         if (!obj)
14142                 addr = 0;
14143         else if (!INTEL_INFO(dev)->cursor_needs_physical)
14144                 addr = i915_gem_obj_ggtt_offset(obj);
14145         else
14146                 addr = obj->phys_handle->busaddr;
14147
14148         intel_crtc->cursor_addr = addr;
14149         intel_crtc_update_cursor(crtc, state);
14150 }
14151
14152 static struct drm_plane *intel_cursor_plane_create(struct drm_device *dev,
14153                                                    int pipe)
14154 {
14155         struct intel_plane *cursor;
14156         struct intel_plane_state *state;
14157
14158         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
14159         if (cursor == NULL)
14160                 return NULL;
14161
14162         state = intel_create_plane_state(&cursor->base);
14163         if (!state) {
14164                 kfree(cursor);
14165                 return NULL;
14166         }
14167         cursor->base.state = &state->base;
14168
14169         cursor->can_scale = false;
14170         cursor->max_downscale = 1;
14171         cursor->pipe = pipe;
14172         cursor->plane = pipe;
14173         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
14174         cursor->check_plane = intel_check_cursor_plane;
14175         cursor->update_plane = intel_update_cursor_plane;
14176         cursor->disable_plane = intel_disable_cursor_plane;
14177
14178         drm_universal_plane_init(dev, &cursor->base, 0,
14179                                  &intel_plane_funcs,
14180                                  intel_cursor_formats,
14181                                  ARRAY_SIZE(intel_cursor_formats),
14182                                  DRM_PLANE_TYPE_CURSOR, NULL);
14183
14184         if (INTEL_INFO(dev)->gen >= 4) {
14185                 if (!dev->mode_config.rotation_property)
14186                         dev->mode_config.rotation_property =
14187                                 drm_mode_create_rotation_property(dev,
14188                                                         BIT(DRM_ROTATE_0) |
14189                                                         BIT(DRM_ROTATE_180));
14190                 if (dev->mode_config.rotation_property)
14191                         drm_object_attach_property(&cursor->base.base,
14192                                 dev->mode_config.rotation_property,
14193                                 state->base.rotation);
14194         }
14195
14196         if (INTEL_INFO(dev)->gen >=9)
14197                 state->scaler_id = -1;
14198
14199         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14200
14201         return &cursor->base;
14202 }
14203
14204 static void skl_init_scalers(struct drm_device *dev, struct intel_crtc *intel_crtc,
14205         struct intel_crtc_state *crtc_state)
14206 {
14207         int i;
14208         struct intel_scaler *intel_scaler;
14209         struct intel_crtc_scaler_state *scaler_state = &crtc_state->scaler_state;
14210
14211         for (i = 0; i < intel_crtc->num_scalers; i++) {
14212                 intel_scaler = &scaler_state->scalers[i];
14213                 intel_scaler->in_use = 0;
14214                 intel_scaler->mode = PS_SCALER_MODE_DYN;
14215         }
14216
14217         scaler_state->scaler_id = -1;
14218 }
14219
14220 static void intel_crtc_init(struct drm_device *dev, int pipe)
14221 {
14222         struct drm_i915_private *dev_priv = dev->dev_private;
14223         struct intel_crtc *intel_crtc;
14224         struct intel_crtc_state *crtc_state = NULL;
14225         struct drm_plane *primary = NULL;
14226         struct drm_plane *cursor = NULL;
14227         int ret;
14228
14229         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14230         if (intel_crtc == NULL)
14231                 return;
14232
14233         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14234         if (!crtc_state)
14235                 goto fail;
14236         intel_crtc->config = crtc_state;
14237         intel_crtc->base.state = &crtc_state->base;
14238         crtc_state->base.crtc = &intel_crtc->base;
14239
14240         /* initialize shared scalers */
14241         if (INTEL_INFO(dev)->gen >= 9) {
14242                 if (pipe == PIPE_C)
14243                         intel_crtc->num_scalers = 1;
14244                 else
14245                         intel_crtc->num_scalers = SKL_NUM_SCALERS;
14246
14247                 skl_init_scalers(dev, intel_crtc, crtc_state);
14248         }
14249
14250         primary = intel_primary_plane_create(dev, pipe);
14251         if (!primary)
14252                 goto fail;
14253
14254         cursor = intel_cursor_plane_create(dev, pipe);
14255         if (!cursor)
14256                 goto fail;
14257
14258         ret = drm_crtc_init_with_planes(dev, &intel_crtc->base, primary,
14259                                         cursor, &intel_crtc_funcs, NULL);
14260         if (ret)
14261                 goto fail;
14262
14263         /*
14264          * On gen2/3 only plane A can do fbc, but the panel fitter and lvds port
14265          * is hooked to pipe B. Hence we want plane A feeding pipe B.
14266          */
14267         intel_crtc->pipe = pipe;
14268         intel_crtc->plane = pipe;
14269         if (HAS_FBC(dev) && INTEL_INFO(dev)->gen < 4) {
14270                 DRM_DEBUG_KMS("swapping pipes & planes for FBC\n");
14271                 intel_crtc->plane = !pipe;
14272         }
14273
14274         intel_crtc->cursor_base = ~0;
14275         intel_crtc->cursor_cntl = ~0;
14276         intel_crtc->cursor_size = ~0;
14277
14278         intel_crtc->wm.cxsr_allowed = true;
14279
14280         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14281                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
14282         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = &intel_crtc->base;
14283         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = &intel_crtc->base;
14284
14285         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14286
14287         intel_color_init(&intel_crtc->base);
14288
14289         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14290         return;
14291
14292 fail:
14293         if (primary)
14294                 drm_plane_cleanup(primary);
14295         if (cursor)
14296                 drm_plane_cleanup(cursor);
14297         kfree(crtc_state);
14298         kfree(intel_crtc);
14299 }
14300
14301 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14302 {
14303         struct drm_encoder *encoder = connector->base.encoder;
14304         struct drm_device *dev = connector->base.dev;
14305
14306         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14307
14308         if (!encoder || WARN_ON(!encoder->crtc))
14309                 return INVALID_PIPE;
14310
14311         return to_intel_crtc(encoder->crtc)->pipe;
14312 }
14313
14314 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
14315                                 struct drm_file *file)
14316 {
14317         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14318         struct drm_crtc *drmmode_crtc;
14319         struct intel_crtc *crtc;
14320
14321         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
14322
14323         if (!drmmode_crtc) {
14324                 DRM_ERROR("no such CRTC id\n");
14325                 return -ENOENT;
14326         }
14327
14328         crtc = to_intel_crtc(drmmode_crtc);
14329         pipe_from_crtc_id->pipe = crtc->pipe;
14330
14331         return 0;
14332 }
14333
14334 static int intel_encoder_clones(struct intel_encoder *encoder)
14335 {
14336         struct drm_device *dev = encoder->base.dev;
14337         struct intel_encoder *source_encoder;
14338         int index_mask = 0;
14339         int entry = 0;
14340
14341         for_each_intel_encoder(dev, source_encoder) {
14342                 if (encoders_cloneable(encoder, source_encoder))
14343                         index_mask |= (1 << entry);
14344
14345                 entry++;
14346         }
14347
14348         return index_mask;
14349 }
14350
14351 static bool has_edp_a(struct drm_device *dev)
14352 {
14353         struct drm_i915_private *dev_priv = dev->dev_private;
14354
14355         if (!IS_MOBILE(dev))
14356                 return false;
14357
14358         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14359                 return false;
14360
14361         if (IS_GEN5(dev) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14362                 return false;
14363
14364         return true;
14365 }
14366
14367 static bool intel_crt_present(struct drm_device *dev)
14368 {
14369         struct drm_i915_private *dev_priv = dev->dev_private;
14370
14371         if (INTEL_INFO(dev)->gen >= 9)
14372                 return false;
14373
14374         if (IS_HSW_ULT(dev) || IS_BDW_ULT(dev))
14375                 return false;
14376
14377         if (IS_CHERRYVIEW(dev))
14378                 return false;
14379
14380         if (HAS_PCH_LPT_H(dev) && I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14381                 return false;
14382
14383         /* DDI E can't be used if DDI A requires 4 lanes */
14384         if (HAS_DDI(dev) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14385                 return false;
14386
14387         if (!dev_priv->vbt.int_crt_support)
14388                 return false;
14389
14390         return true;
14391 }
14392
14393 static void intel_setup_outputs(struct drm_device *dev)
14394 {
14395         struct drm_i915_private *dev_priv = dev->dev_private;
14396         struct intel_encoder *encoder;
14397         bool dpd_is_edp = false;
14398
14399         intel_lvds_init(dev);
14400
14401         if (intel_crt_present(dev))
14402                 intel_crt_init(dev);
14403
14404         if (IS_BROXTON(dev)) {
14405                 /*
14406                  * FIXME: Broxton doesn't support port detection via the
14407                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14408                  * detect the ports.
14409                  */
14410                 intel_ddi_init(dev, PORT_A);
14411                 intel_ddi_init(dev, PORT_B);
14412                 intel_ddi_init(dev, PORT_C);
14413
14414                 intel_dsi_init(dev);
14415         } else if (HAS_DDI(dev)) {
14416                 int found;
14417
14418                 /*
14419                  * Haswell uses DDI functions to detect digital outputs.
14420                  * On SKL pre-D0 the strap isn't connected, so we assume
14421                  * it's there.
14422                  */
14423                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14424                 /* WaIgnoreDDIAStrap: skl */
14425                 if (found || IS_SKYLAKE(dev) || IS_KABYLAKE(dev))
14426                         intel_ddi_init(dev, PORT_A);
14427
14428                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
14429                  * register */
14430                 found = I915_READ(SFUSE_STRAP);
14431
14432                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14433                         intel_ddi_init(dev, PORT_B);
14434                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14435                         intel_ddi_init(dev, PORT_C);
14436                 if (found & SFUSE_STRAP_DDID_DETECTED)
14437                         intel_ddi_init(dev, PORT_D);
14438                 /*
14439                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14440                  */
14441                 if ((IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) &&
14442                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14443                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14444                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14445                         intel_ddi_init(dev, PORT_E);
14446
14447         } else if (HAS_PCH_SPLIT(dev)) {
14448                 int found;
14449                 dpd_is_edp = intel_dp_is_edp(dev, PORT_D);
14450
14451                 if (has_edp_a(dev))
14452                         intel_dp_init(dev, DP_A, PORT_A);
14453
14454                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14455                         /* PCH SDVOB multiplex with HDMIB */
14456                         found = intel_sdvo_init(dev, PCH_SDVOB, PORT_B);
14457                         if (!found)
14458                                 intel_hdmi_init(dev, PCH_HDMIB, PORT_B);
14459                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14460                                 intel_dp_init(dev, PCH_DP_B, PORT_B);
14461                 }
14462
14463                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14464                         intel_hdmi_init(dev, PCH_HDMIC, PORT_C);
14465
14466                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14467                         intel_hdmi_init(dev, PCH_HDMID, PORT_D);
14468
14469                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14470                         intel_dp_init(dev, PCH_DP_C, PORT_C);
14471
14472                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14473                         intel_dp_init(dev, PCH_DP_D, PORT_D);
14474         } else if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev)) {
14475                 /*
14476                  * The DP_DETECTED bit is the latched state of the DDC
14477                  * SDA pin at boot. However since eDP doesn't require DDC
14478                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14479                  * eDP ports may have been muxed to an alternate function.
14480                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14481                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14482                  * detect eDP ports.
14483                  */
14484                 if (I915_READ(VLV_HDMIB) & SDVO_DETECTED &&
14485                     !intel_dp_is_edp(dev, PORT_B))
14486                         intel_hdmi_init(dev, VLV_HDMIB, PORT_B);
14487                 if (I915_READ(VLV_DP_B) & DP_DETECTED ||
14488                     intel_dp_is_edp(dev, PORT_B))
14489                         intel_dp_init(dev, VLV_DP_B, PORT_B);
14490
14491                 if (I915_READ(VLV_HDMIC) & SDVO_DETECTED &&
14492                     !intel_dp_is_edp(dev, PORT_C))
14493                         intel_hdmi_init(dev, VLV_HDMIC, PORT_C);
14494                 if (I915_READ(VLV_DP_C) & DP_DETECTED ||
14495                     intel_dp_is_edp(dev, PORT_C))
14496                         intel_dp_init(dev, VLV_DP_C, PORT_C);
14497
14498                 if (IS_CHERRYVIEW(dev)) {
14499                         /* eDP not supported on port D, so don't check VBT */
14500                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED)
14501                                 intel_hdmi_init(dev, CHV_HDMID, PORT_D);
14502                         if (I915_READ(CHV_DP_D) & DP_DETECTED)
14503                                 intel_dp_init(dev, CHV_DP_D, PORT_D);
14504                 }
14505
14506                 intel_dsi_init(dev);
14507         } else if (!IS_GEN2(dev) && !IS_PINEVIEW(dev)) {
14508                 bool found = false;
14509
14510                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14511                         DRM_DEBUG_KMS("probing SDVOB\n");
14512                         found = intel_sdvo_init(dev, GEN3_SDVOB, PORT_B);
14513                         if (!found && IS_G4X(dev)) {
14514                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14515                                 intel_hdmi_init(dev, GEN4_HDMIB, PORT_B);
14516                         }
14517
14518                         if (!found && IS_G4X(dev))
14519                                 intel_dp_init(dev, DP_B, PORT_B);
14520                 }
14521
14522                 /* Before G4X SDVOC doesn't have its own detect register */
14523
14524                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14525                         DRM_DEBUG_KMS("probing SDVOC\n");
14526                         found = intel_sdvo_init(dev, GEN3_SDVOC, PORT_C);
14527                 }
14528
14529                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14530
14531                         if (IS_G4X(dev)) {
14532                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14533                                 intel_hdmi_init(dev, GEN4_HDMIC, PORT_C);
14534                         }
14535                         if (IS_G4X(dev))
14536                                 intel_dp_init(dev, DP_C, PORT_C);
14537                 }
14538
14539                 if (IS_G4X(dev) &&
14540                     (I915_READ(DP_D) & DP_DETECTED))
14541                         intel_dp_init(dev, DP_D, PORT_D);
14542         } else if (IS_GEN2(dev))
14543                 intel_dvo_init(dev);
14544
14545         if (SUPPORTS_TV(dev))
14546                 intel_tv_init(dev);
14547
14548         intel_psr_init(dev);
14549
14550         for_each_intel_encoder(dev, encoder) {
14551                 encoder->base.possible_crtcs = encoder->crtc_mask;
14552                 encoder->base.possible_clones =
14553                         intel_encoder_clones(encoder);
14554         }
14555
14556         intel_init_pch_refclk(dev);
14557
14558         drm_helper_move_panel_connectors_to_head(dev);
14559 }
14560
14561 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14562 {
14563         struct drm_device *dev = fb->dev;
14564         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14565
14566         drm_framebuffer_cleanup(fb);
14567         mutex_lock(&dev->struct_mutex);
14568         WARN_ON(!intel_fb->obj->framebuffer_references--);
14569         drm_gem_object_unreference(&intel_fb->obj->base);
14570         mutex_unlock(&dev->struct_mutex);
14571         kfree(intel_fb);
14572 }
14573
14574 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14575                                                 struct drm_file *file,
14576                                                 unsigned int *handle)
14577 {
14578         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14579         struct drm_i915_gem_object *obj = intel_fb->obj;
14580
14581         if (obj->userptr.mm) {
14582                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14583                 return -EINVAL;
14584         }
14585
14586         return drm_gem_handle_create(file, &obj->base, handle);
14587 }
14588
14589 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14590                                         struct drm_file *file,
14591                                         unsigned flags, unsigned color,
14592                                         struct drm_clip_rect *clips,
14593                                         unsigned num_clips)
14594 {
14595         struct drm_device *dev = fb->dev;
14596         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14597         struct drm_i915_gem_object *obj = intel_fb->obj;
14598
14599         mutex_lock(&dev->struct_mutex);
14600         intel_fb_obj_flush(obj, false, ORIGIN_DIRTYFB);
14601         mutex_unlock(&dev->struct_mutex);
14602
14603         return 0;
14604 }
14605
14606 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14607         .destroy = intel_user_framebuffer_destroy,
14608         .create_handle = intel_user_framebuffer_create_handle,
14609         .dirty = intel_user_framebuffer_dirty,
14610 };
14611
14612 static
14613 u32 intel_fb_pitch_limit(struct drm_device *dev, uint64_t fb_modifier,
14614                          uint32_t pixel_format)
14615 {
14616         u32 gen = INTEL_INFO(dev)->gen;
14617
14618         if (gen >= 9) {
14619                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14620
14621                 /* "The stride in bytes must not exceed the of the size of 8K
14622                  *  pixels and 32K bytes."
14623                  */
14624                 return min(8192 * cpp, 32768);
14625         } else if (gen >= 5 && !IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14626                 return 32*1024;
14627         } else if (gen >= 4) {
14628                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14629                         return 16*1024;
14630                 else
14631                         return 32*1024;
14632         } else if (gen >= 3) {
14633                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14634                         return 8*1024;
14635                 else
14636                         return 16*1024;
14637         } else {
14638                 /* XXX DSPC is limited to 4k tiled */
14639                 return 8*1024;
14640         }
14641 }
14642
14643 static int intel_framebuffer_init(struct drm_device *dev,
14644                                   struct intel_framebuffer *intel_fb,
14645                                   struct drm_mode_fb_cmd2 *mode_cmd,
14646                                   struct drm_i915_gem_object *obj)
14647 {
14648         struct drm_i915_private *dev_priv = to_i915(dev);
14649         unsigned int aligned_height;
14650         int ret;
14651         u32 pitch_limit, stride_alignment;
14652
14653         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
14654
14655         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14656                 /* Enforce that fb modifier and tiling mode match, but only for
14657                  * X-tiled. This is needed for FBC. */
14658                 if (!!(obj->tiling_mode == I915_TILING_X) !=
14659                     !!(mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED)) {
14660                         DRM_DEBUG("tiling_mode doesn't match fb modifier\n");
14661                         return -EINVAL;
14662                 }
14663         } else {
14664                 if (obj->tiling_mode == I915_TILING_X)
14665                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14666                 else if (obj->tiling_mode == I915_TILING_Y) {
14667                         DRM_DEBUG("No Y tiling for legacy addfb\n");
14668                         return -EINVAL;
14669                 }
14670         }
14671
14672         /* Passed in modifier sanity checking. */
14673         switch (mode_cmd->modifier[0]) {
14674         case I915_FORMAT_MOD_Y_TILED:
14675         case I915_FORMAT_MOD_Yf_TILED:
14676                 if (INTEL_INFO(dev)->gen < 9) {
14677                         DRM_DEBUG("Unsupported tiling 0x%llx!\n",
14678                                   mode_cmd->modifier[0]);
14679                         return -EINVAL;
14680                 }
14681         case DRM_FORMAT_MOD_NONE:
14682         case I915_FORMAT_MOD_X_TILED:
14683                 break;
14684         default:
14685                 DRM_DEBUG("Unsupported fb modifier 0x%llx!\n",
14686                           mode_cmd->modifier[0]);
14687                 return -EINVAL;
14688         }
14689
14690         stride_alignment = intel_fb_stride_alignment(dev_priv,
14691                                                      mode_cmd->modifier[0],
14692                                                      mode_cmd->pixel_format);
14693         if (mode_cmd->pitches[0] & (stride_alignment - 1)) {
14694                 DRM_DEBUG("pitch (%d) must be at least %u byte aligned\n",
14695                           mode_cmd->pitches[0], stride_alignment);
14696                 return -EINVAL;
14697         }
14698
14699         pitch_limit = intel_fb_pitch_limit(dev, mode_cmd->modifier[0],
14700                                            mode_cmd->pixel_format);
14701         if (mode_cmd->pitches[0] > pitch_limit) {
14702                 DRM_DEBUG("%s pitch (%u) must be at less than %d\n",
14703                           mode_cmd->modifier[0] != DRM_FORMAT_MOD_NONE ?
14704                           "tiled" : "linear",
14705                           mode_cmd->pitches[0], pitch_limit);
14706                 return -EINVAL;
14707         }
14708
14709         if (mode_cmd->modifier[0] == I915_FORMAT_MOD_X_TILED &&
14710             mode_cmd->pitches[0] != obj->stride) {
14711                 DRM_DEBUG("pitch (%d) must match tiling stride (%d)\n",
14712                           mode_cmd->pitches[0], obj->stride);
14713                 return -EINVAL;
14714         }
14715
14716         /* Reject formats not supported by any plane early. */
14717         switch (mode_cmd->pixel_format) {
14718         case DRM_FORMAT_C8:
14719         case DRM_FORMAT_RGB565:
14720         case DRM_FORMAT_XRGB8888:
14721         case DRM_FORMAT_ARGB8888:
14722                 break;
14723         case DRM_FORMAT_XRGB1555:
14724                 if (INTEL_INFO(dev)->gen > 3) {
14725                         DRM_DEBUG("unsupported pixel format: %s\n",
14726                                   drm_get_format_name(mode_cmd->pixel_format));
14727                         return -EINVAL;
14728                 }
14729                 break;
14730         case DRM_FORMAT_ABGR8888:
14731                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev) &&
14732                     INTEL_INFO(dev)->gen < 9) {
14733                         DRM_DEBUG("unsupported pixel format: %s\n",
14734                                   drm_get_format_name(mode_cmd->pixel_format));
14735                         return -EINVAL;
14736                 }
14737                 break;
14738         case DRM_FORMAT_XBGR8888:
14739         case DRM_FORMAT_XRGB2101010:
14740         case DRM_FORMAT_XBGR2101010:
14741                 if (INTEL_INFO(dev)->gen < 4) {
14742                         DRM_DEBUG("unsupported pixel format: %s\n",
14743                                   drm_get_format_name(mode_cmd->pixel_format));
14744                         return -EINVAL;
14745                 }
14746                 break;
14747         case DRM_FORMAT_ABGR2101010:
14748                 if (!IS_VALLEYVIEW(dev) && !IS_CHERRYVIEW(dev)) {
14749                         DRM_DEBUG("unsupported pixel format: %s\n",
14750                                   drm_get_format_name(mode_cmd->pixel_format));
14751                         return -EINVAL;
14752                 }
14753                 break;
14754         case DRM_FORMAT_YUYV:
14755         case DRM_FORMAT_UYVY:
14756         case DRM_FORMAT_YVYU:
14757         case DRM_FORMAT_VYUY:
14758                 if (INTEL_INFO(dev)->gen < 5) {
14759                         DRM_DEBUG("unsupported pixel format: %s\n",
14760                                   drm_get_format_name(mode_cmd->pixel_format));
14761                         return -EINVAL;
14762                 }
14763                 break;
14764         default:
14765                 DRM_DEBUG("unsupported pixel format: %s\n",
14766                           drm_get_format_name(mode_cmd->pixel_format));
14767                 return -EINVAL;
14768         }
14769
14770         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14771         if (mode_cmd->offsets[0] != 0)
14772                 return -EINVAL;
14773
14774         aligned_height = intel_fb_align_height(dev, mode_cmd->height,
14775                                                mode_cmd->pixel_format,
14776                                                mode_cmd->modifier[0]);
14777         /* FIXME drm helper for size checks (especially planar formats)? */
14778         if (obj->base.size < aligned_height * mode_cmd->pitches[0])
14779                 return -EINVAL;
14780
14781         drm_helper_mode_fill_fb_struct(&intel_fb->base, mode_cmd);
14782         intel_fb->obj = obj;
14783
14784         intel_fill_fb_info(dev_priv, &intel_fb->base);
14785
14786         ret = drm_framebuffer_init(dev, &intel_fb->base, &intel_fb_funcs);
14787         if (ret) {
14788                 DRM_ERROR("framebuffer init failed %d\n", ret);
14789                 return ret;
14790         }
14791
14792         intel_fb->obj->framebuffer_references++;
14793
14794         return 0;
14795 }
14796
14797 static struct drm_framebuffer *
14798 intel_user_framebuffer_create(struct drm_device *dev,
14799                               struct drm_file *filp,
14800                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14801 {
14802         struct drm_framebuffer *fb;
14803         struct drm_i915_gem_object *obj;
14804         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14805
14806         obj = to_intel_bo(drm_gem_object_lookup(dev, filp,
14807                                                 mode_cmd.handles[0]));
14808         if (&obj->base == NULL)
14809                 return ERR_PTR(-ENOENT);
14810
14811         fb = intel_framebuffer_create(dev, &mode_cmd, obj);
14812         if (IS_ERR(fb))
14813                 drm_gem_object_unreference_unlocked(&obj->base);
14814
14815         return fb;
14816 }
14817
14818 #ifndef CONFIG_DRM_FBDEV_EMULATION
14819 static inline void intel_fbdev_output_poll_changed(struct drm_device *dev)
14820 {
14821 }
14822 #endif
14823
14824 static const struct drm_mode_config_funcs intel_mode_funcs = {
14825         .fb_create = intel_user_framebuffer_create,
14826         .output_poll_changed = intel_fbdev_output_poll_changed,
14827         .atomic_check = intel_atomic_check,
14828         .atomic_commit = intel_atomic_commit,
14829         .atomic_state_alloc = intel_atomic_state_alloc,
14830         .atomic_state_clear = intel_atomic_state_clear,
14831 };
14832
14833 /**
14834  * intel_init_display_hooks - initialize the display modesetting hooks
14835  * @dev_priv: device private
14836  */
14837 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14838 {
14839         if (INTEL_INFO(dev_priv)->gen >= 9) {
14840                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14841                 dev_priv->display.get_initial_plane_config =
14842                         skylake_get_initial_plane_config;
14843                 dev_priv->display.crtc_compute_clock =
14844                         haswell_crtc_compute_clock;
14845                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14846                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14847         } else if (HAS_DDI(dev_priv)) {
14848                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14849                 dev_priv->display.get_initial_plane_config =
14850                         ironlake_get_initial_plane_config;
14851                 dev_priv->display.crtc_compute_clock =
14852                         haswell_crtc_compute_clock;
14853                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14854                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14855         } else if (HAS_PCH_SPLIT(dev_priv)) {
14856                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14857                 dev_priv->display.get_initial_plane_config =
14858                         ironlake_get_initial_plane_config;
14859                 dev_priv->display.crtc_compute_clock =
14860                         ironlake_crtc_compute_clock;
14861                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14862                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14863         } else if (IS_CHERRYVIEW(dev_priv)) {
14864                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14865                 dev_priv->display.get_initial_plane_config =
14866                         i9xx_get_initial_plane_config;
14867                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14868                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14869                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14870         } else if (IS_VALLEYVIEW(dev_priv)) {
14871                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14872                 dev_priv->display.get_initial_plane_config =
14873                         i9xx_get_initial_plane_config;
14874                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14875                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14876                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14877         } else if (IS_G4X(dev_priv)) {
14878                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14879                 dev_priv->display.get_initial_plane_config =
14880                         i9xx_get_initial_plane_config;
14881                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14882                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14883                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14884         } else if (IS_PINEVIEW(dev_priv)) {
14885                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14886                 dev_priv->display.get_initial_plane_config =
14887                         i9xx_get_initial_plane_config;
14888                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14889                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14890                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14891         } else if (!IS_GEN2(dev_priv)) {
14892                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14893                 dev_priv->display.get_initial_plane_config =
14894                         i9xx_get_initial_plane_config;
14895                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14896                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14897                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14898         } else {
14899                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14900                 dev_priv->display.get_initial_plane_config =
14901                         i9xx_get_initial_plane_config;
14902                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14903                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14904                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14905         }
14906
14907         /* Returns the core display clock speed */
14908         if (IS_SKYLAKE(dev_priv) || IS_KABYLAKE(dev_priv))
14909                 dev_priv->display.get_display_clock_speed =
14910                         skylake_get_display_clock_speed;
14911         else if (IS_BROXTON(dev_priv))
14912                 dev_priv->display.get_display_clock_speed =
14913                         broxton_get_display_clock_speed;
14914         else if (IS_BROADWELL(dev_priv))
14915                 dev_priv->display.get_display_clock_speed =
14916                         broadwell_get_display_clock_speed;
14917         else if (IS_HASWELL(dev_priv))
14918                 dev_priv->display.get_display_clock_speed =
14919                         haswell_get_display_clock_speed;
14920         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14921                 dev_priv->display.get_display_clock_speed =
14922                         valleyview_get_display_clock_speed;
14923         else if (IS_GEN5(dev_priv))
14924                 dev_priv->display.get_display_clock_speed =
14925                         ilk_get_display_clock_speed;
14926         else if (IS_I945G(dev_priv) || IS_BROADWATER(dev_priv) ||
14927                  IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
14928                 dev_priv->display.get_display_clock_speed =
14929                         i945_get_display_clock_speed;
14930         else if (IS_GM45(dev_priv))
14931                 dev_priv->display.get_display_clock_speed =
14932                         gm45_get_display_clock_speed;
14933         else if (IS_CRESTLINE(dev_priv))
14934                 dev_priv->display.get_display_clock_speed =
14935                         i965gm_get_display_clock_speed;
14936         else if (IS_PINEVIEW(dev_priv))
14937                 dev_priv->display.get_display_clock_speed =
14938                         pnv_get_display_clock_speed;
14939         else if (IS_G33(dev_priv) || IS_G4X(dev_priv))
14940                 dev_priv->display.get_display_clock_speed =
14941                         g33_get_display_clock_speed;
14942         else if (IS_I915G(dev_priv))
14943                 dev_priv->display.get_display_clock_speed =
14944                         i915_get_display_clock_speed;
14945         else if (IS_I945GM(dev_priv) || IS_845G(dev_priv))
14946                 dev_priv->display.get_display_clock_speed =
14947                         i9xx_misc_get_display_clock_speed;
14948         else if (IS_I915GM(dev_priv))
14949                 dev_priv->display.get_display_clock_speed =
14950                         i915gm_get_display_clock_speed;
14951         else if (IS_I865G(dev_priv))
14952                 dev_priv->display.get_display_clock_speed =
14953                         i865_get_display_clock_speed;
14954         else if (IS_I85X(dev_priv))
14955                 dev_priv->display.get_display_clock_speed =
14956                         i85x_get_display_clock_speed;
14957         else { /* 830 */
14958                 WARN(!IS_I830(dev_priv), "Unknown platform. Assuming 133 MHz CDCLK\n");
14959                 dev_priv->display.get_display_clock_speed =
14960                         i830_get_display_clock_speed;
14961         }
14962
14963         if (IS_GEN5(dev_priv)) {
14964                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14965         } else if (IS_GEN6(dev_priv)) {
14966                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14967         } else if (IS_IVYBRIDGE(dev_priv)) {
14968                 /* FIXME: detect B0+ stepping and use auto training */
14969                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14970         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14971                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14972                 if (IS_BROADWELL(dev_priv)) {
14973                         dev_priv->display.modeset_commit_cdclk =
14974                                 broadwell_modeset_commit_cdclk;
14975                         dev_priv->display.modeset_calc_cdclk =
14976                                 broadwell_modeset_calc_cdclk;
14977                 }
14978         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14979                 dev_priv->display.modeset_commit_cdclk =
14980                         valleyview_modeset_commit_cdclk;
14981                 dev_priv->display.modeset_calc_cdclk =
14982                         valleyview_modeset_calc_cdclk;
14983         } else if (IS_BROXTON(dev_priv)) {
14984                 dev_priv->display.modeset_commit_cdclk =
14985                         broxton_modeset_commit_cdclk;
14986                 dev_priv->display.modeset_calc_cdclk =
14987                         broxton_modeset_calc_cdclk;
14988         }
14989
14990         switch (INTEL_INFO(dev_priv)->gen) {
14991         case 2:
14992                 dev_priv->display.queue_flip = intel_gen2_queue_flip;
14993                 break;
14994
14995         case 3:
14996                 dev_priv->display.queue_flip = intel_gen3_queue_flip;
14997                 break;
14998
14999         case 4:
15000         case 5:
15001                 dev_priv->display.queue_flip = intel_gen4_queue_flip;
15002                 break;
15003
15004         case 6:
15005                 dev_priv->display.queue_flip = intel_gen6_queue_flip;
15006                 break;
15007         case 7:
15008         case 8: /* FIXME(BDW): Check that the gen8 RCS flip works. */
15009                 dev_priv->display.queue_flip = intel_gen7_queue_flip;
15010                 break;
15011         case 9:
15012                 /* Drop through - unsupported since execlist only. */
15013         default:
15014                 /* Default just returns -ENODEV to indicate unsupported */
15015                 dev_priv->display.queue_flip = intel_default_queue_flip;
15016         }
15017 }
15018
15019 /*
15020  * Some BIOSes insist on assuming the GPU's pipe A is enabled at suspend,
15021  * resume, or other times.  This quirk makes sure that's the case for
15022  * affected systems.
15023  */
15024 static void quirk_pipea_force(struct drm_device *dev)
15025 {
15026         struct drm_i915_private *dev_priv = dev->dev_private;
15027
15028         dev_priv->quirks |= QUIRK_PIPEA_FORCE;
15029         DRM_INFO("applying pipe a force quirk\n");
15030 }
15031
15032 static void quirk_pipeb_force(struct drm_device *dev)
15033 {
15034         struct drm_i915_private *dev_priv = dev->dev_private;
15035
15036         dev_priv->quirks |= QUIRK_PIPEB_FORCE;
15037         DRM_INFO("applying pipe b force quirk\n");
15038 }
15039
15040 /*
15041  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
15042  */
15043 static void quirk_ssc_force_disable(struct drm_device *dev)
15044 {
15045         struct drm_i915_private *dev_priv = dev->dev_private;
15046         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
15047         DRM_INFO("applying lvds SSC disable quirk\n");
15048 }
15049
15050 /*
15051  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
15052  * brightness value
15053  */
15054 static void quirk_invert_brightness(struct drm_device *dev)
15055 {
15056         struct drm_i915_private *dev_priv = dev->dev_private;
15057         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
15058         DRM_INFO("applying inverted panel brightness quirk\n");
15059 }
15060
15061 /* Some VBT's incorrectly indicate no backlight is present */
15062 static void quirk_backlight_present(struct drm_device *dev)
15063 {
15064         struct drm_i915_private *dev_priv = dev->dev_private;
15065         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
15066         DRM_INFO("applying backlight present quirk\n");
15067 }
15068
15069 struct intel_quirk {
15070         int device;
15071         int subsystem_vendor;
15072         int subsystem_device;
15073         void (*hook)(struct drm_device *dev);
15074 };
15075
15076 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
15077 struct intel_dmi_quirk {
15078         void (*hook)(struct drm_device *dev);
15079         const struct dmi_system_id (*dmi_id_list)[];
15080 };
15081
15082 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
15083 {
15084         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
15085         return 1;
15086 }
15087
15088 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
15089         {
15090                 .dmi_id_list = &(const struct dmi_system_id[]) {
15091                         {
15092                                 .callback = intel_dmi_reverse_brightness,
15093                                 .ident = "NCR Corporation",
15094                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
15095                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
15096                                 },
15097                         },
15098                         { }  /* terminating entry */
15099                 },
15100                 .hook = quirk_invert_brightness,
15101         },
15102 };
15103
15104 static struct intel_quirk intel_quirks[] = {
15105         /* Toshiba Protege R-205, S-209 needs pipe A force quirk */
15106         { 0x2592, 0x1179, 0x0001, quirk_pipea_force },
15107
15108         /* ThinkPad T60 needs pipe A force quirk (bug #16494) */
15109         { 0x2782, 0x17aa, 0x201a, quirk_pipea_force },
15110
15111         /* 830 needs to leave pipe A & dpll A up */
15112         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipea_force },
15113
15114         /* 830 needs to leave pipe B & dpll B up */
15115         { 0x3577, PCI_ANY_ID, PCI_ANY_ID, quirk_pipeb_force },
15116
15117         /* Lenovo U160 cannot use SSC on LVDS */
15118         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
15119
15120         /* Sony Vaio Y cannot use SSC on LVDS */
15121         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15122
15123         /* Acer Aspire 5734Z must invert backlight brightness */
15124         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15125
15126         /* Acer/eMachines G725 */
15127         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15128
15129         /* Acer/eMachines e725 */
15130         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15131
15132         /* Acer/Packard Bell NCL20 */
15133         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15134
15135         /* Acer Aspire 4736Z */
15136         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15137
15138         /* Acer Aspire 5336 */
15139         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15140
15141         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15142         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15143
15144         /* Acer C720 Chromebook (Core i3 4005U) */
15145         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15146
15147         /* Apple Macbook 2,1 (Core 2 T7400) */
15148         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15149
15150         /* Apple Macbook 4,1 */
15151         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15152
15153         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15154         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15155
15156         /* HP Chromebook 14 (Celeron 2955U) */
15157         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15158
15159         /* Dell Chromebook 11 */
15160         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15161
15162         /* Dell Chromebook 11 (2015 version) */
15163         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15164 };
15165
15166 static void intel_init_quirks(struct drm_device *dev)
15167 {
15168         struct pci_dev *d = dev->pdev;
15169         int i;
15170
15171         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15172                 struct intel_quirk *q = &intel_quirks[i];
15173
15174                 if (d->device == q->device &&
15175                     (d->subsystem_vendor == q->subsystem_vendor ||
15176                      q->subsystem_vendor == PCI_ANY_ID) &&
15177                     (d->subsystem_device == q->subsystem_device ||
15178                      q->subsystem_device == PCI_ANY_ID))
15179                         q->hook(dev);
15180         }
15181         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15182                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15183                         intel_dmi_quirks[i].hook(dev);
15184         }
15185 }
15186
15187 /* Disable the VGA plane that we never use */
15188 static void i915_disable_vga(struct drm_device *dev)
15189 {
15190         struct drm_i915_private *dev_priv = dev->dev_private;
15191         u8 sr1;
15192         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15193
15194         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15195         vga_get_uninterruptible(dev->pdev, VGA_RSRC_LEGACY_IO);
15196         outb(SR01, VGA_SR_INDEX);
15197         sr1 = inb(VGA_SR_DATA);
15198         outb(sr1 | 1<<5, VGA_SR_DATA);
15199         vga_put(dev->pdev, VGA_RSRC_LEGACY_IO);
15200         udelay(300);
15201
15202         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15203         POSTING_READ(vga_reg);
15204 }
15205
15206 void intel_modeset_init_hw(struct drm_device *dev)
15207 {
15208         struct drm_i915_private *dev_priv = dev->dev_private;
15209
15210         intel_update_cdclk(dev);
15211
15212         dev_priv->atomic_cdclk_freq = dev_priv->cdclk_freq;
15213
15214         intel_init_clock_gating(dev);
15215         intel_enable_gt_powersave(dev);
15216 }
15217
15218 /*
15219  * Calculate what we think the watermarks should be for the state we've read
15220  * out of the hardware and then immediately program those watermarks so that
15221  * we ensure the hardware settings match our internal state.
15222  *
15223  * We can calculate what we think WM's should be by creating a duplicate of the
15224  * current state (which was constructed during hardware readout) and running it
15225  * through the atomic check code to calculate new watermark values in the
15226  * state object.
15227  */
15228 static void sanitize_watermarks(struct drm_device *dev)
15229 {
15230         struct drm_i915_private *dev_priv = to_i915(dev);
15231         struct drm_atomic_state *state;
15232         struct drm_crtc *crtc;
15233         struct drm_crtc_state *cstate;
15234         struct drm_modeset_acquire_ctx ctx;
15235         int ret;
15236         int i;
15237
15238         /* Only supported on platforms that use atomic watermark design */
15239         if (!dev_priv->display.optimize_watermarks)
15240                 return;
15241
15242         /*
15243          * We need to hold connection_mutex before calling duplicate_state so
15244          * that the connector loop is protected.
15245          */
15246         drm_modeset_acquire_init(&ctx, 0);
15247 retry:
15248         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15249         if (ret == -EDEADLK) {
15250                 drm_modeset_backoff(&ctx);
15251                 goto retry;
15252         } else if (WARN_ON(ret)) {
15253                 goto fail;
15254         }
15255
15256         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15257         if (WARN_ON(IS_ERR(state)))
15258                 goto fail;
15259
15260         /*
15261          * Hardware readout is the only time we don't want to calculate
15262          * intermediate watermarks (since we don't trust the current
15263          * watermarks).
15264          */
15265         to_intel_atomic_state(state)->skip_intermediate_wm = true;
15266
15267         ret = intel_atomic_check(dev, state);
15268         if (ret) {
15269                 /*
15270                  * If we fail here, it means that the hardware appears to be
15271                  * programmed in a way that shouldn't be possible, given our
15272                  * understanding of watermark requirements.  This might mean a
15273                  * mistake in the hardware readout code or a mistake in the
15274                  * watermark calculations for a given platform.  Raise a WARN
15275                  * so that this is noticeable.
15276                  *
15277                  * If this actually happens, we'll have to just leave the
15278                  * BIOS-programmed watermarks untouched and hope for the best.
15279                  */
15280                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15281                 goto fail;
15282         }
15283
15284         /* Write calculated watermark values back */
15285         to_i915(dev)->wm.config = to_intel_atomic_state(state)->wm_config;
15286         for_each_crtc_in_state(state, crtc, cstate, i) {
15287                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15288
15289                 cs->wm.need_postvbl_update = true;
15290                 dev_priv->display.optimize_watermarks(cs);
15291         }
15292
15293         drm_atomic_state_free(state);
15294 fail:
15295         drm_modeset_drop_locks(&ctx);
15296         drm_modeset_acquire_fini(&ctx);
15297 }
15298
15299 void intel_modeset_init(struct drm_device *dev)
15300 {
15301         struct drm_i915_private *dev_priv = dev->dev_private;
15302         int sprite, ret;
15303         enum pipe pipe;
15304         struct intel_crtc *crtc;
15305
15306         drm_mode_config_init(dev);
15307
15308         dev->mode_config.min_width = 0;
15309         dev->mode_config.min_height = 0;
15310
15311         dev->mode_config.preferred_depth = 24;
15312         dev->mode_config.prefer_shadow = 1;
15313
15314         dev->mode_config.allow_fb_modifiers = true;
15315
15316         dev->mode_config.funcs = &intel_mode_funcs;
15317
15318         intel_init_quirks(dev);
15319
15320         intel_init_pm(dev);
15321
15322         if (INTEL_INFO(dev)->num_pipes == 0)
15323                 return;
15324
15325         /*
15326          * There may be no VBT; and if the BIOS enabled SSC we can
15327          * just keep using it to avoid unnecessary flicker.  Whereas if the
15328          * BIOS isn't using it, don't assume it will work even if the VBT
15329          * indicates as much.
15330          */
15331         if (HAS_PCH_IBX(dev) || HAS_PCH_CPT(dev)) {
15332                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15333                                             DREF_SSC1_ENABLE);
15334
15335                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15336                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15337                                      bios_lvds_use_ssc ? "en" : "dis",
15338                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15339                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15340                 }
15341         }
15342
15343         if (IS_GEN2(dev)) {
15344                 dev->mode_config.max_width = 2048;
15345                 dev->mode_config.max_height = 2048;
15346         } else if (IS_GEN3(dev)) {
15347                 dev->mode_config.max_width = 4096;
15348                 dev->mode_config.max_height = 4096;
15349         } else {
15350                 dev->mode_config.max_width = 8192;
15351                 dev->mode_config.max_height = 8192;
15352         }
15353
15354         if (IS_845G(dev) || IS_I865G(dev)) {
15355                 dev->mode_config.cursor_width = IS_845G(dev) ? 64 : 512;
15356                 dev->mode_config.cursor_height = 1023;
15357         } else if (IS_GEN2(dev)) {
15358                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
15359                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
15360         } else {
15361                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
15362                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
15363         }
15364
15365         dev->mode_config.fb_base = dev_priv->ggtt.mappable_base;
15366
15367         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15368                       INTEL_INFO(dev)->num_pipes,
15369                       INTEL_INFO(dev)->num_pipes > 1 ? "s" : "");
15370
15371         for_each_pipe(dev_priv, pipe) {
15372                 intel_crtc_init(dev, pipe);
15373                 for_each_sprite(dev_priv, pipe, sprite) {
15374                         ret = intel_plane_init(dev, pipe, sprite);
15375                         if (ret)
15376                                 DRM_DEBUG_KMS("pipe %c sprite %c init failed: %d\n",
15377                                               pipe_name(pipe), sprite_name(pipe, sprite), ret);
15378                 }
15379         }
15380
15381         intel_update_czclk(dev_priv);
15382         intel_update_rawclk(dev_priv);
15383         intel_update_cdclk(dev);
15384
15385         intel_shared_dpll_init(dev);
15386
15387         /* Just disable it once at startup */
15388         i915_disable_vga(dev);
15389         intel_setup_outputs(dev);
15390
15391         drm_modeset_lock_all(dev);
15392         intel_modeset_setup_hw_state(dev);
15393         drm_modeset_unlock_all(dev);
15394
15395         for_each_intel_crtc(dev, crtc) {
15396                 struct intel_initial_plane_config plane_config = {};
15397
15398                 if (!crtc->active)
15399                         continue;
15400
15401                 /*
15402                  * Note that reserving the BIOS fb up front prevents us
15403                  * from stuffing other stolen allocations like the ring
15404                  * on top.  This prevents some ugliness at boot time, and
15405                  * can even allow for smooth boot transitions if the BIOS
15406                  * fb is large enough for the active pipe configuration.
15407                  */
15408                 dev_priv->display.get_initial_plane_config(crtc,
15409                                                            &plane_config);
15410
15411                 /*
15412                  * If the fb is shared between multiple heads, we'll
15413                  * just get the first one.
15414                  */
15415                 intel_find_initial_plane_obj(crtc, &plane_config);
15416         }
15417
15418         /*
15419          * Make sure hardware watermarks really match the state we read out.
15420          * Note that we need to do this after reconstructing the BIOS fb's
15421          * since the watermark calculation done here will use pstate->fb.
15422          */
15423         sanitize_watermarks(dev);
15424 }
15425
15426 static void intel_enable_pipe_a(struct drm_device *dev)
15427 {
15428         struct intel_connector *connector;
15429         struct drm_connector *crt = NULL;
15430         struct intel_load_detect_pipe load_detect_temp;
15431         struct drm_modeset_acquire_ctx *ctx = dev->mode_config.acquire_ctx;
15432
15433         /* We can't just switch on the pipe A, we need to set things up with a
15434          * proper mode and output configuration. As a gross hack, enable pipe A
15435          * by enabling the load detect pipe once. */
15436         for_each_intel_connector(dev, connector) {
15437                 if (connector->encoder->type == INTEL_OUTPUT_ANALOG) {
15438                         crt = &connector->base;
15439                         break;
15440                 }
15441         }
15442
15443         if (!crt)
15444                 return;
15445
15446         if (intel_get_load_detect_pipe(crt, NULL, &load_detect_temp, ctx))
15447                 intel_release_load_detect_pipe(crt, &load_detect_temp, ctx);
15448 }
15449
15450 static bool
15451 intel_check_plane_mapping(struct intel_crtc *crtc)
15452 {
15453         struct drm_device *dev = crtc->base.dev;
15454         struct drm_i915_private *dev_priv = dev->dev_private;
15455         u32 val;
15456
15457         if (INTEL_INFO(dev)->num_pipes == 1)
15458                 return true;
15459
15460         val = I915_READ(DSPCNTR(!crtc->plane));
15461
15462         if ((val & DISPLAY_PLANE_ENABLE) &&
15463             (!!(val & DISPPLANE_SEL_PIPE_MASK) == crtc->pipe))
15464                 return false;
15465
15466         return true;
15467 }
15468
15469 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15470 {
15471         struct drm_device *dev = crtc->base.dev;
15472         struct intel_encoder *encoder;
15473
15474         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15475                 return true;
15476
15477         return false;
15478 }
15479
15480 static bool intel_encoder_has_connectors(struct intel_encoder *encoder)
15481 {
15482         struct drm_device *dev = encoder->base.dev;
15483         struct intel_connector *connector;
15484
15485         for_each_connector_on_encoder(dev, &encoder->base, connector)
15486                 return true;
15487
15488         return false;
15489 }
15490
15491 static void intel_sanitize_crtc(struct intel_crtc *crtc)
15492 {
15493         struct drm_device *dev = crtc->base.dev;
15494         struct drm_i915_private *dev_priv = dev->dev_private;
15495         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15496
15497         /* Clear any frame start delays used for debugging left by the BIOS */
15498         if (!transcoder_is_dsi(cpu_transcoder)) {
15499                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15500
15501                 I915_WRITE(reg,
15502                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15503         }
15504
15505         /* restore vblank interrupts to correct state */
15506         drm_crtc_vblank_reset(&crtc->base);
15507         if (crtc->active) {
15508                 struct intel_plane *plane;
15509
15510                 drm_crtc_vblank_on(&crtc->base);
15511
15512                 /* Disable everything but the primary plane */
15513                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15514                         if (plane->base.type == DRM_PLANE_TYPE_PRIMARY)
15515                                 continue;
15516
15517                         plane->disable_plane(&plane->base, &crtc->base);
15518                 }
15519         }
15520
15521         /* We need to sanitize the plane -> pipe mapping first because this will
15522          * disable the crtc (and hence change the state) if it is wrong. Note
15523          * that gen4+ has a fixed plane -> pipe mapping.  */
15524         if (INTEL_INFO(dev)->gen < 4 && !intel_check_plane_mapping(crtc)) {
15525                 bool plane;
15526
15527                 DRM_DEBUG_KMS("[CRTC:%d] wrong plane connection detected!\n",
15528                               crtc->base.base.id);
15529
15530                 /* Pipe has the wrong plane attached and the plane is active.
15531                  * Temporarily change the plane mapping and disable everything
15532                  * ...  */
15533                 plane = crtc->plane;
15534                 to_intel_plane_state(crtc->base.primary->state)->visible = true;
15535                 crtc->plane = !plane;
15536                 intel_crtc_disable_noatomic(&crtc->base);
15537                 crtc->plane = plane;
15538         }
15539
15540         if (dev_priv->quirks & QUIRK_PIPEA_FORCE &&
15541             crtc->pipe == PIPE_A && !crtc->active) {
15542                 /* BIOS forgot to enable pipe A, this mostly happens after
15543                  * resume. Force-enable the pipe to fix this, the update_dpms
15544                  * call below we restore the pipe to the right state, but leave
15545                  * the required bits on. */
15546                 intel_enable_pipe_a(dev);
15547         }
15548
15549         /* Adjust the state of the output pipe according to whether we
15550          * have active connectors/encoders. */
15551         if (crtc->active && !intel_crtc_has_encoders(crtc))
15552                 intel_crtc_disable_noatomic(&crtc->base);
15553
15554         if (crtc->active || HAS_GMCH_DISPLAY(dev)) {
15555                 /*
15556                  * We start out with underrun reporting disabled to avoid races.
15557                  * For correct bookkeeping mark this on active crtcs.
15558                  *
15559                  * Also on gmch platforms we dont have any hardware bits to
15560                  * disable the underrun reporting. Which means we need to start
15561                  * out with underrun reporting disabled also on inactive pipes,
15562                  * since otherwise we'll complain about the garbage we read when
15563                  * e.g. coming up after runtime pm.
15564                  *
15565                  * No protection against concurrent access is required - at
15566                  * worst a fifo underrun happens which also sets this to false.
15567                  */
15568                 crtc->cpu_fifo_underrun_disabled = true;
15569                 crtc->pch_fifo_underrun_disabled = true;
15570         }
15571 }
15572
15573 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15574 {
15575         struct intel_connector *connector;
15576         struct drm_device *dev = encoder->base.dev;
15577
15578         /* We need to check both for a crtc link (meaning that the
15579          * encoder is active and trying to read from a pipe) and the
15580          * pipe itself being active. */
15581         bool has_active_crtc = encoder->base.crtc &&
15582                 to_intel_crtc(encoder->base.crtc)->active;
15583
15584         if (intel_encoder_has_connectors(encoder) && !has_active_crtc) {
15585                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15586                               encoder->base.base.id,
15587                               encoder->base.name);
15588
15589                 /* Connector is active, but has no active pipe. This is
15590                  * fallout from our resume register restoring. Disable
15591                  * the encoder manually again. */
15592                 if (encoder->base.crtc) {
15593                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15594                                       encoder->base.base.id,
15595                                       encoder->base.name);
15596                         encoder->disable(encoder);
15597                         if (encoder->post_disable)
15598                                 encoder->post_disable(encoder);
15599                 }
15600                 encoder->base.crtc = NULL;
15601
15602                 /* Inconsistent output/port/pipe state happens presumably due to
15603                  * a bug in one of the get_hw_state functions. Or someplace else
15604                  * in our code, like the register restore mess on resume. Clamp
15605                  * things to off as a safer default. */
15606                 for_each_intel_connector(dev, connector) {
15607                         if (connector->encoder != encoder)
15608                                 continue;
15609                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15610                         connector->base.encoder = NULL;
15611                 }
15612         }
15613         /* Enabled encoders without active connectors will be fixed in
15614          * the crtc fixup. */
15615 }
15616
15617 void i915_redisable_vga_power_on(struct drm_device *dev)
15618 {
15619         struct drm_i915_private *dev_priv = dev->dev_private;
15620         i915_reg_t vga_reg = i915_vgacntrl_reg(dev);
15621
15622         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15623                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15624                 i915_disable_vga(dev);
15625         }
15626 }
15627
15628 void i915_redisable_vga(struct drm_device *dev)
15629 {
15630         struct drm_i915_private *dev_priv = dev->dev_private;
15631
15632         /* This function can be called both from intel_modeset_setup_hw_state or
15633          * at a very early point in our resume sequence, where the power well
15634          * structures are not yet restored. Since this function is at a very
15635          * paranoid "someone might have enabled VGA while we were not looking"
15636          * level, just check if the power well is enabled instead of trying to
15637          * follow the "don't touch the power well if we don't need it" policy
15638          * the rest of the driver uses. */
15639         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15640                 return;
15641
15642         i915_redisable_vga_power_on(dev);
15643
15644         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15645 }
15646
15647 static bool primary_get_hw_state(struct intel_plane *plane)
15648 {
15649         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
15650
15651         return I915_READ(DSPCNTR(plane->plane)) & DISPLAY_PLANE_ENABLE;
15652 }
15653
15654 /* FIXME read out full plane state for all planes */
15655 static void readout_plane_state(struct intel_crtc *crtc)
15656 {
15657         struct drm_plane *primary = crtc->base.primary;
15658         struct intel_plane_state *plane_state =
15659                 to_intel_plane_state(primary->state);
15660
15661         plane_state->visible = crtc->active &&
15662                 primary_get_hw_state(to_intel_plane(primary));
15663
15664         if (plane_state->visible)
15665                 crtc->base.state->plane_mask |= 1 << drm_plane_index(primary);
15666 }
15667
15668 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15669 {
15670         struct drm_i915_private *dev_priv = dev->dev_private;
15671         enum pipe pipe;
15672         struct intel_crtc *crtc;
15673         struct intel_encoder *encoder;
15674         struct intel_connector *connector;
15675         int i;
15676
15677         dev_priv->active_crtcs = 0;
15678
15679         for_each_intel_crtc(dev, crtc) {
15680                 struct intel_crtc_state *crtc_state = crtc->config;
15681                 int pixclk = 0;
15682
15683                 __drm_atomic_helper_crtc_destroy_state(&crtc->base, &crtc_state->base);
15684                 memset(crtc_state, 0, sizeof(*crtc_state));
15685                 crtc_state->base.crtc = &crtc->base;
15686
15687                 crtc_state->base.active = crtc_state->base.enable =
15688                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15689
15690                 crtc->base.enabled = crtc_state->base.enable;
15691                 crtc->active = crtc_state->base.active;
15692
15693                 if (crtc_state->base.active) {
15694                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15695
15696                         if (IS_BROADWELL(dev_priv)) {
15697                                 pixclk = ilk_pipe_pixel_rate(crtc_state);
15698
15699                                 /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15700                                 if (crtc_state->ips_enabled)
15701                                         pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15702                         } else if (IS_VALLEYVIEW(dev_priv) ||
15703                                    IS_CHERRYVIEW(dev_priv) ||
15704                                    IS_BROXTON(dev_priv))
15705                                 pixclk = crtc_state->base.adjusted_mode.crtc_clock;
15706                         else
15707                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15708                 }
15709
15710                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15711
15712                 readout_plane_state(crtc);
15713
15714                 DRM_DEBUG_KMS("[CRTC:%d] hw state readout: %s\n",
15715                               crtc->base.base.id,
15716                               crtc->active ? "enabled" : "disabled");
15717         }
15718
15719         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15720                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15721
15722                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15723                                                   &pll->config.hw_state);
15724                 pll->config.crtc_mask = 0;
15725                 for_each_intel_crtc(dev, crtc) {
15726                         if (crtc->active && crtc->config->shared_dpll == pll)
15727                                 pll->config.crtc_mask |= 1 << crtc->pipe;
15728                 }
15729                 pll->active_mask = pll->config.crtc_mask;
15730
15731                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15732                               pll->name, pll->config.crtc_mask, pll->on);
15733         }
15734
15735         for_each_intel_encoder(dev, encoder) {
15736                 pipe = 0;
15737
15738                 if (encoder->get_hw_state(encoder, &pipe)) {
15739                         crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15740                         encoder->base.crtc = &crtc->base;
15741                         encoder->get_config(encoder, crtc->config);
15742                 } else {
15743                         encoder->base.crtc = NULL;
15744                 }
15745
15746                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15747                               encoder->base.base.id,
15748                               encoder->base.name,
15749                               encoder->base.crtc ? "enabled" : "disabled",
15750                               pipe_name(pipe));
15751         }
15752
15753         for_each_intel_connector(dev, connector) {
15754                 if (connector->get_hw_state(connector)) {
15755                         connector->base.dpms = DRM_MODE_DPMS_ON;
15756
15757                         encoder = connector->encoder;
15758                         connector->base.encoder = &encoder->base;
15759
15760                         if (encoder->base.crtc &&
15761                             encoder->base.crtc->state->active) {
15762                                 /*
15763                                  * This has to be done during hardware readout
15764                                  * because anything calling .crtc_disable may
15765                                  * rely on the connector_mask being accurate.
15766                                  */
15767                                 encoder->base.crtc->state->connector_mask |=
15768                                         1 << drm_connector_index(&connector->base);
15769                                 encoder->base.crtc->state->encoder_mask |=
15770                                         1 << drm_encoder_index(&encoder->base);
15771                         }
15772
15773                 } else {
15774                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15775                         connector->base.encoder = NULL;
15776                 }
15777                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15778                               connector->base.base.id,
15779                               connector->base.name,
15780                               connector->base.encoder ? "enabled" : "disabled");
15781         }
15782
15783         for_each_intel_crtc(dev, crtc) {
15784                 crtc->base.hwmode = crtc->config->base.adjusted_mode;
15785
15786                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15787                 if (crtc->base.state->active) {
15788                         intel_mode_from_pipe_config(&crtc->base.mode, crtc->config);
15789                         intel_mode_from_pipe_config(&crtc->base.state->adjusted_mode, crtc->config);
15790                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15791
15792                         /*
15793                          * The initial mode needs to be set in order to keep
15794                          * the atomic core happy. It wants a valid mode if the
15795                          * crtc's enabled, so we do the above call.
15796                          *
15797                          * At this point some state updated by the connectors
15798                          * in their ->detect() callback has not run yet, so
15799                          * no recalculation can be done yet.
15800                          *
15801                          * Even if we could do a recalculation and modeset
15802                          * right now it would cause a double modeset if
15803                          * fbdev or userspace chooses a different initial mode.
15804                          *
15805                          * If that happens, someone indicated they wanted a
15806                          * mode change, which means it's safe to do a full
15807                          * recalculation.
15808                          */
15809                         crtc->base.state->mode.private_flags = I915_MODE_FLAG_INHERITED;
15810
15811                         drm_calc_timestamping_constants(&crtc->base, &crtc->base.hwmode);
15812                         update_scanline_offset(crtc);
15813                 }
15814
15815                 intel_pipe_config_sanity_check(dev_priv, crtc->config);
15816         }
15817 }
15818
15819 /* Scan out the current hw modeset state,
15820  * and sanitizes it to the current state
15821  */
15822 static void
15823 intel_modeset_setup_hw_state(struct drm_device *dev)
15824 {
15825         struct drm_i915_private *dev_priv = dev->dev_private;
15826         enum pipe pipe;
15827         struct intel_crtc *crtc;
15828         struct intel_encoder *encoder;
15829         int i;
15830
15831         intel_modeset_readout_hw_state(dev);
15832
15833         /* HW state is read out, now we need to sanitize this mess. */
15834         for_each_intel_encoder(dev, encoder) {
15835                 intel_sanitize_encoder(encoder);
15836         }
15837
15838         for_each_pipe(dev_priv, pipe) {
15839                 crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]);
15840                 intel_sanitize_crtc(crtc);
15841                 intel_dump_pipe_config(crtc, crtc->config,
15842                                        "[setup_hw_state]");
15843         }
15844
15845         intel_modeset_update_connector_atomic_state(dev);
15846
15847         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15848                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15849
15850                 if (!pll->on || pll->active_mask)
15851                         continue;
15852
15853                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15854
15855                 pll->funcs.disable(dev_priv, pll);
15856                 pll->on = false;
15857         }
15858
15859         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
15860                 vlv_wm_get_hw_state(dev);
15861         else if (IS_GEN9(dev))
15862                 skl_wm_get_hw_state(dev);
15863         else if (HAS_PCH_SPLIT(dev))
15864                 ilk_wm_get_hw_state(dev);
15865
15866         for_each_intel_crtc(dev, crtc) {
15867                 unsigned long put_domains;
15868
15869                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15870                 if (WARN_ON(put_domains))
15871                         modeset_put_power_domains(dev_priv, put_domains);
15872         }
15873         intel_display_set_init_power(dev_priv, false);
15874
15875         intel_fbc_init_pipe_state(dev_priv);
15876 }
15877
15878 void intel_display_resume(struct drm_device *dev)
15879 {
15880         struct drm_i915_private *dev_priv = to_i915(dev);
15881         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15882         struct drm_modeset_acquire_ctx ctx;
15883         int ret;
15884         bool setup = false;
15885
15886         dev_priv->modeset_restore_state = NULL;
15887
15888         /*
15889          * This is a cludge because with real atomic modeset mode_config.mutex
15890          * won't be taken. Unfortunately some probed state like
15891          * audio_codec_enable is still protected by mode_config.mutex, so lock
15892          * it here for now.
15893          */
15894         mutex_lock(&dev->mode_config.mutex);
15895         drm_modeset_acquire_init(&ctx, 0);
15896
15897 retry:
15898         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15899
15900         if (ret == 0 && !setup) {
15901                 setup = true;
15902
15903                 intel_modeset_setup_hw_state(dev);
15904                 i915_redisable_vga(dev);
15905         }
15906
15907         if (ret == 0 && state) {
15908                 struct drm_crtc_state *crtc_state;
15909                 struct drm_crtc *crtc;
15910                 int i;
15911
15912                 state->acquire_ctx = &ctx;
15913
15914                 for_each_crtc_in_state(state, crtc, crtc_state, i) {
15915                         /*
15916                          * Force recalculation even if we restore
15917                          * current state. With fast modeset this may not result
15918                          * in a modeset when the state is compatible.
15919                          */
15920                         crtc_state->mode_changed = true;
15921                 }
15922
15923                 ret = drm_atomic_commit(state);
15924         }
15925
15926         if (ret == -EDEADLK) {
15927                 drm_modeset_backoff(&ctx);
15928                 goto retry;
15929         }
15930
15931         drm_modeset_drop_locks(&ctx);
15932         drm_modeset_acquire_fini(&ctx);
15933         mutex_unlock(&dev->mode_config.mutex);
15934
15935         if (ret) {
15936                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15937                 drm_atomic_state_free(state);
15938         }
15939 }
15940
15941 void intel_modeset_gem_init(struct drm_device *dev)
15942 {
15943         struct drm_crtc *c;
15944         struct drm_i915_gem_object *obj;
15945         int ret;
15946
15947         intel_init_gt_powersave(dev);
15948
15949         intel_modeset_init_hw(dev);
15950
15951         intel_setup_overlay(dev);
15952
15953         /*
15954          * Make sure any fbs we allocated at startup are properly
15955          * pinned & fenced.  When we do the allocation it's too early
15956          * for this.
15957          */
15958         for_each_crtc(dev, c) {
15959                 obj = intel_fb_obj(c->primary->fb);
15960                 if (obj == NULL)
15961                         continue;
15962
15963                 mutex_lock(&dev->struct_mutex);
15964                 ret = intel_pin_and_fence_fb_obj(c->primary->fb,
15965                                                  c->primary->state->rotation);
15966                 mutex_unlock(&dev->struct_mutex);
15967                 if (ret) {
15968                         DRM_ERROR("failed to pin boot fb on pipe %d\n",
15969                                   to_intel_crtc(c)->pipe);
15970                         drm_framebuffer_unreference(c->primary->fb);
15971                         c->primary->fb = NULL;
15972                         c->primary->crtc = c->primary->state->crtc = NULL;
15973                         update_state_fb(c->primary);
15974                         c->state->plane_mask &= ~(1 << drm_plane_index(c->primary));
15975                 }
15976         }
15977
15978         intel_backlight_register(dev);
15979 }
15980
15981 void intel_connector_unregister(struct intel_connector *intel_connector)
15982 {
15983         struct drm_connector *connector = &intel_connector->base;
15984
15985         intel_panel_destroy_backlight(connector);
15986         drm_connector_unregister(connector);
15987 }
15988
15989 void intel_modeset_cleanup(struct drm_device *dev)
15990 {
15991         struct drm_i915_private *dev_priv = dev->dev_private;
15992         struct intel_connector *connector;
15993
15994         intel_disable_gt_powersave(dev);
15995
15996         intel_backlight_unregister(dev);
15997
15998         /*
15999          * Interrupts and polling as the first thing to avoid creating havoc.
16000          * Too much stuff here (turning of connectors, ...) would
16001          * experience fancy races otherwise.
16002          */
16003         intel_irq_uninstall(dev_priv);
16004
16005         /*
16006          * Due to the hpd irq storm handling the hotplug work can re-arm the
16007          * poll handlers. Hence disable polling after hpd handling is shut down.
16008          */
16009         drm_kms_helper_poll_fini(dev);
16010
16011         intel_unregister_dsm_handler();
16012
16013         intel_fbc_global_disable(dev_priv);
16014
16015         /* flush any delayed tasks or pending work */
16016         flush_scheduled_work();
16017
16018         /* destroy the backlight and sysfs files before encoders/connectors */
16019         for_each_intel_connector(dev, connector)
16020                 connector->unregister(connector);
16021
16022         drm_mode_config_cleanup(dev);
16023
16024         intel_cleanup_overlay(dev);
16025
16026         intel_cleanup_gt_powersave(dev);
16027
16028         intel_teardown_gmbus(dev);
16029 }
16030
16031 /*
16032  * Return which encoder is currently attached for connector.
16033  */
16034 struct drm_encoder *intel_best_encoder(struct drm_connector *connector)
16035 {
16036         return &intel_attached_encoder(connector)->base;
16037 }
16038
16039 void intel_connector_attach_encoder(struct intel_connector *connector,
16040                                     struct intel_encoder *encoder)
16041 {
16042         connector->encoder = encoder;
16043         drm_mode_connector_attach_encoder(&connector->base,
16044                                           &encoder->base);
16045 }
16046
16047 /*
16048  * set vga decode state - true == enable VGA decode
16049  */
16050 int intel_modeset_vga_set_state(struct drm_device *dev, bool state)
16051 {
16052         struct drm_i915_private *dev_priv = dev->dev_private;
16053         unsigned reg = INTEL_INFO(dev)->gen >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16054         u16 gmch_ctrl;
16055
16056         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16057                 DRM_ERROR("failed to read control word\n");
16058                 return -EIO;
16059         }
16060
16061         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16062                 return 0;
16063
16064         if (state)
16065                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16066         else
16067                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16068
16069         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16070                 DRM_ERROR("failed to write control word\n");
16071                 return -EIO;
16072         }
16073
16074         return 0;
16075 }
16076
16077 struct intel_display_error_state {
16078
16079         u32 power_well_driver;
16080
16081         int num_transcoders;
16082
16083         struct intel_cursor_error_state {
16084                 u32 control;
16085                 u32 position;
16086                 u32 base;
16087                 u32 size;
16088         } cursor[I915_MAX_PIPES];
16089
16090         struct intel_pipe_error_state {
16091                 bool power_domain_on;
16092                 u32 source;
16093                 u32 stat;
16094         } pipe[I915_MAX_PIPES];
16095
16096         struct intel_plane_error_state {
16097                 u32 control;
16098                 u32 stride;
16099                 u32 size;
16100                 u32 pos;
16101                 u32 addr;
16102                 u32 surface;
16103                 u32 tile_offset;
16104         } plane[I915_MAX_PIPES];
16105
16106         struct intel_transcoder_error_state {
16107                 bool power_domain_on;
16108                 enum transcoder cpu_transcoder;
16109
16110                 u32 conf;
16111
16112                 u32 htotal;
16113                 u32 hblank;
16114                 u32 hsync;
16115                 u32 vtotal;
16116                 u32 vblank;
16117                 u32 vsync;
16118         } transcoder[4];
16119 };
16120
16121 struct intel_display_error_state *
16122 intel_display_capture_error_state(struct drm_device *dev)
16123 {
16124         struct drm_i915_private *dev_priv = dev->dev_private;
16125         struct intel_display_error_state *error;
16126         int transcoders[] = {
16127                 TRANSCODER_A,
16128                 TRANSCODER_B,
16129                 TRANSCODER_C,
16130                 TRANSCODER_EDP,
16131         };
16132         int i;
16133
16134         if (INTEL_INFO(dev)->num_pipes == 0)
16135                 return NULL;
16136
16137         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16138         if (error == NULL)
16139                 return NULL;
16140
16141         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16142                 error->power_well_driver = I915_READ(HSW_PWR_WELL_DRIVER);
16143
16144         for_each_pipe(dev_priv, i) {
16145                 error->pipe[i].power_domain_on =
16146                         __intel_display_power_is_enabled(dev_priv,
16147                                                          POWER_DOMAIN_PIPE(i));
16148                 if (!error->pipe[i].power_domain_on)
16149                         continue;
16150
16151                 error->cursor[i].control = I915_READ(CURCNTR(i));
16152                 error->cursor[i].position = I915_READ(CURPOS(i));
16153                 error->cursor[i].base = I915_READ(CURBASE(i));
16154
16155                 error->plane[i].control = I915_READ(DSPCNTR(i));
16156                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16157                 if (INTEL_INFO(dev)->gen <= 3) {
16158                         error->plane[i].size = I915_READ(DSPSIZE(i));
16159                         error->plane[i].pos = I915_READ(DSPPOS(i));
16160                 }
16161                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16162                         error->plane[i].addr = I915_READ(DSPADDR(i));
16163                 if (INTEL_INFO(dev)->gen >= 4) {
16164                         error->plane[i].surface = I915_READ(DSPSURF(i));
16165                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16166                 }
16167
16168                 error->pipe[i].source = I915_READ(PIPESRC(i));
16169
16170                 if (HAS_GMCH_DISPLAY(dev))
16171                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16172         }
16173
16174         /* Note: this does not include DSI transcoders. */
16175         error->num_transcoders = INTEL_INFO(dev)->num_pipes;
16176         if (HAS_DDI(dev_priv->dev))
16177                 error->num_transcoders++; /* Account for eDP. */
16178
16179         for (i = 0; i < error->num_transcoders; i++) {
16180                 enum transcoder cpu_transcoder = transcoders[i];
16181
16182                 error->transcoder[i].power_domain_on =
16183                         __intel_display_power_is_enabled(dev_priv,
16184                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16185                 if (!error->transcoder[i].power_domain_on)
16186                         continue;
16187
16188                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16189
16190                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16191                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16192                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16193                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16194                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16195                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16196                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16197         }
16198
16199         return error;
16200 }
16201
16202 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16203
16204 void
16205 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16206                                 struct drm_device *dev,
16207                                 struct intel_display_error_state *error)
16208 {
16209         struct drm_i915_private *dev_priv = dev->dev_private;
16210         int i;
16211
16212         if (!error)
16213                 return;
16214
16215         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev)->num_pipes);
16216         if (IS_HASWELL(dev) || IS_BROADWELL(dev))
16217                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16218                            error->power_well_driver);
16219         for_each_pipe(dev_priv, i) {
16220                 err_printf(m, "Pipe [%d]:\n", i);
16221                 err_printf(m, "  Power: %s\n",
16222                            onoff(error->pipe[i].power_domain_on));
16223                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16224                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16225
16226                 err_printf(m, "Plane [%d]:\n", i);
16227                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16228                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16229                 if (INTEL_INFO(dev)->gen <= 3) {
16230                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16231                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16232                 }
16233                 if (INTEL_INFO(dev)->gen <= 7 && !IS_HASWELL(dev))
16234                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16235                 if (INTEL_INFO(dev)->gen >= 4) {
16236                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16237                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16238                 }
16239
16240                 err_printf(m, "Cursor [%d]:\n", i);
16241                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16242                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16243                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16244         }
16245
16246         for (i = 0; i < error->num_transcoders; i++) {
16247                 err_printf(m, "CPU transcoder: %s\n",
16248                            transcoder_name(error->transcoder[i].cpu_transcoder));
16249                 err_printf(m, "  Power: %s\n",
16250                            onoff(error->transcoder[i].power_domain_on));
16251                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16252                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16253                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16254                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16255                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16256                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16257                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16258         }
16259 }