GNU Linux-libre 4.14.290-gnu1
[releases.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 "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "i915_gem_clflush.h"
41 #include "intel_dsi.h"
42 #include "i915_trace.h"
43 #include <drm/drm_atomic.h>
44 #include <drm/drm_atomic_helper.h>
45 #include <drm/drm_dp_helper.h>
46 #include <drm/drm_crtc_helper.h>
47 #include <drm/drm_plane_helper.h>
48 #include <drm/drm_rect.h>
49 #include <linux/dma_remapping.h>
50 #include <linux/reservation.h>
51
52 /* Primary plane formats for gen <= 3 */
53 static const uint32_t i8xx_primary_formats[] = {
54         DRM_FORMAT_C8,
55         DRM_FORMAT_RGB565,
56         DRM_FORMAT_XRGB1555,
57         DRM_FORMAT_XRGB8888,
58 };
59
60 /* Primary plane formats for gen >= 4 */
61 static const uint32_t i965_primary_formats[] = {
62         DRM_FORMAT_C8,
63         DRM_FORMAT_RGB565,
64         DRM_FORMAT_XRGB8888,
65         DRM_FORMAT_XBGR8888,
66         DRM_FORMAT_XRGB2101010,
67         DRM_FORMAT_XBGR2101010,
68 };
69
70 static const uint64_t i9xx_format_modifiers[] = {
71         I915_FORMAT_MOD_X_TILED,
72         DRM_FORMAT_MOD_LINEAR,
73         DRM_FORMAT_MOD_INVALID
74 };
75
76 static const uint32_t skl_primary_formats[] = {
77         DRM_FORMAT_C8,
78         DRM_FORMAT_RGB565,
79         DRM_FORMAT_XRGB8888,
80         DRM_FORMAT_XBGR8888,
81         DRM_FORMAT_ARGB8888,
82         DRM_FORMAT_ABGR8888,
83         DRM_FORMAT_XRGB2101010,
84         DRM_FORMAT_XBGR2101010,
85         DRM_FORMAT_YUYV,
86         DRM_FORMAT_YVYU,
87         DRM_FORMAT_UYVY,
88         DRM_FORMAT_VYUY,
89 };
90
91 static const uint64_t skl_format_modifiers_noccs[] = {
92         I915_FORMAT_MOD_Yf_TILED,
93         I915_FORMAT_MOD_Y_TILED,
94         I915_FORMAT_MOD_X_TILED,
95         DRM_FORMAT_MOD_LINEAR,
96         DRM_FORMAT_MOD_INVALID
97 };
98
99 static const uint64_t skl_format_modifiers_ccs[] = {
100         I915_FORMAT_MOD_Yf_TILED_CCS,
101         I915_FORMAT_MOD_Y_TILED_CCS,
102         I915_FORMAT_MOD_Yf_TILED,
103         I915_FORMAT_MOD_Y_TILED,
104         I915_FORMAT_MOD_X_TILED,
105         DRM_FORMAT_MOD_LINEAR,
106         DRM_FORMAT_MOD_INVALID
107 };
108
109 /* Cursor formats */
110 static const uint32_t intel_cursor_formats[] = {
111         DRM_FORMAT_ARGB8888,
112 };
113
114 static const uint64_t cursor_format_modifiers[] = {
115         DRM_FORMAT_MOD_LINEAR,
116         DRM_FORMAT_MOD_INVALID
117 };
118
119 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
120                                 struct intel_crtc_state *pipe_config);
121 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
122                                    struct intel_crtc_state *pipe_config);
123
124 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
125                                   struct drm_i915_gem_object *obj,
126                                   struct drm_mode_fb_cmd2 *mode_cmd);
127 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
128 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
129 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
130 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
131                                          struct intel_link_m_n *m_n,
132                                          struct intel_link_m_n *m2_n2);
133 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
134 static void haswell_set_pipeconf(struct drm_crtc *crtc);
135 static void haswell_set_pipemisc(struct drm_crtc *crtc);
136 static void vlv_prepare_pll(struct intel_crtc *crtc,
137                             const struct intel_crtc_state *pipe_config);
138 static void chv_prepare_pll(struct intel_crtc *crtc,
139                             const struct intel_crtc_state *pipe_config);
140 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
141 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
142 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
143                                     struct intel_crtc_state *crtc_state);
144 static void skylake_pfit_enable(struct intel_crtc *crtc);
145 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
146 static void ironlake_pfit_enable(struct intel_crtc *crtc);
147 static void intel_modeset_setup_hw_state(struct drm_device *dev,
148                                          struct drm_modeset_acquire_ctx *ctx);
149 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
150
151 struct intel_limit {
152         struct {
153                 int min, max;
154         } dot, vco, n, m, m1, m2, p, p1;
155
156         struct {
157                 int dot_limit;
158                 int p2_slow, p2_fast;
159         } p2;
160 };
161
162 /* returns HPLL frequency in kHz */
163 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
164 {
165         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
166
167         /* Obtain SKU information */
168         mutex_lock(&dev_priv->sb_lock);
169         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
170                 CCK_FUSE_HPLL_FREQ_MASK;
171         mutex_unlock(&dev_priv->sb_lock);
172
173         return vco_freq[hpll_freq] * 1000;
174 }
175
176 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
177                       const char *name, u32 reg, int ref_freq)
178 {
179         u32 val;
180         int divider;
181
182         mutex_lock(&dev_priv->sb_lock);
183         val = vlv_cck_read(dev_priv, reg);
184         mutex_unlock(&dev_priv->sb_lock);
185
186         divider = val & CCK_FREQUENCY_VALUES;
187
188         WARN((val & CCK_FREQUENCY_STATUS) !=
189              (divider << CCK_FREQUENCY_STATUS_SHIFT),
190              "%s change in progress\n", name);
191
192         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
193 }
194
195 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
196                            const char *name, u32 reg)
197 {
198         if (dev_priv->hpll_freq == 0)
199                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
200
201         return vlv_get_cck_clock(dev_priv, name, reg,
202                                  dev_priv->hpll_freq);
203 }
204
205 static void intel_update_czclk(struct drm_i915_private *dev_priv)
206 {
207         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
208                 return;
209
210         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
211                                                       CCK_CZ_CLOCK_CONTROL);
212
213         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
214 }
215
216 static inline u32 /* units of 100MHz */
217 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
218                     const struct intel_crtc_state *pipe_config)
219 {
220         if (HAS_DDI(dev_priv))
221                 return pipe_config->port_clock; /* SPLL */
222         else if (IS_GEN5(dev_priv))
223                 return ((I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK) + 2) * 10000;
224         else
225                 return 270000;
226 }
227
228 static const struct intel_limit intel_limits_i8xx_dac = {
229         .dot = { .min = 25000, .max = 350000 },
230         .vco = { .min = 908000, .max = 1512000 },
231         .n = { .min = 2, .max = 16 },
232         .m = { .min = 96, .max = 140 },
233         .m1 = { .min = 18, .max = 26 },
234         .m2 = { .min = 6, .max = 16 },
235         .p = { .min = 4, .max = 128 },
236         .p1 = { .min = 2, .max = 33 },
237         .p2 = { .dot_limit = 165000,
238                 .p2_slow = 4, .p2_fast = 2 },
239 };
240
241 static const struct intel_limit intel_limits_i8xx_dvo = {
242         .dot = { .min = 25000, .max = 350000 },
243         .vco = { .min = 908000, .max = 1512000 },
244         .n = { .min = 2, .max = 16 },
245         .m = { .min = 96, .max = 140 },
246         .m1 = { .min = 18, .max = 26 },
247         .m2 = { .min = 6, .max = 16 },
248         .p = { .min = 4, .max = 128 },
249         .p1 = { .min = 2, .max = 33 },
250         .p2 = { .dot_limit = 165000,
251                 .p2_slow = 4, .p2_fast = 4 },
252 };
253
254 static const struct intel_limit intel_limits_i8xx_lvds = {
255         .dot = { .min = 25000, .max = 350000 },
256         .vco = { .min = 908000, .max = 1512000 },
257         .n = { .min = 2, .max = 16 },
258         .m = { .min = 96, .max = 140 },
259         .m1 = { .min = 18, .max = 26 },
260         .m2 = { .min = 6, .max = 16 },
261         .p = { .min = 4, .max = 128 },
262         .p1 = { .min = 1, .max = 6 },
263         .p2 = { .dot_limit = 165000,
264                 .p2_slow = 14, .p2_fast = 7 },
265 };
266
267 static const struct intel_limit intel_limits_i9xx_sdvo = {
268         .dot = { .min = 20000, .max = 400000 },
269         .vco = { .min = 1400000, .max = 2800000 },
270         .n = { .min = 1, .max = 6 },
271         .m = { .min = 70, .max = 120 },
272         .m1 = { .min = 8, .max = 18 },
273         .m2 = { .min = 3, .max = 7 },
274         .p = { .min = 5, .max = 80 },
275         .p1 = { .min = 1, .max = 8 },
276         .p2 = { .dot_limit = 200000,
277                 .p2_slow = 10, .p2_fast = 5 },
278 };
279
280 static const struct intel_limit intel_limits_i9xx_lvds = {
281         .dot = { .min = 20000, .max = 400000 },
282         .vco = { .min = 1400000, .max = 2800000 },
283         .n = { .min = 1, .max = 6 },
284         .m = { .min = 70, .max = 120 },
285         .m1 = { .min = 8, .max = 18 },
286         .m2 = { .min = 3, .max = 7 },
287         .p = { .min = 7, .max = 98 },
288         .p1 = { .min = 1, .max = 8 },
289         .p2 = { .dot_limit = 112000,
290                 .p2_slow = 14, .p2_fast = 7 },
291 };
292
293
294 static const struct intel_limit intel_limits_g4x_sdvo = {
295         .dot = { .min = 25000, .max = 270000 },
296         .vco = { .min = 1750000, .max = 3500000},
297         .n = { .min = 1, .max = 4 },
298         .m = { .min = 104, .max = 138 },
299         .m1 = { .min = 17, .max = 23 },
300         .m2 = { .min = 5, .max = 11 },
301         .p = { .min = 10, .max = 30 },
302         .p1 = { .min = 1, .max = 3},
303         .p2 = { .dot_limit = 270000,
304                 .p2_slow = 10,
305                 .p2_fast = 10
306         },
307 };
308
309 static const struct intel_limit intel_limits_g4x_hdmi = {
310         .dot = { .min = 22000, .max = 400000 },
311         .vco = { .min = 1750000, .max = 3500000},
312         .n = { .min = 1, .max = 4 },
313         .m = { .min = 104, .max = 138 },
314         .m1 = { .min = 16, .max = 23 },
315         .m2 = { .min = 5, .max = 11 },
316         .p = { .min = 5, .max = 80 },
317         .p1 = { .min = 1, .max = 8},
318         .p2 = { .dot_limit = 165000,
319                 .p2_slow = 10, .p2_fast = 5 },
320 };
321
322 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
323         .dot = { .min = 20000, .max = 115000 },
324         .vco = { .min = 1750000, .max = 3500000 },
325         .n = { .min = 1, .max = 3 },
326         .m = { .min = 104, .max = 138 },
327         .m1 = { .min = 17, .max = 23 },
328         .m2 = { .min = 5, .max = 11 },
329         .p = { .min = 28, .max = 112 },
330         .p1 = { .min = 2, .max = 8 },
331         .p2 = { .dot_limit = 0,
332                 .p2_slow = 14, .p2_fast = 14
333         },
334 };
335
336 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
337         .dot = { .min = 80000, .max = 224000 },
338         .vco = { .min = 1750000, .max = 3500000 },
339         .n = { .min = 1, .max = 3 },
340         .m = { .min = 104, .max = 138 },
341         .m1 = { .min = 17, .max = 23 },
342         .m2 = { .min = 5, .max = 11 },
343         .p = { .min = 14, .max = 42 },
344         .p1 = { .min = 2, .max = 6 },
345         .p2 = { .dot_limit = 0,
346                 .p2_slow = 7, .p2_fast = 7
347         },
348 };
349
350 static const struct intel_limit intel_limits_pineview_sdvo = {
351         .dot = { .min = 20000, .max = 400000},
352         .vco = { .min = 1700000, .max = 3500000 },
353         /* Pineview's Ncounter is a ring counter */
354         .n = { .min = 3, .max = 6 },
355         .m = { .min = 2, .max = 256 },
356         /* Pineview only has one combined m divider, which we treat as m2. */
357         .m1 = { .min = 0, .max = 0 },
358         .m2 = { .min = 0, .max = 254 },
359         .p = { .min = 5, .max = 80 },
360         .p1 = { .min = 1, .max = 8 },
361         .p2 = { .dot_limit = 200000,
362                 .p2_slow = 10, .p2_fast = 5 },
363 };
364
365 static const struct intel_limit intel_limits_pineview_lvds = {
366         .dot = { .min = 20000, .max = 400000 },
367         .vco = { .min = 1700000, .max = 3500000 },
368         .n = { .min = 3, .max = 6 },
369         .m = { .min = 2, .max = 256 },
370         .m1 = { .min = 0, .max = 0 },
371         .m2 = { .min = 0, .max = 254 },
372         .p = { .min = 7, .max = 112 },
373         .p1 = { .min = 1, .max = 8 },
374         .p2 = { .dot_limit = 112000,
375                 .p2_slow = 14, .p2_fast = 14 },
376 };
377
378 /* Ironlake / Sandybridge
379  *
380  * We calculate clock using (register_value + 2) for N/M1/M2, so here
381  * the range value for them is (actual_value - 2).
382  */
383 static const struct intel_limit intel_limits_ironlake_dac = {
384         .dot = { .min = 25000, .max = 350000 },
385         .vco = { .min = 1760000, .max = 3510000 },
386         .n = { .min = 1, .max = 5 },
387         .m = { .min = 79, .max = 127 },
388         .m1 = { .min = 12, .max = 22 },
389         .m2 = { .min = 5, .max = 9 },
390         .p = { .min = 5, .max = 80 },
391         .p1 = { .min = 1, .max = 8 },
392         .p2 = { .dot_limit = 225000,
393                 .p2_slow = 10, .p2_fast = 5 },
394 };
395
396 static const struct intel_limit intel_limits_ironlake_single_lvds = {
397         .dot = { .min = 25000, .max = 350000 },
398         .vco = { .min = 1760000, .max = 3510000 },
399         .n = { .min = 1, .max = 3 },
400         .m = { .min = 79, .max = 118 },
401         .m1 = { .min = 12, .max = 22 },
402         .m2 = { .min = 5, .max = 9 },
403         .p = { .min = 28, .max = 112 },
404         .p1 = { .min = 2, .max = 8 },
405         .p2 = { .dot_limit = 225000,
406                 .p2_slow = 14, .p2_fast = 14 },
407 };
408
409 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
410         .dot = { .min = 25000, .max = 350000 },
411         .vco = { .min = 1760000, .max = 3510000 },
412         .n = { .min = 1, .max = 3 },
413         .m = { .min = 79, .max = 127 },
414         .m1 = { .min = 12, .max = 22 },
415         .m2 = { .min = 5, .max = 9 },
416         .p = { .min = 14, .max = 56 },
417         .p1 = { .min = 2, .max = 8 },
418         .p2 = { .dot_limit = 225000,
419                 .p2_slow = 7, .p2_fast = 7 },
420 };
421
422 /* LVDS 100mhz refclk limits. */
423 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
424         .dot = { .min = 25000, .max = 350000 },
425         .vco = { .min = 1760000, .max = 3510000 },
426         .n = { .min = 1, .max = 2 },
427         .m = { .min = 79, .max = 126 },
428         .m1 = { .min = 12, .max = 22 },
429         .m2 = { .min = 5, .max = 9 },
430         .p = { .min = 28, .max = 112 },
431         .p1 = { .min = 2, .max = 8 },
432         .p2 = { .dot_limit = 225000,
433                 .p2_slow = 14, .p2_fast = 14 },
434 };
435
436 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
437         .dot = { .min = 25000, .max = 350000 },
438         .vco = { .min = 1760000, .max = 3510000 },
439         .n = { .min = 1, .max = 3 },
440         .m = { .min = 79, .max = 126 },
441         .m1 = { .min = 12, .max = 22 },
442         .m2 = { .min = 5, .max = 9 },
443         .p = { .min = 14, .max = 42 },
444         .p1 = { .min = 2, .max = 6 },
445         .p2 = { .dot_limit = 225000,
446                 .p2_slow = 7, .p2_fast = 7 },
447 };
448
449 static const struct intel_limit intel_limits_vlv = {
450          /*
451           * These are the data rate limits (measured in fast clocks)
452           * since those are the strictest limits we have. The fast
453           * clock and actual rate limits are more relaxed, so checking
454           * them would make no difference.
455           */
456         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
457         .vco = { .min = 4000000, .max = 6000000 },
458         .n = { .min = 1, .max = 7 },
459         .m1 = { .min = 2, .max = 3 },
460         .m2 = { .min = 11, .max = 156 },
461         .p1 = { .min = 2, .max = 3 },
462         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
463 };
464
465 static const struct intel_limit intel_limits_chv = {
466         /*
467          * These are the data rate limits (measured in fast clocks)
468          * since those are the strictest limits we have.  The fast
469          * clock and actual rate limits are more relaxed, so checking
470          * them would make no difference.
471          */
472         .dot = { .min = 25000 * 5, .max = 540000 * 5},
473         .vco = { .min = 4800000, .max = 6480000 },
474         .n = { .min = 1, .max = 1 },
475         .m1 = { .min = 2, .max = 2 },
476         .m2 = { .min = 24 << 22, .max = 175 << 22 },
477         .p1 = { .min = 2, .max = 4 },
478         .p2 = { .p2_slow = 1, .p2_fast = 14 },
479 };
480
481 static const struct intel_limit intel_limits_bxt = {
482         /* FIXME: find real dot limits */
483         .dot = { .min = 0, .max = INT_MAX },
484         .vco = { .min = 4800000, .max = 6700000 },
485         .n = { .min = 1, .max = 1 },
486         .m1 = { .min = 2, .max = 2 },
487         /* FIXME: find real m2 limits */
488         .m2 = { .min = 2 << 22, .max = 255 << 22 },
489         .p1 = { .min = 2, .max = 4 },
490         .p2 = { .p2_slow = 1, .p2_fast = 20 },
491 };
492
493 static bool
494 needs_modeset(struct drm_crtc_state *state)
495 {
496         return drm_atomic_crtc_needs_modeset(state);
497 }
498
499 /*
500  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
501  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
502  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
503  * The helpers' return value is the rate of the clock that is fed to the
504  * display engine's pipe which can be the above fast dot clock rate or a
505  * divided-down version of it.
506  */
507 /* m1 is reserved as 0 in Pineview, n is a ring counter */
508 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
509 {
510         clock->m = clock->m2 + 2;
511         clock->p = clock->p1 * clock->p2;
512         if (WARN_ON(clock->n == 0 || clock->p == 0))
513                 return 0;
514         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
515         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
516
517         return clock->dot;
518 }
519
520 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
521 {
522         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
523 }
524
525 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
526 {
527         clock->m = i9xx_dpll_compute_m(clock);
528         clock->p = clock->p1 * clock->p2;
529         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
530                 return 0;
531         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
532         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
533
534         return clock->dot;
535 }
536
537 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
538 {
539         clock->m = clock->m1 * clock->m2;
540         clock->p = clock->p1 * clock->p2;
541         if (WARN_ON(clock->n == 0 || clock->p == 0))
542                 return 0;
543         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
544         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
545
546         return clock->dot / 5;
547 }
548
549 int chv_calc_dpll_params(int refclk, struct dpll *clock)
550 {
551         clock->m = clock->m1 * clock->m2;
552         clock->p = clock->p1 * clock->p2;
553         if (WARN_ON(clock->n == 0 || clock->p == 0))
554                 return 0;
555         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
556                         clock->n << 22);
557         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
558
559         return clock->dot / 5;
560 }
561
562 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
563 /**
564  * Returns whether the given set of divisors are valid for a given refclk with
565  * the given connectors.
566  */
567
568 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
569                                const struct intel_limit *limit,
570                                const struct dpll *clock)
571 {
572         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
573                 INTELPllInvalid("n out of range\n");
574         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
575                 INTELPllInvalid("p1 out of range\n");
576         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
577                 INTELPllInvalid("m2 out of range\n");
578         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
579                 INTELPllInvalid("m1 out of range\n");
580
581         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
582             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
583                 if (clock->m1 <= clock->m2)
584                         INTELPllInvalid("m1 <= m2\n");
585
586         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
587             !IS_GEN9_LP(dev_priv)) {
588                 if (clock->p < limit->p.min || limit->p.max < clock->p)
589                         INTELPllInvalid("p out of range\n");
590                 if (clock->m < limit->m.min || limit->m.max < clock->m)
591                         INTELPllInvalid("m out of range\n");
592         }
593
594         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
595                 INTELPllInvalid("vco out of range\n");
596         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
597          * connector, etc., rather than just a single range.
598          */
599         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
600                 INTELPllInvalid("dot out of range\n");
601
602         return true;
603 }
604
605 static int
606 i9xx_select_p2_div(const struct intel_limit *limit,
607                    const struct intel_crtc_state *crtc_state,
608                    int target)
609 {
610         struct drm_device *dev = crtc_state->base.crtc->dev;
611
612         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
613                 /*
614                  * For LVDS just rely on its current settings for dual-channel.
615                  * We haven't figured out how to reliably set up different
616                  * single/dual channel state, if we even can.
617                  */
618                 if (intel_is_dual_link_lvds(dev))
619                         return limit->p2.p2_fast;
620                 else
621                         return limit->p2.p2_slow;
622         } else {
623                 if (target < limit->p2.dot_limit)
624                         return limit->p2.p2_slow;
625                 else
626                         return limit->p2.p2_fast;
627         }
628 }
629
630 /*
631  * Returns a set of divisors for the desired target clock with the given
632  * refclk, or FALSE.  The returned values represent the clock equation:
633  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
634  *
635  * Target and reference clocks are specified in kHz.
636  *
637  * If match_clock is provided, then best_clock P divider must match the P
638  * divider from @match_clock used for LVDS downclocking.
639  */
640 static bool
641 i9xx_find_best_dpll(const struct intel_limit *limit,
642                     struct intel_crtc_state *crtc_state,
643                     int target, int refclk, struct dpll *match_clock,
644                     struct dpll *best_clock)
645 {
646         struct drm_device *dev = crtc_state->base.crtc->dev;
647         struct dpll clock;
648         int err = target;
649
650         memset(best_clock, 0, sizeof(*best_clock));
651
652         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
653
654         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
655              clock.m1++) {
656                 for (clock.m2 = limit->m2.min;
657                      clock.m2 <= limit->m2.max; clock.m2++) {
658                         if (clock.m2 >= clock.m1)
659                                 break;
660                         for (clock.n = limit->n.min;
661                              clock.n <= limit->n.max; clock.n++) {
662                                 for (clock.p1 = limit->p1.min;
663                                         clock.p1 <= limit->p1.max; clock.p1++) {
664                                         int this_err;
665
666                                         i9xx_calc_dpll_params(refclk, &clock);
667                                         if (!intel_PLL_is_valid(to_i915(dev),
668                                                                 limit,
669                                                                 &clock))
670                                                 continue;
671                                         if (match_clock &&
672                                             clock.p != match_clock->p)
673                                                 continue;
674
675                                         this_err = abs(clock.dot - target);
676                                         if (this_err < err) {
677                                                 *best_clock = clock;
678                                                 err = this_err;
679                                         }
680                                 }
681                         }
682                 }
683         }
684
685         return (err != target);
686 }
687
688 /*
689  * Returns a set of divisors for the desired target clock with the given
690  * refclk, or FALSE.  The returned values represent the clock equation:
691  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
692  *
693  * Target and reference clocks are specified in kHz.
694  *
695  * If match_clock is provided, then best_clock P divider must match the P
696  * divider from @match_clock used for LVDS downclocking.
697  */
698 static bool
699 pnv_find_best_dpll(const struct intel_limit *limit,
700                    struct intel_crtc_state *crtc_state,
701                    int target, int refclk, struct dpll *match_clock,
702                    struct dpll *best_clock)
703 {
704         struct drm_device *dev = crtc_state->base.crtc->dev;
705         struct dpll clock;
706         int err = target;
707
708         memset(best_clock, 0, sizeof(*best_clock));
709
710         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
711
712         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
713              clock.m1++) {
714                 for (clock.m2 = limit->m2.min;
715                      clock.m2 <= limit->m2.max; clock.m2++) {
716                         for (clock.n = limit->n.min;
717                              clock.n <= limit->n.max; clock.n++) {
718                                 for (clock.p1 = limit->p1.min;
719                                         clock.p1 <= limit->p1.max; clock.p1++) {
720                                         int this_err;
721
722                                         pnv_calc_dpll_params(refclk, &clock);
723                                         if (!intel_PLL_is_valid(to_i915(dev),
724                                                                 limit,
725                                                                 &clock))
726                                                 continue;
727                                         if (match_clock &&
728                                             clock.p != match_clock->p)
729                                                 continue;
730
731                                         this_err = abs(clock.dot - target);
732                                         if (this_err < err) {
733                                                 *best_clock = clock;
734                                                 err = this_err;
735                                         }
736                                 }
737                         }
738                 }
739         }
740
741         return (err != target);
742 }
743
744 /*
745  * Returns a set of divisors for the desired target clock with the given
746  * refclk, or FALSE.  The returned values represent the clock equation:
747  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
748  *
749  * Target and reference clocks are specified in kHz.
750  *
751  * If match_clock is provided, then best_clock P divider must match the P
752  * divider from @match_clock used for LVDS downclocking.
753  */
754 static bool
755 g4x_find_best_dpll(const struct intel_limit *limit,
756                    struct intel_crtc_state *crtc_state,
757                    int target, int refclk, struct dpll *match_clock,
758                    struct dpll *best_clock)
759 {
760         struct drm_device *dev = crtc_state->base.crtc->dev;
761         struct dpll clock;
762         int max_n;
763         bool found = false;
764         /* approximately equals target * 0.00585 */
765         int err_most = (target >> 8) + (target >> 9);
766
767         memset(best_clock, 0, sizeof(*best_clock));
768
769         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
770
771         max_n = limit->n.max;
772         /* based on hardware requirement, prefer smaller n to precision */
773         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
774                 /* based on hardware requirement, prefere larger m1,m2 */
775                 for (clock.m1 = limit->m1.max;
776                      clock.m1 >= limit->m1.min; clock.m1--) {
777                         for (clock.m2 = limit->m2.max;
778                              clock.m2 >= limit->m2.min; clock.m2--) {
779                                 for (clock.p1 = limit->p1.max;
780                                      clock.p1 >= limit->p1.min; clock.p1--) {
781                                         int this_err;
782
783                                         i9xx_calc_dpll_params(refclk, &clock);
784                                         if (!intel_PLL_is_valid(to_i915(dev),
785                                                                 limit,
786                                                                 &clock))
787                                                 continue;
788
789                                         this_err = abs(clock.dot - target);
790                                         if (this_err < err_most) {
791                                                 *best_clock = clock;
792                                                 err_most = this_err;
793                                                 max_n = clock.n;
794                                                 found = true;
795                                         }
796                                 }
797                         }
798                 }
799         }
800         return found;
801 }
802
803 /*
804  * Check if the calculated PLL configuration is more optimal compared to the
805  * best configuration and error found so far. Return the calculated error.
806  */
807 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
808                                const struct dpll *calculated_clock,
809                                const struct dpll *best_clock,
810                                unsigned int best_error_ppm,
811                                unsigned int *error_ppm)
812 {
813         /*
814          * For CHV ignore the error and consider only the P value.
815          * Prefer a bigger P value based on HW requirements.
816          */
817         if (IS_CHERRYVIEW(to_i915(dev))) {
818                 *error_ppm = 0;
819
820                 return calculated_clock->p > best_clock->p;
821         }
822
823         if (WARN_ON_ONCE(!target_freq))
824                 return false;
825
826         *error_ppm = div_u64(1000000ULL *
827                                 abs(target_freq - calculated_clock->dot),
828                              target_freq);
829         /*
830          * Prefer a better P value over a better (smaller) error if the error
831          * is small. Ensure this preference for future configurations too by
832          * setting the error to 0.
833          */
834         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
835                 *error_ppm = 0;
836
837                 return true;
838         }
839
840         return *error_ppm + 10 < best_error_ppm;
841 }
842
843 /*
844  * Returns a set of divisors for the desired target clock with the given
845  * refclk, or FALSE.  The returned values represent the clock equation:
846  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
847  */
848 static bool
849 vlv_find_best_dpll(const struct intel_limit *limit,
850                    struct intel_crtc_state *crtc_state,
851                    int target, int refclk, struct dpll *match_clock,
852                    struct dpll *best_clock)
853 {
854         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
855         struct drm_device *dev = crtc->base.dev;
856         struct dpll clock;
857         unsigned int bestppm = 1000000;
858         /* min update 19.2 MHz */
859         int max_n = min(limit->n.max, refclk / 19200);
860         bool found = false;
861
862         target *= 5; /* fast clock */
863
864         memset(best_clock, 0, sizeof(*best_clock));
865
866         /* based on hardware requirement, prefer smaller n to precision */
867         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
868                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
869                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
870                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
871                                 clock.p = clock.p1 * clock.p2;
872                                 /* based on hardware requirement, prefer bigger m1,m2 values */
873                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
874                                         unsigned int ppm;
875
876                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
877                                                                      refclk * clock.m1);
878
879                                         vlv_calc_dpll_params(refclk, &clock);
880
881                                         if (!intel_PLL_is_valid(to_i915(dev),
882                                                                 limit,
883                                                                 &clock))
884                                                 continue;
885
886                                         if (!vlv_PLL_is_optimal(dev, target,
887                                                                 &clock,
888                                                                 best_clock,
889                                                                 bestppm, &ppm))
890                                                 continue;
891
892                                         *best_clock = clock;
893                                         bestppm = ppm;
894                                         found = true;
895                                 }
896                         }
897                 }
898         }
899
900         return found;
901 }
902
903 /*
904  * Returns a set of divisors for the desired target clock with the given
905  * refclk, or FALSE.  The returned values represent the clock equation:
906  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
907  */
908 static bool
909 chv_find_best_dpll(const struct intel_limit *limit,
910                    struct intel_crtc_state *crtc_state,
911                    int target, int refclk, struct dpll *match_clock,
912                    struct dpll *best_clock)
913 {
914         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
915         struct drm_device *dev = crtc->base.dev;
916         unsigned int best_error_ppm;
917         struct dpll clock;
918         uint64_t m2;
919         int found = false;
920
921         memset(best_clock, 0, sizeof(*best_clock));
922         best_error_ppm = 1000000;
923
924         /*
925          * Based on hardware doc, the n always set to 1, and m1 always
926          * set to 2.  If requires to support 200Mhz refclk, we need to
927          * revisit this because n may not 1 anymore.
928          */
929         clock.n = 1, clock.m1 = 2;
930         target *= 5;    /* fast clock */
931
932         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
933                 for (clock.p2 = limit->p2.p2_fast;
934                                 clock.p2 >= limit->p2.p2_slow;
935                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
936                         unsigned int error_ppm;
937
938                         clock.p = clock.p1 * clock.p2;
939
940                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
941                                         clock.n) << 22, refclk * clock.m1);
942
943                         if (m2 > INT_MAX/clock.m1)
944                                 continue;
945
946                         clock.m2 = m2;
947
948                         chv_calc_dpll_params(refclk, &clock);
949
950                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
951                                 continue;
952
953                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
954                                                 best_error_ppm, &error_ppm))
955                                 continue;
956
957                         *best_clock = clock;
958                         best_error_ppm = error_ppm;
959                         found = true;
960                 }
961         }
962
963         return found;
964 }
965
966 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
967                         struct dpll *best_clock)
968 {
969         int refclk = 100000;
970         const struct intel_limit *limit = &intel_limits_bxt;
971
972         return chv_find_best_dpll(limit, crtc_state,
973                                   target_clock, refclk, NULL, best_clock);
974 }
975
976 bool intel_crtc_active(struct intel_crtc *crtc)
977 {
978         /* Be paranoid as we can arrive here with only partial
979          * state retrieved from the hardware during setup.
980          *
981          * We can ditch the adjusted_mode.crtc_clock check as soon
982          * as Haswell has gained clock readout/fastboot support.
983          *
984          * We can ditch the crtc->primary->fb check as soon as we can
985          * properly reconstruct framebuffers.
986          *
987          * FIXME: The intel_crtc->active here should be switched to
988          * crtc->state->active once we have proper CRTC states wired up
989          * for atomic.
990          */
991         return crtc->active && crtc->base.primary->state->fb &&
992                 crtc->config->base.adjusted_mode.crtc_clock;
993 }
994
995 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
996                                              enum pipe pipe)
997 {
998         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
999
1000         return crtc->config->cpu_transcoder;
1001 }
1002
1003 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
1004                                     enum pipe pipe)
1005 {
1006         i915_reg_t reg = PIPEDSL(pipe);
1007         u32 line1, line2;
1008         u32 line_mask;
1009
1010         if (IS_GEN2(dev_priv))
1011                 line_mask = DSL_LINEMASK_GEN2;
1012         else
1013                 line_mask = DSL_LINEMASK_GEN3;
1014
1015         line1 = I915_READ(reg) & line_mask;
1016         msleep(5);
1017         line2 = I915_READ(reg) & line_mask;
1018
1019         return line1 != line2;
1020 }
1021
1022 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1023 {
1024         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1025         enum pipe pipe = crtc->pipe;
1026
1027         /* Wait for the display line to settle/start moving */
1028         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1029                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1030                           pipe_name(pipe), onoff(state));
1031 }
1032
1033 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1034 {
1035         wait_for_pipe_scanline_moving(crtc, false);
1036 }
1037
1038 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1039 {
1040         wait_for_pipe_scanline_moving(crtc, true);
1041 }
1042
1043 /*
1044  * intel_wait_for_pipe_off - wait for pipe to turn off
1045  * @crtc: crtc whose pipe to wait for
1046  *
1047  * After disabling a pipe, we can't wait for vblank in the usual way,
1048  * spinning on the vblank interrupt status bit, since we won't actually
1049  * see an interrupt when the pipe is disabled.
1050  *
1051  * On Gen4 and above:
1052  *   wait for the pipe register state bit to turn off
1053  *
1054  * Otherwise:
1055  *   wait for the display line value to settle (it usually
1056  *   ends up stopping at the start of the next frame).
1057  *
1058  */
1059 static void intel_wait_for_pipe_off(struct intel_crtc *crtc)
1060 {
1061         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1062         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1063
1064         if (INTEL_GEN(dev_priv) >= 4) {
1065                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1066
1067                 /* Wait for the Pipe State to go off */
1068                 if (intel_wait_for_register(dev_priv,
1069                                             reg, I965_PIPECONF_ACTIVE, 0,
1070                                             100))
1071                         WARN(1, "pipe_off wait timed out\n");
1072         } else {
1073                 intel_wait_for_pipe_scanline_stopped(crtc);
1074         }
1075 }
1076
1077 /* Only for pre-ILK configs */
1078 void assert_pll(struct drm_i915_private *dev_priv,
1079                 enum pipe pipe, bool state)
1080 {
1081         u32 val;
1082         bool cur_state;
1083
1084         val = I915_READ(DPLL(pipe));
1085         cur_state = !!(val & DPLL_VCO_ENABLE);
1086         I915_STATE_WARN(cur_state != state,
1087              "PLL state assertion failure (expected %s, current %s)\n",
1088                         onoff(state), onoff(cur_state));
1089 }
1090
1091 /* XXX: the dsi pll is shared between MIPI DSI ports */
1092 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1093 {
1094         u32 val;
1095         bool cur_state;
1096
1097         mutex_lock(&dev_priv->sb_lock);
1098         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1099         mutex_unlock(&dev_priv->sb_lock);
1100
1101         cur_state = val & DSI_PLL_VCO_EN;
1102         I915_STATE_WARN(cur_state != state,
1103              "DSI PLL state assertion failure (expected %s, current %s)\n",
1104                         onoff(state), onoff(cur_state));
1105 }
1106
1107 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1108                           enum pipe pipe, bool state)
1109 {
1110         bool cur_state;
1111         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1112                                                                       pipe);
1113
1114         if (HAS_DDI(dev_priv)) {
1115                 /* DDI does not have a specific FDI_TX register */
1116                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1117                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1118         } else {
1119                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1120                 cur_state = !!(val & FDI_TX_ENABLE);
1121         }
1122         I915_STATE_WARN(cur_state != state,
1123              "FDI TX state assertion failure (expected %s, current %s)\n",
1124                         onoff(state), onoff(cur_state));
1125 }
1126 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1127 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1128
1129 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1130                           enum pipe pipe, bool state)
1131 {
1132         u32 val;
1133         bool cur_state;
1134
1135         val = I915_READ(FDI_RX_CTL(pipe));
1136         cur_state = !!(val & FDI_RX_ENABLE);
1137         I915_STATE_WARN(cur_state != state,
1138              "FDI RX state assertion failure (expected %s, current %s)\n",
1139                         onoff(state), onoff(cur_state));
1140 }
1141 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1142 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1143
1144 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1145                                       enum pipe pipe)
1146 {
1147         u32 val;
1148
1149         /* ILK FDI PLL is always enabled */
1150         if (IS_GEN5(dev_priv))
1151                 return;
1152
1153         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1154         if (HAS_DDI(dev_priv))
1155                 return;
1156
1157         val = I915_READ(FDI_TX_CTL(pipe));
1158         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1159 }
1160
1161 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1162                        enum pipe pipe, bool state)
1163 {
1164         u32 val;
1165         bool cur_state;
1166
1167         val = I915_READ(FDI_RX_CTL(pipe));
1168         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1169         I915_STATE_WARN(cur_state != state,
1170              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1171                         onoff(state), onoff(cur_state));
1172 }
1173
1174 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1175 {
1176         i915_reg_t pp_reg;
1177         u32 val;
1178         enum pipe panel_pipe = PIPE_A;
1179         bool locked = true;
1180
1181         if (WARN_ON(HAS_DDI(dev_priv)))
1182                 return;
1183
1184         if (HAS_PCH_SPLIT(dev_priv)) {
1185                 u32 port_sel;
1186
1187                 pp_reg = PP_CONTROL(0);
1188                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1189
1190                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1191                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1192                         panel_pipe = PIPE_B;
1193                 /* XXX: else fix for eDP */
1194         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1195                 /* presumably write lock depends on pipe, not port select */
1196                 pp_reg = PP_CONTROL(pipe);
1197                 panel_pipe = pipe;
1198         } else {
1199                 pp_reg = PP_CONTROL(0);
1200                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1201                         panel_pipe = PIPE_B;
1202         }
1203
1204         val = I915_READ(pp_reg);
1205         if (!(val & PANEL_POWER_ON) ||
1206             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1207                 locked = false;
1208
1209         I915_STATE_WARN(panel_pipe == pipe && locked,
1210              "panel assertion failure, pipe %c regs locked\n",
1211              pipe_name(pipe));
1212 }
1213
1214 void assert_pipe(struct drm_i915_private *dev_priv,
1215                  enum pipe pipe, bool state)
1216 {
1217         bool cur_state;
1218         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1219                                                                       pipe);
1220         enum intel_display_power_domain power_domain;
1221
1222         /* we keep both pipes enabled on 830 */
1223         if (IS_I830(dev_priv))
1224                 state = true;
1225
1226         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1227         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1228                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1229                 cur_state = !!(val & PIPECONF_ENABLE);
1230
1231                 intel_display_power_put(dev_priv, power_domain);
1232         } else {
1233                 cur_state = false;
1234         }
1235
1236         I915_STATE_WARN(cur_state != state,
1237              "pipe %c assertion failure (expected %s, current %s)\n",
1238                         pipe_name(pipe), onoff(state), onoff(cur_state));
1239 }
1240
1241 static void assert_plane(struct intel_plane *plane, bool state)
1242 {
1243         bool cur_state = plane->get_hw_state(plane);
1244
1245         I915_STATE_WARN(cur_state != state,
1246                         "%s assertion failure (expected %s, current %s)\n",
1247                         plane->base.name, onoff(state), onoff(cur_state));
1248 }
1249
1250 #define assert_plane_enabled(p) assert_plane(p, true)
1251 #define assert_plane_disabled(p) assert_plane(p, false)
1252
1253 static void assert_planes_disabled(struct intel_crtc *crtc)
1254 {
1255         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1256         struct intel_plane *plane;
1257
1258         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1259                 assert_plane_disabled(plane);
1260 }
1261
1262 static void assert_vblank_disabled(struct drm_crtc *crtc)
1263 {
1264         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1265                 drm_crtc_vblank_put(crtc);
1266 }
1267
1268 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1269                                     enum pipe pipe)
1270 {
1271         u32 val;
1272         bool enabled;
1273
1274         val = I915_READ(PCH_TRANSCONF(pipe));
1275         enabled = !!(val & TRANS_ENABLE);
1276         I915_STATE_WARN(enabled,
1277              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1278              pipe_name(pipe));
1279 }
1280
1281 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1282                             enum pipe pipe, u32 port_sel, u32 val)
1283 {
1284         if ((val & DP_PORT_EN) == 0)
1285                 return false;
1286
1287         if (HAS_PCH_CPT(dev_priv)) {
1288                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1289                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1290                         return false;
1291         } else if (IS_CHERRYVIEW(dev_priv)) {
1292                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1293                         return false;
1294         } else {
1295                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1296                         return false;
1297         }
1298         return true;
1299 }
1300
1301 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1302                               enum pipe pipe, u32 val)
1303 {
1304         if ((val & SDVO_ENABLE) == 0)
1305                 return false;
1306
1307         if (HAS_PCH_CPT(dev_priv)) {
1308                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1309                         return false;
1310         } else if (IS_CHERRYVIEW(dev_priv)) {
1311                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1312                         return false;
1313         } else {
1314                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1315                         return false;
1316         }
1317         return true;
1318 }
1319
1320 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1321                               enum pipe pipe, u32 val)
1322 {
1323         if ((val & LVDS_PORT_EN) == 0)
1324                 return false;
1325
1326         if (HAS_PCH_CPT(dev_priv)) {
1327                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1328                         return false;
1329         } else {
1330                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1331                         return false;
1332         }
1333         return true;
1334 }
1335
1336 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1337                               enum pipe pipe, u32 val)
1338 {
1339         if ((val & ADPA_DAC_ENABLE) == 0)
1340                 return false;
1341         if (HAS_PCH_CPT(dev_priv)) {
1342                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1343                         return false;
1344         } else {
1345                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1346                         return false;
1347         }
1348         return true;
1349 }
1350
1351 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1352                                    enum pipe pipe, i915_reg_t reg,
1353                                    u32 port_sel)
1354 {
1355         u32 val = I915_READ(reg);
1356         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1357              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1358              i915_mmio_reg_offset(reg), pipe_name(pipe));
1359
1360         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1361              && (val & DP_PIPEB_SELECT),
1362              "IBX PCH dp port still using transcoder B\n");
1363 }
1364
1365 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1366                                      enum pipe pipe, i915_reg_t reg)
1367 {
1368         u32 val = I915_READ(reg);
1369         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1370              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1371              i915_mmio_reg_offset(reg), pipe_name(pipe));
1372
1373         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1374              && (val & SDVO_PIPE_B_SELECT),
1375              "IBX PCH hdmi port still using transcoder B\n");
1376 }
1377
1378 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1379                                       enum pipe pipe)
1380 {
1381         u32 val;
1382
1383         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1384         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1385         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1386
1387         val = I915_READ(PCH_ADPA);
1388         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1389              "PCH VGA enabled on transcoder %c, should be disabled\n",
1390              pipe_name(pipe));
1391
1392         val = I915_READ(PCH_LVDS);
1393         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1394              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1395              pipe_name(pipe));
1396
1397         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1398         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1399         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1400 }
1401
1402 static void _vlv_enable_pll(struct intel_crtc *crtc,
1403                             const struct intel_crtc_state *pipe_config)
1404 {
1405         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1406         enum pipe pipe = crtc->pipe;
1407
1408         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1409         POSTING_READ(DPLL(pipe));
1410         udelay(150);
1411
1412         if (intel_wait_for_register(dev_priv,
1413                                     DPLL(pipe),
1414                                     DPLL_LOCK_VLV,
1415                                     DPLL_LOCK_VLV,
1416                                     1))
1417                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1418 }
1419
1420 static void vlv_enable_pll(struct intel_crtc *crtc,
1421                            const struct intel_crtc_state *pipe_config)
1422 {
1423         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1424         enum pipe pipe = crtc->pipe;
1425
1426         assert_pipe_disabled(dev_priv, pipe);
1427
1428         /* PLL is protected by panel, make sure we can write it */
1429         assert_panel_unlocked(dev_priv, pipe);
1430
1431         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1432                 _vlv_enable_pll(crtc, pipe_config);
1433
1434         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1435         POSTING_READ(DPLL_MD(pipe));
1436 }
1437
1438
1439 static void _chv_enable_pll(struct intel_crtc *crtc,
1440                             const struct intel_crtc_state *pipe_config)
1441 {
1442         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1443         enum pipe pipe = crtc->pipe;
1444         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1445         u32 tmp;
1446
1447         mutex_lock(&dev_priv->sb_lock);
1448
1449         /* Enable back the 10bit clock to display controller */
1450         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1451         tmp |= DPIO_DCLKP_EN;
1452         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1453
1454         mutex_unlock(&dev_priv->sb_lock);
1455
1456         /*
1457          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1458          */
1459         udelay(1);
1460
1461         /* Enable PLL */
1462         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1463
1464         /* Check PLL is locked */
1465         if (intel_wait_for_register(dev_priv,
1466                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1467                                     1))
1468                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1469 }
1470
1471 static void chv_enable_pll(struct intel_crtc *crtc,
1472                            const struct intel_crtc_state *pipe_config)
1473 {
1474         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1475         enum pipe pipe = crtc->pipe;
1476
1477         assert_pipe_disabled(dev_priv, pipe);
1478
1479         /* PLL is protected by panel, make sure we can write it */
1480         assert_panel_unlocked(dev_priv, pipe);
1481
1482         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1483                 _chv_enable_pll(crtc, pipe_config);
1484
1485         if (pipe != PIPE_A) {
1486                 /*
1487                  * WaPixelRepeatModeFixForC0:chv
1488                  *
1489                  * DPLLCMD is AWOL. Use chicken bits to propagate
1490                  * the value from DPLLBMD to either pipe B or C.
1491                  */
1492                 I915_WRITE(CBR4_VLV, pipe == PIPE_B ? CBR_DPLLBMD_PIPE_B : CBR_DPLLBMD_PIPE_C);
1493                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1494                 I915_WRITE(CBR4_VLV, 0);
1495                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1496
1497                 /*
1498                  * DPLLB VGA mode also seems to cause problems.
1499                  * We should always have it disabled.
1500                  */
1501                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1502         } else {
1503                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1504                 POSTING_READ(DPLL_MD(pipe));
1505         }
1506 }
1507
1508 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1509 {
1510         struct intel_crtc *crtc;
1511         int count = 0;
1512
1513         for_each_intel_crtc(&dev_priv->drm, crtc) {
1514                 count += crtc->base.state->active &&
1515                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1516         }
1517
1518         return count;
1519 }
1520
1521 static void i9xx_enable_pll(struct intel_crtc *crtc)
1522 {
1523         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1524         i915_reg_t reg = DPLL(crtc->pipe);
1525         u32 dpll = crtc->config->dpll_hw_state.dpll;
1526         int i;
1527
1528         assert_pipe_disabled(dev_priv, crtc->pipe);
1529
1530         /* PLL is protected by panel, make sure we can write it */
1531         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1532                 assert_panel_unlocked(dev_priv, crtc->pipe);
1533
1534         /* Enable DVO 2x clock on both PLLs if necessary */
1535         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1536                 /*
1537                  * It appears to be important that we don't enable this
1538                  * for the current pipe before otherwise configuring the
1539                  * PLL. No idea how this should be handled if multiple
1540                  * DVO outputs are enabled simultaneosly.
1541                  */
1542                 dpll |= DPLL_DVO_2X_MODE;
1543                 I915_WRITE(DPLL(!crtc->pipe),
1544                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1545         }
1546
1547         /*
1548          * Apparently we need to have VGA mode enabled prior to changing
1549          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1550          * dividers, even though the register value does change.
1551          */
1552         I915_WRITE(reg, 0);
1553
1554         I915_WRITE(reg, dpll);
1555
1556         /* Wait for the clocks to stabilize. */
1557         POSTING_READ(reg);
1558         udelay(150);
1559
1560         if (INTEL_GEN(dev_priv) >= 4) {
1561                 I915_WRITE(DPLL_MD(crtc->pipe),
1562                            crtc->config->dpll_hw_state.dpll_md);
1563         } else {
1564                 /* The pixel multiplier can only be updated once the
1565                  * DPLL is enabled and the clocks are stable.
1566                  *
1567                  * So write it again.
1568                  */
1569                 I915_WRITE(reg, dpll);
1570         }
1571
1572         /* We do this three times for luck */
1573         for (i = 0; i < 3; i++) {
1574                 I915_WRITE(reg, dpll);
1575                 POSTING_READ(reg);
1576                 udelay(150); /* wait for warmup */
1577         }
1578 }
1579
1580 /**
1581  * i9xx_disable_pll - disable a PLL
1582  * @dev_priv: i915 private structure
1583  * @pipe: pipe PLL to disable
1584  *
1585  * Disable the PLL for @pipe, making sure the pipe is off first.
1586  *
1587  * Note!  This is for pre-ILK only.
1588  */
1589 static void i9xx_disable_pll(struct intel_crtc *crtc)
1590 {
1591         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1592         enum pipe pipe = crtc->pipe;
1593
1594         /* Disable DVO 2x clock on both PLLs if necessary */
1595         if (IS_I830(dev_priv) &&
1596             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1597             !intel_num_dvo_pipes(dev_priv)) {
1598                 I915_WRITE(DPLL(PIPE_B),
1599                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1600                 I915_WRITE(DPLL(PIPE_A),
1601                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1602         }
1603
1604         /* Don't disable pipe or pipe PLLs if needed */
1605         if (IS_I830(dev_priv))
1606                 return;
1607
1608         /* Make sure the pipe isn't still relying on us */
1609         assert_pipe_disabled(dev_priv, pipe);
1610
1611         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1612         POSTING_READ(DPLL(pipe));
1613 }
1614
1615 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1616 {
1617         u32 val;
1618
1619         /* Make sure the pipe isn't still relying on us */
1620         assert_pipe_disabled(dev_priv, pipe);
1621
1622         val = DPLL_INTEGRATED_REF_CLK_VLV |
1623                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1624         if (pipe != PIPE_A)
1625                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1626
1627         I915_WRITE(DPLL(pipe), val);
1628         POSTING_READ(DPLL(pipe));
1629 }
1630
1631 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1632 {
1633         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1634         u32 val;
1635
1636         /* Make sure the pipe isn't still relying on us */
1637         assert_pipe_disabled(dev_priv, pipe);
1638
1639         val = DPLL_SSC_REF_CLK_CHV |
1640                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1641         if (pipe != PIPE_A)
1642                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1643
1644         I915_WRITE(DPLL(pipe), val);
1645         POSTING_READ(DPLL(pipe));
1646
1647         mutex_lock(&dev_priv->sb_lock);
1648
1649         /* Disable 10bit clock to display controller */
1650         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1651         val &= ~DPIO_DCLKP_EN;
1652         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1653
1654         mutex_unlock(&dev_priv->sb_lock);
1655 }
1656
1657 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1658                          struct intel_digital_port *dport,
1659                          unsigned int expected_mask)
1660 {
1661         u32 port_mask;
1662         i915_reg_t dpll_reg;
1663
1664         switch (dport->port) {
1665         case PORT_B:
1666                 port_mask = DPLL_PORTB_READY_MASK;
1667                 dpll_reg = DPLL(0);
1668                 break;
1669         case PORT_C:
1670                 port_mask = DPLL_PORTC_READY_MASK;
1671                 dpll_reg = DPLL(0);
1672                 expected_mask <<= 4;
1673                 break;
1674         case PORT_D:
1675                 port_mask = DPLL_PORTD_READY_MASK;
1676                 dpll_reg = DPIO_PHY_STATUS;
1677                 break;
1678         default:
1679                 BUG();
1680         }
1681
1682         if (intel_wait_for_register(dev_priv,
1683                                     dpll_reg, port_mask, expected_mask,
1684                                     1000))
1685                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1686                      port_name(dport->port), I915_READ(dpll_reg) & port_mask, expected_mask);
1687 }
1688
1689 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1690                                            enum pipe pipe)
1691 {
1692         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1693                                                                 pipe);
1694         i915_reg_t reg;
1695         uint32_t val, pipeconf_val;
1696
1697         /* Make sure PCH DPLL is enabled */
1698         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1699
1700         /* FDI must be feeding us bits for PCH ports */
1701         assert_fdi_tx_enabled(dev_priv, pipe);
1702         assert_fdi_rx_enabled(dev_priv, pipe);
1703
1704         if (HAS_PCH_CPT(dev_priv)) {
1705                 /* Workaround: Set the timing override bit before enabling the
1706                  * pch transcoder. */
1707                 reg = TRANS_CHICKEN2(pipe);
1708                 val = I915_READ(reg);
1709                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1710                 I915_WRITE(reg, val);
1711         }
1712
1713         reg = PCH_TRANSCONF(pipe);
1714         val = I915_READ(reg);
1715         pipeconf_val = I915_READ(PIPECONF(pipe));
1716
1717         if (HAS_PCH_IBX(dev_priv)) {
1718                 /*
1719                  * Make the BPC in transcoder be consistent with
1720                  * that in pipeconf reg. For HDMI we must use 8bpc
1721                  * here for both 8bpc and 12bpc.
1722                  */
1723                 val &= ~PIPECONF_BPC_MASK;
1724                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1725                         val |= PIPECONF_8BPC;
1726                 else
1727                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1728         }
1729
1730         val &= ~TRANS_INTERLACE_MASK;
1731         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1732                 if (HAS_PCH_IBX(dev_priv) &&
1733                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1734                         val |= TRANS_LEGACY_INTERLACED_ILK;
1735                 else
1736                         val |= TRANS_INTERLACED;
1737         else
1738                 val |= TRANS_PROGRESSIVE;
1739
1740         I915_WRITE(reg, val | TRANS_ENABLE);
1741         if (intel_wait_for_register(dev_priv,
1742                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1743                                     100))
1744                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1745 }
1746
1747 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1748                                       enum transcoder cpu_transcoder)
1749 {
1750         u32 val, pipeconf_val;
1751
1752         /* FDI must be feeding us bits for PCH ports */
1753         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1754         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1755
1756         /* Workaround: set timing override bit. */
1757         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1758         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1759         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1760
1761         val = TRANS_ENABLE;
1762         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1763
1764         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1765             PIPECONF_INTERLACED_ILK)
1766                 val |= TRANS_INTERLACED;
1767         else
1768                 val |= TRANS_PROGRESSIVE;
1769
1770         I915_WRITE(LPT_TRANSCONF, val);
1771         if (intel_wait_for_register(dev_priv,
1772                                     LPT_TRANSCONF,
1773                                     TRANS_STATE_ENABLE,
1774                                     TRANS_STATE_ENABLE,
1775                                     100))
1776                 DRM_ERROR("Failed to enable PCH transcoder\n");
1777 }
1778
1779 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1780                                             enum pipe pipe)
1781 {
1782         i915_reg_t reg;
1783         uint32_t val;
1784
1785         /* FDI relies on the transcoder */
1786         assert_fdi_tx_disabled(dev_priv, pipe);
1787         assert_fdi_rx_disabled(dev_priv, pipe);
1788
1789         /* Ports must be off as well */
1790         assert_pch_ports_disabled(dev_priv, pipe);
1791
1792         reg = PCH_TRANSCONF(pipe);
1793         val = I915_READ(reg);
1794         val &= ~TRANS_ENABLE;
1795         I915_WRITE(reg, val);
1796         /* wait for PCH transcoder off, transcoder state */
1797         if (intel_wait_for_register(dev_priv,
1798                                     reg, TRANS_STATE_ENABLE, 0,
1799                                     50))
1800                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1801
1802         if (HAS_PCH_CPT(dev_priv)) {
1803                 /* Workaround: Clear the timing override chicken bit again. */
1804                 reg = TRANS_CHICKEN2(pipe);
1805                 val = I915_READ(reg);
1806                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1807                 I915_WRITE(reg, val);
1808         }
1809 }
1810
1811 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1812 {
1813         u32 val;
1814
1815         val = I915_READ(LPT_TRANSCONF);
1816         val &= ~TRANS_ENABLE;
1817         I915_WRITE(LPT_TRANSCONF, val);
1818         /* wait for PCH transcoder off, transcoder state */
1819         if (intel_wait_for_register(dev_priv,
1820                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1821                                     50))
1822                 DRM_ERROR("Failed to disable PCH transcoder\n");
1823
1824         /* Workaround: clear timing override bit. */
1825         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1826         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1827         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1828 }
1829
1830 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1831 {
1832         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1833
1834         WARN_ON(!crtc->config->has_pch_encoder);
1835
1836         if (HAS_PCH_LPT(dev_priv))
1837                 return PIPE_A;
1838         else
1839                 return crtc->pipe;
1840 }
1841
1842 /**
1843  * intel_enable_pipe - enable a pipe, asserting requirements
1844  * @crtc: crtc responsible for the pipe
1845  *
1846  * Enable @crtc's pipe, making sure that various hardware specific requirements
1847  * are met, if applicable, e.g. PLL enabled, LVDS pairs enabled, etc.
1848  */
1849 static void intel_enable_pipe(struct intel_crtc *crtc)
1850 {
1851         struct drm_device *dev = crtc->base.dev;
1852         struct drm_i915_private *dev_priv = to_i915(dev);
1853         enum pipe pipe = crtc->pipe;
1854         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1855         i915_reg_t reg;
1856         u32 val;
1857
1858         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1859
1860         assert_planes_disabled(crtc);
1861
1862         /*
1863          * A pipe without a PLL won't actually be able to drive bits from
1864          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1865          * need the check.
1866          */
1867         if (HAS_GMCH_DISPLAY(dev_priv)) {
1868                 if (intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DSI))
1869                         assert_dsi_pll_enabled(dev_priv);
1870                 else
1871                         assert_pll_enabled(dev_priv, pipe);
1872         } else {
1873                 if (crtc->config->has_pch_encoder) {
1874                         /* if driving the PCH, we need FDI enabled */
1875                         assert_fdi_rx_pll_enabled(dev_priv,
1876                                                   intel_crtc_pch_transcoder(crtc));
1877                         assert_fdi_tx_pll_enabled(dev_priv,
1878                                                   (enum pipe) cpu_transcoder);
1879                 }
1880                 /* FIXME: assert CPU port conditions for SNB+ */
1881         }
1882
1883         reg = PIPECONF(cpu_transcoder);
1884         val = I915_READ(reg);
1885         if (val & PIPECONF_ENABLE) {
1886                 /* we keep both pipes enabled on 830 */
1887                 WARN_ON(!IS_I830(dev_priv));
1888                 return;
1889         }
1890
1891         I915_WRITE(reg, val | PIPECONF_ENABLE);
1892         POSTING_READ(reg);
1893
1894         /*
1895          * Until the pipe starts PIPEDSL reads will return a stale value,
1896          * which causes an apparent vblank timestamp jump when PIPEDSL
1897          * resets to its proper value. That also messes up the frame count
1898          * when it's derived from the timestamps. So let's wait for the
1899          * pipe to start properly before we call drm_crtc_vblank_on()
1900          */
1901         if (dev->max_vblank_count == 0)
1902                 intel_wait_for_pipe_scanline_moving(crtc);
1903 }
1904
1905 /**
1906  * intel_disable_pipe - disable a pipe, asserting requirements
1907  * @crtc: crtc whose pipes is to be disabled
1908  *
1909  * Disable the pipe of @crtc, making sure that various hardware
1910  * specific requirements are met, if applicable, e.g. plane
1911  * disabled, panel fitter off, etc.
1912  *
1913  * Will wait until the pipe has shut down before returning.
1914  */
1915 static void intel_disable_pipe(struct intel_crtc *crtc)
1916 {
1917         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1918         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
1919         enum pipe pipe = crtc->pipe;
1920         i915_reg_t reg;
1921         u32 val;
1922
1923         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1924
1925         /*
1926          * Make sure planes won't keep trying to pump pixels to us,
1927          * or we might hang the display.
1928          */
1929         assert_planes_disabled(crtc);
1930
1931         reg = PIPECONF(cpu_transcoder);
1932         val = I915_READ(reg);
1933         if ((val & PIPECONF_ENABLE) == 0)
1934                 return;
1935
1936         /*
1937          * Double wide has implications for planes
1938          * so best keep it disabled when not needed.
1939          */
1940         if (crtc->config->double_wide)
1941                 val &= ~PIPECONF_DOUBLE_WIDE;
1942
1943         /* Don't disable pipe or pipe PLLs if needed */
1944         if (!IS_I830(dev_priv))
1945                 val &= ~PIPECONF_ENABLE;
1946
1947         I915_WRITE(reg, val);
1948         if ((val & PIPECONF_ENABLE) == 0)
1949                 intel_wait_for_pipe_off(crtc);
1950 }
1951
1952 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1953 {
1954         return IS_GEN2(dev_priv) ? 2048 : 4096;
1955 }
1956
1957 static unsigned int
1958 intel_tile_width_bytes(const struct drm_framebuffer *fb, int plane)
1959 {
1960         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1961         unsigned int cpp = fb->format->cpp[plane];
1962
1963         switch (fb->modifier) {
1964         case DRM_FORMAT_MOD_LINEAR:
1965                 return cpp;
1966         case I915_FORMAT_MOD_X_TILED:
1967                 if (IS_GEN2(dev_priv))
1968                         return 128;
1969                 else
1970                         return 512;
1971         case I915_FORMAT_MOD_Y_TILED_CCS:
1972                 if (plane == 1)
1973                         return 128;
1974                 /* fall through */
1975         case I915_FORMAT_MOD_Y_TILED:
1976                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
1977                         return 128;
1978                 else
1979                         return 512;
1980         case I915_FORMAT_MOD_Yf_TILED_CCS:
1981                 if (plane == 1)
1982                         return 128;
1983                 /* fall through */
1984         case I915_FORMAT_MOD_Yf_TILED:
1985                 switch (cpp) {
1986                 case 1:
1987                         return 64;
1988                 case 2:
1989                 case 4:
1990                         return 128;
1991                 case 8:
1992                 case 16:
1993                         return 256;
1994                 default:
1995                         MISSING_CASE(cpp);
1996                         return cpp;
1997                 }
1998                 break;
1999         default:
2000                 MISSING_CASE(fb->modifier);
2001                 return cpp;
2002         }
2003 }
2004
2005 static unsigned int
2006 intel_tile_height(const struct drm_framebuffer *fb, int plane)
2007 {
2008         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
2009                 return 1;
2010         else
2011                 return intel_tile_size(to_i915(fb->dev)) /
2012                         intel_tile_width_bytes(fb, plane);
2013 }
2014
2015 /* Return the tile dimensions in pixel units */
2016 static void intel_tile_dims(const struct drm_framebuffer *fb, int plane,
2017                             unsigned int *tile_width,
2018                             unsigned int *tile_height)
2019 {
2020         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, plane);
2021         unsigned int cpp = fb->format->cpp[plane];
2022
2023         *tile_width = tile_width_bytes / cpp;
2024         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
2025 }
2026
2027 unsigned int
2028 intel_fb_align_height(const struct drm_framebuffer *fb,
2029                       int plane, unsigned int height)
2030 {
2031         unsigned int tile_height = intel_tile_height(fb, plane);
2032
2033         return ALIGN(height, tile_height);
2034 }
2035
2036 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
2037 {
2038         unsigned int size = 0;
2039         int i;
2040
2041         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2042                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2043
2044         return size;
2045 }
2046
2047 static void
2048 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2049                         const struct drm_framebuffer *fb,
2050                         unsigned int rotation)
2051 {
2052         view->type = I915_GGTT_VIEW_NORMAL;
2053         if (drm_rotation_90_or_270(rotation)) {
2054                 view->type = I915_GGTT_VIEW_ROTATED;
2055                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2056         }
2057 }
2058
2059 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2060 {
2061         if (IS_I830(dev_priv))
2062                 return 16 * 1024;
2063         else if (IS_I85X(dev_priv))
2064                 return 256;
2065         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2066                 return 32;
2067         else
2068                 return 4 * 1024;
2069 }
2070
2071 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2072 {
2073         if (INTEL_INFO(dev_priv)->gen >= 9)
2074                 return 256 * 1024;
2075         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2076                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2077                 return 128 * 1024;
2078         else if (INTEL_INFO(dev_priv)->gen >= 4)
2079                 return 4 * 1024;
2080         else
2081                 return 0;
2082 }
2083
2084 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2085                                          int plane)
2086 {
2087         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2088
2089         /* AUX_DIST needs only 4K alignment */
2090         if (plane == 1)
2091                 return 4096;
2092
2093         switch (fb->modifier) {
2094         case DRM_FORMAT_MOD_LINEAR:
2095                 return intel_linear_alignment(dev_priv);
2096         case I915_FORMAT_MOD_X_TILED:
2097                 if (INTEL_GEN(dev_priv) >= 9)
2098                         return 256 * 1024;
2099                 return 0;
2100         case I915_FORMAT_MOD_Y_TILED_CCS:
2101         case I915_FORMAT_MOD_Yf_TILED_CCS:
2102         case I915_FORMAT_MOD_Y_TILED:
2103         case I915_FORMAT_MOD_Yf_TILED:
2104                 return 1 * 1024 * 1024;
2105         default:
2106                 MISSING_CASE(fb->modifier);
2107                 return 0;
2108         }
2109 }
2110
2111 struct i915_vma *
2112 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2113 {
2114         struct drm_device *dev = fb->dev;
2115         struct drm_i915_private *dev_priv = to_i915(dev);
2116         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2117         struct i915_ggtt_view view;
2118         struct i915_vma *vma;
2119         u32 alignment;
2120
2121         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2122
2123         alignment = intel_surf_alignment(fb, 0);
2124
2125         intel_fill_fb_ggtt_view(&view, fb, rotation);
2126
2127         /* Note that the w/a also requires 64 PTE of padding following the
2128          * bo. We currently fill all unused PTE with the shadow page and so
2129          * we should always have valid PTE following the scanout preventing
2130          * the VT-d warning.
2131          */
2132         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2133                 alignment = 256 * 1024;
2134
2135         /*
2136          * Global gtt pte registers are special registers which actually forward
2137          * writes to a chunk of system memory. Which means that there is no risk
2138          * that the register values disappear as soon as we call
2139          * intel_runtime_pm_put(), so it is correct to wrap only the
2140          * pin/unpin/fence and not more.
2141          */
2142         intel_runtime_pm_get(dev_priv);
2143
2144         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2145
2146         vma = i915_gem_object_pin_to_display_plane(obj, alignment, &view);
2147         if (IS_ERR(vma))
2148                 goto err;
2149
2150         if (i915_vma_is_map_and_fenceable(vma)) {
2151                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2152                  * fence, whereas 965+ only requires a fence if using
2153                  * framebuffer compression.  For simplicity, we always, when
2154                  * possible, install a fence as the cost is not that onerous.
2155                  *
2156                  * If we fail to fence the tiled scanout, then either the
2157                  * modeset will reject the change (which is highly unlikely as
2158                  * the affected systems, all but one, do not have unmappable
2159                  * space) or we will not be able to enable full powersaving
2160                  * techniques (also likely not to apply due to various limits
2161                  * FBC and the like impose on the size of the buffer, which
2162                  * presumably we violated anyway with this unmappable buffer).
2163                  * Anyway, it is presumably better to stumble onwards with
2164                  * something and try to run the system in a "less than optimal"
2165                  * mode that matches the user configuration.
2166                  */
2167                 if (i915_vma_get_fence(vma) == 0)
2168                         i915_vma_pin_fence(vma);
2169         }
2170
2171         i915_vma_get(vma);
2172 err:
2173         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2174
2175         intel_runtime_pm_put(dev_priv);
2176         return vma;
2177 }
2178
2179 void intel_unpin_fb_vma(struct i915_vma *vma)
2180 {
2181         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2182
2183         i915_vma_unpin_fence(vma);
2184         i915_gem_object_unpin_from_display_plane(vma);
2185         i915_vma_put(vma);
2186 }
2187
2188 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2189                           unsigned int rotation)
2190 {
2191         if (drm_rotation_90_or_270(rotation))
2192                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2193         else
2194                 return fb->pitches[plane];
2195 }
2196
2197 /*
2198  * Convert the x/y offsets into a linear offset.
2199  * Only valid with 0/180 degree rotation, which is fine since linear
2200  * offset is only used with linear buffers on pre-hsw and tiled buffers
2201  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2202  */
2203 u32 intel_fb_xy_to_linear(int x, int y,
2204                           const struct intel_plane_state *state,
2205                           int plane)
2206 {
2207         const struct drm_framebuffer *fb = state->base.fb;
2208         unsigned int cpp = fb->format->cpp[plane];
2209         unsigned int pitch = fb->pitches[plane];
2210
2211         return y * pitch + x * cpp;
2212 }
2213
2214 /*
2215  * Add the x/y offsets derived from fb->offsets[] to the user
2216  * specified plane src x/y offsets. The resulting x/y offsets
2217  * specify the start of scanout from the beginning of the gtt mapping.
2218  */
2219 void intel_add_fb_offsets(int *x, int *y,
2220                           const struct intel_plane_state *state,
2221                           int plane)
2222
2223 {
2224         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2225         unsigned int rotation = state->base.rotation;
2226
2227         if (drm_rotation_90_or_270(rotation)) {
2228                 *x += intel_fb->rotated[plane].x;
2229                 *y += intel_fb->rotated[plane].y;
2230         } else {
2231                 *x += intel_fb->normal[plane].x;
2232                 *y += intel_fb->normal[plane].y;
2233         }
2234 }
2235
2236 static u32 __intel_adjust_tile_offset(int *x, int *y,
2237                                       unsigned int tile_width,
2238                                       unsigned int tile_height,
2239                                       unsigned int tile_size,
2240                                       unsigned int pitch_tiles,
2241                                       u32 old_offset,
2242                                       u32 new_offset)
2243 {
2244         unsigned int pitch_pixels = pitch_tiles * tile_width;
2245         unsigned int tiles;
2246
2247         WARN_ON(old_offset & (tile_size - 1));
2248         WARN_ON(new_offset & (tile_size - 1));
2249         WARN_ON(new_offset > old_offset);
2250
2251         tiles = (old_offset - new_offset) / tile_size;
2252
2253         *y += tiles / pitch_tiles * tile_height;
2254         *x += tiles % pitch_tiles * tile_width;
2255
2256         /* minimize x in case it got needlessly big */
2257         *y += *x / pitch_pixels * tile_height;
2258         *x %= pitch_pixels;
2259
2260         return new_offset;
2261 }
2262
2263 static u32 _intel_adjust_tile_offset(int *x, int *y,
2264                                      const struct drm_framebuffer *fb, int plane,
2265                                      unsigned int rotation,
2266                                      u32 old_offset, u32 new_offset)
2267 {
2268         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2269         unsigned int cpp = fb->format->cpp[plane];
2270         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2271
2272         WARN_ON(new_offset > old_offset);
2273
2274         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2275                 unsigned int tile_size, tile_width, tile_height;
2276                 unsigned int pitch_tiles;
2277
2278                 tile_size = intel_tile_size(dev_priv);
2279                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2280
2281                 if (drm_rotation_90_or_270(rotation)) {
2282                         pitch_tiles = pitch / tile_height;
2283                         swap(tile_width, tile_height);
2284                 } else {
2285                         pitch_tiles = pitch / (tile_width * cpp);
2286                 }
2287
2288                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2289                                            tile_size, pitch_tiles,
2290                                            old_offset, new_offset);
2291         } else {
2292                 old_offset += *y * pitch + *x * cpp;
2293
2294                 *y = (old_offset - new_offset) / pitch;
2295                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2296         }
2297
2298         return new_offset;
2299 }
2300
2301 /*
2302  * Adjust the tile offset by moving the difference into
2303  * the x/y offsets.
2304  */
2305 static u32 intel_adjust_tile_offset(int *x, int *y,
2306                                     const struct intel_plane_state *state, int plane,
2307                                     u32 old_offset, u32 new_offset)
2308 {
2309         return _intel_adjust_tile_offset(x, y, state->base.fb, plane,
2310                                          state->base.rotation,
2311                                          old_offset, new_offset);
2312 }
2313
2314 /*
2315  * Computes the linear offset to the base tile and adjusts
2316  * x, y. bytes per pixel is assumed to be a power-of-two.
2317  *
2318  * In the 90/270 rotated case, x and y are assumed
2319  * to be already rotated to match the rotated GTT view, and
2320  * pitch is the tile_height aligned framebuffer height.
2321  *
2322  * This function is used when computing the derived information
2323  * under intel_framebuffer, so using any of that information
2324  * here is not allowed. Anything under drm_framebuffer can be
2325  * used. This is why the user has to pass in the pitch since it
2326  * is specified in the rotated orientation.
2327  */
2328 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2329                                       int *x, int *y,
2330                                       const struct drm_framebuffer *fb, int plane,
2331                                       unsigned int pitch,
2332                                       unsigned int rotation,
2333                                       u32 alignment)
2334 {
2335         uint64_t fb_modifier = fb->modifier;
2336         unsigned int cpp = fb->format->cpp[plane];
2337         u32 offset, offset_aligned;
2338
2339         if (alignment)
2340                 alignment--;
2341
2342         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2343                 unsigned int tile_size, tile_width, tile_height;
2344                 unsigned int tile_rows, tiles, pitch_tiles;
2345
2346                 tile_size = intel_tile_size(dev_priv);
2347                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2348
2349                 if (drm_rotation_90_or_270(rotation)) {
2350                         pitch_tiles = pitch / tile_height;
2351                         swap(tile_width, tile_height);
2352                 } else {
2353                         pitch_tiles = pitch / (tile_width * cpp);
2354                 }
2355
2356                 tile_rows = *y / tile_height;
2357                 *y %= tile_height;
2358
2359                 tiles = *x / tile_width;
2360                 *x %= tile_width;
2361
2362                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2363                 offset_aligned = offset & ~alignment;
2364
2365                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2366                                            tile_size, pitch_tiles,
2367                                            offset, offset_aligned);
2368         } else {
2369                 offset = *y * pitch + *x * cpp;
2370                 offset_aligned = offset & ~alignment;
2371
2372                 *y = (offset & alignment) / pitch;
2373                 *x = ((offset & alignment) - *y * pitch) / cpp;
2374         }
2375
2376         return offset_aligned;
2377 }
2378
2379 u32 intel_compute_tile_offset(int *x, int *y,
2380                               const struct intel_plane_state *state,
2381                               int plane)
2382 {
2383         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2384         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2385         const struct drm_framebuffer *fb = state->base.fb;
2386         unsigned int rotation = state->base.rotation;
2387         int pitch = intel_fb_pitch(fb, plane, rotation);
2388         u32 alignment;
2389
2390         if (intel_plane->id == PLANE_CURSOR)
2391                 alignment = intel_cursor_alignment(dev_priv);
2392         else
2393                 alignment = intel_surf_alignment(fb, plane);
2394
2395         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2396                                           rotation, alignment);
2397 }
2398
2399 /* Convert the fb->offset[] into x/y offsets */
2400 static int intel_fb_offset_to_xy(int *x, int *y,
2401                                  const struct drm_framebuffer *fb, int plane)
2402 {
2403         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2404
2405         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2406             fb->offsets[plane] % intel_tile_size(dev_priv))
2407                 return -EINVAL;
2408
2409         *x = 0;
2410         *y = 0;
2411
2412         _intel_adjust_tile_offset(x, y,
2413                                   fb, plane, DRM_MODE_ROTATE_0,
2414                                   fb->offsets[plane], 0);
2415
2416         return 0;
2417 }
2418
2419 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2420 {
2421         switch (fb_modifier) {
2422         case I915_FORMAT_MOD_X_TILED:
2423                 return I915_TILING_X;
2424         case I915_FORMAT_MOD_Y_TILED:
2425         case I915_FORMAT_MOD_Y_TILED_CCS:
2426                 return I915_TILING_Y;
2427         default:
2428                 return I915_TILING_NONE;
2429         }
2430 }
2431
2432 static const struct drm_format_info ccs_formats[] = {
2433         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2434         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2435         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2436         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2437 };
2438
2439 static const struct drm_format_info *
2440 lookup_format_info(const struct drm_format_info formats[],
2441                    int num_formats, u32 format)
2442 {
2443         int i;
2444
2445         for (i = 0; i < num_formats; i++) {
2446                 if (formats[i].format == format)
2447                         return &formats[i];
2448         }
2449
2450         return NULL;
2451 }
2452
2453 static const struct drm_format_info *
2454 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2455 {
2456         switch (cmd->modifier[0]) {
2457         case I915_FORMAT_MOD_Y_TILED_CCS:
2458         case I915_FORMAT_MOD_Yf_TILED_CCS:
2459                 return lookup_format_info(ccs_formats,
2460                                           ARRAY_SIZE(ccs_formats),
2461                                           cmd->pixel_format);
2462         default:
2463                 return NULL;
2464         }
2465 }
2466
2467 static int
2468 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2469                    struct drm_framebuffer *fb)
2470 {
2471         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2472         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2473         u32 gtt_offset_rotated = 0;
2474         unsigned int max_size = 0;
2475         int i, num_planes = fb->format->num_planes;
2476         unsigned int tile_size = intel_tile_size(dev_priv);
2477
2478         for (i = 0; i < num_planes; i++) {
2479                 unsigned int width, height;
2480                 unsigned int cpp, size;
2481                 u32 offset;
2482                 int x, y;
2483                 int ret;
2484
2485                 cpp = fb->format->cpp[i];
2486                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2487                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2488
2489                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2490                 if (ret) {
2491                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2492                                       i, fb->offsets[i]);
2493                         return ret;
2494                 }
2495
2496                 if ((fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2497                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) && i == 1) {
2498                         int hsub = fb->format->hsub;
2499                         int vsub = fb->format->vsub;
2500                         int tile_width, tile_height;
2501                         int main_x, main_y;
2502                         int ccs_x, ccs_y;
2503
2504                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2505                         tile_width *= hsub;
2506                         tile_height *= vsub;
2507
2508                         ccs_x = (x * hsub) % tile_width;
2509                         ccs_y = (y * vsub) % tile_height;
2510                         main_x = intel_fb->normal[0].x % tile_width;
2511                         main_y = intel_fb->normal[0].y % tile_height;
2512
2513                         /*
2514                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2515                          * x/y offsets must match between CCS and the main surface.
2516                          */
2517                         if (main_x != ccs_x || main_y != ccs_y) {
2518                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2519                                               main_x, main_y,
2520                                               ccs_x, ccs_y,
2521                                               intel_fb->normal[0].x,
2522                                               intel_fb->normal[0].y,
2523                                               x, y);
2524                                 return -EINVAL;
2525                         }
2526                 }
2527
2528                 /*
2529                  * The fence (if used) is aligned to the start of the object
2530                  * so having the framebuffer wrap around across the edge of the
2531                  * fenced region doesn't really work. We have no API to configure
2532                  * the fence start offset within the object (nor could we probably
2533                  * on gen2/3). So it's just easier if we just require that the
2534                  * fb layout agrees with the fence layout. We already check that the
2535                  * fb stride matches the fence stride elsewhere.
2536                  */
2537                 if (i == 0 && i915_gem_object_is_tiled(intel_fb->obj) &&
2538                     (x + width) * cpp > fb->pitches[i]) {
2539                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2540                                       i, fb->offsets[i]);
2541                         return -EINVAL;
2542                 }
2543
2544                 /*
2545                  * First pixel of the framebuffer from
2546                  * the start of the normal gtt mapping.
2547                  */
2548                 intel_fb->normal[i].x = x;
2549                 intel_fb->normal[i].y = y;
2550
2551                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2552                                                     fb, i, fb->pitches[i],
2553                                                     DRM_MODE_ROTATE_0, tile_size);
2554                 offset /= tile_size;
2555
2556                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2557                         unsigned int tile_width, tile_height;
2558                         unsigned int pitch_tiles;
2559                         struct drm_rect r;
2560
2561                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2562
2563                         rot_info->plane[i].offset = offset;
2564                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2565                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2566                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2567
2568                         intel_fb->rotated[i].pitch =
2569                                 rot_info->plane[i].height * tile_height;
2570
2571                         /* how many tiles does this plane need */
2572                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2573                         /*
2574                          * If the plane isn't horizontally tile aligned,
2575                          * we need one more tile.
2576                          */
2577                         if (x != 0)
2578                                 size++;
2579
2580                         /* rotate the x/y offsets to match the GTT view */
2581                         r.x1 = x;
2582                         r.y1 = y;
2583                         r.x2 = x + width;
2584                         r.y2 = y + height;
2585                         drm_rect_rotate(&r,
2586                                         rot_info->plane[i].width * tile_width,
2587                                         rot_info->plane[i].height * tile_height,
2588                                         DRM_MODE_ROTATE_270);
2589                         x = r.x1;
2590                         y = r.y1;
2591
2592                         /* rotate the tile dimensions to match the GTT view */
2593                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2594                         swap(tile_width, tile_height);
2595
2596                         /*
2597                          * We only keep the x/y offsets, so push all of the
2598                          * gtt offset into the x/y offsets.
2599                          */
2600                         __intel_adjust_tile_offset(&x, &y,
2601                                                    tile_width, tile_height,
2602                                                    tile_size, pitch_tiles,
2603                                                    gtt_offset_rotated * tile_size, 0);
2604
2605                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2606
2607                         /*
2608                          * First pixel of the framebuffer from
2609                          * the start of the rotated gtt mapping.
2610                          */
2611                         intel_fb->rotated[i].x = x;
2612                         intel_fb->rotated[i].y = y;
2613                 } else {
2614                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2615                                             x * cpp, tile_size);
2616                 }
2617
2618                 /* how many tiles in total needed in the bo */
2619                 max_size = max(max_size, offset + size);
2620         }
2621
2622         if (max_size * tile_size > intel_fb->obj->base.size) {
2623                 DRM_DEBUG_KMS("fb too big for bo (need %u bytes, have %zu bytes)\n",
2624                               max_size * tile_size, intel_fb->obj->base.size);
2625                 return -EINVAL;
2626         }
2627
2628         return 0;
2629 }
2630
2631 static int i9xx_format_to_fourcc(int format)
2632 {
2633         switch (format) {
2634         case DISPPLANE_8BPP:
2635                 return DRM_FORMAT_C8;
2636         case DISPPLANE_BGRX555:
2637                 return DRM_FORMAT_XRGB1555;
2638         case DISPPLANE_BGRX565:
2639                 return DRM_FORMAT_RGB565;
2640         default:
2641         case DISPPLANE_BGRX888:
2642                 return DRM_FORMAT_XRGB8888;
2643         case DISPPLANE_RGBX888:
2644                 return DRM_FORMAT_XBGR8888;
2645         case DISPPLANE_BGRX101010:
2646                 return DRM_FORMAT_XRGB2101010;
2647         case DISPPLANE_RGBX101010:
2648                 return DRM_FORMAT_XBGR2101010;
2649         }
2650 }
2651
2652 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2653 {
2654         switch (format) {
2655         case PLANE_CTL_FORMAT_RGB_565:
2656                 return DRM_FORMAT_RGB565;
2657         default:
2658         case PLANE_CTL_FORMAT_XRGB_8888:
2659                 if (rgb_order) {
2660                         if (alpha)
2661                                 return DRM_FORMAT_ABGR8888;
2662                         else
2663                                 return DRM_FORMAT_XBGR8888;
2664                 } else {
2665                         if (alpha)
2666                                 return DRM_FORMAT_ARGB8888;
2667                         else
2668                                 return DRM_FORMAT_XRGB8888;
2669                 }
2670         case PLANE_CTL_FORMAT_XRGB_2101010:
2671                 if (rgb_order)
2672                         return DRM_FORMAT_XBGR2101010;
2673                 else
2674                         return DRM_FORMAT_XRGB2101010;
2675         }
2676 }
2677
2678 static bool
2679 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2680                               struct intel_initial_plane_config *plane_config)
2681 {
2682         struct drm_device *dev = crtc->base.dev;
2683         struct drm_i915_private *dev_priv = to_i915(dev);
2684         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2685         struct drm_i915_gem_object *obj = NULL;
2686         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2687         struct drm_framebuffer *fb = &plane_config->fb->base;
2688         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2689         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2690                                     PAGE_SIZE);
2691
2692         size_aligned -= base_aligned;
2693
2694         if (plane_config->size == 0)
2695                 return false;
2696
2697         /* If the FB is too big, just don't use it since fbdev is not very
2698          * important and we should probably use that space with FBC or other
2699          * features. */
2700         if (size_aligned * 2 > ggtt->stolen_usable_size)
2701                 return false;
2702
2703         mutex_lock(&dev->struct_mutex);
2704         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2705                                                              base_aligned,
2706                                                              base_aligned,
2707                                                              size_aligned);
2708         mutex_unlock(&dev->struct_mutex);
2709         if (!obj)
2710                 return false;
2711
2712         if (plane_config->tiling == I915_TILING_X)
2713                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2714
2715         mode_cmd.pixel_format = fb->format->format;
2716         mode_cmd.width = fb->width;
2717         mode_cmd.height = fb->height;
2718         mode_cmd.pitches[0] = fb->pitches[0];
2719         mode_cmd.modifier[0] = fb->modifier;
2720         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2721
2722         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2723                 DRM_DEBUG_KMS("intel fb init failed\n");
2724                 goto out_unref_obj;
2725         }
2726
2727
2728         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2729         return true;
2730
2731 out_unref_obj:
2732         i915_gem_object_put(obj);
2733         return false;
2734 }
2735
2736 static void
2737 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2738                         struct intel_plane_state *plane_state,
2739                         bool visible)
2740 {
2741         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2742
2743         plane_state->base.visible = visible;
2744
2745         /* FIXME pre-g4x don't work like this */
2746         if (visible) {
2747                 crtc_state->base.plane_mask |= BIT(drm_plane_index(&plane->base));
2748                 crtc_state->active_planes |= BIT(plane->id);
2749         } else {
2750                 crtc_state->base.plane_mask &= ~BIT(drm_plane_index(&plane->base));
2751                 crtc_state->active_planes &= ~BIT(plane->id);
2752         }
2753
2754         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2755                       crtc_state->base.crtc->name,
2756                       crtc_state->active_planes);
2757 }
2758
2759 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2760                                          struct intel_plane *plane)
2761 {
2762         struct intel_crtc_state *crtc_state =
2763                 to_intel_crtc_state(crtc->base.state);
2764         struct intel_plane_state *plane_state =
2765                 to_intel_plane_state(plane->base.state);
2766
2767         intel_set_plane_visible(crtc_state, plane_state, false);
2768
2769         if (plane->id == PLANE_PRIMARY)
2770                 intel_pre_disable_primary_noatomic(&crtc->base);
2771
2772         trace_intel_disable_plane(&plane->base, crtc);
2773         plane->disable_plane(plane, crtc);
2774 }
2775
2776 static void
2777 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2778                              struct intel_initial_plane_config *plane_config)
2779 {
2780         struct drm_device *dev = intel_crtc->base.dev;
2781         struct drm_i915_private *dev_priv = to_i915(dev);
2782         struct drm_crtc *c;
2783         struct drm_i915_gem_object *obj;
2784         struct drm_plane *primary = intel_crtc->base.primary;
2785         struct drm_plane_state *plane_state = primary->state;
2786         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2787         struct intel_plane *intel_plane = to_intel_plane(primary);
2788         struct intel_plane_state *intel_state =
2789                 to_intel_plane_state(plane_state);
2790         struct drm_framebuffer *fb;
2791
2792         if (!plane_config->fb)
2793                 return;
2794
2795         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2796                 fb = &plane_config->fb->base;
2797                 goto valid_fb;
2798         }
2799
2800         kfree(plane_config->fb);
2801
2802         /*
2803          * Failed to alloc the obj, check to see if we should share
2804          * an fb with another CRTC instead
2805          */
2806         for_each_crtc(dev, c) {
2807                 struct intel_plane_state *state;
2808
2809                 if (c == &intel_crtc->base)
2810                         continue;
2811
2812                 if (!to_intel_crtc(c)->active)
2813                         continue;
2814
2815                 state = to_intel_plane_state(c->primary->state);
2816                 if (!state->vma)
2817                         continue;
2818
2819                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2820                         fb = c->primary->fb;
2821                         drm_framebuffer_reference(fb);
2822                         goto valid_fb;
2823                 }
2824         }
2825
2826         /*
2827          * We've failed to reconstruct the BIOS FB.  Current display state
2828          * indicates that the primary plane is visible, but has a NULL FB,
2829          * which will lead to problems later if we don't fix it up.  The
2830          * simplest solution is to just disable the primary plane now and
2831          * pretend the BIOS never had it enabled.
2832          */
2833         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2834
2835         return;
2836
2837 valid_fb:
2838         mutex_lock(&dev->struct_mutex);
2839         intel_state->vma =
2840                 intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
2841         mutex_unlock(&dev->struct_mutex);
2842         if (IS_ERR(intel_state->vma)) {
2843                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2844                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2845
2846                 intel_state->vma = NULL;
2847                 drm_framebuffer_unreference(fb);
2848                 return;
2849         }
2850
2851         plane_state->src_x = 0;
2852         plane_state->src_y = 0;
2853         plane_state->src_w = fb->width << 16;
2854         plane_state->src_h = fb->height << 16;
2855
2856         plane_state->crtc_x = 0;
2857         plane_state->crtc_y = 0;
2858         plane_state->crtc_w = fb->width;
2859         plane_state->crtc_h = fb->height;
2860
2861         intel_state->base.src = drm_plane_state_src(plane_state);
2862         intel_state->base.dst = drm_plane_state_dest(plane_state);
2863
2864         obj = intel_fb_obj(fb);
2865         if (i915_gem_object_is_tiled(obj))
2866                 dev_priv->preserve_bios_swizzle = true;
2867
2868         drm_framebuffer_reference(fb);
2869         primary->fb = primary->state->fb = fb;
2870         primary->crtc = primary->state->crtc = &intel_crtc->base;
2871
2872         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2873                                 to_intel_plane_state(plane_state),
2874                                 true);
2875
2876         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2877                   &obj->frontbuffer_bits);
2878 }
2879
2880 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2881                                unsigned int rotation)
2882 {
2883         int cpp = fb->format->cpp[plane];
2884
2885         switch (fb->modifier) {
2886         case DRM_FORMAT_MOD_LINEAR:
2887         case I915_FORMAT_MOD_X_TILED:
2888                 switch (cpp) {
2889                 case 8:
2890                         return 4096;
2891                 case 4:
2892                 case 2:
2893                 case 1:
2894                         return 8192;
2895                 default:
2896                         MISSING_CASE(cpp);
2897                         break;
2898                 }
2899                 break;
2900         case I915_FORMAT_MOD_Y_TILED_CCS:
2901         case I915_FORMAT_MOD_Yf_TILED_CCS:
2902                 /* FIXME AUX plane? */
2903         case I915_FORMAT_MOD_Y_TILED:
2904         case I915_FORMAT_MOD_Yf_TILED:
2905                 switch (cpp) {
2906                 case 8:
2907                         return 2048;
2908                 case 4:
2909                         return 4096;
2910                 case 2:
2911                 case 1:
2912                         return 8192;
2913                 default:
2914                         MISSING_CASE(cpp);
2915                         break;
2916                 }
2917                 break;
2918         default:
2919                 MISSING_CASE(fb->modifier);
2920         }
2921
2922         return 2048;
2923 }
2924
2925 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2926                                            int main_x, int main_y, u32 main_offset)
2927 {
2928         const struct drm_framebuffer *fb = plane_state->base.fb;
2929         int hsub = fb->format->hsub;
2930         int vsub = fb->format->vsub;
2931         int aux_x = plane_state->aux.x;
2932         int aux_y = plane_state->aux.y;
2933         u32 aux_offset = plane_state->aux.offset;
2934         u32 alignment = intel_surf_alignment(fb, 1);
2935
2936         while (aux_offset >= main_offset && aux_y <= main_y) {
2937                 int x, y;
2938
2939                 if (aux_x == main_x && aux_y == main_y)
2940                         break;
2941
2942                 if (aux_offset == 0)
2943                         break;
2944
2945                 x = aux_x / hsub;
2946                 y = aux_y / vsub;
2947                 aux_offset = intel_adjust_tile_offset(&x, &y, plane_state, 1,
2948                                                       aux_offset, aux_offset - alignment);
2949                 aux_x = x * hsub + aux_x % hsub;
2950                 aux_y = y * vsub + aux_y % vsub;
2951         }
2952
2953         if (aux_x != main_x || aux_y != main_y)
2954                 return false;
2955
2956         plane_state->aux.offset = aux_offset;
2957         plane_state->aux.x = aux_x;
2958         plane_state->aux.y = aux_y;
2959
2960         return true;
2961 }
2962
2963 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2964 {
2965         const struct drm_framebuffer *fb = plane_state->base.fb;
2966         unsigned int rotation = plane_state->base.rotation;
2967         int x = plane_state->base.src.x1 >> 16;
2968         int y = plane_state->base.src.y1 >> 16;
2969         int w = drm_rect_width(&plane_state->base.src) >> 16;
2970         int h = drm_rect_height(&plane_state->base.src) >> 16;
2971         int max_width = skl_max_plane_width(fb, 0, rotation);
2972         int max_height = 4096;
2973         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2974
2975         if (w > max_width || h > max_height) {
2976                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2977                               w, h, max_width, max_height);
2978                 return -EINVAL;
2979         }
2980
2981         intel_add_fb_offsets(&x, &y, plane_state, 0);
2982         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
2983         alignment = intel_surf_alignment(fb, 0);
2984
2985         /*
2986          * AUX surface offset is specified as the distance from the
2987          * main surface offset, and it must be non-negative. Make
2988          * sure that is what we will get.
2989          */
2990         if (offset > aux_offset)
2991                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2992                                                   offset, aux_offset & ~(alignment - 1));
2993
2994         /*
2995          * When using an X-tiled surface, the plane blows up
2996          * if the x offset + width exceed the stride.
2997          *
2998          * TODO: linear and Y-tiled seem fine, Yf untested,
2999          */
3000         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3001                 int cpp = fb->format->cpp[0];
3002
3003                 while ((x + w) * cpp > fb->pitches[0]) {
3004                         if (offset == 0) {
3005                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3006                                 return -EINVAL;
3007                         }
3008
3009                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3010                                                           offset, offset - alignment);
3011                 }
3012         }
3013
3014         /*
3015          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3016          * they match with the main surface x/y offsets.
3017          */
3018         if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3019             fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3020                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3021                         if (offset == 0)
3022                                 break;
3023
3024                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3025                                                           offset, offset - alignment);
3026                 }
3027
3028                 if (x != plane_state->aux.x || y != plane_state->aux.y) {
3029                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3030                         return -EINVAL;
3031                 }
3032         }
3033
3034         plane_state->main.offset = offset;
3035         plane_state->main.x = x;
3036         plane_state->main.y = y;
3037
3038         return 0;
3039 }
3040
3041 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3042 {
3043         const struct drm_framebuffer *fb = plane_state->base.fb;
3044         unsigned int rotation = plane_state->base.rotation;
3045         int max_width = skl_max_plane_width(fb, 1, rotation);
3046         int max_height = 4096;
3047         int x = plane_state->base.src.x1 >> 17;
3048         int y = plane_state->base.src.y1 >> 17;
3049         int w = drm_rect_width(&plane_state->base.src) >> 17;
3050         int h = drm_rect_height(&plane_state->base.src) >> 17;
3051         u32 offset;
3052
3053         intel_add_fb_offsets(&x, &y, plane_state, 1);
3054         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3055
3056         /* FIXME not quite sure how/if these apply to the chroma plane */
3057         if (w > max_width || h > max_height) {
3058                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3059                               w, h, max_width, max_height);
3060                 return -EINVAL;
3061         }
3062
3063         plane_state->aux.offset = offset;
3064         plane_state->aux.x = x;
3065         plane_state->aux.y = y;
3066
3067         return 0;
3068 }
3069
3070 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3071 {
3072         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3073         struct intel_crtc *crtc = to_intel_crtc(plane_state->base.crtc);
3074         const struct drm_framebuffer *fb = plane_state->base.fb;
3075         int src_x = plane_state->base.src.x1 >> 16;
3076         int src_y = plane_state->base.src.y1 >> 16;
3077         int hsub = fb->format->hsub;
3078         int vsub = fb->format->vsub;
3079         int x = src_x / hsub;
3080         int y = src_y / vsub;
3081         u32 offset;
3082
3083         switch (plane->id) {
3084         case PLANE_PRIMARY:
3085         case PLANE_SPRITE0:
3086                 break;
3087         default:
3088                 DRM_DEBUG_KMS("RC support only on plane 1 and 2\n");
3089                 return -EINVAL;
3090         }
3091
3092         if (crtc->pipe == PIPE_C) {
3093                 DRM_DEBUG_KMS("No RC support on pipe C\n");
3094                 return -EINVAL;
3095         }
3096
3097         if (plane_state->base.rotation & ~(DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180)) {
3098                 DRM_DEBUG_KMS("RC support only with 0/180 degree rotation %x\n",
3099                               plane_state->base.rotation);
3100                 return -EINVAL;
3101         }
3102
3103         intel_add_fb_offsets(&x, &y, plane_state, 1);
3104         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3105
3106         plane_state->aux.offset = offset;
3107         plane_state->aux.x = x * hsub + src_x % hsub;
3108         plane_state->aux.y = y * vsub + src_y % vsub;
3109
3110         return 0;
3111 }
3112
3113 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3114 {
3115         const struct drm_framebuffer *fb = plane_state->base.fb;
3116         unsigned int rotation = plane_state->base.rotation;
3117         int ret;
3118
3119         if (!plane_state->base.visible)
3120                 return 0;
3121
3122         /* Rotate src coordinates to match rotated GTT view */
3123         if (drm_rotation_90_or_270(rotation))
3124                 drm_rect_rotate(&plane_state->base.src,
3125                                 fb->width << 16, fb->height << 16,
3126                                 DRM_MODE_ROTATE_270);
3127
3128         /*
3129          * Handle the AUX surface first since
3130          * the main surface setup depends on it.
3131          */
3132         if (fb->format->format == DRM_FORMAT_NV12) {
3133                 ret = skl_check_nv12_aux_surface(plane_state);
3134                 if (ret)
3135                         return ret;
3136         } else if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3137                    fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3138                 ret = skl_check_ccs_aux_surface(plane_state);
3139                 if (ret)
3140                         return ret;
3141         } else {
3142                 plane_state->aux.offset = ~0xfff;
3143                 plane_state->aux.x = 0;
3144                 plane_state->aux.y = 0;
3145         }
3146
3147         ret = skl_check_main_surface(plane_state);
3148         if (ret)
3149                 return ret;
3150
3151         return 0;
3152 }
3153
3154 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3155                           const struct intel_plane_state *plane_state)
3156 {
3157         struct drm_i915_private *dev_priv =
3158                 to_i915(plane_state->base.plane->dev);
3159         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3160         const struct drm_framebuffer *fb = plane_state->base.fb;
3161         unsigned int rotation = plane_state->base.rotation;
3162         u32 dspcntr;
3163
3164         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3165
3166         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3167             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3168                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3169
3170         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3171                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3172
3173         if (INTEL_GEN(dev_priv) < 4)
3174                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3175
3176         switch (fb->format->format) {
3177         case DRM_FORMAT_C8:
3178                 dspcntr |= DISPPLANE_8BPP;
3179                 break;
3180         case DRM_FORMAT_XRGB1555:
3181                 dspcntr |= DISPPLANE_BGRX555;
3182                 break;
3183         case DRM_FORMAT_RGB565:
3184                 dspcntr |= DISPPLANE_BGRX565;
3185                 break;
3186         case DRM_FORMAT_XRGB8888:
3187                 dspcntr |= DISPPLANE_BGRX888;
3188                 break;
3189         case DRM_FORMAT_XBGR8888:
3190                 dspcntr |= DISPPLANE_RGBX888;
3191                 break;
3192         case DRM_FORMAT_XRGB2101010:
3193                 dspcntr |= DISPPLANE_BGRX101010;
3194                 break;
3195         case DRM_FORMAT_XBGR2101010:
3196                 dspcntr |= DISPPLANE_RGBX101010;
3197                 break;
3198         default:
3199                 MISSING_CASE(fb->format->format);
3200                 return 0;
3201         }
3202
3203         if (INTEL_GEN(dev_priv) >= 4 &&
3204             fb->modifier == I915_FORMAT_MOD_X_TILED)
3205                 dspcntr |= DISPPLANE_TILED;
3206
3207         if (rotation & DRM_MODE_ROTATE_180)
3208                 dspcntr |= DISPPLANE_ROTATE_180;
3209
3210         if (rotation & DRM_MODE_REFLECT_X)
3211                 dspcntr |= DISPPLANE_MIRROR;
3212
3213         return dspcntr;
3214 }
3215
3216 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3217 {
3218         struct drm_i915_private *dev_priv =
3219                 to_i915(plane_state->base.plane->dev);
3220         int src_x = plane_state->base.src.x1 >> 16;
3221         int src_y = plane_state->base.src.y1 >> 16;
3222         u32 offset;
3223
3224         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3225
3226         if (INTEL_GEN(dev_priv) >= 4)
3227                 offset = intel_compute_tile_offset(&src_x, &src_y,
3228                                                    plane_state, 0);
3229         else
3230                 offset = 0;
3231
3232         /* HSW/BDW do this automagically in hardware */
3233         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3234                 unsigned int rotation = plane_state->base.rotation;
3235                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3236                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3237
3238                 if (rotation & DRM_MODE_ROTATE_180) {
3239                         src_x += src_w - 1;
3240                         src_y += src_h - 1;
3241                 } else if (rotation & DRM_MODE_REFLECT_X) {
3242                         src_x += src_w - 1;
3243                 }
3244         }
3245
3246         plane_state->main.offset = offset;
3247         plane_state->main.x = src_x;
3248         plane_state->main.y = src_y;
3249
3250         return 0;
3251 }
3252
3253 static void i9xx_update_primary_plane(struct intel_plane *primary,
3254                                       const struct intel_crtc_state *crtc_state,
3255                                       const struct intel_plane_state *plane_state)
3256 {
3257         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3258         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3259         const struct drm_framebuffer *fb = plane_state->base.fb;
3260         enum plane plane = primary->plane;
3261         u32 linear_offset;
3262         u32 dspcntr = plane_state->ctl;
3263         i915_reg_t reg = DSPCNTR(plane);
3264         int x = plane_state->main.x;
3265         int y = plane_state->main.y;
3266         unsigned long irqflags;
3267
3268         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3269
3270         if (INTEL_GEN(dev_priv) >= 4)
3271                 crtc->dspaddr_offset = plane_state->main.offset;
3272         else
3273                 crtc->dspaddr_offset = linear_offset;
3274
3275         crtc->adjusted_x = x;
3276         crtc->adjusted_y = y;
3277
3278         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3279
3280         if (INTEL_GEN(dev_priv) < 4) {
3281                 /* pipesrc and dspsize control the size that is scaled from,
3282                  * which should always be the user's requested size.
3283                  */
3284                 I915_WRITE_FW(DSPSIZE(plane),
3285                               ((crtc_state->pipe_src_h - 1) << 16) |
3286                               (crtc_state->pipe_src_w - 1));
3287                 I915_WRITE_FW(DSPPOS(plane), 0);
3288         } else if (IS_CHERRYVIEW(dev_priv) && plane == PLANE_B) {
3289                 I915_WRITE_FW(PRIMSIZE(plane),
3290                               ((crtc_state->pipe_src_h - 1) << 16) |
3291                               (crtc_state->pipe_src_w - 1));
3292                 I915_WRITE_FW(PRIMPOS(plane), 0);
3293                 I915_WRITE_FW(PRIMCNSTALPHA(plane), 0);
3294         }
3295
3296         I915_WRITE_FW(reg, dspcntr);
3297
3298         I915_WRITE_FW(DSPSTRIDE(plane), fb->pitches[0]);
3299         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3300                 I915_WRITE_FW(DSPSURF(plane),
3301                               intel_plane_ggtt_offset(plane_state) +
3302                               crtc->dspaddr_offset);
3303                 I915_WRITE_FW(DSPOFFSET(plane), (y << 16) | x);
3304         } else if (INTEL_GEN(dev_priv) >= 4) {
3305                 I915_WRITE_FW(DSPSURF(plane),
3306                               intel_plane_ggtt_offset(plane_state) +
3307                               crtc->dspaddr_offset);
3308                 I915_WRITE_FW(DSPTILEOFF(plane), (y << 16) | x);
3309                 I915_WRITE_FW(DSPLINOFF(plane), linear_offset);
3310         } else {
3311                 I915_WRITE_FW(DSPADDR(plane),
3312                               intel_plane_ggtt_offset(plane_state) +
3313                               crtc->dspaddr_offset);
3314         }
3315         POSTING_READ_FW(reg);
3316
3317         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3318 }
3319
3320 static void i9xx_disable_primary_plane(struct intel_plane *primary,
3321                                        struct intel_crtc *crtc)
3322 {
3323         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3324         enum plane plane = primary->plane;
3325         unsigned long irqflags;
3326
3327         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3328
3329         I915_WRITE_FW(DSPCNTR(plane), 0);
3330         if (INTEL_INFO(dev_priv)->gen >= 4)
3331                 I915_WRITE_FW(DSPSURF(plane), 0);
3332         else
3333                 I915_WRITE_FW(DSPADDR(plane), 0);
3334         POSTING_READ_FW(DSPCNTR(plane));
3335
3336         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3337 }
3338
3339 static bool i9xx_plane_get_hw_state(struct intel_plane *primary)
3340 {
3341
3342         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3343         enum intel_display_power_domain power_domain;
3344         enum plane plane = primary->plane;
3345         enum pipe pipe = primary->pipe;
3346         bool ret;
3347
3348         /*
3349          * Not 100% correct for planes that can move between pipes,
3350          * but that's only the case for gen2-4 which don't have any
3351          * display power wells.
3352          */
3353         power_domain = POWER_DOMAIN_PIPE(pipe);
3354         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3355                 return false;
3356
3357         ret = I915_READ(DSPCNTR(plane)) & DISPLAY_PLANE_ENABLE;
3358
3359         intel_display_power_put(dev_priv, power_domain);
3360
3361         return ret;
3362 }
3363
3364 static u32
3365 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int plane)
3366 {
3367         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3368                 return 64;
3369         else
3370                 return intel_tile_width_bytes(fb, plane);
3371 }
3372
3373 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3374 {
3375         struct drm_device *dev = intel_crtc->base.dev;
3376         struct drm_i915_private *dev_priv = to_i915(dev);
3377
3378         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3379         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3380         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3381 }
3382
3383 /*
3384  * This function detaches (aka. unbinds) unused scalers in hardware
3385  */
3386 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3387 {
3388         struct intel_crtc_scaler_state *scaler_state;
3389         int i;
3390
3391         scaler_state = &intel_crtc->config->scaler_state;
3392
3393         /* loop through and disable scalers that aren't in use */
3394         for (i = 0; i < intel_crtc->num_scalers; i++) {
3395                 if (!scaler_state->scalers[i].in_use)
3396                         skl_detach_scaler(intel_crtc, i);
3397         }
3398 }
3399
3400 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3401                      unsigned int rotation)
3402 {
3403         u32 stride;
3404
3405         if (plane >= fb->format->num_planes)
3406                 return 0;
3407
3408         stride = intel_fb_pitch(fb, plane, rotation);
3409
3410         /*
3411          * The stride is either expressed as a multiple of 64 bytes chunks for
3412          * linear buffers or in number of tiles for tiled buffers.
3413          */
3414         if (drm_rotation_90_or_270(rotation))
3415                 stride /= intel_tile_height(fb, plane);
3416         else
3417                 stride /= intel_fb_stride_alignment(fb, plane);
3418
3419         return stride;
3420 }
3421
3422 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3423 {
3424         switch (pixel_format) {
3425         case DRM_FORMAT_C8:
3426                 return PLANE_CTL_FORMAT_INDEXED;
3427         case DRM_FORMAT_RGB565:
3428                 return PLANE_CTL_FORMAT_RGB_565;
3429         case DRM_FORMAT_XBGR8888:
3430                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3431         case DRM_FORMAT_XRGB8888:
3432                 return PLANE_CTL_FORMAT_XRGB_8888;
3433         /*
3434          * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3435          * to be already pre-multiplied. We need to add a knob (or a different
3436          * DRM_FORMAT) for user-space to configure that.
3437          */
3438         case DRM_FORMAT_ABGR8888:
3439                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX |
3440                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3441         case DRM_FORMAT_ARGB8888:
3442                 return PLANE_CTL_FORMAT_XRGB_8888 |
3443                         PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3444         case DRM_FORMAT_XRGB2101010:
3445                 return PLANE_CTL_FORMAT_XRGB_2101010;
3446         case DRM_FORMAT_XBGR2101010:
3447                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3448         case DRM_FORMAT_YUYV:
3449                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3450         case DRM_FORMAT_YVYU:
3451                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3452         case DRM_FORMAT_UYVY:
3453                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3454         case DRM_FORMAT_VYUY:
3455                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3456         default:
3457                 MISSING_CASE(pixel_format);
3458         }
3459
3460         return 0;
3461 }
3462
3463 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3464 {
3465         switch (fb_modifier) {
3466         case DRM_FORMAT_MOD_LINEAR:
3467                 break;
3468         case I915_FORMAT_MOD_X_TILED:
3469                 return PLANE_CTL_TILED_X;
3470         case I915_FORMAT_MOD_Y_TILED:
3471                 return PLANE_CTL_TILED_Y;
3472         case I915_FORMAT_MOD_Y_TILED_CCS:
3473                 return PLANE_CTL_TILED_Y | PLANE_CTL_DECOMPRESSION_ENABLE;
3474         case I915_FORMAT_MOD_Yf_TILED:
3475                 return PLANE_CTL_TILED_YF;
3476         case I915_FORMAT_MOD_Yf_TILED_CCS:
3477                 return PLANE_CTL_TILED_YF | PLANE_CTL_DECOMPRESSION_ENABLE;
3478         default:
3479                 MISSING_CASE(fb_modifier);
3480         }
3481
3482         return 0;
3483 }
3484
3485 static u32 skl_plane_ctl_rotation(unsigned int rotation)
3486 {
3487         switch (rotation) {
3488         case DRM_MODE_ROTATE_0:
3489                 break;
3490         /*
3491          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3492          * while i915 HW rotation is clockwise, thats why this swapping.
3493          */
3494         case DRM_MODE_ROTATE_90:
3495                 return PLANE_CTL_ROTATE_270;
3496         case DRM_MODE_ROTATE_180:
3497                 return PLANE_CTL_ROTATE_180;
3498         case DRM_MODE_ROTATE_270:
3499                 return PLANE_CTL_ROTATE_90;
3500         default:
3501                 MISSING_CASE(rotation);
3502         }
3503
3504         return 0;
3505 }
3506
3507 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3508                   const struct intel_plane_state *plane_state)
3509 {
3510         struct drm_i915_private *dev_priv =
3511                 to_i915(plane_state->base.plane->dev);
3512         const struct drm_framebuffer *fb = plane_state->base.fb;
3513         unsigned int rotation = plane_state->base.rotation;
3514         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3515         u32 plane_ctl;
3516
3517         plane_ctl = PLANE_CTL_ENABLE;
3518
3519         if (!IS_GEMINILAKE(dev_priv) && !IS_CANNONLAKE(dev_priv)) {
3520                 plane_ctl |=
3521                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3522                         PLANE_CTL_PIPE_CSC_ENABLE |
3523                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3524         }
3525
3526         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3527         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3528         plane_ctl |= skl_plane_ctl_rotation(rotation);
3529
3530         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3531                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3532         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3533                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3534
3535         return plane_ctl;
3536 }
3537
3538 static void skylake_update_primary_plane(struct intel_plane *plane,
3539                                          const struct intel_crtc_state *crtc_state,
3540                                          const struct intel_plane_state *plane_state)
3541 {
3542         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3543         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3544         const struct drm_framebuffer *fb = plane_state->base.fb;
3545         enum plane_id plane_id = plane->id;
3546         enum pipe pipe = plane->pipe;
3547         u32 plane_ctl = plane_state->ctl;
3548         unsigned int rotation = plane_state->base.rotation;
3549         u32 stride = skl_plane_stride(fb, 0, rotation);
3550         u32 aux_stride = skl_plane_stride(fb, 1, rotation);
3551         u32 surf_addr = plane_state->main.offset;
3552         int scaler_id = plane_state->scaler_id;
3553         int src_x = plane_state->main.x;
3554         int src_y = plane_state->main.y;
3555         int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3556         int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3557         int dst_x = plane_state->base.dst.x1;
3558         int dst_y = plane_state->base.dst.y1;
3559         int dst_w = drm_rect_width(&plane_state->base.dst);
3560         int dst_h = drm_rect_height(&plane_state->base.dst);
3561         unsigned long irqflags;
3562
3563         /* Sizes are 0 based */
3564         src_w--;
3565         src_h--;
3566         dst_w--;
3567         dst_h--;
3568
3569         crtc->dspaddr_offset = surf_addr;
3570
3571         crtc->adjusted_x = src_x;
3572         crtc->adjusted_y = src_y;
3573
3574         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3575
3576         if (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) {
3577                 I915_WRITE_FW(PLANE_COLOR_CTL(pipe, plane_id),
3578                               PLANE_COLOR_PIPE_GAMMA_ENABLE |
3579                               PLANE_COLOR_PIPE_CSC_ENABLE |
3580                               PLANE_COLOR_PLANE_GAMMA_DISABLE);
3581         }
3582
3583         I915_WRITE_FW(PLANE_CTL(pipe, plane_id), plane_ctl);
3584         I915_WRITE_FW(PLANE_OFFSET(pipe, plane_id), (src_y << 16) | src_x);
3585         I915_WRITE_FW(PLANE_STRIDE(pipe, plane_id), stride);
3586         I915_WRITE_FW(PLANE_SIZE(pipe, plane_id), (src_h << 16) | src_w);
3587         I915_WRITE_FW(PLANE_AUX_DIST(pipe, plane_id),
3588                       (plane_state->aux.offset - surf_addr) | aux_stride);
3589         I915_WRITE_FW(PLANE_AUX_OFFSET(pipe, plane_id),
3590                       (plane_state->aux.y << 16) | plane_state->aux.x);
3591
3592         if (scaler_id >= 0) {
3593                 uint32_t ps_ctrl = 0;
3594
3595                 WARN_ON(!dst_w || !dst_h);
3596                 ps_ctrl = PS_SCALER_EN | PS_PLANE_SEL(plane_id) |
3597                         crtc_state->scaler_state.scalers[scaler_id].mode;
3598                 I915_WRITE_FW(SKL_PS_CTRL(pipe, scaler_id), ps_ctrl);
3599                 I915_WRITE_FW(SKL_PS_PWR_GATE(pipe, scaler_id), 0);
3600                 I915_WRITE_FW(SKL_PS_WIN_POS(pipe, scaler_id), (dst_x << 16) | dst_y);
3601                 I915_WRITE_FW(SKL_PS_WIN_SZ(pipe, scaler_id), (dst_w << 16) | dst_h);
3602                 I915_WRITE_FW(PLANE_POS(pipe, plane_id), 0);
3603         } else {
3604                 I915_WRITE_FW(PLANE_POS(pipe, plane_id), (dst_y << 16) | dst_x);
3605         }
3606
3607         I915_WRITE_FW(PLANE_SURF(pipe, plane_id),
3608                       intel_plane_ggtt_offset(plane_state) + surf_addr);
3609
3610         POSTING_READ_FW(PLANE_SURF(pipe, plane_id));
3611
3612         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3613 }
3614
3615 static void skylake_disable_primary_plane(struct intel_plane *primary,
3616                                           struct intel_crtc *crtc)
3617 {
3618         struct drm_i915_private *dev_priv = to_i915(primary->base.dev);
3619         enum plane_id plane_id = primary->id;
3620         enum pipe pipe = primary->pipe;
3621         unsigned long irqflags;
3622
3623         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3624
3625         I915_WRITE_FW(PLANE_CTL(pipe, plane_id), 0);
3626         I915_WRITE_FW(PLANE_SURF(pipe, plane_id), 0);
3627         POSTING_READ_FW(PLANE_SURF(pipe, plane_id));
3628
3629         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3630 }
3631
3632 static int
3633 __intel_display_resume(struct drm_device *dev,
3634                        struct drm_atomic_state *state,
3635                        struct drm_modeset_acquire_ctx *ctx)
3636 {
3637         struct drm_crtc_state *crtc_state;
3638         struct drm_crtc *crtc;
3639         int i, ret;
3640
3641         intel_modeset_setup_hw_state(dev, ctx);
3642         i915_redisable_vga(to_i915(dev));
3643
3644         if (!state)
3645                 return 0;
3646
3647         /*
3648          * We've duplicated the state, pointers to the old state are invalid.
3649          *
3650          * Don't attempt to use the old state until we commit the duplicated state.
3651          */
3652         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3653                 /*
3654                  * Force recalculation even if we restore
3655                  * current state. With fast modeset this may not result
3656                  * in a modeset when the state is compatible.
3657                  */
3658                 crtc_state->mode_changed = true;
3659         }
3660
3661         /* ignore any reset values/BIOS leftovers in the WM registers */
3662         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3663                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3664
3665         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3666
3667         WARN_ON(ret == -EDEADLK);
3668         return ret;
3669 }
3670
3671 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3672 {
3673         return intel_has_gpu_reset(dev_priv) &&
3674                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3675 }
3676
3677 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3678 {
3679         struct drm_device *dev = &dev_priv->drm;
3680         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3681         struct drm_atomic_state *state;
3682         int ret;
3683
3684
3685         /* reset doesn't touch the display */
3686         if (!i915.force_reset_modeset_test &&
3687             !gpu_reset_clobbers_display(dev_priv))
3688                 return;
3689
3690         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3691         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3692         wake_up_all(&dev_priv->gpu_error.wait_queue);
3693
3694         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3695                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3696                 i915_gem_set_wedged(dev_priv);
3697         }
3698
3699         /*
3700          * Need mode_config.mutex so that we don't
3701          * trample ongoing ->detect() and whatnot.
3702          */
3703         mutex_lock(&dev->mode_config.mutex);
3704         drm_modeset_acquire_init(ctx, 0);
3705         while (1) {
3706                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3707                 if (ret != -EDEADLK)
3708                         break;
3709
3710                 drm_modeset_backoff(ctx);
3711         }
3712         /*
3713          * Disabling the crtcs gracefully seems nicer. Also the
3714          * g33 docs say we should at least disable all the planes.
3715          */
3716         state = drm_atomic_helper_duplicate_state(dev, ctx);
3717         if (IS_ERR(state)) {
3718                 ret = PTR_ERR(state);
3719                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3720                 return;
3721         }
3722
3723         ret = drm_atomic_helper_disable_all(dev, ctx);
3724         if (ret) {
3725                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3726                 drm_atomic_state_put(state);
3727                 return;
3728         }
3729
3730         dev_priv->modeset_restore_state = state;
3731         state->acquire_ctx = ctx;
3732 }
3733
3734 void intel_finish_reset(struct drm_i915_private *dev_priv)
3735 {
3736         struct drm_device *dev = &dev_priv->drm;
3737         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3738         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3739         int ret;
3740
3741         /* reset doesn't touch the display */
3742         if (!i915.force_reset_modeset_test &&
3743             !gpu_reset_clobbers_display(dev_priv))
3744                 return;
3745
3746         if (!state)
3747                 goto unlock;
3748
3749         dev_priv->modeset_restore_state = NULL;
3750
3751         /* reset doesn't touch the display */
3752         if (!gpu_reset_clobbers_display(dev_priv)) {
3753                 /* for testing only restore the display */
3754                 ret = __intel_display_resume(dev, state, ctx);
3755                         if (ret)
3756                                 DRM_ERROR("Restoring old state failed with %i\n", ret);
3757         } else {
3758                 /*
3759                  * The display has been reset as well,
3760                  * so need a full re-initialization.
3761                  */
3762                 intel_runtime_pm_disable_interrupts(dev_priv);
3763                 intel_runtime_pm_enable_interrupts(dev_priv);
3764
3765                 intel_pps_unlock_regs_wa(dev_priv);
3766                 intel_modeset_init_hw(dev);
3767                 intel_init_clock_gating(dev_priv);
3768
3769                 spin_lock_irq(&dev_priv->irq_lock);
3770                 if (dev_priv->display.hpd_irq_setup)
3771                         dev_priv->display.hpd_irq_setup(dev_priv);
3772                 spin_unlock_irq(&dev_priv->irq_lock);
3773
3774                 ret = __intel_display_resume(dev, state, ctx);
3775                 if (ret)
3776                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3777
3778                 intel_hpd_init(dev_priv);
3779         }
3780
3781         drm_atomic_state_put(state);
3782 unlock:
3783         drm_modeset_drop_locks(ctx);
3784         drm_modeset_acquire_fini(ctx);
3785         mutex_unlock(&dev->mode_config.mutex);
3786
3787         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3788 }
3789
3790 static void intel_update_pipe_config(struct intel_crtc *crtc,
3791                                      struct intel_crtc_state *old_crtc_state)
3792 {
3793         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3794         struct intel_crtc_state *pipe_config =
3795                 to_intel_crtc_state(crtc->base.state);
3796
3797         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3798         crtc->base.mode = crtc->base.state->mode;
3799
3800         /*
3801          * Update pipe size and adjust fitter if needed: the reason for this is
3802          * that in compute_mode_changes we check the native mode (not the pfit
3803          * mode) to see if we can flip rather than do a full mode set. In the
3804          * fastboot case, we'll flip, but if we don't update the pipesrc and
3805          * pfit state, we'll end up with a big fb scanned out into the wrong
3806          * sized surface.
3807          */
3808
3809         I915_WRITE(PIPESRC(crtc->pipe),
3810                    ((pipe_config->pipe_src_w - 1) << 16) |
3811                    (pipe_config->pipe_src_h - 1));
3812
3813         /* on skylake this is done by detaching scalers */
3814         if (INTEL_GEN(dev_priv) >= 9) {
3815                 skl_detach_scalers(crtc);
3816
3817                 if (pipe_config->pch_pfit.enabled)
3818                         skylake_pfit_enable(crtc);
3819         } else if (HAS_PCH_SPLIT(dev_priv)) {
3820                 if (pipe_config->pch_pfit.enabled)
3821                         ironlake_pfit_enable(crtc);
3822                 else if (old_crtc_state->pch_pfit.enabled)
3823                         ironlake_pfit_disable(crtc, true);
3824         }
3825 }
3826
3827 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3828 {
3829         struct drm_device *dev = crtc->base.dev;
3830         struct drm_i915_private *dev_priv = to_i915(dev);
3831         int pipe = crtc->pipe;
3832         i915_reg_t reg;
3833         u32 temp;
3834
3835         /* enable normal train */
3836         reg = FDI_TX_CTL(pipe);
3837         temp = I915_READ(reg);
3838         if (IS_IVYBRIDGE(dev_priv)) {
3839                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3840                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3841         } else {
3842                 temp &= ~FDI_LINK_TRAIN_NONE;
3843                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3844         }
3845         I915_WRITE(reg, temp);
3846
3847         reg = FDI_RX_CTL(pipe);
3848         temp = I915_READ(reg);
3849         if (HAS_PCH_CPT(dev_priv)) {
3850                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3851                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3852         } else {
3853                 temp &= ~FDI_LINK_TRAIN_NONE;
3854                 temp |= FDI_LINK_TRAIN_NONE;
3855         }
3856         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3857
3858         /* wait one idle pattern time */
3859         POSTING_READ(reg);
3860         udelay(1000);
3861
3862         /* IVB wants error correction enabled */
3863         if (IS_IVYBRIDGE(dev_priv))
3864                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3865                            FDI_FE_ERRC_ENABLE);
3866 }
3867
3868 /* The FDI link training functions for ILK/Ibexpeak. */
3869 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3870                                     const struct intel_crtc_state *crtc_state)
3871 {
3872         struct drm_device *dev = crtc->base.dev;
3873         struct drm_i915_private *dev_priv = to_i915(dev);
3874         int pipe = crtc->pipe;
3875         i915_reg_t reg;
3876         u32 temp, tries;
3877
3878         /* FDI needs bits from pipe first */
3879         assert_pipe_enabled(dev_priv, pipe);
3880
3881         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3882            for train result */
3883         reg = FDI_RX_IMR(pipe);
3884         temp = I915_READ(reg);
3885         temp &= ~FDI_RX_SYMBOL_LOCK;
3886         temp &= ~FDI_RX_BIT_LOCK;
3887         I915_WRITE(reg, temp);
3888         I915_READ(reg);
3889         udelay(150);
3890
3891         /* enable CPU FDI TX and PCH FDI RX */
3892         reg = FDI_TX_CTL(pipe);
3893         temp = I915_READ(reg);
3894         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3895         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3896         temp &= ~FDI_LINK_TRAIN_NONE;
3897         temp |= FDI_LINK_TRAIN_PATTERN_1;
3898         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3899
3900         reg = FDI_RX_CTL(pipe);
3901         temp = I915_READ(reg);
3902         temp &= ~FDI_LINK_TRAIN_NONE;
3903         temp |= FDI_LINK_TRAIN_PATTERN_1;
3904         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3905
3906         POSTING_READ(reg);
3907         udelay(150);
3908
3909         /* Ironlake workaround, enable clock pointer after FDI enable*/
3910         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3911         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3912                    FDI_RX_PHASE_SYNC_POINTER_EN);
3913
3914         reg = FDI_RX_IIR(pipe);
3915         for (tries = 0; tries < 5; tries++) {
3916                 temp = I915_READ(reg);
3917                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3918
3919                 if ((temp & FDI_RX_BIT_LOCK)) {
3920                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3921                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3922                         break;
3923                 }
3924         }
3925         if (tries == 5)
3926                 DRM_ERROR("FDI train 1 fail!\n");
3927
3928         /* Train 2 */
3929         reg = FDI_TX_CTL(pipe);
3930         temp = I915_READ(reg);
3931         temp &= ~FDI_LINK_TRAIN_NONE;
3932         temp |= FDI_LINK_TRAIN_PATTERN_2;
3933         I915_WRITE(reg, temp);
3934
3935         reg = FDI_RX_CTL(pipe);
3936         temp = I915_READ(reg);
3937         temp &= ~FDI_LINK_TRAIN_NONE;
3938         temp |= FDI_LINK_TRAIN_PATTERN_2;
3939         I915_WRITE(reg, temp);
3940
3941         POSTING_READ(reg);
3942         udelay(150);
3943
3944         reg = FDI_RX_IIR(pipe);
3945         for (tries = 0; tries < 5; tries++) {
3946                 temp = I915_READ(reg);
3947                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3948
3949                 if (temp & FDI_RX_SYMBOL_LOCK) {
3950                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3951                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3952                         break;
3953                 }
3954         }
3955         if (tries == 5)
3956                 DRM_ERROR("FDI train 2 fail!\n");
3957
3958         DRM_DEBUG_KMS("FDI train done\n");
3959
3960 }
3961
3962 static const int snb_b_fdi_train_param[] = {
3963         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3964         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3965         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3966         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3967 };
3968
3969 /* The FDI link training functions for SNB/Cougarpoint. */
3970 static void gen6_fdi_link_train(struct intel_crtc *crtc,
3971                                 const struct intel_crtc_state *crtc_state)
3972 {
3973         struct drm_device *dev = crtc->base.dev;
3974         struct drm_i915_private *dev_priv = to_i915(dev);
3975         int pipe = crtc->pipe;
3976         i915_reg_t reg;
3977         u32 temp, i, retry;
3978
3979         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3980            for train result */
3981         reg = FDI_RX_IMR(pipe);
3982         temp = I915_READ(reg);
3983         temp &= ~FDI_RX_SYMBOL_LOCK;
3984         temp &= ~FDI_RX_BIT_LOCK;
3985         I915_WRITE(reg, temp);
3986
3987         POSTING_READ(reg);
3988         udelay(150);
3989
3990         /* enable CPU FDI TX and PCH FDI RX */
3991         reg = FDI_TX_CTL(pipe);
3992         temp = I915_READ(reg);
3993         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3994         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3995         temp &= ~FDI_LINK_TRAIN_NONE;
3996         temp |= FDI_LINK_TRAIN_PATTERN_1;
3997         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3998         /* SNB-B */
3999         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4000         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4001
4002         I915_WRITE(FDI_RX_MISC(pipe),
4003                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4004
4005         reg = FDI_RX_CTL(pipe);
4006         temp = I915_READ(reg);
4007         if (HAS_PCH_CPT(dev_priv)) {
4008                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4009                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4010         } else {
4011                 temp &= ~FDI_LINK_TRAIN_NONE;
4012                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4013         }
4014         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4015
4016         POSTING_READ(reg);
4017         udelay(150);
4018
4019         for (i = 0; i < 4; i++) {
4020                 reg = FDI_TX_CTL(pipe);
4021                 temp = I915_READ(reg);
4022                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4023                 temp |= snb_b_fdi_train_param[i];
4024                 I915_WRITE(reg, temp);
4025
4026                 POSTING_READ(reg);
4027                 udelay(500);
4028
4029                 for (retry = 0; retry < 5; retry++) {
4030                         reg = FDI_RX_IIR(pipe);
4031                         temp = I915_READ(reg);
4032                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4033                         if (temp & FDI_RX_BIT_LOCK) {
4034                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4035                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4036                                 break;
4037                         }
4038                         udelay(50);
4039                 }
4040                 if (retry < 5)
4041                         break;
4042         }
4043         if (i == 4)
4044                 DRM_ERROR("FDI train 1 fail!\n");
4045
4046         /* Train 2 */
4047         reg = FDI_TX_CTL(pipe);
4048         temp = I915_READ(reg);
4049         temp &= ~FDI_LINK_TRAIN_NONE;
4050         temp |= FDI_LINK_TRAIN_PATTERN_2;
4051         if (IS_GEN6(dev_priv)) {
4052                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4053                 /* SNB-B */
4054                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4055         }
4056         I915_WRITE(reg, temp);
4057
4058         reg = FDI_RX_CTL(pipe);
4059         temp = I915_READ(reg);
4060         if (HAS_PCH_CPT(dev_priv)) {
4061                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4062                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4063         } else {
4064                 temp &= ~FDI_LINK_TRAIN_NONE;
4065                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4066         }
4067         I915_WRITE(reg, temp);
4068
4069         POSTING_READ(reg);
4070         udelay(150);
4071
4072         for (i = 0; i < 4; i++) {
4073                 reg = FDI_TX_CTL(pipe);
4074                 temp = I915_READ(reg);
4075                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4076                 temp |= snb_b_fdi_train_param[i];
4077                 I915_WRITE(reg, temp);
4078
4079                 POSTING_READ(reg);
4080                 udelay(500);
4081
4082                 for (retry = 0; retry < 5; retry++) {
4083                         reg = FDI_RX_IIR(pipe);
4084                         temp = I915_READ(reg);
4085                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4086                         if (temp & FDI_RX_SYMBOL_LOCK) {
4087                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4088                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4089                                 break;
4090                         }
4091                         udelay(50);
4092                 }
4093                 if (retry < 5)
4094                         break;
4095         }
4096         if (i == 4)
4097                 DRM_ERROR("FDI train 2 fail!\n");
4098
4099         DRM_DEBUG_KMS("FDI train done.\n");
4100 }
4101
4102 /* Manual link training for Ivy Bridge A0 parts */
4103 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4104                                       const struct intel_crtc_state *crtc_state)
4105 {
4106         struct drm_device *dev = crtc->base.dev;
4107         struct drm_i915_private *dev_priv = to_i915(dev);
4108         int pipe = crtc->pipe;
4109         i915_reg_t reg;
4110         u32 temp, i, j;
4111
4112         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4113            for train result */
4114         reg = FDI_RX_IMR(pipe);
4115         temp = I915_READ(reg);
4116         temp &= ~FDI_RX_SYMBOL_LOCK;
4117         temp &= ~FDI_RX_BIT_LOCK;
4118         I915_WRITE(reg, temp);
4119
4120         POSTING_READ(reg);
4121         udelay(150);
4122
4123         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4124                       I915_READ(FDI_RX_IIR(pipe)));
4125
4126         /* Try each vswing and preemphasis setting twice before moving on */
4127         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4128                 /* disable first in case we need to retry */
4129                 reg = FDI_TX_CTL(pipe);
4130                 temp = I915_READ(reg);
4131                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4132                 temp &= ~FDI_TX_ENABLE;
4133                 I915_WRITE(reg, temp);
4134
4135                 reg = FDI_RX_CTL(pipe);
4136                 temp = I915_READ(reg);
4137                 temp &= ~FDI_LINK_TRAIN_AUTO;
4138                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4139                 temp &= ~FDI_RX_ENABLE;
4140                 I915_WRITE(reg, temp);
4141
4142                 /* enable CPU FDI TX and PCH FDI RX */
4143                 reg = FDI_TX_CTL(pipe);
4144                 temp = I915_READ(reg);
4145                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4146                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4147                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4148                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4149                 temp |= snb_b_fdi_train_param[j/2];
4150                 temp |= FDI_COMPOSITE_SYNC;
4151                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4152
4153                 I915_WRITE(FDI_RX_MISC(pipe),
4154                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4155
4156                 reg = FDI_RX_CTL(pipe);
4157                 temp = I915_READ(reg);
4158                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4159                 temp |= FDI_COMPOSITE_SYNC;
4160                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4161
4162                 POSTING_READ(reg);
4163                 udelay(1); /* should be 0.5us */
4164
4165                 for (i = 0; i < 4; i++) {
4166                         reg = FDI_RX_IIR(pipe);
4167                         temp = I915_READ(reg);
4168                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4169
4170                         if (temp & FDI_RX_BIT_LOCK ||
4171                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4172                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4173                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4174                                               i);
4175                                 break;
4176                         }
4177                         udelay(1); /* should be 0.5us */
4178                 }
4179                 if (i == 4) {
4180                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4181                         continue;
4182                 }
4183
4184                 /* Train 2 */
4185                 reg = FDI_TX_CTL(pipe);
4186                 temp = I915_READ(reg);
4187                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4188                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4189                 I915_WRITE(reg, temp);
4190
4191                 reg = FDI_RX_CTL(pipe);
4192                 temp = I915_READ(reg);
4193                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4194                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4195                 I915_WRITE(reg, temp);
4196
4197                 POSTING_READ(reg);
4198                 udelay(2); /* should be 1.5us */
4199
4200                 for (i = 0; i < 4; i++) {
4201                         reg = FDI_RX_IIR(pipe);
4202                         temp = I915_READ(reg);
4203                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4204
4205                         if (temp & FDI_RX_SYMBOL_LOCK ||
4206                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4207                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4208                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4209                                               i);
4210                                 goto train_done;
4211                         }
4212                         udelay(2); /* should be 1.5us */
4213                 }
4214                 if (i == 4)
4215                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4216         }
4217
4218 train_done:
4219         DRM_DEBUG_KMS("FDI train done.\n");
4220 }
4221
4222 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4223 {
4224         struct drm_device *dev = intel_crtc->base.dev;
4225         struct drm_i915_private *dev_priv = to_i915(dev);
4226         int pipe = intel_crtc->pipe;
4227         i915_reg_t reg;
4228         u32 temp;
4229
4230         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4231         reg = FDI_RX_CTL(pipe);
4232         temp = I915_READ(reg);
4233         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4234         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4235         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4236         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4237
4238         POSTING_READ(reg);
4239         udelay(200);
4240
4241         /* Switch from Rawclk to PCDclk */
4242         temp = I915_READ(reg);
4243         I915_WRITE(reg, temp | FDI_PCDCLK);
4244
4245         POSTING_READ(reg);
4246         udelay(200);
4247
4248         /* Enable CPU FDI TX PLL, always on for Ironlake */
4249         reg = FDI_TX_CTL(pipe);
4250         temp = I915_READ(reg);
4251         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4252                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4253
4254                 POSTING_READ(reg);
4255                 udelay(100);
4256         }
4257 }
4258
4259 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4260 {
4261         struct drm_device *dev = intel_crtc->base.dev;
4262         struct drm_i915_private *dev_priv = to_i915(dev);
4263         int pipe = intel_crtc->pipe;
4264         i915_reg_t reg;
4265         u32 temp;
4266
4267         /* Switch from PCDclk to Rawclk */
4268         reg = FDI_RX_CTL(pipe);
4269         temp = I915_READ(reg);
4270         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4271
4272         /* Disable CPU FDI TX PLL */
4273         reg = FDI_TX_CTL(pipe);
4274         temp = I915_READ(reg);
4275         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4276
4277         POSTING_READ(reg);
4278         udelay(100);
4279
4280         reg = FDI_RX_CTL(pipe);
4281         temp = I915_READ(reg);
4282         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4283
4284         /* Wait for the clocks to turn off. */
4285         POSTING_READ(reg);
4286         udelay(100);
4287 }
4288
4289 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4290 {
4291         struct drm_device *dev = crtc->dev;
4292         struct drm_i915_private *dev_priv = to_i915(dev);
4293         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4294         int pipe = intel_crtc->pipe;
4295         i915_reg_t reg;
4296         u32 temp;
4297
4298         /* disable CPU FDI tx and PCH FDI rx */
4299         reg = FDI_TX_CTL(pipe);
4300         temp = I915_READ(reg);
4301         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4302         POSTING_READ(reg);
4303
4304         reg = FDI_RX_CTL(pipe);
4305         temp = I915_READ(reg);
4306         temp &= ~(0x7 << 16);
4307         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4308         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4309
4310         POSTING_READ(reg);
4311         udelay(100);
4312
4313         /* Ironlake workaround, disable clock pointer after downing FDI */
4314         if (HAS_PCH_IBX(dev_priv))
4315                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4316
4317         /* still set train pattern 1 */
4318         reg = FDI_TX_CTL(pipe);
4319         temp = I915_READ(reg);
4320         temp &= ~FDI_LINK_TRAIN_NONE;
4321         temp |= FDI_LINK_TRAIN_PATTERN_1;
4322         I915_WRITE(reg, temp);
4323
4324         reg = FDI_RX_CTL(pipe);
4325         temp = I915_READ(reg);
4326         if (HAS_PCH_CPT(dev_priv)) {
4327                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4328                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4329         } else {
4330                 temp &= ~FDI_LINK_TRAIN_NONE;
4331                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4332         }
4333         /* BPC in FDI rx is consistent with that in PIPECONF */
4334         temp &= ~(0x07 << 16);
4335         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4336         I915_WRITE(reg, temp);
4337
4338         POSTING_READ(reg);
4339         udelay(100);
4340 }
4341
4342 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4343 {
4344         struct drm_crtc *crtc;
4345         bool cleanup_done;
4346
4347         drm_for_each_crtc(crtc, &dev_priv->drm) {
4348                 struct drm_crtc_commit *commit;
4349                 spin_lock(&crtc->commit_lock);
4350                 commit = list_first_entry_or_null(&crtc->commit_list,
4351                                                   struct drm_crtc_commit, commit_entry);
4352                 cleanup_done = commit ?
4353                         try_wait_for_completion(&commit->cleanup_done) : true;
4354                 spin_unlock(&crtc->commit_lock);
4355
4356                 if (cleanup_done)
4357                         continue;
4358
4359                 drm_crtc_wait_one_vblank(crtc);
4360
4361                 return true;
4362         }
4363
4364         return false;
4365 }
4366
4367 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4368 {
4369         u32 temp;
4370
4371         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4372
4373         mutex_lock(&dev_priv->sb_lock);
4374
4375         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4376         temp |= SBI_SSCCTL_DISABLE;
4377         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4378
4379         mutex_unlock(&dev_priv->sb_lock);
4380 }
4381
4382 /* Program iCLKIP clock to the desired frequency */
4383 static void lpt_program_iclkip(struct intel_crtc *crtc)
4384 {
4385         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4386         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4387         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4388         u32 temp;
4389
4390         lpt_disable_iclkip(dev_priv);
4391
4392         /* The iCLK virtual clock root frequency is in MHz,
4393          * but the adjusted_mode->crtc_clock in in KHz. To get the
4394          * divisors, it is necessary to divide one by another, so we
4395          * convert the virtual clock precision to KHz here for higher
4396          * precision.
4397          */
4398         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4399                 u32 iclk_virtual_root_freq = 172800 * 1000;
4400                 u32 iclk_pi_range = 64;
4401                 u32 desired_divisor;
4402
4403                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4404                                                     clock << auxdiv);
4405                 divsel = (desired_divisor / iclk_pi_range) - 2;
4406                 phaseinc = desired_divisor % iclk_pi_range;
4407
4408                 /*
4409                  * Near 20MHz is a corner case which is
4410                  * out of range for the 7-bit divisor
4411                  */
4412                 if (divsel <= 0x7f)
4413                         break;
4414         }
4415
4416         /* This should not happen with any sane values */
4417         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4418                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4419         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4420                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4421
4422         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4423                         clock,
4424                         auxdiv,
4425                         divsel,
4426                         phasedir,
4427                         phaseinc);
4428
4429         mutex_lock(&dev_priv->sb_lock);
4430
4431         /* Program SSCDIVINTPHASE6 */
4432         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4433         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4434         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4435         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4436         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4437         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4438         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4439         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4440
4441         /* Program SSCAUXDIV */
4442         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4443         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4444         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4445         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4446
4447         /* Enable modulator and associated divider */
4448         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4449         temp &= ~SBI_SSCCTL_DISABLE;
4450         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4451
4452         mutex_unlock(&dev_priv->sb_lock);
4453
4454         /* Wait for initialization time */
4455         udelay(24);
4456
4457         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4458 }
4459
4460 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4461 {
4462         u32 divsel, phaseinc, auxdiv;
4463         u32 iclk_virtual_root_freq = 172800 * 1000;
4464         u32 iclk_pi_range = 64;
4465         u32 desired_divisor;
4466         u32 temp;
4467
4468         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4469                 return 0;
4470
4471         mutex_lock(&dev_priv->sb_lock);
4472
4473         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4474         if (temp & SBI_SSCCTL_DISABLE) {
4475                 mutex_unlock(&dev_priv->sb_lock);
4476                 return 0;
4477         }
4478
4479         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4480         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4481                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4482         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4483                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4484
4485         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4486         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4487                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4488
4489         mutex_unlock(&dev_priv->sb_lock);
4490
4491         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4492
4493         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4494                                  desired_divisor << auxdiv);
4495 }
4496
4497 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4498                                                 enum pipe pch_transcoder)
4499 {
4500         struct drm_device *dev = crtc->base.dev;
4501         struct drm_i915_private *dev_priv = to_i915(dev);
4502         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4503
4504         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4505                    I915_READ(HTOTAL(cpu_transcoder)));
4506         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4507                    I915_READ(HBLANK(cpu_transcoder)));
4508         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4509                    I915_READ(HSYNC(cpu_transcoder)));
4510
4511         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4512                    I915_READ(VTOTAL(cpu_transcoder)));
4513         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4514                    I915_READ(VBLANK(cpu_transcoder)));
4515         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4516                    I915_READ(VSYNC(cpu_transcoder)));
4517         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4518                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4519 }
4520
4521 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4522 {
4523         struct drm_i915_private *dev_priv = to_i915(dev);
4524         uint32_t temp;
4525
4526         temp = I915_READ(SOUTH_CHICKEN1);
4527         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4528                 return;
4529
4530         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4531         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4532
4533         temp &= ~FDI_BC_BIFURCATION_SELECT;
4534         if (enable)
4535                 temp |= FDI_BC_BIFURCATION_SELECT;
4536
4537         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4538         I915_WRITE(SOUTH_CHICKEN1, temp);
4539         POSTING_READ(SOUTH_CHICKEN1);
4540 }
4541
4542 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4543 {
4544         struct drm_device *dev = intel_crtc->base.dev;
4545
4546         switch (intel_crtc->pipe) {
4547         case PIPE_A:
4548                 break;
4549         case PIPE_B:
4550                 if (intel_crtc->config->fdi_lanes > 2)
4551                         cpt_set_fdi_bc_bifurcation(dev, false);
4552                 else
4553                         cpt_set_fdi_bc_bifurcation(dev, true);
4554
4555                 break;
4556         case PIPE_C:
4557                 cpt_set_fdi_bc_bifurcation(dev, true);
4558
4559                 break;
4560         default:
4561                 BUG();
4562         }
4563 }
4564
4565 /* Return which DP Port should be selected for Transcoder DP control */
4566 static enum port
4567 intel_trans_dp_port_sel(struct intel_crtc *crtc)
4568 {
4569         struct drm_device *dev = crtc->base.dev;
4570         struct intel_encoder *encoder;
4571
4572         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
4573                 if (encoder->type == INTEL_OUTPUT_DP ||
4574                     encoder->type == INTEL_OUTPUT_EDP)
4575                         return enc_to_dig_port(&encoder->base)->port;
4576         }
4577
4578         return -1;
4579 }
4580
4581 /*
4582  * Enable PCH resources required for PCH ports:
4583  *   - PCH PLLs
4584  *   - FDI training & RX/TX
4585  *   - update transcoder timings
4586  *   - DP transcoding bits
4587  *   - transcoder
4588  */
4589 static void ironlake_pch_enable(const struct intel_crtc_state *crtc_state)
4590 {
4591         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4592         struct drm_device *dev = crtc->base.dev;
4593         struct drm_i915_private *dev_priv = to_i915(dev);
4594         int pipe = crtc->pipe;
4595         u32 temp;
4596
4597         assert_pch_transcoder_disabled(dev_priv, pipe);
4598
4599         if (IS_IVYBRIDGE(dev_priv))
4600                 ivybridge_update_fdi_bc_bifurcation(crtc);
4601
4602         /* Write the TU size bits before fdi link training, so that error
4603          * detection works. */
4604         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4605                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4606
4607         /* For PCH output, training FDI link */
4608         dev_priv->display.fdi_link_train(crtc, crtc_state);
4609
4610         /* We need to program the right clock selection before writing the pixel
4611          * mutliplier into the DPLL. */
4612         if (HAS_PCH_CPT(dev_priv)) {
4613                 u32 sel;
4614
4615                 temp = I915_READ(PCH_DPLL_SEL);
4616                 temp |= TRANS_DPLL_ENABLE(pipe);
4617                 sel = TRANS_DPLLB_SEL(pipe);
4618                 if (crtc_state->shared_dpll ==
4619                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4620                         temp |= sel;
4621                 else
4622                         temp &= ~sel;
4623                 I915_WRITE(PCH_DPLL_SEL, temp);
4624         }
4625
4626         /* XXX: pch pll's can be enabled any time before we enable the PCH
4627          * transcoder, and we actually should do this to not upset any PCH
4628          * transcoder that already use the clock when we share it.
4629          *
4630          * Note that enable_shared_dpll tries to do the right thing, but
4631          * get_shared_dpll unconditionally resets the pll - we need that to have
4632          * the right LVDS enable sequence. */
4633         intel_enable_shared_dpll(crtc);
4634
4635         /* set transcoder timing, panel must allow it */
4636         assert_panel_unlocked(dev_priv, pipe);
4637         ironlake_pch_transcoder_set_timings(crtc, pipe);
4638
4639         intel_fdi_normal_train(crtc);
4640
4641         /* For PCH DP, enable TRANS_DP_CTL */
4642         if (HAS_PCH_CPT(dev_priv) &&
4643             intel_crtc_has_dp_encoder(crtc_state)) {
4644                 const struct drm_display_mode *adjusted_mode =
4645                         &crtc_state->base.adjusted_mode;
4646                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4647                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4648                 temp = I915_READ(reg);
4649                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4650                           TRANS_DP_SYNC_MASK |
4651                           TRANS_DP_BPC_MASK);
4652                 temp |= TRANS_DP_OUTPUT_ENABLE;
4653                 temp |= bpc << 9; /* same format but at 11:9 */
4654
4655                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4656                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4657                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4658                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4659
4660                 switch (intel_trans_dp_port_sel(crtc)) {
4661                 case PORT_B:
4662                         temp |= TRANS_DP_PORT_SEL_B;
4663                         break;
4664                 case PORT_C:
4665                         temp |= TRANS_DP_PORT_SEL_C;
4666                         break;
4667                 case PORT_D:
4668                         temp |= TRANS_DP_PORT_SEL_D;
4669                         break;
4670                 default:
4671                         BUG();
4672                 }
4673
4674                 I915_WRITE(reg, temp);
4675         }
4676
4677         ironlake_enable_pch_transcoder(dev_priv, pipe);
4678 }
4679
4680 static void lpt_pch_enable(const struct intel_crtc_state *crtc_state)
4681 {
4682         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4683         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4684         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4685
4686         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4687
4688         lpt_program_iclkip(crtc);
4689
4690         /* Set transcoder timing. */
4691         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4692
4693         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4694 }
4695
4696 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4697 {
4698         struct drm_i915_private *dev_priv = to_i915(dev);
4699         i915_reg_t dslreg = PIPEDSL(pipe);
4700         u32 temp;
4701
4702         temp = I915_READ(dslreg);
4703         udelay(500);
4704         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4705                 if (wait_for(I915_READ(dslreg) != temp, 5))
4706                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4707         }
4708 }
4709
4710 static int
4711 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4712                   unsigned int scaler_user, int *scaler_id,
4713                   int src_w, int src_h, int dst_w, int dst_h)
4714 {
4715         struct intel_crtc_scaler_state *scaler_state =
4716                 &crtc_state->scaler_state;
4717         struct intel_crtc *intel_crtc =
4718                 to_intel_crtc(crtc_state->base.crtc);
4719         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4720         const struct drm_display_mode *adjusted_mode =
4721                 &crtc_state->base.adjusted_mode;
4722         int need_scaling;
4723
4724         /*
4725          * Src coordinates are already rotated by 270 degrees for
4726          * the 90/270 degree plane rotation cases (to match the
4727          * GTT mapping), hence no need to account for rotation here.
4728          */
4729         need_scaling = src_w != dst_w || src_h != dst_h;
4730
4731         if (crtc_state->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4732                 need_scaling = true;
4733
4734         /*
4735          * Scaling/fitting not supported in IF-ID mode in GEN9+
4736          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4737          * Once NV12 is enabled, handle it here while allocating scaler
4738          * for NV12.
4739          */
4740         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4741             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4742                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4743                 return -EINVAL;
4744         }
4745
4746         /*
4747          * if plane is being disabled or scaler is no more required or force detach
4748          *  - free scaler binded to this plane/crtc
4749          *  - in order to do this, update crtc->scaler_usage
4750          *
4751          * Here scaler state in crtc_state is set free so that
4752          * scaler can be assigned to other user. Actual register
4753          * update to free the scaler is done in plane/panel-fit programming.
4754          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4755          */
4756         if (force_detach || !need_scaling) {
4757                 if (*scaler_id >= 0) {
4758                         scaler_state->scaler_users &= ~(1 << scaler_user);
4759                         scaler_state->scalers[*scaler_id].in_use = 0;
4760
4761                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4762                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4763                                 intel_crtc->pipe, scaler_user, *scaler_id,
4764                                 scaler_state->scaler_users);
4765                         *scaler_id = -1;
4766                 }
4767                 return 0;
4768         }
4769
4770         /* range checks */
4771         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4772                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4773
4774                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4775                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4776                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4777                         "size is out of scaler range\n",
4778                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4779                 return -EINVAL;
4780         }
4781
4782         /* mark this plane as a scaler user in crtc_state */
4783         scaler_state->scaler_users |= (1 << scaler_user);
4784         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4785                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4786                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4787                 scaler_state->scaler_users);
4788
4789         return 0;
4790 }
4791
4792 /**
4793  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4794  *
4795  * @state: crtc's scaler state
4796  *
4797  * Return
4798  *     0 - scaler_usage updated successfully
4799  *    error - requested scaling cannot be supported or other error condition
4800  */
4801 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4802 {
4803         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4804
4805         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4806                 &state->scaler_state.scaler_id,
4807                 state->pipe_src_w, state->pipe_src_h,
4808                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4809 }
4810
4811 /**
4812  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4813  *
4814  * @state: crtc's scaler state
4815  * @plane_state: atomic plane state to update
4816  *
4817  * Return
4818  *     0 - scaler_usage updated successfully
4819  *    error - requested scaling cannot be supported or other error condition
4820  */
4821 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4822                                    struct intel_plane_state *plane_state)
4823 {
4824
4825         struct intel_plane *intel_plane =
4826                 to_intel_plane(plane_state->base.plane);
4827         struct drm_framebuffer *fb = plane_state->base.fb;
4828         int ret;
4829
4830         bool force_detach = !fb || !plane_state->base.visible;
4831
4832         ret = skl_update_scaler(crtc_state, force_detach,
4833                                 drm_plane_index(&intel_plane->base),
4834                                 &plane_state->scaler_id,
4835                                 drm_rect_width(&plane_state->base.src) >> 16,
4836                                 drm_rect_height(&plane_state->base.src) >> 16,
4837                                 drm_rect_width(&plane_state->base.dst),
4838                                 drm_rect_height(&plane_state->base.dst));
4839
4840         if (ret || plane_state->scaler_id < 0)
4841                 return ret;
4842
4843         /* check colorkey */
4844         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4845                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4846                               intel_plane->base.base.id,
4847                               intel_plane->base.name);
4848                 return -EINVAL;
4849         }
4850
4851         /* Check src format */
4852         switch (fb->format->format) {
4853         case DRM_FORMAT_RGB565:
4854         case DRM_FORMAT_XBGR8888:
4855         case DRM_FORMAT_XRGB8888:
4856         case DRM_FORMAT_ABGR8888:
4857         case DRM_FORMAT_ARGB8888:
4858         case DRM_FORMAT_XRGB2101010:
4859         case DRM_FORMAT_XBGR2101010:
4860         case DRM_FORMAT_YUYV:
4861         case DRM_FORMAT_YVYU:
4862         case DRM_FORMAT_UYVY:
4863         case DRM_FORMAT_VYUY:
4864                 break;
4865         default:
4866                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4867                               intel_plane->base.base.id, intel_plane->base.name,
4868                               fb->base.id, fb->format->format);
4869                 return -EINVAL;
4870         }
4871
4872         return 0;
4873 }
4874
4875 static void skylake_scaler_disable(struct intel_crtc *crtc)
4876 {
4877         int i;
4878
4879         for (i = 0; i < crtc->num_scalers; i++)
4880                 skl_detach_scaler(crtc, i);
4881 }
4882
4883 static void skylake_pfit_enable(struct intel_crtc *crtc)
4884 {
4885         struct drm_device *dev = crtc->base.dev;
4886         struct drm_i915_private *dev_priv = to_i915(dev);
4887         int pipe = crtc->pipe;
4888         struct intel_crtc_scaler_state *scaler_state =
4889                 &crtc->config->scaler_state;
4890
4891         if (crtc->config->pch_pfit.enabled) {
4892                 int id;
4893
4894                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4895                         return;
4896
4897                 id = scaler_state->scaler_id;
4898                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4899                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4900                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4901                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4902         }
4903 }
4904
4905 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4906 {
4907         struct drm_device *dev = crtc->base.dev;
4908         struct drm_i915_private *dev_priv = to_i915(dev);
4909         int pipe = crtc->pipe;
4910
4911         if (crtc->config->pch_pfit.enabled) {
4912                 /* Force use of hard-coded filter coefficients
4913                  * as some pre-programmed values are broken,
4914                  * e.g. x201.
4915                  */
4916                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4917                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4918                                                  PF_PIPE_SEL_IVB(pipe));
4919                 else
4920                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4921                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4922                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4923         }
4924 }
4925
4926 void hsw_enable_ips(struct intel_crtc *crtc)
4927 {
4928         struct drm_device *dev = crtc->base.dev;
4929         struct drm_i915_private *dev_priv = to_i915(dev);
4930
4931         if (!crtc->config->ips_enabled)
4932                 return;
4933
4934         /*
4935          * We can only enable IPS after we enable a plane and wait for a vblank
4936          * This function is called from post_plane_update, which is run after
4937          * a vblank wait.
4938          */
4939
4940         assert_plane_enabled(to_intel_plane(crtc->base.primary));
4941
4942         if (IS_BROADWELL(dev_priv)) {
4943                 mutex_lock(&dev_priv->rps.hw_lock);
4944                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0xc0000000));
4945                 mutex_unlock(&dev_priv->rps.hw_lock);
4946                 /* Quoting Art Runyan: "its not safe to expect any particular
4947                  * value in IPS_CTL bit 31 after enabling IPS through the
4948                  * mailbox." Moreover, the mailbox may return a bogus state,
4949                  * so we need to just enable it and continue on.
4950                  */
4951         } else {
4952                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4953                 /* The bit only becomes 1 in the next vblank, so this wait here
4954                  * is essentially intel_wait_for_vblank. If we don't have this
4955                  * and don't wait for vblanks until the end of crtc_enable, then
4956                  * the HW state readout code will complain that the expected
4957                  * IPS_CTL value is not the one we read. */
4958                 if (intel_wait_for_register(dev_priv,
4959                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4960                                             50))
4961                         DRM_ERROR("Timed out waiting for IPS enable\n");
4962         }
4963 }
4964
4965 void hsw_disable_ips(struct intel_crtc *crtc)
4966 {
4967         struct drm_device *dev = crtc->base.dev;
4968         struct drm_i915_private *dev_priv = to_i915(dev);
4969
4970         if (!crtc->config->ips_enabled)
4971                 return;
4972
4973         assert_plane_enabled(to_intel_plane(crtc->base.primary));
4974
4975         if (IS_BROADWELL(dev_priv)) {
4976                 mutex_lock(&dev_priv->rps.hw_lock);
4977                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4978                 mutex_unlock(&dev_priv->rps.hw_lock);
4979                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4980                 if (intel_wait_for_register(dev_priv,
4981                                             IPS_CTL, IPS_ENABLE, 0,
4982                                             42))
4983                         DRM_ERROR("Timed out waiting for IPS disable\n");
4984         } else {
4985                 I915_WRITE(IPS_CTL, 0);
4986                 POSTING_READ(IPS_CTL);
4987         }
4988
4989         /* We need to wait for a vblank before we can disable the plane. */
4990         intel_wait_for_vblank(dev_priv, crtc->pipe);
4991 }
4992
4993 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4994 {
4995         if (intel_crtc->overlay) {
4996                 struct drm_device *dev = intel_crtc->base.dev;
4997
4998                 mutex_lock(&dev->struct_mutex);
4999                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5000                 mutex_unlock(&dev->struct_mutex);
5001         }
5002
5003         /* Let userspace switch the overlay on again. In most cases userspace
5004          * has to recompute where to put it anyway.
5005          */
5006 }
5007
5008 /**
5009  * intel_post_enable_primary - Perform operations after enabling primary plane
5010  * @crtc: the CRTC whose primary plane was just enabled
5011  *
5012  * Performs potentially sleeping operations that must be done after the primary
5013  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5014  * called due to an explicit primary plane update, or due to an implicit
5015  * re-enable that is caused when a sprite plane is updated to no longer
5016  * completely hide the primary plane.
5017  */
5018 static void
5019 intel_post_enable_primary(struct drm_crtc *crtc)
5020 {
5021         struct drm_device *dev = crtc->dev;
5022         struct drm_i915_private *dev_priv = to_i915(dev);
5023         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5024         int pipe = intel_crtc->pipe;
5025
5026         /*
5027          * FIXME IPS should be fine as long as one plane is
5028          * enabled, but in practice it seems to have problems
5029          * when going from primary only to sprite only and vice
5030          * versa.
5031          */
5032         hsw_enable_ips(intel_crtc);
5033
5034         /*
5035          * Gen2 reports pipe underruns whenever all planes are disabled.
5036          * So don't enable underrun reporting before at least some planes
5037          * are enabled.
5038          * FIXME: Need to fix the logic to work when we turn off all planes
5039          * but leave the pipe running.
5040          */
5041         if (IS_GEN2(dev_priv))
5042                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5043
5044         /* Underruns don't always raise interrupts, so check manually. */
5045         intel_check_cpu_fifo_underruns(dev_priv);
5046         intel_check_pch_fifo_underruns(dev_priv);
5047 }
5048
5049 /* FIXME move all this to pre_plane_update() with proper state tracking */
5050 static void
5051 intel_pre_disable_primary(struct drm_crtc *crtc)
5052 {
5053         struct drm_device *dev = crtc->dev;
5054         struct drm_i915_private *dev_priv = to_i915(dev);
5055         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5056         int pipe = intel_crtc->pipe;
5057
5058         /*
5059          * Gen2 reports pipe underruns whenever all planes are disabled.
5060          * So diasble underrun reporting before all the planes get disabled.
5061          * FIXME: Need to fix the logic to work when we turn off all planes
5062          * but leave the pipe running.
5063          */
5064         if (IS_GEN2(dev_priv))
5065                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5066
5067         /*
5068          * FIXME IPS should be fine as long as one plane is
5069          * enabled, but in practice it seems to have problems
5070          * when going from primary only to sprite only and vice
5071          * versa.
5072          */
5073         hsw_disable_ips(intel_crtc);
5074 }
5075
5076 /* FIXME get rid of this and use pre_plane_update */
5077 static void
5078 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5079 {
5080         struct drm_device *dev = crtc->dev;
5081         struct drm_i915_private *dev_priv = to_i915(dev);
5082         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5083         int pipe = intel_crtc->pipe;
5084
5085         intel_pre_disable_primary(crtc);
5086
5087         /*
5088          * Vblank time updates from the shadow to live plane control register
5089          * are blocked if the memory self-refresh mode is active at that
5090          * moment. So to make sure the plane gets truly disabled, disable
5091          * first the self-refresh mode. The self-refresh enable bit in turn
5092          * will be checked/applied by the HW only at the next frame start
5093          * event which is after the vblank start event, so we need to have a
5094          * wait-for-vblank between disabling the plane and the pipe.
5095          */
5096         if (HAS_GMCH_DISPLAY(dev_priv) &&
5097             intel_set_memory_cxsr(dev_priv, false))
5098                 intel_wait_for_vblank(dev_priv, pipe);
5099 }
5100
5101 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5102 {
5103         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5104         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5105         struct intel_crtc_state *pipe_config =
5106                 to_intel_crtc_state(crtc->base.state);
5107         struct drm_plane *primary = crtc->base.primary;
5108         struct drm_plane_state *old_pri_state =
5109                 drm_atomic_get_existing_plane_state(old_state, primary);
5110
5111         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5112
5113         if (pipe_config->update_wm_post && pipe_config->base.active)
5114                 intel_update_watermarks(crtc);
5115
5116         if (old_pri_state) {
5117                 struct intel_plane_state *primary_state =
5118                         to_intel_plane_state(primary->state);
5119                 struct intel_plane_state *old_primary_state =
5120                         to_intel_plane_state(old_pri_state);
5121
5122                 intel_fbc_post_update(crtc);
5123
5124                 if (primary_state->base.visible &&
5125                     (needs_modeset(&pipe_config->base) ||
5126                      !old_primary_state->base.visible))
5127                         intel_post_enable_primary(&crtc->base);
5128         }
5129 }
5130
5131 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5132                                    struct intel_crtc_state *pipe_config)
5133 {
5134         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5135         struct drm_device *dev = crtc->base.dev;
5136         struct drm_i915_private *dev_priv = to_i915(dev);
5137         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5138         struct drm_plane *primary = crtc->base.primary;
5139         struct drm_plane_state *old_pri_state =
5140                 drm_atomic_get_existing_plane_state(old_state, primary);
5141         bool modeset = needs_modeset(&pipe_config->base);
5142         struct intel_atomic_state *old_intel_state =
5143                 to_intel_atomic_state(old_state);
5144
5145         if (old_pri_state) {
5146                 struct intel_plane_state *primary_state =
5147                         to_intel_plane_state(primary->state);
5148                 struct intel_plane_state *old_primary_state =
5149                         to_intel_plane_state(old_pri_state);
5150
5151                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5152
5153                 if (old_primary_state->base.visible &&
5154                     (modeset || !primary_state->base.visible))
5155                         intel_pre_disable_primary(&crtc->base);
5156         }
5157
5158         /*
5159          * Vblank time updates from the shadow to live plane control register
5160          * are blocked if the memory self-refresh mode is active at that
5161          * moment. So to make sure the plane gets truly disabled, disable
5162          * first the self-refresh mode. The self-refresh enable bit in turn
5163          * will be checked/applied by the HW only at the next frame start
5164          * event which is after the vblank start event, so we need to have a
5165          * wait-for-vblank between disabling the plane and the pipe.
5166          */
5167         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5168             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5169                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5170
5171         /*
5172          * IVB workaround: must disable low power watermarks for at least
5173          * one frame before enabling scaling.  LP watermarks can be re-enabled
5174          * when scaling is disabled.
5175          *
5176          * WaCxSRDisabledForSpriteScaling:ivb
5177          */
5178         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5179                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5180
5181         /*
5182          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5183          * watermark programming here.
5184          */
5185         if (needs_modeset(&pipe_config->base))
5186                 return;
5187
5188         /*
5189          * For platforms that support atomic watermarks, program the
5190          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5191          * will be the intermediate values that are safe for both pre- and
5192          * post- vblank; when vblank happens, the 'active' values will be set
5193          * to the final 'target' values and we'll do this again to get the
5194          * optimal watermarks.  For gen9+ platforms, the values we program here
5195          * will be the final target values which will get automatically latched
5196          * at vblank time; no further programming will be necessary.
5197          *
5198          * If a platform hasn't been transitioned to atomic watermarks yet,
5199          * we'll continue to update watermarks the old way, if flags tell
5200          * us to.
5201          */
5202         if (dev_priv->display.initial_watermarks != NULL)
5203                 dev_priv->display.initial_watermarks(old_intel_state,
5204                                                      pipe_config);
5205         else if (pipe_config->update_wm_pre)
5206                 intel_update_watermarks(crtc);
5207 }
5208
5209 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5210 {
5211         struct drm_device *dev = crtc->dev;
5212         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5213         struct drm_plane *p;
5214         int pipe = intel_crtc->pipe;
5215
5216         intel_crtc_dpms_overlay_disable(intel_crtc);
5217
5218         drm_for_each_plane_mask(p, dev, plane_mask)
5219                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5220
5221         /*
5222          * FIXME: Once we grow proper nuclear flip support out of this we need
5223          * to compute the mask of flip planes precisely. For the time being
5224          * consider this a flip to a NULL plane.
5225          */
5226         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5227 }
5228
5229 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5230                                           struct intel_crtc_state *crtc_state,
5231                                           struct drm_atomic_state *old_state)
5232 {
5233         struct drm_connector_state *conn_state;
5234         struct drm_connector *conn;
5235         int i;
5236
5237         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5238                 struct intel_encoder *encoder =
5239                         to_intel_encoder(conn_state->best_encoder);
5240
5241                 if (conn_state->crtc != crtc)
5242                         continue;
5243
5244                 if (encoder->pre_pll_enable)
5245                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5246         }
5247 }
5248
5249 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5250                                       struct intel_crtc_state *crtc_state,
5251                                       struct drm_atomic_state *old_state)
5252 {
5253         struct drm_connector_state *conn_state;
5254         struct drm_connector *conn;
5255         int i;
5256
5257         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5258                 struct intel_encoder *encoder =
5259                         to_intel_encoder(conn_state->best_encoder);
5260
5261                 if (conn_state->crtc != crtc)
5262                         continue;
5263
5264                 if (encoder->pre_enable)
5265                         encoder->pre_enable(encoder, crtc_state, conn_state);
5266         }
5267 }
5268
5269 static void intel_encoders_enable(struct drm_crtc *crtc,
5270                                   struct intel_crtc_state *crtc_state,
5271                                   struct drm_atomic_state *old_state)
5272 {
5273         struct drm_connector_state *conn_state;
5274         struct drm_connector *conn;
5275         int i;
5276
5277         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5278                 struct intel_encoder *encoder =
5279                         to_intel_encoder(conn_state->best_encoder);
5280
5281                 if (conn_state->crtc != crtc)
5282                         continue;
5283
5284                 encoder->enable(encoder, crtc_state, conn_state);
5285                 intel_opregion_notify_encoder(encoder, true);
5286         }
5287 }
5288
5289 static void intel_encoders_disable(struct drm_crtc *crtc,
5290                                    struct intel_crtc_state *old_crtc_state,
5291                                    struct drm_atomic_state *old_state)
5292 {
5293         struct drm_connector_state *old_conn_state;
5294         struct drm_connector *conn;
5295         int i;
5296
5297         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5298                 struct intel_encoder *encoder =
5299                         to_intel_encoder(old_conn_state->best_encoder);
5300
5301                 if (old_conn_state->crtc != crtc)
5302                         continue;
5303
5304                 intel_opregion_notify_encoder(encoder, false);
5305                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5306         }
5307 }
5308
5309 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5310                                         struct intel_crtc_state *old_crtc_state,
5311                                         struct drm_atomic_state *old_state)
5312 {
5313         struct drm_connector_state *old_conn_state;
5314         struct drm_connector *conn;
5315         int i;
5316
5317         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5318                 struct intel_encoder *encoder =
5319                         to_intel_encoder(old_conn_state->best_encoder);
5320
5321                 if (old_conn_state->crtc != crtc)
5322                         continue;
5323
5324                 if (encoder->post_disable)
5325                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5326         }
5327 }
5328
5329 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5330                                             struct intel_crtc_state *old_crtc_state,
5331                                             struct drm_atomic_state *old_state)
5332 {
5333         struct drm_connector_state *old_conn_state;
5334         struct drm_connector *conn;
5335         int i;
5336
5337         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5338                 struct intel_encoder *encoder =
5339                         to_intel_encoder(old_conn_state->best_encoder);
5340
5341                 if (old_conn_state->crtc != crtc)
5342                         continue;
5343
5344                 if (encoder->post_pll_disable)
5345                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5346         }
5347 }
5348
5349 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5350                                  struct drm_atomic_state *old_state)
5351 {
5352         struct drm_crtc *crtc = pipe_config->base.crtc;
5353         struct drm_device *dev = crtc->dev;
5354         struct drm_i915_private *dev_priv = to_i915(dev);
5355         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5356         int pipe = intel_crtc->pipe;
5357         struct intel_atomic_state *old_intel_state =
5358                 to_intel_atomic_state(old_state);
5359
5360         if (WARN_ON(intel_crtc->active))
5361                 return;
5362
5363         /*
5364          * Sometimes spurious CPU pipe underruns happen during FDI
5365          * training, at least with VGA+HDMI cloning. Suppress them.
5366          *
5367          * On ILK we get an occasional spurious CPU pipe underruns
5368          * between eDP port A enable and vdd enable. Also PCH port
5369          * enable seems to result in the occasional CPU pipe underrun.
5370          *
5371          * Spurious PCH underruns also occur during PCH enabling.
5372          */
5373         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5374                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5375         if (intel_crtc->config->has_pch_encoder)
5376                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5377
5378         if (intel_crtc->config->has_pch_encoder)
5379                 intel_prepare_shared_dpll(intel_crtc);
5380
5381         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5382                 intel_dp_set_m_n(intel_crtc, M1_N1);
5383
5384         intel_set_pipe_timings(intel_crtc);
5385         intel_set_pipe_src_size(intel_crtc);
5386
5387         if (intel_crtc->config->has_pch_encoder) {
5388                 intel_cpu_transcoder_set_m_n(intel_crtc,
5389                                      &intel_crtc->config->fdi_m_n, NULL);
5390         }
5391
5392         ironlake_set_pipeconf(crtc);
5393
5394         intel_crtc->active = true;
5395
5396         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5397
5398         if (intel_crtc->config->has_pch_encoder) {
5399                 /* Note: FDI PLL enabling _must_ be done before we enable the
5400                  * cpu pipes, hence this is separate from all the other fdi/pch
5401                  * enabling. */
5402                 ironlake_fdi_pll_enable(intel_crtc);
5403         } else {
5404                 assert_fdi_tx_disabled(dev_priv, pipe);
5405                 assert_fdi_rx_disabled(dev_priv, pipe);
5406         }
5407
5408         ironlake_pfit_enable(intel_crtc);
5409
5410         /*
5411          * On ILK+ LUT must be loaded before the pipe is running but with
5412          * clocks enabled
5413          */
5414         intel_color_load_luts(&pipe_config->base);
5415
5416         if (dev_priv->display.initial_watermarks != NULL)
5417                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5418         intel_enable_pipe(intel_crtc);
5419
5420         if (intel_crtc->config->has_pch_encoder)
5421                 ironlake_pch_enable(pipe_config);
5422
5423         assert_vblank_disabled(crtc);
5424         drm_crtc_vblank_on(crtc);
5425
5426         intel_encoders_enable(crtc, pipe_config, old_state);
5427
5428         if (HAS_PCH_CPT(dev_priv))
5429                 cpt_verify_modeset(dev, intel_crtc->pipe);
5430
5431         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5432         if (intel_crtc->config->has_pch_encoder)
5433                 intel_wait_for_vblank(dev_priv, pipe);
5434         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5435         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5436 }
5437
5438 /* IPS only exists on ULT machines and is tied to pipe A. */
5439 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5440 {
5441         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5442 }
5443
5444 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5445                                 struct drm_atomic_state *old_state)
5446 {
5447         struct drm_crtc *crtc = pipe_config->base.crtc;
5448         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5449         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5450         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5451         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5452         struct intel_atomic_state *old_intel_state =
5453                 to_intel_atomic_state(old_state);
5454
5455         if (WARN_ON(intel_crtc->active))
5456                 return;
5457
5458         if (intel_crtc->config->has_pch_encoder)
5459                 intel_set_pch_fifo_underrun_reporting(dev_priv, PIPE_A, false);
5460
5461         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5462
5463         if (intel_crtc->config->shared_dpll)
5464                 intel_enable_shared_dpll(intel_crtc);
5465
5466         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5467                 intel_dp_set_m_n(intel_crtc, M1_N1);
5468
5469         if (!transcoder_is_dsi(cpu_transcoder))
5470                 intel_set_pipe_timings(intel_crtc);
5471
5472         intel_set_pipe_src_size(intel_crtc);
5473
5474         if (cpu_transcoder != TRANSCODER_EDP &&
5475             !transcoder_is_dsi(cpu_transcoder)) {
5476                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5477                            intel_crtc->config->pixel_multiplier - 1);
5478         }
5479
5480         if (intel_crtc->config->has_pch_encoder) {
5481                 intel_cpu_transcoder_set_m_n(intel_crtc,
5482                                      &intel_crtc->config->fdi_m_n, NULL);
5483         }
5484
5485         if (!transcoder_is_dsi(cpu_transcoder))
5486                 haswell_set_pipeconf(crtc);
5487
5488         haswell_set_pipemisc(crtc);
5489
5490         intel_color_set_csc(&pipe_config->base);
5491
5492         intel_crtc->active = true;
5493
5494         if (intel_crtc->config->has_pch_encoder)
5495                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5496         else
5497                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5498
5499         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5500
5501         if (intel_crtc->config->has_pch_encoder)
5502                 dev_priv->display.fdi_link_train(intel_crtc, pipe_config);
5503
5504         if (!transcoder_is_dsi(cpu_transcoder))
5505                 intel_ddi_enable_pipe_clock(pipe_config);
5506
5507         if (INTEL_GEN(dev_priv) >= 9)
5508                 skylake_pfit_enable(intel_crtc);
5509         else
5510                 ironlake_pfit_enable(intel_crtc);
5511
5512         /*
5513          * On ILK+ LUT must be loaded before the pipe is running but with
5514          * clocks enabled
5515          */
5516         intel_color_load_luts(&pipe_config->base);
5517
5518         intel_ddi_set_pipe_settings(pipe_config);
5519         if (!transcoder_is_dsi(cpu_transcoder))
5520                 intel_ddi_enable_transcoder_func(pipe_config);
5521
5522         if (dev_priv->display.initial_watermarks != NULL)
5523                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5524
5525         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5526         if (!transcoder_is_dsi(cpu_transcoder))
5527                 intel_enable_pipe(intel_crtc);
5528
5529         if (intel_crtc->config->has_pch_encoder)
5530                 lpt_pch_enable(pipe_config);
5531
5532         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5533                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5534
5535         assert_vblank_disabled(crtc);
5536         drm_crtc_vblank_on(crtc);
5537
5538         intel_encoders_enable(crtc, pipe_config, old_state);
5539
5540         if (intel_crtc->config->has_pch_encoder) {
5541                 intel_wait_for_vblank(dev_priv, pipe);
5542                 intel_wait_for_vblank(dev_priv, pipe);
5543                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5544                 intel_set_pch_fifo_underrun_reporting(dev_priv, PIPE_A, true);
5545         }
5546
5547         /* If we change the relative order between pipe/planes enabling, we need
5548          * to change the workaround. */
5549         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5550         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5551                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5552                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5553         }
5554 }
5555
5556 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5557 {
5558         struct drm_device *dev = crtc->base.dev;
5559         struct drm_i915_private *dev_priv = to_i915(dev);
5560         int pipe = crtc->pipe;
5561
5562         /* To avoid upsetting the power well on haswell only disable the pfit if
5563          * it's in use. The hw state code will make sure we get this right. */
5564         if (force || crtc->config->pch_pfit.enabled) {
5565                 I915_WRITE(PF_CTL(pipe), 0);
5566                 I915_WRITE(PF_WIN_POS(pipe), 0);
5567                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5568         }
5569 }
5570
5571 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5572                                   struct drm_atomic_state *old_state)
5573 {
5574         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5575         struct drm_device *dev = crtc->dev;
5576         struct drm_i915_private *dev_priv = to_i915(dev);
5577         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5578         int pipe = intel_crtc->pipe;
5579
5580         /*
5581          * Sometimes spurious CPU pipe underruns happen when the
5582          * pipe is already disabled, but FDI RX/TX is still enabled.
5583          * Happens at least with VGA+HDMI cloning. Suppress them.
5584          */
5585         if (intel_crtc->config->has_pch_encoder) {
5586                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5587                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5588         }
5589
5590         intel_encoders_disable(crtc, old_crtc_state, old_state);
5591
5592         drm_crtc_vblank_off(crtc);
5593         assert_vblank_disabled(crtc);
5594
5595         intel_disable_pipe(intel_crtc);
5596
5597         ironlake_pfit_disable(intel_crtc, false);
5598
5599         if (intel_crtc->config->has_pch_encoder)
5600                 ironlake_fdi_disable(crtc);
5601
5602         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5603
5604         if (intel_crtc->config->has_pch_encoder) {
5605                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5606
5607                 if (HAS_PCH_CPT(dev_priv)) {
5608                         i915_reg_t reg;
5609                         u32 temp;
5610
5611                         /* disable TRANS_DP_CTL */
5612                         reg = TRANS_DP_CTL(pipe);
5613                         temp = I915_READ(reg);
5614                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5615                                   TRANS_DP_PORT_SEL_MASK);
5616                         temp |= TRANS_DP_PORT_SEL_NONE;
5617                         I915_WRITE(reg, temp);
5618
5619                         /* disable DPLL_SEL */
5620                         temp = I915_READ(PCH_DPLL_SEL);
5621                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5622                         I915_WRITE(PCH_DPLL_SEL, temp);
5623                 }
5624
5625                 ironlake_fdi_pll_disable(intel_crtc);
5626         }
5627
5628         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5629         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5630 }
5631
5632 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5633                                  struct drm_atomic_state *old_state)
5634 {
5635         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5636         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5637         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5638         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5639
5640         if (intel_crtc->config->has_pch_encoder)
5641                 intel_set_pch_fifo_underrun_reporting(dev_priv, PIPE_A, false);
5642
5643         intel_encoders_disable(crtc, old_crtc_state, old_state);
5644
5645         drm_crtc_vblank_off(crtc);
5646         assert_vblank_disabled(crtc);
5647
5648         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5649         if (!transcoder_is_dsi(cpu_transcoder))
5650                 intel_disable_pipe(intel_crtc);
5651
5652         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5653                 intel_ddi_set_vc_payload_alloc(intel_crtc->config, false);
5654
5655         if (!transcoder_is_dsi(cpu_transcoder))
5656                 intel_ddi_disable_transcoder_func(old_crtc_state);
5657
5658         if (INTEL_GEN(dev_priv) >= 9)
5659                 skylake_scaler_disable(intel_crtc);
5660         else
5661                 ironlake_pfit_disable(intel_crtc, false);
5662
5663         if (!transcoder_is_dsi(cpu_transcoder))
5664                 intel_ddi_disable_pipe_clock(intel_crtc->config);
5665
5666         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5667
5668         if (old_crtc_state->has_pch_encoder)
5669                 intel_set_pch_fifo_underrun_reporting(dev_priv, PIPE_A, true);
5670 }
5671
5672 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5673 {
5674         struct drm_device *dev = crtc->base.dev;
5675         struct drm_i915_private *dev_priv = to_i915(dev);
5676         struct intel_crtc_state *pipe_config = crtc->config;
5677
5678         if (!pipe_config->gmch_pfit.control)
5679                 return;
5680
5681         /*
5682          * The panel fitter should only be adjusted whilst the pipe is disabled,
5683          * according to register description and PRM.
5684          */
5685         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5686         assert_pipe_disabled(dev_priv, crtc->pipe);
5687
5688         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5689         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5690
5691         /* Border color in case we don't scale up to the full screen. Black by
5692          * default, change to something else for debugging. */
5693         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5694 }
5695
5696 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5697 {
5698         switch (port) {
5699         case PORT_A:
5700                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5701         case PORT_B:
5702                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5703         case PORT_C:
5704                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5705         case PORT_D:
5706                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5707         case PORT_E:
5708                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5709         default:
5710                 MISSING_CASE(port);
5711                 return POWER_DOMAIN_PORT_OTHER;
5712         }
5713 }
5714
5715 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5716                                   struct intel_crtc_state *crtc_state)
5717 {
5718         struct drm_device *dev = crtc->dev;
5719         struct drm_i915_private *dev_priv = to_i915(dev);
5720         struct drm_encoder *encoder;
5721         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5722         enum pipe pipe = intel_crtc->pipe;
5723         u64 mask;
5724         enum transcoder transcoder = crtc_state->cpu_transcoder;
5725
5726         if (!crtc_state->base.active)
5727                 return 0;
5728
5729         mask = BIT(POWER_DOMAIN_PIPE(pipe));
5730         mask |= BIT(POWER_DOMAIN_TRANSCODER(transcoder));
5731         if (crtc_state->pch_pfit.enabled ||
5732             crtc_state->pch_pfit.force_thru)
5733                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5734
5735         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5736                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5737
5738                 mask |= BIT_ULL(intel_encoder->power_domain);
5739         }
5740
5741         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5742                 mask |= BIT(POWER_DOMAIN_AUDIO);
5743
5744         if (crtc_state->shared_dpll)
5745                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5746
5747         return mask;
5748 }
5749
5750 static u64
5751 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5752                                struct intel_crtc_state *crtc_state)
5753 {
5754         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5755         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5756         enum intel_display_power_domain domain;
5757         u64 domains, new_domains, old_domains;
5758
5759         old_domains = intel_crtc->enabled_power_domains;
5760         intel_crtc->enabled_power_domains = new_domains =
5761                 get_crtc_power_domains(crtc, crtc_state);
5762
5763         domains = new_domains & ~old_domains;
5764
5765         for_each_power_domain(domain, domains)
5766                 intel_display_power_get(dev_priv, domain);
5767
5768         return old_domains & ~new_domains;
5769 }
5770
5771 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5772                                       u64 domains)
5773 {
5774         enum intel_display_power_domain domain;
5775
5776         for_each_power_domain(domain, domains)
5777                 intel_display_power_put(dev_priv, domain);
5778 }
5779
5780 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5781                                    struct drm_atomic_state *old_state)
5782 {
5783         struct intel_atomic_state *old_intel_state =
5784                 to_intel_atomic_state(old_state);
5785         struct drm_crtc *crtc = pipe_config->base.crtc;
5786         struct drm_device *dev = crtc->dev;
5787         struct drm_i915_private *dev_priv = to_i915(dev);
5788         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5789         int pipe = intel_crtc->pipe;
5790
5791         if (WARN_ON(intel_crtc->active))
5792                 return;
5793
5794         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5795                 intel_dp_set_m_n(intel_crtc, M1_N1);
5796
5797         intel_set_pipe_timings(intel_crtc);
5798         intel_set_pipe_src_size(intel_crtc);
5799
5800         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
5801                 struct drm_i915_private *dev_priv = to_i915(dev);
5802
5803                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5804                 I915_WRITE(CHV_CANVAS(pipe), 0);
5805         }
5806
5807         i9xx_set_pipeconf(intel_crtc);
5808
5809         intel_crtc->active = true;
5810
5811         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5812
5813         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5814
5815         if (IS_CHERRYVIEW(dev_priv)) {
5816                 chv_prepare_pll(intel_crtc, intel_crtc->config);
5817                 chv_enable_pll(intel_crtc, intel_crtc->config);
5818         } else {
5819                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
5820                 vlv_enable_pll(intel_crtc, intel_crtc->config);
5821         }
5822
5823         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5824
5825         i9xx_pfit_enable(intel_crtc);
5826
5827         intel_color_load_luts(&pipe_config->base);
5828
5829         dev_priv->display.initial_watermarks(old_intel_state,
5830                                              pipe_config);
5831         intel_enable_pipe(intel_crtc);
5832
5833         assert_vblank_disabled(crtc);
5834         drm_crtc_vblank_on(crtc);
5835
5836         intel_encoders_enable(crtc, pipe_config, old_state);
5837 }
5838
5839 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5840 {
5841         struct drm_device *dev = crtc->base.dev;
5842         struct drm_i915_private *dev_priv = to_i915(dev);
5843
5844         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5845         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5846 }
5847
5848 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
5849                              struct drm_atomic_state *old_state)
5850 {
5851         struct intel_atomic_state *old_intel_state =
5852                 to_intel_atomic_state(old_state);
5853         struct drm_crtc *crtc = pipe_config->base.crtc;
5854         struct drm_device *dev = crtc->dev;
5855         struct drm_i915_private *dev_priv = to_i915(dev);
5856         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5857         enum pipe pipe = intel_crtc->pipe;
5858
5859         if (WARN_ON(intel_crtc->active))
5860                 return;
5861
5862         i9xx_set_pll_dividers(intel_crtc);
5863
5864         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5865                 intel_dp_set_m_n(intel_crtc, M1_N1);
5866
5867         intel_set_pipe_timings(intel_crtc);
5868         intel_set_pipe_src_size(intel_crtc);
5869
5870         i9xx_set_pipeconf(intel_crtc);
5871
5872         intel_crtc->active = true;
5873
5874         if (!IS_GEN2(dev_priv))
5875                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5876
5877         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5878
5879         i9xx_enable_pll(intel_crtc);
5880
5881         i9xx_pfit_enable(intel_crtc);
5882
5883         intel_color_load_luts(&pipe_config->base);
5884
5885         if (dev_priv->display.initial_watermarks != NULL)
5886                 dev_priv->display.initial_watermarks(old_intel_state,
5887                                                      intel_crtc->config);
5888         else
5889                 intel_update_watermarks(intel_crtc);
5890         intel_enable_pipe(intel_crtc);
5891
5892         assert_vblank_disabled(crtc);
5893         drm_crtc_vblank_on(crtc);
5894
5895         intel_encoders_enable(crtc, pipe_config, old_state);
5896 }
5897
5898 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5899 {
5900         struct drm_device *dev = crtc->base.dev;
5901         struct drm_i915_private *dev_priv = to_i915(dev);
5902
5903         if (!crtc->config->gmch_pfit.control)
5904                 return;
5905
5906         assert_pipe_disabled(dev_priv, crtc->pipe);
5907
5908         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5909                          I915_READ(PFIT_CONTROL));
5910         I915_WRITE(PFIT_CONTROL, 0);
5911 }
5912
5913 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
5914                               struct drm_atomic_state *old_state)
5915 {
5916         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5917         struct drm_device *dev = crtc->dev;
5918         struct drm_i915_private *dev_priv = to_i915(dev);
5919         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5920         int pipe = intel_crtc->pipe;
5921
5922         /*
5923          * On gen2 planes are double buffered but the pipe isn't, so we must
5924          * wait for planes to fully turn off before disabling the pipe.
5925          */
5926         if (IS_GEN2(dev_priv))
5927                 intel_wait_for_vblank(dev_priv, pipe);
5928
5929         intel_encoders_disable(crtc, old_crtc_state, old_state);
5930
5931         drm_crtc_vblank_off(crtc);
5932         assert_vblank_disabled(crtc);
5933
5934         intel_disable_pipe(intel_crtc);
5935
5936         i9xx_pfit_disable(intel_crtc);
5937
5938         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5939
5940         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
5941                 if (IS_CHERRYVIEW(dev_priv))
5942                         chv_disable_pll(dev_priv, pipe);
5943                 else if (IS_VALLEYVIEW(dev_priv))
5944                         vlv_disable_pll(dev_priv, pipe);
5945                 else
5946                         i9xx_disable_pll(intel_crtc);
5947         }
5948
5949         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
5950
5951         if (!IS_GEN2(dev_priv))
5952                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5953
5954         if (!dev_priv->display.initial_watermarks)
5955                 intel_update_watermarks(intel_crtc);
5956
5957         /* clock the pipe down to 640x480@60 to potentially save power */
5958         if (IS_I830(dev_priv))
5959                 i830_enable_pipe(dev_priv, pipe);
5960 }
5961
5962 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
5963                                         struct drm_modeset_acquire_ctx *ctx)
5964 {
5965         struct intel_encoder *encoder;
5966         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5967         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5968         enum intel_display_power_domain domain;
5969         struct intel_plane *plane;
5970         u64 domains;
5971         struct drm_atomic_state *state;
5972         struct intel_crtc_state *crtc_state;
5973         int ret;
5974
5975         if (!intel_crtc->active)
5976                 return;
5977
5978         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
5979                 const struct intel_plane_state *plane_state =
5980                         to_intel_plane_state(plane->base.state);
5981
5982                 if (plane_state->base.visible)
5983                         intel_plane_disable_noatomic(intel_crtc, plane);
5984         }
5985
5986         state = drm_atomic_state_alloc(crtc->dev);
5987         if (!state) {
5988                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
5989                               crtc->base.id, crtc->name);
5990                 return;
5991         }
5992
5993         state->acquire_ctx = ctx;
5994
5995         /* Everything's already locked, -EDEADLK can't happen. */
5996         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
5997         ret = drm_atomic_add_affected_connectors(state, crtc);
5998
5999         WARN_ON(IS_ERR(crtc_state) || ret);
6000
6001         dev_priv->display.crtc_disable(crtc_state, state);
6002
6003         drm_atomic_state_put(state);
6004
6005         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6006                       crtc->base.id, crtc->name);
6007
6008         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6009         crtc->state->active = false;
6010         intel_crtc->active = false;
6011         crtc->enabled = false;
6012         crtc->state->connector_mask = 0;
6013         crtc->state->encoder_mask = 0;
6014
6015         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6016                 encoder->base.crtc = NULL;
6017
6018         intel_fbc_disable(intel_crtc);
6019         intel_update_watermarks(intel_crtc);
6020         intel_disable_shared_dpll(intel_crtc);
6021
6022         domains = intel_crtc->enabled_power_domains;
6023         for_each_power_domain(domain, domains)
6024                 intel_display_power_put(dev_priv, domain);
6025         intel_crtc->enabled_power_domains = 0;
6026
6027         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6028         dev_priv->min_pixclk[intel_crtc->pipe] = 0;
6029 }
6030
6031 /*
6032  * turn all crtc's off, but do not adjust state
6033  * This has to be paired with a call to intel_modeset_setup_hw_state.
6034  */
6035 int intel_display_suspend(struct drm_device *dev)
6036 {
6037         struct drm_i915_private *dev_priv = to_i915(dev);
6038         struct drm_atomic_state *state;
6039         int ret;
6040
6041         state = drm_atomic_helper_suspend(dev);
6042         ret = PTR_ERR_OR_ZERO(state);
6043         if (ret)
6044                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6045         else
6046                 dev_priv->modeset_restore_state = state;
6047         return ret;
6048 }
6049
6050 void intel_encoder_destroy(struct drm_encoder *encoder)
6051 {
6052         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6053
6054         drm_encoder_cleanup(encoder);
6055         kfree(intel_encoder);
6056 }
6057
6058 /* Cross check the actual hw state with our own modeset state tracking (and it's
6059  * internal consistency). */
6060 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6061                                          struct drm_connector_state *conn_state)
6062 {
6063         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6064
6065         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6066                       connector->base.base.id,
6067                       connector->base.name);
6068
6069         if (connector->get_hw_state(connector)) {
6070                 struct intel_encoder *encoder = connector->encoder;
6071
6072                 I915_STATE_WARN(!crtc_state,
6073                          "connector enabled without attached crtc\n");
6074
6075                 if (!crtc_state)
6076                         return;
6077
6078                 I915_STATE_WARN(!crtc_state->active,
6079                       "connector is active, but attached crtc isn't\n");
6080
6081                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6082                         return;
6083
6084                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6085                         "atomic encoder doesn't match attached encoder\n");
6086
6087                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6088                         "attached encoder crtc differs from connector crtc\n");
6089         } else {
6090                 I915_STATE_WARN(crtc_state && crtc_state->active,
6091                         "attached crtc is active, but connector isn't\n");
6092                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6093                         "best encoder set without crtc!\n");
6094         }
6095 }
6096
6097 int intel_connector_init(struct intel_connector *connector)
6098 {
6099         struct intel_digital_connector_state *conn_state;
6100
6101         /*
6102          * Allocate enough memory to hold intel_digital_connector_state,
6103          * This might be a few bytes too many, but for connectors that don't
6104          * need it we'll free the state and allocate a smaller one on the first
6105          * succesful commit anyway.
6106          */
6107         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
6108         if (!conn_state)
6109                 return -ENOMEM;
6110
6111         __drm_atomic_helper_connector_reset(&connector->base,
6112                                             &conn_state->base);
6113
6114         return 0;
6115 }
6116
6117 struct intel_connector *intel_connector_alloc(void)
6118 {
6119         struct intel_connector *connector;
6120
6121         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6122         if (!connector)
6123                 return NULL;
6124
6125         if (intel_connector_init(connector) < 0) {
6126                 kfree(connector);
6127                 return NULL;
6128         }
6129
6130         return connector;
6131 }
6132
6133 /* Simple connector->get_hw_state implementation for encoders that support only
6134  * one connector and no cloning and hence the encoder state determines the state
6135  * of the connector. */
6136 bool intel_connector_get_hw_state(struct intel_connector *connector)
6137 {
6138         enum pipe pipe = 0;
6139         struct intel_encoder *encoder = connector->encoder;
6140
6141         return encoder->get_hw_state(encoder, &pipe);
6142 }
6143
6144 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6145 {
6146         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6147                 return crtc_state->fdi_lanes;
6148
6149         return 0;
6150 }
6151
6152 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6153                                      struct intel_crtc_state *pipe_config)
6154 {
6155         struct drm_i915_private *dev_priv = to_i915(dev);
6156         struct drm_atomic_state *state = pipe_config->base.state;
6157         struct intel_crtc *other_crtc;
6158         struct intel_crtc_state *other_crtc_state;
6159
6160         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6161                       pipe_name(pipe), pipe_config->fdi_lanes);
6162         if (pipe_config->fdi_lanes > 4) {
6163                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6164                               pipe_name(pipe), pipe_config->fdi_lanes);
6165                 return -EINVAL;
6166         }
6167
6168         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6169                 if (pipe_config->fdi_lanes > 2) {
6170                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6171                                       pipe_config->fdi_lanes);
6172                         return -EINVAL;
6173                 } else {
6174                         return 0;
6175                 }
6176         }
6177
6178         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6179                 return 0;
6180
6181         /* Ivybridge 3 pipe is really complicated */
6182         switch (pipe) {
6183         case PIPE_A:
6184                 return 0;
6185         case PIPE_B:
6186                 if (pipe_config->fdi_lanes <= 2)
6187                         return 0;
6188
6189                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6190                 other_crtc_state =
6191                         intel_atomic_get_crtc_state(state, other_crtc);
6192                 if (IS_ERR(other_crtc_state))
6193                         return PTR_ERR(other_crtc_state);
6194
6195                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6196                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6197                                       pipe_name(pipe), pipe_config->fdi_lanes);
6198                         return -EINVAL;
6199                 }
6200                 return 0;
6201         case PIPE_C:
6202                 if (pipe_config->fdi_lanes > 2) {
6203                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6204                                       pipe_name(pipe), pipe_config->fdi_lanes);
6205                         return -EINVAL;
6206                 }
6207
6208                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6209                 other_crtc_state =
6210                         intel_atomic_get_crtc_state(state, other_crtc);
6211                 if (IS_ERR(other_crtc_state))
6212                         return PTR_ERR(other_crtc_state);
6213
6214                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6215                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6216                         return -EINVAL;
6217                 }
6218                 return 0;
6219         default:
6220                 BUG();
6221         }
6222 }
6223
6224 #define RETRY 1
6225 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6226                                        struct intel_crtc_state *pipe_config)
6227 {
6228         struct drm_device *dev = intel_crtc->base.dev;
6229         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6230         int lane, link_bw, fdi_dotclock, ret;
6231         bool needs_recompute = false;
6232
6233 retry:
6234         /* FDI is a binary signal running at ~2.7GHz, encoding
6235          * each output octet as 10 bits. The actual frequency
6236          * is stored as a divider into a 100MHz clock, and the
6237          * mode pixel clock is stored in units of 1KHz.
6238          * Hence the bw of each lane in terms of the mode signal
6239          * is:
6240          */
6241         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6242
6243         fdi_dotclock = adjusted_mode->crtc_clock;
6244
6245         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6246                                            pipe_config->pipe_bpp);
6247
6248         pipe_config->fdi_lanes = lane;
6249
6250         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6251                                link_bw, &pipe_config->fdi_m_n, false);
6252
6253         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6254         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6255                 pipe_config->pipe_bpp -= 2*3;
6256                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6257                               pipe_config->pipe_bpp);
6258                 needs_recompute = true;
6259                 pipe_config->bw_constrained = true;
6260
6261                 goto retry;
6262         }
6263
6264         if (needs_recompute)
6265                 return RETRY;
6266
6267         return ret;
6268 }
6269
6270 static bool pipe_config_supports_ips(struct drm_i915_private *dev_priv,
6271                                      struct intel_crtc_state *pipe_config)
6272 {
6273         if (pipe_config->pipe_bpp > 24)
6274                 return false;
6275
6276         /* HSW can handle pixel rate up to cdclk? */
6277         if (IS_HASWELL(dev_priv))
6278                 return true;
6279
6280         /*
6281          * We compare against max which means we must take
6282          * the increased cdclk requirement into account when
6283          * calculating the new cdclk.
6284          *
6285          * Should measure whether using a lower cdclk w/o IPS
6286          */
6287         return pipe_config->pixel_rate <=
6288                 dev_priv->max_cdclk_freq * 95 / 100;
6289 }
6290
6291 static void hsw_compute_ips_config(struct intel_crtc *crtc,
6292                                    struct intel_crtc_state *pipe_config)
6293 {
6294         struct drm_device *dev = crtc->base.dev;
6295         struct drm_i915_private *dev_priv = to_i915(dev);
6296
6297         pipe_config->ips_enabled = i915.enable_ips &&
6298                 hsw_crtc_supports_ips(crtc) &&
6299                 pipe_config_supports_ips(dev_priv, pipe_config);
6300 }
6301
6302 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6303 {
6304         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6305
6306         /* GDG double wide on either pipe, otherwise pipe A only */
6307         return INTEL_INFO(dev_priv)->gen < 4 &&
6308                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6309 }
6310
6311 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6312 {
6313         uint32_t pixel_rate;
6314
6315         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6316
6317         /*
6318          * We only use IF-ID interlacing. If we ever use
6319          * PF-ID we'll need to adjust the pixel_rate here.
6320          */
6321
6322         if (pipe_config->pch_pfit.enabled) {
6323                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6324                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6325
6326                 pipe_w = pipe_config->pipe_src_w;
6327                 pipe_h = pipe_config->pipe_src_h;
6328
6329                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6330                 pfit_h = pfit_size & 0xFFFF;
6331                 if (pipe_w < pfit_w)
6332                         pipe_w = pfit_w;
6333                 if (pipe_h < pfit_h)
6334                         pipe_h = pfit_h;
6335
6336                 if (WARN_ON(!pfit_w || !pfit_h))
6337                         return pixel_rate;
6338
6339                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6340                                      pfit_w * pfit_h);
6341         }
6342
6343         return pixel_rate;
6344 }
6345
6346 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6347 {
6348         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6349
6350         if (HAS_GMCH_DISPLAY(dev_priv))
6351                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6352                 crtc_state->pixel_rate =
6353                         crtc_state->base.adjusted_mode.crtc_clock;
6354         else
6355                 crtc_state->pixel_rate =
6356                         ilk_pipe_pixel_rate(crtc_state);
6357 }
6358
6359 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6360                                      struct intel_crtc_state *pipe_config)
6361 {
6362         struct drm_device *dev = crtc->base.dev;
6363         struct drm_i915_private *dev_priv = to_i915(dev);
6364         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6365         int clock_limit = dev_priv->max_dotclk_freq;
6366
6367         if (INTEL_GEN(dev_priv) < 4) {
6368                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6369
6370                 /*
6371                  * Enable double wide mode when the dot clock
6372                  * is > 90% of the (display) core speed.
6373                  */
6374                 if (intel_crtc_supports_double_wide(crtc) &&
6375                     adjusted_mode->crtc_clock > clock_limit) {
6376                         clock_limit = dev_priv->max_dotclk_freq;
6377                         pipe_config->double_wide = true;
6378                 }
6379         }
6380
6381         if (adjusted_mode->crtc_clock > clock_limit) {
6382                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6383                               adjusted_mode->crtc_clock, clock_limit,
6384                               yesno(pipe_config->double_wide));
6385                 return -EINVAL;
6386         }
6387
6388         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6389                 /*
6390                  * There is only one pipe CSC unit per pipe, and we need that
6391                  * for output conversion from RGB->YCBCR. So if CTM is already
6392                  * applied we can't support YCBCR420 output.
6393                  */
6394                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6395                 return -EINVAL;
6396         }
6397
6398         /*
6399          * Pipe horizontal size must be even in:
6400          * - DVO ganged mode
6401          * - LVDS dual channel mode
6402          * - Double wide pipe
6403          */
6404         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6405              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6406                 pipe_config->pipe_src_w &= ~1;
6407
6408         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6409          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6410          */
6411         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6412                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6413                 return -EINVAL;
6414
6415         intel_crtc_compute_pixel_rate(pipe_config);
6416
6417         if (HAS_IPS(dev_priv))
6418                 hsw_compute_ips_config(crtc, pipe_config);
6419
6420         if (pipe_config->has_pch_encoder)
6421                 return ironlake_fdi_compute_config(crtc, pipe_config);
6422
6423         return 0;
6424 }
6425
6426 static void
6427 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6428 {
6429         while (*num > DATA_LINK_M_N_MASK ||
6430                *den > DATA_LINK_M_N_MASK) {
6431                 *num >>= 1;
6432                 *den >>= 1;
6433         }
6434 }
6435
6436 static void compute_m_n(unsigned int m, unsigned int n,
6437                         uint32_t *ret_m, uint32_t *ret_n,
6438                         bool reduce_m_n)
6439 {
6440         /*
6441          * Reduce M/N as much as possible without loss in precision. Several DP
6442          * dongles in particular seem to be fussy about too large *link* M/N
6443          * values. The passed in values are more likely to have the least
6444          * significant bits zero than M after rounding below, so do this first.
6445          */
6446         if (reduce_m_n) {
6447                 while ((m & 1) == 0 && (n & 1) == 0) {
6448                         m >>= 1;
6449                         n >>= 1;
6450                 }
6451         }
6452
6453         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6454         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6455         intel_reduce_m_n_ratio(ret_m, ret_n);
6456 }
6457
6458 void
6459 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6460                        int pixel_clock, int link_clock,
6461                        struct intel_link_m_n *m_n,
6462                        bool reduce_m_n)
6463 {
6464         m_n->tu = 64;
6465
6466         compute_m_n(bits_per_pixel * pixel_clock,
6467                     link_clock * nlanes * 8,
6468                     &m_n->gmch_m, &m_n->gmch_n,
6469                     reduce_m_n);
6470
6471         compute_m_n(pixel_clock, link_clock,
6472                     &m_n->link_m, &m_n->link_n,
6473                     reduce_m_n);
6474 }
6475
6476 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6477 {
6478         if (i915.panel_use_ssc >= 0)
6479                 return i915.panel_use_ssc != 0;
6480         return dev_priv->vbt.lvds_use_ssc
6481                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6482 }
6483
6484 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6485 {
6486         return (1 << dpll->n) << 16 | dpll->m2;
6487 }
6488
6489 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6490 {
6491         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6492 }
6493
6494 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6495                                      struct intel_crtc_state *crtc_state,
6496                                      struct dpll *reduced_clock)
6497 {
6498         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6499         u32 fp, fp2 = 0;
6500
6501         if (IS_PINEVIEW(dev_priv)) {
6502                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6503                 if (reduced_clock)
6504                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6505         } else {
6506                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6507                 if (reduced_clock)
6508                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6509         }
6510
6511         crtc_state->dpll_hw_state.fp0 = fp;
6512
6513         crtc->lowfreq_avail = false;
6514         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6515             reduced_clock) {
6516                 crtc_state->dpll_hw_state.fp1 = fp2;
6517                 crtc->lowfreq_avail = true;
6518         } else {
6519                 crtc_state->dpll_hw_state.fp1 = fp;
6520         }
6521 }
6522
6523 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6524                 pipe)
6525 {
6526         u32 reg_val;
6527
6528         /*
6529          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6530          * and set it to a reasonable value instead.
6531          */
6532         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6533         reg_val &= 0xffffff00;
6534         reg_val |= 0x00000030;
6535         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6536
6537         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6538         reg_val &= 0x00ffffff;
6539         reg_val |= 0x8c000000;
6540         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6541
6542         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6543         reg_val &= 0xffffff00;
6544         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6545
6546         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6547         reg_val &= 0x00ffffff;
6548         reg_val |= 0xb0000000;
6549         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6550 }
6551
6552 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6553                                          struct intel_link_m_n *m_n)
6554 {
6555         struct drm_device *dev = crtc->base.dev;
6556         struct drm_i915_private *dev_priv = to_i915(dev);
6557         int pipe = crtc->pipe;
6558
6559         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6560         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6561         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6562         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6563 }
6564
6565 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6566                                          struct intel_link_m_n *m_n,
6567                                          struct intel_link_m_n *m2_n2)
6568 {
6569         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6570         int pipe = crtc->pipe;
6571         enum transcoder transcoder = crtc->config->cpu_transcoder;
6572
6573         if (INTEL_GEN(dev_priv) >= 5) {
6574                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6575                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6576                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6577                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6578                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6579                  * for gen < 8) and if DRRS is supported (to make sure the
6580                  * registers are not unnecessarily accessed).
6581                  */
6582                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6583                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6584                         I915_WRITE(PIPE_DATA_M2(transcoder),
6585                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6586                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6587                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6588                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6589                 }
6590         } else {
6591                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6592                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6593                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6594                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6595         }
6596 }
6597
6598 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6599 {
6600         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6601
6602         if (m_n == M1_N1) {
6603                 dp_m_n = &crtc->config->dp_m_n;
6604                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6605         } else if (m_n == M2_N2) {
6606
6607                 /*
6608                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6609                  * needs to be programmed into M1_N1.
6610                  */
6611                 dp_m_n = &crtc->config->dp_m2_n2;
6612         } else {
6613                 DRM_ERROR("Unsupported divider value\n");
6614                 return;
6615         }
6616
6617         if (crtc->config->has_pch_encoder)
6618                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6619         else
6620                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6621 }
6622
6623 static void vlv_compute_dpll(struct intel_crtc *crtc,
6624                              struct intel_crtc_state *pipe_config)
6625 {
6626         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6627                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6628         if (crtc->pipe != PIPE_A)
6629                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6630
6631         /* DPLL not used with DSI, but still need the rest set up */
6632         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6633                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6634                         DPLL_EXT_BUFFER_ENABLE_VLV;
6635
6636         pipe_config->dpll_hw_state.dpll_md =
6637                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6638 }
6639
6640 static void chv_compute_dpll(struct intel_crtc *crtc,
6641                              struct intel_crtc_state *pipe_config)
6642 {
6643         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6644                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6645         if (crtc->pipe != PIPE_A)
6646                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6647
6648         /* DPLL not used with DSI, but still need the rest set up */
6649         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6650                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6651
6652         pipe_config->dpll_hw_state.dpll_md =
6653                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6654 }
6655
6656 static void vlv_prepare_pll(struct intel_crtc *crtc,
6657                             const struct intel_crtc_state *pipe_config)
6658 {
6659         struct drm_device *dev = crtc->base.dev;
6660         struct drm_i915_private *dev_priv = to_i915(dev);
6661         enum pipe pipe = crtc->pipe;
6662         u32 mdiv;
6663         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6664         u32 coreclk, reg_val;
6665
6666         /* Enable Refclk */
6667         I915_WRITE(DPLL(pipe),
6668                    pipe_config->dpll_hw_state.dpll &
6669                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6670
6671         /* No need to actually set up the DPLL with DSI */
6672         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6673                 return;
6674
6675         mutex_lock(&dev_priv->sb_lock);
6676
6677         bestn = pipe_config->dpll.n;
6678         bestm1 = pipe_config->dpll.m1;
6679         bestm2 = pipe_config->dpll.m2;
6680         bestp1 = pipe_config->dpll.p1;
6681         bestp2 = pipe_config->dpll.p2;
6682
6683         /* See eDP HDMI DPIO driver vbios notes doc */
6684
6685         /* PLL B needs special handling */
6686         if (pipe == PIPE_B)
6687                 vlv_pllb_recal_opamp(dev_priv, pipe);
6688
6689         /* Set up Tx target for periodic Rcomp update */
6690         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6691
6692         /* Disable target IRef on PLL */
6693         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6694         reg_val &= 0x00ffffff;
6695         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6696
6697         /* Disable fast lock */
6698         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6699
6700         /* Set idtafcrecal before PLL is enabled */
6701         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6702         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6703         mdiv |= ((bestn << DPIO_N_SHIFT));
6704         mdiv |= (1 << DPIO_K_SHIFT);
6705
6706         /*
6707          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6708          * but we don't support that).
6709          * Note: don't use the DAC post divider as it seems unstable.
6710          */
6711         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6712         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6713
6714         mdiv |= DPIO_ENABLE_CALIBRATION;
6715         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6716
6717         /* Set HBR and RBR LPF coefficients */
6718         if (pipe_config->port_clock == 162000 ||
6719             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6720             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6721                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6722                                  0x009f0003);
6723         else
6724                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6725                                  0x00d0000f);
6726
6727         if (intel_crtc_has_dp_encoder(pipe_config)) {
6728                 /* Use SSC source */
6729                 if (pipe == PIPE_A)
6730                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6731                                          0x0df40000);
6732                 else
6733                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6734                                          0x0df70000);
6735         } else { /* HDMI or VGA */
6736                 /* Use bend source */
6737                 if (pipe == PIPE_A)
6738                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6739                                          0x0df70000);
6740                 else
6741                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6742                                          0x0df40000);
6743         }
6744
6745         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6746         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6747         if (intel_crtc_has_dp_encoder(crtc->config))
6748                 coreclk |= 0x01000000;
6749         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6750
6751         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6752         mutex_unlock(&dev_priv->sb_lock);
6753 }
6754
6755 static void chv_prepare_pll(struct intel_crtc *crtc,
6756                             const struct intel_crtc_state *pipe_config)
6757 {
6758         struct drm_device *dev = crtc->base.dev;
6759         struct drm_i915_private *dev_priv = to_i915(dev);
6760         enum pipe pipe = crtc->pipe;
6761         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6762         u32 loopfilter, tribuf_calcntr;
6763         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6764         u32 dpio_val;
6765         int vco;
6766
6767         /* Enable Refclk and SSC */
6768         I915_WRITE(DPLL(pipe),
6769                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6770
6771         /* No need to actually set up the DPLL with DSI */
6772         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6773                 return;
6774
6775         bestn = pipe_config->dpll.n;
6776         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6777         bestm1 = pipe_config->dpll.m1;
6778         bestm2 = pipe_config->dpll.m2 >> 22;
6779         bestp1 = pipe_config->dpll.p1;
6780         bestp2 = pipe_config->dpll.p2;
6781         vco = pipe_config->dpll.vco;
6782         dpio_val = 0;
6783         loopfilter = 0;
6784
6785         mutex_lock(&dev_priv->sb_lock);
6786
6787         /* p1 and p2 divider */
6788         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6789                         5 << DPIO_CHV_S1_DIV_SHIFT |
6790                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6791                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6792                         1 << DPIO_CHV_K_DIV_SHIFT);
6793
6794         /* Feedback post-divider - m2 */
6795         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6796
6797         /* Feedback refclk divider - n and m1 */
6798         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6799                         DPIO_CHV_M1_DIV_BY_2 |
6800                         1 << DPIO_CHV_N_DIV_SHIFT);
6801
6802         /* M2 fraction division */
6803         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6804
6805         /* M2 fraction division enable */
6806         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6807         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6808         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6809         if (bestm2_frac)
6810                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6811         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6812
6813         /* Program digital lock detect threshold */
6814         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6815         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6816                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6817         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6818         if (!bestm2_frac)
6819                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6820         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6821
6822         /* Loop filter */
6823         if (vco == 5400000) {
6824                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6825                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6826                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6827                 tribuf_calcntr = 0x9;
6828         } else if (vco <= 6200000) {
6829                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6830                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6831                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6832                 tribuf_calcntr = 0x9;
6833         } else if (vco <= 6480000) {
6834                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6835                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6836                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6837                 tribuf_calcntr = 0x8;
6838         } else {
6839                 /* Not supported. Apply the same limits as in the max case */
6840                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6841                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6842                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6843                 tribuf_calcntr = 0;
6844         }
6845         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6846
6847         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6848         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6849         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6850         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
6851
6852         /* AFC Recal */
6853         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6854                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6855                         DPIO_AFC_RECAL);
6856
6857         mutex_unlock(&dev_priv->sb_lock);
6858 }
6859
6860 /**
6861  * vlv_force_pll_on - forcibly enable just the PLL
6862  * @dev_priv: i915 private structure
6863  * @pipe: pipe PLL to enable
6864  * @dpll: PLL configuration
6865  *
6866  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6867  * in cases where we need the PLL enabled even when @pipe is not going to
6868  * be enabled.
6869  */
6870 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
6871                      const struct dpll *dpll)
6872 {
6873         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
6874         struct intel_crtc_state *pipe_config;
6875
6876         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
6877         if (!pipe_config)
6878                 return -ENOMEM;
6879
6880         pipe_config->base.crtc = &crtc->base;
6881         pipe_config->pixel_multiplier = 1;
6882         pipe_config->dpll = *dpll;
6883
6884         if (IS_CHERRYVIEW(dev_priv)) {
6885                 chv_compute_dpll(crtc, pipe_config);
6886                 chv_prepare_pll(crtc, pipe_config);
6887                 chv_enable_pll(crtc, pipe_config);
6888         } else {
6889                 vlv_compute_dpll(crtc, pipe_config);
6890                 vlv_prepare_pll(crtc, pipe_config);
6891                 vlv_enable_pll(crtc, pipe_config);
6892         }
6893
6894         kfree(pipe_config);
6895
6896         return 0;
6897 }
6898
6899 /**
6900  * vlv_force_pll_off - forcibly disable just the PLL
6901  * @dev_priv: i915 private structure
6902  * @pipe: pipe PLL to disable
6903  *
6904  * Disable the PLL for @pipe. To be used in cases where we need
6905  * the PLL enabled even when @pipe is not going to be enabled.
6906  */
6907 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
6908 {
6909         if (IS_CHERRYVIEW(dev_priv))
6910                 chv_disable_pll(dev_priv, pipe);
6911         else
6912                 vlv_disable_pll(dev_priv, pipe);
6913 }
6914
6915 static void i9xx_compute_dpll(struct intel_crtc *crtc,
6916                               struct intel_crtc_state *crtc_state,
6917                               struct dpll *reduced_clock)
6918 {
6919         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6920         u32 dpll;
6921         struct dpll *clock = &crtc_state->dpll;
6922
6923         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6924
6925         dpll = DPLL_VGA_MODE_DIS;
6926
6927         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
6928                 dpll |= DPLLB_MODE_LVDS;
6929         else
6930                 dpll |= DPLLB_MODE_DAC_SERIAL;
6931
6932         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
6933             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
6934                 dpll |= (crtc_state->pixel_multiplier - 1)
6935                         << SDVO_MULTIPLIER_SHIFT_HIRES;
6936         }
6937
6938         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
6939             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
6940                 dpll |= DPLL_SDVO_HIGH_SPEED;
6941
6942         if (intel_crtc_has_dp_encoder(crtc_state))
6943                 dpll |= DPLL_SDVO_HIGH_SPEED;
6944
6945         /* compute bitmask from p1 value */
6946         if (IS_PINEVIEW(dev_priv))
6947                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
6948         else {
6949                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6950                 if (IS_G4X(dev_priv) && reduced_clock)
6951                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
6952         }
6953         switch (clock->p2) {
6954         case 5:
6955                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
6956                 break;
6957         case 7:
6958                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
6959                 break;
6960         case 10:
6961                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
6962                 break;
6963         case 14:
6964                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
6965                 break;
6966         }
6967         if (INTEL_GEN(dev_priv) >= 4)
6968                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
6969
6970         if (crtc_state->sdvo_tv_clock)
6971                 dpll |= PLL_REF_INPUT_TVCLKINBC;
6972         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6973                  intel_panel_use_ssc(dev_priv))
6974                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6975         else
6976                 dpll |= PLL_REF_INPUT_DREFCLK;
6977
6978         dpll |= DPLL_VCO_ENABLE;
6979         crtc_state->dpll_hw_state.dpll = dpll;
6980
6981         if (INTEL_GEN(dev_priv) >= 4) {
6982                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
6983                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6984                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
6985         }
6986 }
6987
6988 static void i8xx_compute_dpll(struct intel_crtc *crtc,
6989                               struct intel_crtc_state *crtc_state,
6990                               struct dpll *reduced_clock)
6991 {
6992         struct drm_device *dev = crtc->base.dev;
6993         struct drm_i915_private *dev_priv = to_i915(dev);
6994         u32 dpll;
6995         struct dpll *clock = &crtc_state->dpll;
6996
6997         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6998
6999         dpll = DPLL_VGA_MODE_DIS;
7000
7001         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7002                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7003         } else {
7004                 if (clock->p1 == 2)
7005                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7006                 else
7007                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7008                 if (clock->p2 == 4)
7009                         dpll |= PLL_P2_DIVIDE_BY_4;
7010         }
7011
7012         if (!IS_I830(dev_priv) &&
7013             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7014                 dpll |= DPLL_DVO_2X_MODE;
7015
7016         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7017             intel_panel_use_ssc(dev_priv))
7018                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7019         else
7020                 dpll |= PLL_REF_INPUT_DREFCLK;
7021
7022         dpll |= DPLL_VCO_ENABLE;
7023         crtc_state->dpll_hw_state.dpll = dpll;
7024 }
7025
7026 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7027 {
7028         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7029         enum pipe pipe = intel_crtc->pipe;
7030         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7031         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7032         uint32_t crtc_vtotal, crtc_vblank_end;
7033         int vsyncshift = 0;
7034
7035         /* We need to be careful not to changed the adjusted mode, for otherwise
7036          * the hw state checker will get angry at the mismatch. */
7037         crtc_vtotal = adjusted_mode->crtc_vtotal;
7038         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7039
7040         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7041                 /* the chip adds 2 halflines automatically */
7042                 crtc_vtotal -= 1;
7043                 crtc_vblank_end -= 1;
7044
7045                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7046                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7047                 else
7048                         vsyncshift = adjusted_mode->crtc_hsync_start -
7049                                 adjusted_mode->crtc_htotal / 2;
7050                 if (vsyncshift < 0)
7051                         vsyncshift += adjusted_mode->crtc_htotal;
7052         }
7053
7054         if (INTEL_GEN(dev_priv) > 3)
7055                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7056
7057         I915_WRITE(HTOTAL(cpu_transcoder),
7058                    (adjusted_mode->crtc_hdisplay - 1) |
7059                    ((adjusted_mode->crtc_htotal - 1) << 16));
7060         I915_WRITE(HBLANK(cpu_transcoder),
7061                    (adjusted_mode->crtc_hblank_start - 1) |
7062                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7063         I915_WRITE(HSYNC(cpu_transcoder),
7064                    (adjusted_mode->crtc_hsync_start - 1) |
7065                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7066
7067         I915_WRITE(VTOTAL(cpu_transcoder),
7068                    (adjusted_mode->crtc_vdisplay - 1) |
7069                    ((crtc_vtotal - 1) << 16));
7070         I915_WRITE(VBLANK(cpu_transcoder),
7071                    (adjusted_mode->crtc_vblank_start - 1) |
7072                    ((crtc_vblank_end - 1) << 16));
7073         I915_WRITE(VSYNC(cpu_transcoder),
7074                    (adjusted_mode->crtc_vsync_start - 1) |
7075                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7076
7077         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7078          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7079          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7080          * bits. */
7081         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7082             (pipe == PIPE_B || pipe == PIPE_C))
7083                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7084
7085 }
7086
7087 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7088 {
7089         struct drm_device *dev = intel_crtc->base.dev;
7090         struct drm_i915_private *dev_priv = to_i915(dev);
7091         enum pipe pipe = intel_crtc->pipe;
7092
7093         /* pipesrc controls the size that is scaled from, which should
7094          * always be the user's requested size.
7095          */
7096         I915_WRITE(PIPESRC(pipe),
7097                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7098                    (intel_crtc->config->pipe_src_h - 1));
7099 }
7100
7101 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7102                                    struct intel_crtc_state *pipe_config)
7103 {
7104         struct drm_device *dev = crtc->base.dev;
7105         struct drm_i915_private *dev_priv = to_i915(dev);
7106         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7107         uint32_t tmp;
7108
7109         tmp = I915_READ(HTOTAL(cpu_transcoder));
7110         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7111         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7112         tmp = I915_READ(HBLANK(cpu_transcoder));
7113         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7114         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7115         tmp = I915_READ(HSYNC(cpu_transcoder));
7116         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7117         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7118
7119         tmp = I915_READ(VTOTAL(cpu_transcoder));
7120         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7121         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7122         tmp = I915_READ(VBLANK(cpu_transcoder));
7123         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7124         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7125         tmp = I915_READ(VSYNC(cpu_transcoder));
7126         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7127         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7128
7129         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7130                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7131                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7132                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7133         }
7134 }
7135
7136 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7137                                     struct intel_crtc_state *pipe_config)
7138 {
7139         struct drm_device *dev = crtc->base.dev;
7140         struct drm_i915_private *dev_priv = to_i915(dev);
7141         u32 tmp;
7142
7143         tmp = I915_READ(PIPESRC(crtc->pipe));
7144         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7145         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7146
7147         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7148         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7149 }
7150
7151 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7152                                  struct intel_crtc_state *pipe_config)
7153 {
7154         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7155         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7156         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7157         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7158
7159         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7160         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7161         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7162         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7163
7164         mode->flags = pipe_config->base.adjusted_mode.flags;
7165         mode->type = DRM_MODE_TYPE_DRIVER;
7166
7167         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7168
7169         mode->hsync = drm_mode_hsync(mode);
7170         mode->vrefresh = drm_mode_vrefresh(mode);
7171         drm_mode_set_name(mode);
7172 }
7173
7174 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7175 {
7176         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7177         uint32_t pipeconf;
7178
7179         pipeconf = 0;
7180
7181         /* we keep both pipes enabled on 830 */
7182         if (IS_I830(dev_priv))
7183                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7184
7185         if (intel_crtc->config->double_wide)
7186                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7187
7188         /* only g4x and later have fancy bpc/dither controls */
7189         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7190             IS_CHERRYVIEW(dev_priv)) {
7191                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7192                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7193                         pipeconf |= PIPECONF_DITHER_EN |
7194                                     PIPECONF_DITHER_TYPE_SP;
7195
7196                 switch (intel_crtc->config->pipe_bpp) {
7197                 case 18:
7198                         pipeconf |= PIPECONF_6BPC;
7199                         break;
7200                 case 24:
7201                         pipeconf |= PIPECONF_8BPC;
7202                         break;
7203                 case 30:
7204                         pipeconf |= PIPECONF_10BPC;
7205                         break;
7206                 default:
7207                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7208                         BUG();
7209                 }
7210         }
7211
7212         if (HAS_PIPE_CXSR(dev_priv)) {
7213                 if (intel_crtc->lowfreq_avail) {
7214                         DRM_DEBUG_KMS("enabling CxSR downclocking\n");
7215                         pipeconf |= PIPECONF_CXSR_DOWNCLOCK;
7216                 } else {
7217                         DRM_DEBUG_KMS("disabling CxSR downclocking\n");
7218                 }
7219         }
7220
7221         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7222                 if (INTEL_GEN(dev_priv) < 4 ||
7223                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7224                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7225                 else
7226                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7227         } else
7228                 pipeconf |= PIPECONF_PROGRESSIVE;
7229
7230         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7231              intel_crtc->config->limited_color_range)
7232                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7233
7234         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7235         POSTING_READ(PIPECONF(intel_crtc->pipe));
7236 }
7237
7238 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7239                                    struct intel_crtc_state *crtc_state)
7240 {
7241         struct drm_device *dev = crtc->base.dev;
7242         struct drm_i915_private *dev_priv = to_i915(dev);
7243         const struct intel_limit *limit;
7244         int refclk = 48000;
7245
7246         memset(&crtc_state->dpll_hw_state, 0,
7247                sizeof(crtc_state->dpll_hw_state));
7248
7249         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7250                 if (intel_panel_use_ssc(dev_priv)) {
7251                         refclk = dev_priv->vbt.lvds_ssc_freq;
7252                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7253                 }
7254
7255                 limit = &intel_limits_i8xx_lvds;
7256         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7257                 limit = &intel_limits_i8xx_dvo;
7258         } else {
7259                 limit = &intel_limits_i8xx_dac;
7260         }
7261
7262         if (!crtc_state->clock_set &&
7263             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7264                                  refclk, NULL, &crtc_state->dpll)) {
7265                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7266                 return -EINVAL;
7267         }
7268
7269         i8xx_compute_dpll(crtc, crtc_state, NULL);
7270
7271         return 0;
7272 }
7273
7274 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7275                                   struct intel_crtc_state *crtc_state)
7276 {
7277         struct drm_device *dev = crtc->base.dev;
7278         struct drm_i915_private *dev_priv = to_i915(dev);
7279         const struct intel_limit *limit;
7280         int refclk = 96000;
7281
7282         memset(&crtc_state->dpll_hw_state, 0,
7283                sizeof(crtc_state->dpll_hw_state));
7284
7285         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7286                 if (intel_panel_use_ssc(dev_priv)) {
7287                         refclk = dev_priv->vbt.lvds_ssc_freq;
7288                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7289                 }
7290
7291                 if (intel_is_dual_link_lvds(dev))
7292                         limit = &intel_limits_g4x_dual_channel_lvds;
7293                 else
7294                         limit = &intel_limits_g4x_single_channel_lvds;
7295         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7296                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7297                 limit = &intel_limits_g4x_hdmi;
7298         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7299                 limit = &intel_limits_g4x_sdvo;
7300         } else {
7301                 /* The option is for other outputs */
7302                 limit = &intel_limits_i9xx_sdvo;
7303         }
7304
7305         if (!crtc_state->clock_set &&
7306             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7307                                 refclk, NULL, &crtc_state->dpll)) {
7308                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7309                 return -EINVAL;
7310         }
7311
7312         i9xx_compute_dpll(crtc, crtc_state, NULL);
7313
7314         return 0;
7315 }
7316
7317 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7318                                   struct intel_crtc_state *crtc_state)
7319 {
7320         struct drm_device *dev = crtc->base.dev;
7321         struct drm_i915_private *dev_priv = to_i915(dev);
7322         const struct intel_limit *limit;
7323         int refclk = 96000;
7324
7325         memset(&crtc_state->dpll_hw_state, 0,
7326                sizeof(crtc_state->dpll_hw_state));
7327
7328         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7329                 if (intel_panel_use_ssc(dev_priv)) {
7330                         refclk = dev_priv->vbt.lvds_ssc_freq;
7331                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7332                 }
7333
7334                 limit = &intel_limits_pineview_lvds;
7335         } else {
7336                 limit = &intel_limits_pineview_sdvo;
7337         }
7338
7339         if (!crtc_state->clock_set &&
7340             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7341                                 refclk, NULL, &crtc_state->dpll)) {
7342                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7343                 return -EINVAL;
7344         }
7345
7346         i9xx_compute_dpll(crtc, crtc_state, NULL);
7347
7348         return 0;
7349 }
7350
7351 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7352                                    struct intel_crtc_state *crtc_state)
7353 {
7354         struct drm_device *dev = crtc->base.dev;
7355         struct drm_i915_private *dev_priv = to_i915(dev);
7356         const struct intel_limit *limit;
7357         int refclk = 96000;
7358
7359         memset(&crtc_state->dpll_hw_state, 0,
7360                sizeof(crtc_state->dpll_hw_state));
7361
7362         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7363                 if (intel_panel_use_ssc(dev_priv)) {
7364                         refclk = dev_priv->vbt.lvds_ssc_freq;
7365                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7366                 }
7367
7368                 limit = &intel_limits_i9xx_lvds;
7369         } else {
7370                 limit = &intel_limits_i9xx_sdvo;
7371         }
7372
7373         if (!crtc_state->clock_set &&
7374             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7375                                  refclk, NULL, &crtc_state->dpll)) {
7376                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7377                 return -EINVAL;
7378         }
7379
7380         i9xx_compute_dpll(crtc, crtc_state, NULL);
7381
7382         return 0;
7383 }
7384
7385 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7386                                   struct intel_crtc_state *crtc_state)
7387 {
7388         int refclk = 100000;
7389         const struct intel_limit *limit = &intel_limits_chv;
7390
7391         memset(&crtc_state->dpll_hw_state, 0,
7392                sizeof(crtc_state->dpll_hw_state));
7393
7394         if (!crtc_state->clock_set &&
7395             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7396                                 refclk, NULL, &crtc_state->dpll)) {
7397                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7398                 return -EINVAL;
7399         }
7400
7401         chv_compute_dpll(crtc, crtc_state);
7402
7403         return 0;
7404 }
7405
7406 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7407                                   struct intel_crtc_state *crtc_state)
7408 {
7409         int refclk = 100000;
7410         const struct intel_limit *limit = &intel_limits_vlv;
7411
7412         memset(&crtc_state->dpll_hw_state, 0,
7413                sizeof(crtc_state->dpll_hw_state));
7414
7415         if (!crtc_state->clock_set &&
7416             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7417                                 refclk, NULL, &crtc_state->dpll)) {
7418                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7419                 return -EINVAL;
7420         }
7421
7422         vlv_compute_dpll(crtc, crtc_state);
7423
7424         return 0;
7425 }
7426
7427 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7428                                  struct intel_crtc_state *pipe_config)
7429 {
7430         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7431         uint32_t tmp;
7432
7433         if (INTEL_GEN(dev_priv) <= 3 &&
7434             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7435                 return;
7436
7437         tmp = I915_READ(PFIT_CONTROL);
7438         if (!(tmp & PFIT_ENABLE))
7439                 return;
7440
7441         /* Check whether the pfit is attached to our pipe. */
7442         if (INTEL_GEN(dev_priv) < 4) {
7443                 if (crtc->pipe != PIPE_B)
7444                         return;
7445         } else {
7446                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7447                         return;
7448         }
7449
7450         pipe_config->gmch_pfit.control = tmp;
7451         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7452 }
7453
7454 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7455                                struct intel_crtc_state *pipe_config)
7456 {
7457         struct drm_device *dev = crtc->base.dev;
7458         struct drm_i915_private *dev_priv = to_i915(dev);
7459         int pipe = pipe_config->cpu_transcoder;
7460         struct dpll clock;
7461         u32 mdiv;
7462         int refclk = 100000;
7463
7464         /* In case of DSI, DPLL will not be used */
7465         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7466                 return;
7467
7468         mutex_lock(&dev_priv->sb_lock);
7469         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7470         mutex_unlock(&dev_priv->sb_lock);
7471
7472         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7473         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7474         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7475         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7476         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7477
7478         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7479 }
7480
7481 static void
7482 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7483                               struct intel_initial_plane_config *plane_config)
7484 {
7485         struct drm_device *dev = crtc->base.dev;
7486         struct drm_i915_private *dev_priv = to_i915(dev);
7487         u32 val, base, offset;
7488         int pipe = crtc->pipe, plane = crtc->plane;
7489         int fourcc, pixel_format;
7490         unsigned int aligned_height;
7491         struct drm_framebuffer *fb;
7492         struct intel_framebuffer *intel_fb;
7493
7494         val = I915_READ(DSPCNTR(plane));
7495         if (!(val & DISPLAY_PLANE_ENABLE))
7496                 return;
7497
7498         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7499         if (!intel_fb) {
7500                 DRM_DEBUG_KMS("failed to alloc fb\n");
7501                 return;
7502         }
7503
7504         fb = &intel_fb->base;
7505
7506         fb->dev = dev;
7507
7508         if (INTEL_GEN(dev_priv) >= 4) {
7509                 if (val & DISPPLANE_TILED) {
7510                         plane_config->tiling = I915_TILING_X;
7511                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7512                 }
7513         }
7514
7515         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7516         fourcc = i9xx_format_to_fourcc(pixel_format);
7517         fb->format = drm_format_info(fourcc);
7518
7519         if (INTEL_GEN(dev_priv) >= 4) {
7520                 if (plane_config->tiling)
7521                         offset = I915_READ(DSPTILEOFF(plane));
7522                 else
7523                         offset = I915_READ(DSPLINOFF(plane));
7524                 base = I915_READ(DSPSURF(plane)) & 0xfffff000;
7525         } else {
7526                 base = I915_READ(DSPADDR(plane));
7527         }
7528         plane_config->base = base;
7529
7530         val = I915_READ(PIPESRC(pipe));
7531         fb->width = ((val >> 16) & 0xfff) + 1;
7532         fb->height = ((val >> 0) & 0xfff) + 1;
7533
7534         val = I915_READ(DSPSTRIDE(pipe));
7535         fb->pitches[0] = val & 0xffffffc0;
7536
7537         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7538
7539         plane_config->size = fb->pitches[0] * aligned_height;
7540
7541         DRM_DEBUG_KMS("pipe/plane %c/%d with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7542                       pipe_name(pipe), plane, fb->width, fb->height,
7543                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7544                       plane_config->size);
7545
7546         plane_config->fb = intel_fb;
7547 }
7548
7549 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7550                                struct intel_crtc_state *pipe_config)
7551 {
7552         struct drm_device *dev = crtc->base.dev;
7553         struct drm_i915_private *dev_priv = to_i915(dev);
7554         int pipe = pipe_config->cpu_transcoder;
7555         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7556         struct dpll clock;
7557         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7558         int refclk = 100000;
7559
7560         /* In case of DSI, DPLL will not be used */
7561         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7562                 return;
7563
7564         mutex_lock(&dev_priv->sb_lock);
7565         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7566         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7567         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7568         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7569         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7570         mutex_unlock(&dev_priv->sb_lock);
7571
7572         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7573         clock.m2 = (pll_dw0 & 0xff) << 22;
7574         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7575                 clock.m2 |= pll_dw2 & 0x3fffff;
7576         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7577         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7578         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7579
7580         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7581 }
7582
7583 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7584                                  struct intel_crtc_state *pipe_config)
7585 {
7586         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7587         enum intel_display_power_domain power_domain;
7588         uint32_t tmp;
7589         bool ret;
7590
7591         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7592         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7593                 return false;
7594
7595         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7596         pipe_config->shared_dpll = NULL;
7597
7598         ret = false;
7599
7600         tmp = I915_READ(PIPECONF(crtc->pipe));
7601         if (!(tmp & PIPECONF_ENABLE))
7602                 goto out;
7603
7604         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7605             IS_CHERRYVIEW(dev_priv)) {
7606                 switch (tmp & PIPECONF_BPC_MASK) {
7607                 case PIPECONF_6BPC:
7608                         pipe_config->pipe_bpp = 18;
7609                         break;
7610                 case PIPECONF_8BPC:
7611                         pipe_config->pipe_bpp = 24;
7612                         break;
7613                 case PIPECONF_10BPC:
7614                         pipe_config->pipe_bpp = 30;
7615                         break;
7616                 default:
7617                         break;
7618                 }
7619         }
7620
7621         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7622             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7623                 pipe_config->limited_color_range = true;
7624
7625         if (INTEL_GEN(dev_priv) < 4)
7626                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7627
7628         intel_get_pipe_timings(crtc, pipe_config);
7629         intel_get_pipe_src_size(crtc, pipe_config);
7630
7631         i9xx_get_pfit_config(crtc, pipe_config);
7632
7633         if (INTEL_GEN(dev_priv) >= 4) {
7634                 /* No way to read it out on pipes B and C */
7635                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7636                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7637                 else
7638                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7639                 pipe_config->pixel_multiplier =
7640                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7641                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7642                 pipe_config->dpll_hw_state.dpll_md = tmp;
7643         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7644                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7645                 tmp = I915_READ(DPLL(crtc->pipe));
7646                 pipe_config->pixel_multiplier =
7647                         ((tmp & SDVO_MULTIPLIER_MASK)
7648                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7649         } else {
7650                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7651                  * port and will be fixed up in the encoder->get_config
7652                  * function. */
7653                 pipe_config->pixel_multiplier = 1;
7654         }
7655         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7656         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7657                 /*
7658                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7659                  * on 830. Filter it out here so that we don't
7660                  * report errors due to that.
7661                  */
7662                 if (IS_I830(dev_priv))
7663                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7664
7665                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7666                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7667         } else {
7668                 /* Mask out read-only status bits. */
7669                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7670                                                      DPLL_PORTC_READY_MASK |
7671                                                      DPLL_PORTB_READY_MASK);
7672         }
7673
7674         if (IS_CHERRYVIEW(dev_priv))
7675                 chv_crtc_clock_get(crtc, pipe_config);
7676         else if (IS_VALLEYVIEW(dev_priv))
7677                 vlv_crtc_clock_get(crtc, pipe_config);
7678         else
7679                 i9xx_crtc_clock_get(crtc, pipe_config);
7680
7681         /*
7682          * Normally the dotclock is filled in by the encoder .get_config()
7683          * but in case the pipe is enabled w/o any ports we need a sane
7684          * default.
7685          */
7686         pipe_config->base.adjusted_mode.crtc_clock =
7687                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7688
7689         ret = true;
7690
7691 out:
7692         intel_display_power_put(dev_priv, power_domain);
7693
7694         return ret;
7695 }
7696
7697 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7698 {
7699         struct intel_encoder *encoder;
7700         int i;
7701         u32 val, final;
7702         bool has_lvds = false;
7703         bool has_cpu_edp = false;
7704         bool has_panel = false;
7705         bool has_ck505 = false;
7706         bool can_ssc = false;
7707         bool using_ssc_source = false;
7708
7709         /* We need to take the global config into account */
7710         for_each_intel_encoder(&dev_priv->drm, encoder) {
7711                 switch (encoder->type) {
7712                 case INTEL_OUTPUT_LVDS:
7713                         has_panel = true;
7714                         has_lvds = true;
7715                         break;
7716                 case INTEL_OUTPUT_EDP:
7717                         has_panel = true;
7718                         if (enc_to_dig_port(&encoder->base)->port == PORT_A)
7719                                 has_cpu_edp = true;
7720                         break;
7721                 default:
7722                         break;
7723                 }
7724         }
7725
7726         if (HAS_PCH_IBX(dev_priv)) {
7727                 has_ck505 = dev_priv->vbt.display_clock_mode;
7728                 can_ssc = has_ck505;
7729         } else {
7730                 has_ck505 = false;
7731                 can_ssc = true;
7732         }
7733
7734         /* Check if any DPLLs are using the SSC source */
7735         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7736                 u32 temp = I915_READ(PCH_DPLL(i));
7737
7738                 if (!(temp & DPLL_VCO_ENABLE))
7739                         continue;
7740
7741                 if ((temp & PLL_REF_INPUT_MASK) ==
7742                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7743                         using_ssc_source = true;
7744                         break;
7745                 }
7746         }
7747
7748         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7749                       has_panel, has_lvds, has_ck505, using_ssc_source);
7750
7751         /* Ironlake: try to setup display ref clock before DPLL
7752          * enabling. This is only under driver's control after
7753          * PCH B stepping, previous chipset stepping should be
7754          * ignoring this setting.
7755          */
7756         val = I915_READ(PCH_DREF_CONTROL);
7757
7758         /* As we must carefully and slowly disable/enable each source in turn,
7759          * compute the final state we want first and check if we need to
7760          * make any changes at all.
7761          */
7762         final = val;
7763         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7764         if (has_ck505)
7765                 final |= DREF_NONSPREAD_CK505_ENABLE;
7766         else
7767                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7768
7769         final &= ~DREF_SSC_SOURCE_MASK;
7770         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7771         final &= ~DREF_SSC1_ENABLE;
7772
7773         if (has_panel) {
7774                 final |= DREF_SSC_SOURCE_ENABLE;
7775
7776                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7777                         final |= DREF_SSC1_ENABLE;
7778
7779                 if (has_cpu_edp) {
7780                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7781                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7782                         else
7783                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7784                 } else
7785                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7786         } else if (using_ssc_source) {
7787                 final |= DREF_SSC_SOURCE_ENABLE;
7788                 final |= DREF_SSC1_ENABLE;
7789         }
7790
7791         if (final == val)
7792                 return;
7793
7794         /* Always enable nonspread source */
7795         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7796
7797         if (has_ck505)
7798                 val |= DREF_NONSPREAD_CK505_ENABLE;
7799         else
7800                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7801
7802         if (has_panel) {
7803                 val &= ~DREF_SSC_SOURCE_MASK;
7804                 val |= DREF_SSC_SOURCE_ENABLE;
7805
7806                 /* SSC must be turned on before enabling the CPU output  */
7807                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7808                         DRM_DEBUG_KMS("Using SSC on panel\n");
7809                         val |= DREF_SSC1_ENABLE;
7810                 } else
7811                         val &= ~DREF_SSC1_ENABLE;
7812
7813                 /* Get SSC going before enabling the outputs */
7814                 I915_WRITE(PCH_DREF_CONTROL, val);
7815                 POSTING_READ(PCH_DREF_CONTROL);
7816                 udelay(200);
7817
7818                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7819
7820                 /* Enable CPU source on CPU attached eDP */
7821                 if (has_cpu_edp) {
7822                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7823                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7824                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7825                         } else
7826                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7827                 } else
7828                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7829
7830                 I915_WRITE(PCH_DREF_CONTROL, val);
7831                 POSTING_READ(PCH_DREF_CONTROL);
7832                 udelay(200);
7833         } else {
7834                 DRM_DEBUG_KMS("Disabling CPU source output\n");
7835
7836                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7837
7838                 /* Turn off CPU output */
7839                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7840
7841                 I915_WRITE(PCH_DREF_CONTROL, val);
7842                 POSTING_READ(PCH_DREF_CONTROL);
7843                 udelay(200);
7844
7845                 if (!using_ssc_source) {
7846                         DRM_DEBUG_KMS("Disabling SSC source\n");
7847
7848                         /* Turn off the SSC source */
7849                         val &= ~DREF_SSC_SOURCE_MASK;
7850                         val |= DREF_SSC_SOURCE_DISABLE;
7851
7852                         /* Turn off SSC1 */
7853                         val &= ~DREF_SSC1_ENABLE;
7854
7855                         I915_WRITE(PCH_DREF_CONTROL, val);
7856                         POSTING_READ(PCH_DREF_CONTROL);
7857                         udelay(200);
7858                 }
7859         }
7860
7861         BUG_ON(val != final);
7862 }
7863
7864 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7865 {
7866         uint32_t tmp;
7867
7868         tmp = I915_READ(SOUTH_CHICKEN2);
7869         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7870         I915_WRITE(SOUTH_CHICKEN2, tmp);
7871
7872         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
7873                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7874                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7875
7876         tmp = I915_READ(SOUTH_CHICKEN2);
7877         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7878         I915_WRITE(SOUTH_CHICKEN2, tmp);
7879
7880         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
7881                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7882                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7883 }
7884
7885 /* WaMPhyProgramming:hsw */
7886 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7887 {
7888         uint32_t tmp;
7889
7890         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7891         tmp &= ~(0xFF << 24);
7892         tmp |= (0x12 << 24);
7893         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
7894
7895         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
7896         tmp |= (1 << 11);
7897         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
7898
7899         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
7900         tmp |= (1 << 11);
7901         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
7902
7903         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
7904         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7905         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
7906
7907         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
7908         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7909         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
7910
7911         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
7912         tmp &= ~(7 << 13);
7913         tmp |= (5 << 13);
7914         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
7915
7916         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
7917         tmp &= ~(7 << 13);
7918         tmp |= (5 << 13);
7919         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
7920
7921         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
7922         tmp &= ~0xFF;
7923         tmp |= 0x1C;
7924         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
7925
7926         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
7927         tmp &= ~0xFF;
7928         tmp |= 0x1C;
7929         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
7930
7931         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
7932         tmp &= ~(0xFF << 16);
7933         tmp |= (0x1C << 16);
7934         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
7935
7936         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
7937         tmp &= ~(0xFF << 16);
7938         tmp |= (0x1C << 16);
7939         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
7940
7941         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
7942         tmp |= (1 << 27);
7943         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
7944
7945         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
7946         tmp |= (1 << 27);
7947         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
7948
7949         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
7950         tmp &= ~(0xF << 28);
7951         tmp |= (4 << 28);
7952         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
7953
7954         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
7955         tmp &= ~(0xF << 28);
7956         tmp |= (4 << 28);
7957         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
7958 }
7959
7960 /* Implements 3 different sequences from BSpec chapter "Display iCLK
7961  * Programming" based on the parameters passed:
7962  * - Sequence to enable CLKOUT_DP
7963  * - Sequence to enable CLKOUT_DP without spread
7964  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
7965  */
7966 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
7967                                  bool with_spread, bool with_fdi)
7968 {
7969         uint32_t reg, tmp;
7970
7971         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
7972                 with_spread = true;
7973         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
7974             with_fdi, "LP PCH doesn't have FDI\n"))
7975                 with_fdi = false;
7976
7977         mutex_lock(&dev_priv->sb_lock);
7978
7979         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7980         tmp &= ~SBI_SSCCTL_DISABLE;
7981         tmp |= SBI_SSCCTL_PATHALT;
7982         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7983
7984         udelay(24);
7985
7986         if (with_spread) {
7987                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7988                 tmp &= ~SBI_SSCCTL_PATHALT;
7989                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7990
7991                 if (with_fdi) {
7992                         lpt_reset_fdi_mphy(dev_priv);
7993                         lpt_program_fdi_mphy(dev_priv);
7994                 }
7995         }
7996
7997         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
7998         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7999         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8000         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8001
8002         mutex_unlock(&dev_priv->sb_lock);
8003 }
8004
8005 /* Sequence to disable CLKOUT_DP */
8006 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8007 {
8008         uint32_t reg, tmp;
8009
8010         mutex_lock(&dev_priv->sb_lock);
8011
8012         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8013         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8014         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8015         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8016
8017         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8018         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8019                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8020                         tmp |= SBI_SSCCTL_PATHALT;
8021                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8022                         udelay(32);
8023                 }
8024                 tmp |= SBI_SSCCTL_DISABLE;
8025                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8026         }
8027
8028         mutex_unlock(&dev_priv->sb_lock);
8029 }
8030
8031 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8032
8033 static const uint16_t sscdivintphase[] = {
8034         [BEND_IDX( 50)] = 0x3B23,
8035         [BEND_IDX( 45)] = 0x3B23,
8036         [BEND_IDX( 40)] = 0x3C23,
8037         [BEND_IDX( 35)] = 0x3C23,
8038         [BEND_IDX( 30)] = 0x3D23,
8039         [BEND_IDX( 25)] = 0x3D23,
8040         [BEND_IDX( 20)] = 0x3E23,
8041         [BEND_IDX( 15)] = 0x3E23,
8042         [BEND_IDX( 10)] = 0x3F23,
8043         [BEND_IDX(  5)] = 0x3F23,
8044         [BEND_IDX(  0)] = 0x0025,
8045         [BEND_IDX( -5)] = 0x0025,
8046         [BEND_IDX(-10)] = 0x0125,
8047         [BEND_IDX(-15)] = 0x0125,
8048         [BEND_IDX(-20)] = 0x0225,
8049         [BEND_IDX(-25)] = 0x0225,
8050         [BEND_IDX(-30)] = 0x0325,
8051         [BEND_IDX(-35)] = 0x0325,
8052         [BEND_IDX(-40)] = 0x0425,
8053         [BEND_IDX(-45)] = 0x0425,
8054         [BEND_IDX(-50)] = 0x0525,
8055 };
8056
8057 /*
8058  * Bend CLKOUT_DP
8059  * steps -50 to 50 inclusive, in steps of 5
8060  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8061  * change in clock period = -(steps / 10) * 5.787 ps
8062  */
8063 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8064 {
8065         uint32_t tmp;
8066         int idx = BEND_IDX(steps);
8067
8068         if (WARN_ON(steps % 5 != 0))
8069                 return;
8070
8071         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8072                 return;
8073
8074         mutex_lock(&dev_priv->sb_lock);
8075
8076         if (steps % 10 != 0)
8077                 tmp = 0xAAAAAAAB;
8078         else
8079                 tmp = 0x00000000;
8080         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8081
8082         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8083         tmp &= 0xffff0000;
8084         tmp |= sscdivintphase[idx];
8085         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8086
8087         mutex_unlock(&dev_priv->sb_lock);
8088 }
8089
8090 #undef BEND_IDX
8091
8092 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8093 {
8094         struct intel_encoder *encoder;
8095         bool has_vga = false;
8096
8097         for_each_intel_encoder(&dev_priv->drm, encoder) {
8098                 switch (encoder->type) {
8099                 case INTEL_OUTPUT_ANALOG:
8100                         has_vga = true;
8101                         break;
8102                 default:
8103                         break;
8104                 }
8105         }
8106
8107         if (has_vga) {
8108                 lpt_bend_clkout_dp(dev_priv, 0);
8109                 lpt_enable_clkout_dp(dev_priv, true, true);
8110         } else {
8111                 lpt_disable_clkout_dp(dev_priv);
8112         }
8113 }
8114
8115 /*
8116  * Initialize reference clocks when the driver loads
8117  */
8118 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8119 {
8120         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8121                 ironlake_init_pch_refclk(dev_priv);
8122         else if (HAS_PCH_LPT(dev_priv))
8123                 lpt_init_pch_refclk(dev_priv);
8124 }
8125
8126 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8127 {
8128         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8129         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8130         int pipe = intel_crtc->pipe;
8131         uint32_t val;
8132
8133         val = 0;
8134
8135         switch (intel_crtc->config->pipe_bpp) {
8136         case 18:
8137                 val |= PIPECONF_6BPC;
8138                 break;
8139         case 24:
8140                 val |= PIPECONF_8BPC;
8141                 break;
8142         case 30:
8143                 val |= PIPECONF_10BPC;
8144                 break;
8145         case 36:
8146                 val |= PIPECONF_12BPC;
8147                 break;
8148         default:
8149                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8150                 BUG();
8151         }
8152
8153         if (intel_crtc->config->dither)
8154                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8155
8156         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8157                 val |= PIPECONF_INTERLACED_ILK;
8158         else
8159                 val |= PIPECONF_PROGRESSIVE;
8160
8161         if (intel_crtc->config->limited_color_range)
8162                 val |= PIPECONF_COLOR_RANGE_SELECT;
8163
8164         I915_WRITE(PIPECONF(pipe), val);
8165         POSTING_READ(PIPECONF(pipe));
8166 }
8167
8168 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8169 {
8170         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8171         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8172         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8173         u32 val = 0;
8174
8175         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8176                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8177
8178         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8179                 val |= PIPECONF_INTERLACED_ILK;
8180         else
8181                 val |= PIPECONF_PROGRESSIVE;
8182
8183         I915_WRITE(PIPECONF(cpu_transcoder), val);
8184         POSTING_READ(PIPECONF(cpu_transcoder));
8185 }
8186
8187 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8188 {
8189         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8190         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8191         struct intel_crtc_state *config = intel_crtc->config;
8192
8193         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8194                 u32 val = 0;
8195
8196                 switch (intel_crtc->config->pipe_bpp) {
8197                 case 18:
8198                         val |= PIPEMISC_DITHER_6_BPC;
8199                         break;
8200                 case 24:
8201                         val |= PIPEMISC_DITHER_8_BPC;
8202                         break;
8203                 case 30:
8204                         val |= PIPEMISC_DITHER_10_BPC;
8205                         break;
8206                 case 36:
8207                         val |= PIPEMISC_DITHER_12_BPC;
8208                         break;
8209                 default:
8210                         /* Case prevented by pipe_config_set_bpp. */
8211                         BUG();
8212                 }
8213
8214                 if (intel_crtc->config->dither)
8215                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8216
8217                 if (config->ycbcr420) {
8218                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8219                                 PIPEMISC_YUV420_ENABLE |
8220                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8221                 }
8222
8223                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8224         }
8225 }
8226
8227 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8228 {
8229         /*
8230          * Account for spread spectrum to avoid
8231          * oversubscribing the link. Max center spread
8232          * is 2.5%; use 5% for safety's sake.
8233          */
8234         u32 bps = target_clock * bpp * 21 / 20;
8235         return DIV_ROUND_UP(bps, link_bw * 8);
8236 }
8237
8238 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8239 {
8240         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8241 }
8242
8243 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8244                                   struct intel_crtc_state *crtc_state,
8245                                   struct dpll *reduced_clock)
8246 {
8247         struct drm_crtc *crtc = &intel_crtc->base;
8248         struct drm_device *dev = crtc->dev;
8249         struct drm_i915_private *dev_priv = to_i915(dev);
8250         u32 dpll, fp, fp2;
8251         int factor;
8252
8253         /* Enable autotuning of the PLL clock (if permissible) */
8254         factor = 21;
8255         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8256                 if ((intel_panel_use_ssc(dev_priv) &&
8257                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8258                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8259                         factor = 25;
8260         } else if (crtc_state->sdvo_tv_clock)
8261                 factor = 20;
8262
8263         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8264
8265         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8266                 fp |= FP_CB_TUNE;
8267
8268         if (reduced_clock) {
8269                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8270
8271                 if (reduced_clock->m < factor * reduced_clock->n)
8272                         fp2 |= FP_CB_TUNE;
8273         } else {
8274                 fp2 = fp;
8275         }
8276
8277         dpll = 0;
8278
8279         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8280                 dpll |= DPLLB_MODE_LVDS;
8281         else
8282                 dpll |= DPLLB_MODE_DAC_SERIAL;
8283
8284         dpll |= (crtc_state->pixel_multiplier - 1)
8285                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8286
8287         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8288             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8289                 dpll |= DPLL_SDVO_HIGH_SPEED;
8290
8291         if (intel_crtc_has_dp_encoder(crtc_state))
8292                 dpll |= DPLL_SDVO_HIGH_SPEED;
8293
8294         /*
8295          * The high speed IO clock is only really required for
8296          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8297          * possible to share the DPLL between CRT and HDMI. Enabling
8298          * the clock needlessly does no real harm, except use up a
8299          * bit of power potentially.
8300          *
8301          * We'll limit this to IVB with 3 pipes, since it has only two
8302          * DPLLs and so DPLL sharing is the only way to get three pipes
8303          * driving PCH ports at the same time. On SNB we could do this,
8304          * and potentially avoid enabling the second DPLL, but it's not
8305          * clear if it''s a win or loss power wise. No point in doing
8306          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8307          */
8308         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8309             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8310                 dpll |= DPLL_SDVO_HIGH_SPEED;
8311
8312         /* compute bitmask from p1 value */
8313         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8314         /* also FPA1 */
8315         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8316
8317         switch (crtc_state->dpll.p2) {
8318         case 5:
8319                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8320                 break;
8321         case 7:
8322                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8323                 break;
8324         case 10:
8325                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8326                 break;
8327         case 14:
8328                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8329                 break;
8330         }
8331
8332         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8333             intel_panel_use_ssc(dev_priv))
8334                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8335         else
8336                 dpll |= PLL_REF_INPUT_DREFCLK;
8337
8338         dpll |= DPLL_VCO_ENABLE;
8339
8340         crtc_state->dpll_hw_state.dpll = dpll;
8341         crtc_state->dpll_hw_state.fp0 = fp;
8342         crtc_state->dpll_hw_state.fp1 = fp2;
8343 }
8344
8345 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8346                                        struct intel_crtc_state *crtc_state)
8347 {
8348         struct drm_device *dev = crtc->base.dev;
8349         struct drm_i915_private *dev_priv = to_i915(dev);
8350         const struct intel_limit *limit;
8351         int refclk = 120000;
8352
8353         memset(&crtc_state->dpll_hw_state, 0,
8354                sizeof(crtc_state->dpll_hw_state));
8355
8356         crtc->lowfreq_avail = false;
8357
8358         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8359         if (!crtc_state->has_pch_encoder)
8360                 return 0;
8361
8362         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8363                 if (intel_panel_use_ssc(dev_priv)) {
8364                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8365                                       dev_priv->vbt.lvds_ssc_freq);
8366                         refclk = dev_priv->vbt.lvds_ssc_freq;
8367                 }
8368
8369                 if (intel_is_dual_link_lvds(dev)) {
8370                         if (refclk == 100000)
8371                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8372                         else
8373                                 limit = &intel_limits_ironlake_dual_lvds;
8374                 } else {
8375                         if (refclk == 100000)
8376                                 limit = &intel_limits_ironlake_single_lvds_100m;
8377                         else
8378                                 limit = &intel_limits_ironlake_single_lvds;
8379                 }
8380         } else {
8381                 limit = &intel_limits_ironlake_dac;
8382         }
8383
8384         if (!crtc_state->clock_set &&
8385             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8386                                 refclk, NULL, &crtc_state->dpll)) {
8387                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8388                 return -EINVAL;
8389         }
8390
8391         ironlake_compute_dpll(crtc, crtc_state, NULL);
8392
8393         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8394                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8395                                  pipe_name(crtc->pipe));
8396                 return -EINVAL;
8397         }
8398
8399         return 0;
8400 }
8401
8402 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8403                                          struct intel_link_m_n *m_n)
8404 {
8405         struct drm_device *dev = crtc->base.dev;
8406         struct drm_i915_private *dev_priv = to_i915(dev);
8407         enum pipe pipe = crtc->pipe;
8408
8409         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8410         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8411         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8412                 & ~TU_SIZE_MASK;
8413         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8414         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8415                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8416 }
8417
8418 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8419                                          enum transcoder transcoder,
8420                                          struct intel_link_m_n *m_n,
8421                                          struct intel_link_m_n *m2_n2)
8422 {
8423         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8424         enum pipe pipe = crtc->pipe;
8425
8426         if (INTEL_GEN(dev_priv) >= 5) {
8427                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8428                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8429                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8430                         & ~TU_SIZE_MASK;
8431                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8432                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8433                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8434                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8435                  * gen < 8) and if DRRS is supported (to make sure the
8436                  * registers are not unnecessarily read).
8437                  */
8438                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8439                         crtc->config->has_drrs) {
8440                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8441                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8442                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8443                                         & ~TU_SIZE_MASK;
8444                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8445                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8446                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8447                 }
8448         } else {
8449                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8450                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8451                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8452                         & ~TU_SIZE_MASK;
8453                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8454                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8455                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8456         }
8457 }
8458
8459 void intel_dp_get_m_n(struct intel_crtc *crtc,
8460                       struct intel_crtc_state *pipe_config)
8461 {
8462         if (pipe_config->has_pch_encoder)
8463                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8464         else
8465                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8466                                              &pipe_config->dp_m_n,
8467                                              &pipe_config->dp_m2_n2);
8468 }
8469
8470 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8471                                         struct intel_crtc_state *pipe_config)
8472 {
8473         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8474                                      &pipe_config->fdi_m_n, NULL);
8475 }
8476
8477 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8478                                     struct intel_crtc_state *pipe_config)
8479 {
8480         struct drm_device *dev = crtc->base.dev;
8481         struct drm_i915_private *dev_priv = to_i915(dev);
8482         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8483         uint32_t ps_ctrl = 0;
8484         int id = -1;
8485         int i;
8486
8487         /* find scaler attached to this pipe */
8488         for (i = 0; i < crtc->num_scalers; i++) {
8489                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8490                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8491                         id = i;
8492                         pipe_config->pch_pfit.enabled = true;
8493                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8494                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8495                         break;
8496                 }
8497         }
8498
8499         scaler_state->scaler_id = id;
8500         if (id >= 0) {
8501                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8502         } else {
8503                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8504         }
8505 }
8506
8507 static void
8508 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8509                                  struct intel_initial_plane_config *plane_config)
8510 {
8511         struct drm_device *dev = crtc->base.dev;
8512         struct drm_i915_private *dev_priv = to_i915(dev);
8513         u32 val, base, offset, stride_mult, tiling;
8514         int pipe = crtc->pipe;
8515         int fourcc, pixel_format;
8516         unsigned int aligned_height;
8517         struct drm_framebuffer *fb;
8518         struct intel_framebuffer *intel_fb;
8519
8520         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8521         if (!intel_fb) {
8522                 DRM_DEBUG_KMS("failed to alloc fb\n");
8523                 return;
8524         }
8525
8526         fb = &intel_fb->base;
8527
8528         fb->dev = dev;
8529
8530         val = I915_READ(PLANE_CTL(pipe, 0));
8531         if (!(val & PLANE_CTL_ENABLE))
8532                 goto error;
8533
8534         pixel_format = val & PLANE_CTL_FORMAT_MASK;
8535         fourcc = skl_format_to_fourcc(pixel_format,
8536                                       val & PLANE_CTL_ORDER_RGBX,
8537                                       val & PLANE_CTL_ALPHA_MASK);
8538         fb->format = drm_format_info(fourcc);
8539
8540         tiling = val & PLANE_CTL_TILED_MASK;
8541         switch (tiling) {
8542         case PLANE_CTL_TILED_LINEAR:
8543                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8544                 break;
8545         case PLANE_CTL_TILED_X:
8546                 plane_config->tiling = I915_TILING_X;
8547                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8548                 break;
8549         case PLANE_CTL_TILED_Y:
8550                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8551                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8552                 else
8553                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8554                 break;
8555         case PLANE_CTL_TILED_YF:
8556                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8557                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8558                 else
8559                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8560                 break;
8561         default:
8562                 MISSING_CASE(tiling);
8563                 goto error;
8564         }
8565
8566         base = I915_READ(PLANE_SURF(pipe, 0)) & 0xfffff000;
8567         plane_config->base = base;
8568
8569         offset = I915_READ(PLANE_OFFSET(pipe, 0));
8570
8571         val = I915_READ(PLANE_SIZE(pipe, 0));
8572         fb->height = ((val >> 16) & 0xfff) + 1;
8573         fb->width = ((val >> 0) & 0x1fff) + 1;
8574
8575         val = I915_READ(PLANE_STRIDE(pipe, 0));
8576         stride_mult = intel_fb_stride_alignment(fb, 0);
8577         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8578
8579         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8580
8581         plane_config->size = fb->pitches[0] * aligned_height;
8582
8583         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8584                       pipe_name(pipe), fb->width, fb->height,
8585                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8586                       plane_config->size);
8587
8588         plane_config->fb = intel_fb;
8589         return;
8590
8591 error:
8592         kfree(intel_fb);
8593 }
8594
8595 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8596                                      struct intel_crtc_state *pipe_config)
8597 {
8598         struct drm_device *dev = crtc->base.dev;
8599         struct drm_i915_private *dev_priv = to_i915(dev);
8600         uint32_t tmp;
8601
8602         tmp = I915_READ(PF_CTL(crtc->pipe));
8603
8604         if (tmp & PF_ENABLE) {
8605                 pipe_config->pch_pfit.enabled = true;
8606                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8607                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8608
8609                 /* We currently do not free assignements of panel fitters on
8610                  * ivb/hsw (since we don't use the higher upscaling modes which
8611                  * differentiates them) so just WARN about this case for now. */
8612                 if (IS_GEN7(dev_priv)) {
8613                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8614                                 PF_PIPE_SEL_IVB(crtc->pipe));
8615                 }
8616         }
8617 }
8618
8619 static void
8620 ironlake_get_initial_plane_config(struct intel_crtc *crtc,
8621                                   struct intel_initial_plane_config *plane_config)
8622 {
8623         struct drm_device *dev = crtc->base.dev;
8624         struct drm_i915_private *dev_priv = to_i915(dev);
8625         u32 val, base, offset;
8626         int pipe = crtc->pipe;
8627         int fourcc, pixel_format;
8628         unsigned int aligned_height;
8629         struct drm_framebuffer *fb;
8630         struct intel_framebuffer *intel_fb;
8631
8632         val = I915_READ(DSPCNTR(pipe));
8633         if (!(val & DISPLAY_PLANE_ENABLE))
8634                 return;
8635
8636         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8637         if (!intel_fb) {
8638                 DRM_DEBUG_KMS("failed to alloc fb\n");
8639                 return;
8640         }
8641
8642         fb = &intel_fb->base;
8643
8644         fb->dev = dev;
8645
8646         if (INTEL_GEN(dev_priv) >= 4) {
8647                 if (val & DISPPLANE_TILED) {
8648                         plane_config->tiling = I915_TILING_X;
8649                         fb->modifier = I915_FORMAT_MOD_X_TILED;
8650                 }
8651         }
8652
8653         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
8654         fourcc = i9xx_format_to_fourcc(pixel_format);
8655         fb->format = drm_format_info(fourcc);
8656
8657         base = I915_READ(DSPSURF(pipe)) & 0xfffff000;
8658         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
8659                 offset = I915_READ(DSPOFFSET(pipe));
8660         } else {
8661                 if (plane_config->tiling)
8662                         offset = I915_READ(DSPTILEOFF(pipe));
8663                 else
8664                         offset = I915_READ(DSPLINOFF(pipe));
8665         }
8666         plane_config->base = base;
8667
8668         val = I915_READ(PIPESRC(pipe));
8669         fb->width = ((val >> 16) & 0xfff) + 1;
8670         fb->height = ((val >> 0) & 0xfff) + 1;
8671
8672         val = I915_READ(DSPSTRIDE(pipe));
8673         fb->pitches[0] = val & 0xffffffc0;
8674
8675         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8676
8677         plane_config->size = fb->pitches[0] * aligned_height;
8678
8679         DRM_DEBUG_KMS("pipe %c with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8680                       pipe_name(pipe), fb->width, fb->height,
8681                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8682                       plane_config->size);
8683
8684         plane_config->fb = intel_fb;
8685 }
8686
8687 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8688                                      struct intel_crtc_state *pipe_config)
8689 {
8690         struct drm_device *dev = crtc->base.dev;
8691         struct drm_i915_private *dev_priv = to_i915(dev);
8692         enum intel_display_power_domain power_domain;
8693         uint32_t tmp;
8694         bool ret;
8695
8696         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8697         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8698                 return false;
8699
8700         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8701         pipe_config->shared_dpll = NULL;
8702
8703         ret = false;
8704         tmp = I915_READ(PIPECONF(crtc->pipe));
8705         if (!(tmp & PIPECONF_ENABLE))
8706                 goto out;
8707
8708         switch (tmp & PIPECONF_BPC_MASK) {
8709         case PIPECONF_6BPC:
8710                 pipe_config->pipe_bpp = 18;
8711                 break;
8712         case PIPECONF_8BPC:
8713                 pipe_config->pipe_bpp = 24;
8714                 break;
8715         case PIPECONF_10BPC:
8716                 pipe_config->pipe_bpp = 30;
8717                 break;
8718         case PIPECONF_12BPC:
8719                 pipe_config->pipe_bpp = 36;
8720                 break;
8721         default:
8722                 break;
8723         }
8724
8725         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8726                 pipe_config->limited_color_range = true;
8727
8728         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8729                 struct intel_shared_dpll *pll;
8730                 enum intel_dpll_id pll_id;
8731
8732                 pipe_config->has_pch_encoder = true;
8733
8734                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8735                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8736                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8737
8738                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8739
8740                 if (HAS_PCH_IBX(dev_priv)) {
8741                         /*
8742                          * The pipe->pch transcoder and pch transcoder->pll
8743                          * mapping is fixed.
8744                          */
8745                         pll_id = (enum intel_dpll_id) crtc->pipe;
8746                 } else {
8747                         tmp = I915_READ(PCH_DPLL_SEL);
8748                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8749                                 pll_id = DPLL_ID_PCH_PLL_B;
8750                         else
8751                                 pll_id= DPLL_ID_PCH_PLL_A;
8752                 }
8753
8754                 pipe_config->shared_dpll =
8755                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8756                 pll = pipe_config->shared_dpll;
8757
8758                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
8759                                                  &pipe_config->dpll_hw_state));
8760
8761                 tmp = pipe_config->dpll_hw_state.dpll;
8762                 pipe_config->pixel_multiplier =
8763                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8764                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8765
8766                 ironlake_pch_clock_get(crtc, pipe_config);
8767         } else {
8768                 pipe_config->pixel_multiplier = 1;
8769         }
8770
8771         intel_get_pipe_timings(crtc, pipe_config);
8772         intel_get_pipe_src_size(crtc, pipe_config);
8773
8774         ironlake_get_pfit_config(crtc, pipe_config);
8775
8776         ret = true;
8777
8778 out:
8779         intel_display_power_put(dev_priv, power_domain);
8780
8781         return ret;
8782 }
8783
8784 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8785 {
8786         struct drm_device *dev = &dev_priv->drm;
8787         struct intel_crtc *crtc;
8788
8789         for_each_intel_crtc(dev, crtc)
8790                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8791                      pipe_name(crtc->pipe));
8792
8793         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL)),
8794                         "Display power well on\n");
8795         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8796         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8797         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8798         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8799         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8800              "CPU PWM1 enabled\n");
8801         if (IS_HASWELL(dev_priv))
8802                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8803                      "CPU PWM2 enabled\n");
8804         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8805              "PCH PWM1 enabled\n");
8806         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8807              "Utility pin enabled\n");
8808         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8809
8810         /*
8811          * In theory we can still leave IRQs enabled, as long as only the HPD
8812          * interrupts remain enabled. We used to check for that, but since it's
8813          * gen-specific and since we only disable LCPLL after we fully disable
8814          * the interrupts, the check below should be enough.
8815          */
8816         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8817 }
8818
8819 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8820 {
8821         if (IS_HASWELL(dev_priv))
8822                 return I915_READ(D_COMP_HSW);
8823         else
8824                 return I915_READ(D_COMP_BDW);
8825 }
8826
8827 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8828 {
8829         if (IS_HASWELL(dev_priv)) {
8830                 mutex_lock(&dev_priv->rps.hw_lock);
8831                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8832                                             val))
8833                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
8834                 mutex_unlock(&dev_priv->rps.hw_lock);
8835         } else {
8836                 I915_WRITE(D_COMP_BDW, val);
8837                 POSTING_READ(D_COMP_BDW);
8838         }
8839 }
8840
8841 /*
8842  * This function implements pieces of two sequences from BSpec:
8843  * - Sequence for display software to disable LCPLL
8844  * - Sequence for display software to allow package C8+
8845  * The steps implemented here are just the steps that actually touch the LCPLL
8846  * register. Callers should take care of disabling all the display engine
8847  * functions, doing the mode unset, fixing interrupts, etc.
8848  */
8849 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8850                               bool switch_to_fclk, bool allow_power_down)
8851 {
8852         uint32_t val;
8853
8854         assert_can_disable_lcpll(dev_priv);
8855
8856         val = I915_READ(LCPLL_CTL);
8857
8858         if (switch_to_fclk) {
8859                 val |= LCPLL_CD_SOURCE_FCLK;
8860                 I915_WRITE(LCPLL_CTL, val);
8861
8862                 if (wait_for_us(I915_READ(LCPLL_CTL) &
8863                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
8864                         DRM_ERROR("Switching to FCLK failed\n");
8865
8866                 val = I915_READ(LCPLL_CTL);
8867         }
8868
8869         val |= LCPLL_PLL_DISABLE;
8870         I915_WRITE(LCPLL_CTL, val);
8871         POSTING_READ(LCPLL_CTL);
8872
8873         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
8874                 DRM_ERROR("LCPLL still locked\n");
8875
8876         val = hsw_read_dcomp(dev_priv);
8877         val |= D_COMP_COMP_DISABLE;
8878         hsw_write_dcomp(dev_priv, val);
8879         ndelay(100);
8880
8881         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8882                      1))
8883                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8884
8885         if (allow_power_down) {
8886                 val = I915_READ(LCPLL_CTL);
8887                 val |= LCPLL_POWER_DOWN_ALLOW;
8888                 I915_WRITE(LCPLL_CTL, val);
8889                 POSTING_READ(LCPLL_CTL);
8890         }
8891 }
8892
8893 /*
8894  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8895  * source.
8896  */
8897 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8898 {
8899         uint32_t val;
8900
8901         val = I915_READ(LCPLL_CTL);
8902
8903         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8904                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8905                 return;
8906
8907         /*
8908          * Make sure we're not on PC8 state before disabling PC8, otherwise
8909          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8910          */
8911         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8912
8913         if (val & LCPLL_POWER_DOWN_ALLOW) {
8914                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8915                 I915_WRITE(LCPLL_CTL, val);
8916                 POSTING_READ(LCPLL_CTL);
8917         }
8918
8919         val = hsw_read_dcomp(dev_priv);
8920         val |= D_COMP_COMP_FORCE;
8921         val &= ~D_COMP_COMP_DISABLE;
8922         hsw_write_dcomp(dev_priv, val);
8923
8924         val = I915_READ(LCPLL_CTL);
8925         val &= ~LCPLL_PLL_DISABLE;
8926         I915_WRITE(LCPLL_CTL, val);
8927
8928         if (intel_wait_for_register(dev_priv,
8929                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
8930                                     5))
8931                 DRM_ERROR("LCPLL not locked yet\n");
8932
8933         if (val & LCPLL_CD_SOURCE_FCLK) {
8934                 val = I915_READ(LCPLL_CTL);
8935                 val &= ~LCPLL_CD_SOURCE_FCLK;
8936                 I915_WRITE(LCPLL_CTL, val);
8937
8938                 if (wait_for_us((I915_READ(LCPLL_CTL) &
8939                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8940                         DRM_ERROR("Switching back to LCPLL failed\n");
8941         }
8942
8943         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8944         intel_update_cdclk(dev_priv);
8945 }
8946
8947 /*
8948  * Package states C8 and deeper are really deep PC states that can only be
8949  * reached when all the devices on the system allow it, so even if the graphics
8950  * device allows PC8+, it doesn't mean the system will actually get to these
8951  * states. Our driver only allows PC8+ when going into runtime PM.
8952  *
8953  * The requirements for PC8+ are that all the outputs are disabled, the power
8954  * well is disabled and most interrupts are disabled, and these are also
8955  * requirements for runtime PM. When these conditions are met, we manually do
8956  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
8957  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
8958  * hang the machine.
8959  *
8960  * When we really reach PC8 or deeper states (not just when we allow it) we lose
8961  * the state of some registers, so when we come back from PC8+ we need to
8962  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
8963  * need to take care of the registers kept by RC6. Notice that this happens even
8964  * if we don't put the device in PCI D3 state (which is what currently happens
8965  * because of the runtime PM support).
8966  *
8967  * For more, read "Display Sequences for Package C8" on the hardware
8968  * documentation.
8969  */
8970 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
8971 {
8972         uint32_t val;
8973
8974         DRM_DEBUG_KMS("Enabling package C8+\n");
8975
8976         if (HAS_PCH_LPT_LP(dev_priv)) {
8977                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8978                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
8979                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8980         }
8981
8982         lpt_disable_clkout_dp(dev_priv);
8983         hsw_disable_lcpll(dev_priv, true, true);
8984 }
8985
8986 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
8987 {
8988         uint32_t val;
8989
8990         DRM_DEBUG_KMS("Disabling package C8+\n");
8991
8992         hsw_restore_lcpll(dev_priv);
8993         lpt_init_pch_refclk(dev_priv);
8994
8995         if (HAS_PCH_LPT_LP(dev_priv)) {
8996                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8997                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
8998                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8999         }
9000 }
9001
9002 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9003                                       struct intel_crtc_state *crtc_state)
9004 {
9005         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9006                 struct intel_encoder *encoder =
9007                         intel_ddi_get_crtc_new_encoder(crtc_state);
9008
9009                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9010                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9011                                          pipe_name(crtc->pipe));
9012                         return -EINVAL;
9013                 }
9014         }
9015
9016         crtc->lowfreq_avail = false;
9017
9018         return 0;
9019 }
9020
9021 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9022                                    enum port port,
9023                                    struct intel_crtc_state *pipe_config)
9024 {
9025         enum intel_dpll_id id;
9026         u32 temp;
9027
9028         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9029         id = temp >> (port * 2);
9030
9031         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9032                 return;
9033
9034         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9035 }
9036
9037 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9038                                 enum port port,
9039                                 struct intel_crtc_state *pipe_config)
9040 {
9041         enum intel_dpll_id id;
9042
9043         switch (port) {
9044         case PORT_A:
9045                 id = DPLL_ID_SKL_DPLL0;
9046                 break;
9047         case PORT_B:
9048                 id = DPLL_ID_SKL_DPLL1;
9049                 break;
9050         case PORT_C:
9051                 id = DPLL_ID_SKL_DPLL2;
9052                 break;
9053         default:
9054                 DRM_ERROR("Incorrect port type\n");
9055                 return;
9056         }
9057
9058         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9059 }
9060
9061 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9062                                 enum port port,
9063                                 struct intel_crtc_state *pipe_config)
9064 {
9065         enum intel_dpll_id id;
9066         u32 temp;
9067
9068         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9069         id = temp >> (port * 3 + 1);
9070
9071         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9072                 return;
9073
9074         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9075 }
9076
9077 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9078                                 enum port port,
9079                                 struct intel_crtc_state *pipe_config)
9080 {
9081         enum intel_dpll_id id;
9082         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9083
9084         switch (ddi_pll_sel) {
9085         case PORT_CLK_SEL_WRPLL1:
9086                 id = DPLL_ID_WRPLL1;
9087                 break;
9088         case PORT_CLK_SEL_WRPLL2:
9089                 id = DPLL_ID_WRPLL2;
9090                 break;
9091         case PORT_CLK_SEL_SPLL:
9092                 id = DPLL_ID_SPLL;
9093                 break;
9094         case PORT_CLK_SEL_LCPLL_810:
9095                 id = DPLL_ID_LCPLL_810;
9096                 break;
9097         case PORT_CLK_SEL_LCPLL_1350:
9098                 id = DPLL_ID_LCPLL_1350;
9099                 break;
9100         case PORT_CLK_SEL_LCPLL_2700:
9101                 id = DPLL_ID_LCPLL_2700;
9102                 break;
9103         default:
9104                 MISSING_CASE(ddi_pll_sel);
9105                 /* fall through */
9106         case PORT_CLK_SEL_NONE:
9107                 return;
9108         }
9109
9110         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9111 }
9112
9113 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9114                                      struct intel_crtc_state *pipe_config,
9115                                      u64 *power_domain_mask)
9116 {
9117         struct drm_device *dev = crtc->base.dev;
9118         struct drm_i915_private *dev_priv = to_i915(dev);
9119         enum intel_display_power_domain power_domain;
9120         u32 tmp;
9121
9122         /*
9123          * The pipe->transcoder mapping is fixed with the exception of the eDP
9124          * transcoder handled below.
9125          */
9126         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9127
9128         /*
9129          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9130          * consistency and less surprising code; it's in always on power).
9131          */
9132         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9133         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9134                 enum pipe trans_edp_pipe;
9135                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9136                 default:
9137                         WARN(1, "unknown pipe linked to edp transcoder\n");
9138                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9139                 case TRANS_DDI_EDP_INPUT_A_ON:
9140                         trans_edp_pipe = PIPE_A;
9141                         break;
9142                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9143                         trans_edp_pipe = PIPE_B;
9144                         break;
9145                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9146                         trans_edp_pipe = PIPE_C;
9147                         break;
9148                 }
9149
9150                 if (trans_edp_pipe == crtc->pipe)
9151                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9152         }
9153
9154         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9155         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9156                 return false;
9157         *power_domain_mask |= BIT_ULL(power_domain);
9158
9159         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9160
9161         return tmp & PIPECONF_ENABLE;
9162 }
9163
9164 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9165                                          struct intel_crtc_state *pipe_config,
9166                                          u64 *power_domain_mask)
9167 {
9168         struct drm_device *dev = crtc->base.dev;
9169         struct drm_i915_private *dev_priv = to_i915(dev);
9170         enum intel_display_power_domain power_domain;
9171         enum port port;
9172         enum transcoder cpu_transcoder;
9173         u32 tmp;
9174
9175         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9176                 if (port == PORT_A)
9177                         cpu_transcoder = TRANSCODER_DSI_A;
9178                 else
9179                         cpu_transcoder = TRANSCODER_DSI_C;
9180
9181                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9182                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9183                         continue;
9184                 *power_domain_mask |= BIT_ULL(power_domain);
9185
9186                 /*
9187                  * The PLL needs to be enabled with a valid divider
9188                  * configuration, otherwise accessing DSI registers will hang
9189                  * the machine. See BSpec North Display Engine
9190                  * registers/MIPI[BXT]. We can break out here early, since we
9191                  * need the same DSI PLL to be enabled for both DSI ports.
9192                  */
9193                 if (!intel_dsi_pll_is_enabled(dev_priv))
9194                         break;
9195
9196                 /* XXX: this works for video mode only */
9197                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9198                 if (!(tmp & DPI_ENABLE))
9199                         continue;
9200
9201                 tmp = I915_READ(MIPI_CTRL(port));
9202                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9203                         continue;
9204
9205                 pipe_config->cpu_transcoder = cpu_transcoder;
9206                 break;
9207         }
9208
9209         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9210 }
9211
9212 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9213                                        struct intel_crtc_state *pipe_config)
9214 {
9215         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9216         struct intel_shared_dpll *pll;
9217         enum port port;
9218         uint32_t tmp;
9219
9220         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9221
9222         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9223
9224         if (IS_CANNONLAKE(dev_priv))
9225                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9226         else if (IS_GEN9_BC(dev_priv))
9227                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9228         else if (IS_GEN9_LP(dev_priv))
9229                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9230         else
9231                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9232
9233         pll = pipe_config->shared_dpll;
9234         if (pll) {
9235                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9236                                                  &pipe_config->dpll_hw_state));
9237         }
9238
9239         /*
9240          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9241          * DDI E. So just check whether this pipe is wired to DDI E and whether
9242          * the PCH transcoder is on.
9243          */
9244         if (INTEL_GEN(dev_priv) < 9 &&
9245             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9246                 pipe_config->has_pch_encoder = true;
9247
9248                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9249                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9250                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9251
9252                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9253         }
9254 }
9255
9256 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9257                                     struct intel_crtc_state *pipe_config)
9258 {
9259         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9260         enum intel_display_power_domain power_domain;
9261         u64 power_domain_mask;
9262         bool active;
9263
9264         intel_crtc_init_scalers(crtc, pipe_config);
9265
9266         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9267         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9268                 return false;
9269         power_domain_mask = BIT_ULL(power_domain);
9270
9271         pipe_config->shared_dpll = NULL;
9272
9273         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9274
9275         if (IS_GEN9_LP(dev_priv) &&
9276             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9277                 WARN_ON(active);
9278                 active = true;
9279         }
9280
9281         if (!active)
9282                 goto out;
9283
9284         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9285                 haswell_get_ddi_port_state(crtc, pipe_config);
9286                 intel_get_pipe_timings(crtc, pipe_config);
9287         }
9288
9289         intel_get_pipe_src_size(crtc, pipe_config);
9290
9291         pipe_config->gamma_mode =
9292                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9293
9294         if (IS_BROADWELL(dev_priv) || dev_priv->info.gen >= 9) {
9295                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9296                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9297
9298                 if (IS_GEMINILAKE(dev_priv) || dev_priv->info.gen >= 10) {
9299                         bool blend_mode_420 = tmp &
9300                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9301
9302                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9303                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9304                             pipe_config->ycbcr420 != blend_mode_420)
9305                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9306                 } else if (clrspace_yuv) {
9307                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9308                 }
9309         }
9310
9311         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9312         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9313                 power_domain_mask |= BIT_ULL(power_domain);
9314                 if (INTEL_GEN(dev_priv) >= 9)
9315                         skylake_get_pfit_config(crtc, pipe_config);
9316                 else
9317                         ironlake_get_pfit_config(crtc, pipe_config);
9318         }
9319
9320         if (IS_HASWELL(dev_priv))
9321                 pipe_config->ips_enabled = hsw_crtc_supports_ips(crtc) &&
9322                         (I915_READ(IPS_CTL) & IPS_ENABLE);
9323
9324         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9325             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9326                 pipe_config->pixel_multiplier =
9327                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9328         } else {
9329                 pipe_config->pixel_multiplier = 1;
9330         }
9331
9332 out:
9333         for_each_power_domain(power_domain, power_domain_mask)
9334                 intel_display_power_put(dev_priv, power_domain);
9335
9336         return active;
9337 }
9338
9339 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9340 {
9341         struct drm_i915_private *dev_priv =
9342                 to_i915(plane_state->base.plane->dev);
9343         const struct drm_framebuffer *fb = plane_state->base.fb;
9344         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9345         u32 base;
9346
9347         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9348                 base = obj->phys_handle->busaddr;
9349         else
9350                 base = intel_plane_ggtt_offset(plane_state);
9351
9352         base += plane_state->main.offset;
9353
9354         /* ILK+ do this automagically */
9355         if (HAS_GMCH_DISPLAY(dev_priv) &&
9356             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9357                 base += (plane_state->base.crtc_h *
9358                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9359
9360         return base;
9361 }
9362
9363 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9364 {
9365         int x = plane_state->base.crtc_x;
9366         int y = plane_state->base.crtc_y;
9367         u32 pos = 0;
9368
9369         if (x < 0) {
9370                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9371                 x = -x;
9372         }
9373         pos |= x << CURSOR_X_SHIFT;
9374
9375         if (y < 0) {
9376                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9377                 y = -y;
9378         }
9379         pos |= y << CURSOR_Y_SHIFT;
9380
9381         return pos;
9382 }
9383
9384 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9385 {
9386         const struct drm_mode_config *config =
9387                 &plane_state->base.plane->dev->mode_config;
9388         int width = plane_state->base.crtc_w;
9389         int height = plane_state->base.crtc_h;
9390
9391         return width > 0 && width <= config->cursor_width &&
9392                 height > 0 && height <= config->cursor_height;
9393 }
9394
9395 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9396                               struct intel_plane_state *plane_state)
9397 {
9398         const struct drm_framebuffer *fb = plane_state->base.fb;
9399         int src_x, src_y;
9400         u32 offset;
9401         int ret;
9402
9403         ret = drm_plane_helper_check_state(&plane_state->base,
9404                                            &plane_state->clip,
9405                                            DRM_PLANE_HELPER_NO_SCALING,
9406                                            DRM_PLANE_HELPER_NO_SCALING,
9407                                            true, true);
9408         if (ret)
9409                 return ret;
9410
9411         if (!fb)
9412                 return 0;
9413
9414         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9415                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9416                 return -EINVAL;
9417         }
9418
9419         src_x = plane_state->base.src_x >> 16;
9420         src_y = plane_state->base.src_y >> 16;
9421
9422         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9423         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9424
9425         if (src_x != 0 || src_y != 0) {
9426                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9427                 return -EINVAL;
9428         }
9429
9430         plane_state->main.offset = offset;
9431
9432         return 0;
9433 }
9434
9435 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9436                            const struct intel_plane_state *plane_state)
9437 {
9438         const struct drm_framebuffer *fb = plane_state->base.fb;
9439
9440         return CURSOR_ENABLE |
9441                 CURSOR_GAMMA_ENABLE |
9442                 CURSOR_FORMAT_ARGB |
9443                 CURSOR_STRIDE(fb->pitches[0]);
9444 }
9445
9446 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9447 {
9448         int width = plane_state->base.crtc_w;
9449
9450         /*
9451          * 845g/865g are only limited by the width of their cursors,
9452          * the height is arbitrary up to the precision of the register.
9453          */
9454         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9455 }
9456
9457 static int i845_check_cursor(struct intel_plane *plane,
9458                              struct intel_crtc_state *crtc_state,
9459                              struct intel_plane_state *plane_state)
9460 {
9461         const struct drm_framebuffer *fb = plane_state->base.fb;
9462         int ret;
9463
9464         ret = intel_check_cursor(crtc_state, plane_state);
9465         if (ret)
9466                 return ret;
9467
9468         /* if we want to turn off the cursor ignore width and height */
9469         if (!fb)
9470                 return 0;
9471
9472         /* Check for which cursor types we support */
9473         if (!i845_cursor_size_ok(plane_state)) {
9474                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9475                           plane_state->base.crtc_w,
9476                           plane_state->base.crtc_h);
9477                 return -EINVAL;
9478         }
9479
9480         switch (fb->pitches[0]) {
9481         case 256:
9482         case 512:
9483         case 1024:
9484         case 2048:
9485                 break;
9486         default:
9487                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9488                               fb->pitches[0]);
9489                 return -EINVAL;
9490         }
9491
9492         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9493
9494         return 0;
9495 }
9496
9497 static void i845_update_cursor(struct intel_plane *plane,
9498                                const struct intel_crtc_state *crtc_state,
9499                                const struct intel_plane_state *plane_state)
9500 {
9501         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9502         u32 cntl = 0, base = 0, pos = 0, size = 0;
9503         unsigned long irqflags;
9504
9505         if (plane_state && plane_state->base.visible) {
9506                 unsigned int width = plane_state->base.crtc_w;
9507                 unsigned int height = plane_state->base.crtc_h;
9508
9509                 cntl = plane_state->ctl;
9510                 size = (height << 12) | width;
9511
9512                 base = intel_cursor_base(plane_state);
9513                 pos = intel_cursor_position(plane_state);
9514         }
9515
9516         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9517
9518         /* On these chipsets we can only modify the base/size/stride
9519          * whilst the cursor is disabled.
9520          */
9521         if (plane->cursor.base != base ||
9522             plane->cursor.size != size ||
9523             plane->cursor.cntl != cntl) {
9524                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9525                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9526                 I915_WRITE_FW(CURSIZE, size);
9527                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9528                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9529
9530                 plane->cursor.base = base;
9531                 plane->cursor.size = size;
9532                 plane->cursor.cntl = cntl;
9533         } else {
9534                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9535         }
9536
9537         POSTING_READ_FW(CURCNTR(PIPE_A));
9538
9539         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9540 }
9541
9542 static void i845_disable_cursor(struct intel_plane *plane,
9543                                 struct intel_crtc *crtc)
9544 {
9545         i845_update_cursor(plane, NULL, NULL);
9546 }
9547
9548 static bool i845_cursor_get_hw_state(struct intel_plane *plane)
9549 {
9550         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9551         enum intel_display_power_domain power_domain;
9552         bool ret;
9553
9554         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9555         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9556                 return false;
9557
9558         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9559
9560         intel_display_power_put(dev_priv, power_domain);
9561
9562         return ret;
9563 }
9564
9565 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9566                            const struct intel_plane_state *plane_state)
9567 {
9568         struct drm_i915_private *dev_priv =
9569                 to_i915(plane_state->base.plane->dev);
9570         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9571         u32 cntl;
9572
9573         cntl = MCURSOR_GAMMA_ENABLE;
9574
9575         if (HAS_DDI(dev_priv))
9576                 cntl |= CURSOR_PIPE_CSC_ENABLE;
9577
9578         cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9579
9580         switch (plane_state->base.crtc_w) {
9581         case 64:
9582                 cntl |= CURSOR_MODE_64_ARGB_AX;
9583                 break;
9584         case 128:
9585                 cntl |= CURSOR_MODE_128_ARGB_AX;
9586                 break;
9587         case 256:
9588                 cntl |= CURSOR_MODE_256_ARGB_AX;
9589                 break;
9590         default:
9591                 MISSING_CASE(plane_state->base.crtc_w);
9592                 return 0;
9593         }
9594
9595         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9596                 cntl |= CURSOR_ROTATE_180;
9597
9598         return cntl;
9599 }
9600
9601 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9602 {
9603         struct drm_i915_private *dev_priv =
9604                 to_i915(plane_state->base.plane->dev);
9605         int width = plane_state->base.crtc_w;
9606         int height = plane_state->base.crtc_h;
9607
9608         if (!intel_cursor_size_ok(plane_state))
9609                 return false;
9610
9611         /* Cursor width is limited to a few power-of-two sizes */
9612         switch (width) {
9613         case 256:
9614         case 128:
9615         case 64:
9616                 break;
9617         default:
9618                 return false;
9619         }
9620
9621         /*
9622          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9623          * height from 8 lines up to the cursor width, when the
9624          * cursor is not rotated. Everything else requires square
9625          * cursors.
9626          */
9627         if (HAS_CUR_FBC(dev_priv) &&
9628             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9629                 if (height < 8 || height > width)
9630                         return false;
9631         } else {
9632                 if (height != width)
9633                         return false;
9634         }
9635
9636         return true;
9637 }
9638
9639 static int i9xx_check_cursor(struct intel_plane *plane,
9640                              struct intel_crtc_state *crtc_state,
9641                              struct intel_plane_state *plane_state)
9642 {
9643         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9644         const struct drm_framebuffer *fb = plane_state->base.fb;
9645         enum pipe pipe = plane->pipe;
9646         int ret;
9647
9648         ret = intel_check_cursor(crtc_state, plane_state);
9649         if (ret)
9650                 return ret;
9651
9652         /* if we want to turn off the cursor ignore width and height */
9653         if (!fb)
9654                 return 0;
9655
9656         /* Check for which cursor types we support */
9657         if (!i9xx_cursor_size_ok(plane_state)) {
9658                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9659                           plane_state->base.crtc_w,
9660                           plane_state->base.crtc_h);
9661                 return -EINVAL;
9662         }
9663
9664         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9665                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9666                               fb->pitches[0], plane_state->base.crtc_w);
9667                 return -EINVAL;
9668         }
9669
9670         /*
9671          * There's something wrong with the cursor on CHV pipe C.
9672          * If it straddles the left edge of the screen then
9673          * moving it away from the edge or disabling it often
9674          * results in a pipe underrun, and often that can lead to
9675          * dead pipe (constant underrun reported, and it scans
9676          * out just a solid color). To recover from that, the
9677          * display power well must be turned off and on again.
9678          * Refuse the put the cursor into that compromised position.
9679          */
9680         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9681             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9682                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9683                 return -EINVAL;
9684         }
9685
9686         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9687
9688         return 0;
9689 }
9690
9691 static void i9xx_update_cursor(struct intel_plane *plane,
9692                                const struct intel_crtc_state *crtc_state,
9693                                const struct intel_plane_state *plane_state)
9694 {
9695         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9696         enum pipe pipe = plane->pipe;
9697         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9698         unsigned long irqflags;
9699
9700         if (plane_state && plane_state->base.visible) {
9701                 cntl = plane_state->ctl;
9702
9703                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9704                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9705
9706                 base = intel_cursor_base(plane_state);
9707                 pos = intel_cursor_position(plane_state);
9708         }
9709
9710         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9711
9712         /*
9713          * On some platforms writing CURCNTR first will also
9714          * cause CURPOS to be armed by the CURBASE write.
9715          * Without the CURCNTR write the CURPOS write would
9716          * arm itself. Thus we always start the full update
9717          * with a CURCNTR write.
9718          *
9719          * On other platforms CURPOS always requires the
9720          * CURBASE write to arm the update. Additonally
9721          * a write to any of the cursor register will cancel
9722          * an already armed cursor update. Thus leaving out
9723          * the CURBASE write after CURPOS could lead to a
9724          * cursor that doesn't appear to move, or even change
9725          * shape. Thus we always write CURBASE.
9726          *
9727          * CURCNTR and CUR_FBC_CTL are always
9728          * armed by the CURBASE write only.
9729          */
9730         if (plane->cursor.base != base ||
9731             plane->cursor.size != fbc_ctl ||
9732             plane->cursor.cntl != cntl) {
9733                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9734                 if (HAS_CUR_FBC(dev_priv))
9735                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9736                 I915_WRITE_FW(CURPOS(pipe), pos);
9737                 I915_WRITE_FW(CURBASE(pipe), base);
9738
9739                 plane->cursor.base = base;
9740                 plane->cursor.size = fbc_ctl;
9741                 plane->cursor.cntl = cntl;
9742         } else {
9743                 I915_WRITE_FW(CURPOS(pipe), pos);
9744                 I915_WRITE_FW(CURBASE(pipe), base);
9745         }
9746
9747         POSTING_READ_FW(CURBASE(pipe));
9748
9749         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9750 }
9751
9752 static void i9xx_disable_cursor(struct intel_plane *plane,
9753                                 struct intel_crtc *crtc)
9754 {
9755         i9xx_update_cursor(plane, NULL, NULL);
9756 }
9757
9758 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane)
9759 {
9760         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9761         enum intel_display_power_domain power_domain;
9762         enum pipe pipe = plane->pipe;
9763         bool ret;
9764
9765         /*
9766          * Not 100% correct for planes that can move between pipes,
9767          * but that's only the case for gen2-3 which don't have any
9768          * display power wells.
9769          */
9770         power_domain = POWER_DOMAIN_PIPE(pipe);
9771         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9772                 return false;
9773
9774         ret = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
9775
9776         intel_display_power_put(dev_priv, power_domain);
9777
9778         return ret;
9779 }
9780
9781 /* VESA 640x480x72Hz mode to set on the pipe */
9782 static struct drm_display_mode load_detect_mode = {
9783         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9784                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9785 };
9786
9787 struct drm_framebuffer *
9788 intel_framebuffer_create(struct drm_i915_gem_object *obj,
9789                          struct drm_mode_fb_cmd2 *mode_cmd)
9790 {
9791         struct intel_framebuffer *intel_fb;
9792         int ret;
9793
9794         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9795         if (!intel_fb)
9796                 return ERR_PTR(-ENOMEM);
9797
9798         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
9799         if (ret)
9800                 goto err;
9801
9802         return &intel_fb->base;
9803
9804 err:
9805         kfree(intel_fb);
9806         return ERR_PTR(ret);
9807 }
9808
9809 static u32
9810 intel_framebuffer_pitch_for_width(int width, int bpp)
9811 {
9812         u32 pitch = DIV_ROUND_UP(width * bpp, 8);
9813         return ALIGN(pitch, 64);
9814 }
9815
9816 static u32
9817 intel_framebuffer_size_for_mode(struct drm_display_mode *mode, int bpp)
9818 {
9819         u32 pitch = intel_framebuffer_pitch_for_width(mode->hdisplay, bpp);
9820         return PAGE_ALIGN(pitch * mode->vdisplay);
9821 }
9822
9823 static struct drm_framebuffer *
9824 intel_framebuffer_create_for_mode(struct drm_device *dev,
9825                                   struct drm_display_mode *mode,
9826                                   int depth, int bpp)
9827 {
9828         struct drm_framebuffer *fb;
9829         struct drm_i915_gem_object *obj;
9830         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
9831
9832         obj = i915_gem_object_create(to_i915(dev),
9833                                     intel_framebuffer_size_for_mode(mode, bpp));
9834         if (IS_ERR(obj))
9835                 return ERR_CAST(obj);
9836
9837         mode_cmd.width = mode->hdisplay;
9838         mode_cmd.height = mode->vdisplay;
9839         mode_cmd.pitches[0] = intel_framebuffer_pitch_for_width(mode_cmd.width,
9840                                                                 bpp);
9841         mode_cmd.pixel_format = drm_mode_legacy_fb_format(bpp, depth);
9842
9843         fb = intel_framebuffer_create(obj, &mode_cmd);
9844         if (IS_ERR(fb))
9845                 i915_gem_object_put(obj);
9846
9847         return fb;
9848 }
9849
9850 static struct drm_framebuffer *
9851 mode_fits_in_fbdev(struct drm_device *dev,
9852                    struct drm_display_mode *mode)
9853 {
9854 #ifdef CONFIG_DRM_FBDEV_EMULATION
9855         struct drm_i915_private *dev_priv = to_i915(dev);
9856         struct drm_i915_gem_object *obj;
9857         struct drm_framebuffer *fb;
9858
9859         if (!dev_priv->fbdev)
9860                 return NULL;
9861
9862         if (!dev_priv->fbdev->fb)
9863                 return NULL;
9864
9865         obj = dev_priv->fbdev->fb->obj;
9866         BUG_ON(!obj);
9867
9868         fb = &dev_priv->fbdev->fb->base;
9869         if (fb->pitches[0] < intel_framebuffer_pitch_for_width(mode->hdisplay,
9870                                                                fb->format->cpp[0] * 8))
9871                 return NULL;
9872
9873         if (obj->base.size < mode->vdisplay * fb->pitches[0])
9874                 return NULL;
9875
9876         drm_framebuffer_reference(fb);
9877         return fb;
9878 #else
9879         return NULL;
9880 #endif
9881 }
9882
9883 static int intel_modeset_setup_plane_state(struct drm_atomic_state *state,
9884                                            struct drm_crtc *crtc,
9885                                            struct drm_display_mode *mode,
9886                                            struct drm_framebuffer *fb,
9887                                            int x, int y)
9888 {
9889         struct drm_plane_state *plane_state;
9890         int hdisplay, vdisplay;
9891         int ret;
9892
9893         plane_state = drm_atomic_get_plane_state(state, crtc->primary);
9894         if (IS_ERR(plane_state))
9895                 return PTR_ERR(plane_state);
9896
9897         if (mode)
9898                 drm_mode_get_hv_timing(mode, &hdisplay, &vdisplay);
9899         else
9900                 hdisplay = vdisplay = 0;
9901
9902         ret = drm_atomic_set_crtc_for_plane(plane_state, fb ? crtc : NULL);
9903         if (ret)
9904                 return ret;
9905         drm_atomic_set_fb_for_plane(plane_state, fb);
9906         plane_state->crtc_x = 0;
9907         plane_state->crtc_y = 0;
9908         plane_state->crtc_w = hdisplay;
9909         plane_state->crtc_h = vdisplay;
9910         plane_state->src_x = x << 16;
9911         plane_state->src_y = y << 16;
9912         plane_state->src_w = hdisplay << 16;
9913         plane_state->src_h = vdisplay << 16;
9914
9915         return 0;
9916 }
9917
9918 int intel_get_load_detect_pipe(struct drm_connector *connector,
9919                                struct drm_display_mode *mode,
9920                                struct intel_load_detect_pipe *old,
9921                                struct drm_modeset_acquire_ctx *ctx)
9922 {
9923         struct intel_crtc *intel_crtc;
9924         struct intel_encoder *intel_encoder =
9925                 intel_attached_encoder(connector);
9926         struct drm_crtc *possible_crtc;
9927         struct drm_encoder *encoder = &intel_encoder->base;
9928         struct drm_crtc *crtc = NULL;
9929         struct drm_device *dev = encoder->dev;
9930         struct drm_i915_private *dev_priv = to_i915(dev);
9931         struct drm_framebuffer *fb;
9932         struct drm_mode_config *config = &dev->mode_config;
9933         struct drm_atomic_state *state = NULL, *restore_state = NULL;
9934         struct drm_connector_state *connector_state;
9935         struct intel_crtc_state *crtc_state;
9936         int ret, i = -1;
9937
9938         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9939                       connector->base.id, connector->name,
9940                       encoder->base.id, encoder->name);
9941
9942         old->restore_state = NULL;
9943
9944         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
9945
9946         /*
9947          * Algorithm gets a little messy:
9948          *
9949          *   - if the connector already has an assigned crtc, use it (but make
9950          *     sure it's on first)
9951          *
9952          *   - try to find the first unused crtc that can drive this connector,
9953          *     and use that if we find one
9954          */
9955
9956         /* See if we already have a CRTC for this connector */
9957         if (connector->state->crtc) {
9958                 crtc = connector->state->crtc;
9959
9960                 ret = drm_modeset_lock(&crtc->mutex, ctx);
9961                 if (ret)
9962                         goto fail;
9963
9964                 /* Make sure the crtc and connector are running */
9965                 goto found;
9966         }
9967
9968         /* Find an unused one (if possible) */
9969         for_each_crtc(dev, possible_crtc) {
9970                 i++;
9971                 if (!(encoder->possible_crtcs & (1 << i)))
9972                         continue;
9973
9974                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
9975                 if (ret)
9976                         goto fail;
9977
9978                 if (possible_crtc->state->enable) {
9979                         drm_modeset_unlock(&possible_crtc->mutex);
9980                         continue;
9981                 }
9982
9983                 crtc = possible_crtc;
9984                 break;
9985         }
9986
9987         /*
9988          * If we didn't find an unused CRTC, don't use any.
9989          */
9990         if (!crtc) {
9991                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
9992                 ret = -ENODEV;
9993                 goto fail;
9994         }
9995
9996 found:
9997         intel_crtc = to_intel_crtc(crtc);
9998
9999         ret = drm_modeset_lock(&crtc->primary->mutex, ctx);
10000         if (ret)
10001                 goto fail;
10002
10003         state = drm_atomic_state_alloc(dev);
10004         restore_state = drm_atomic_state_alloc(dev);
10005         if (!state || !restore_state) {
10006                 ret = -ENOMEM;
10007                 goto fail;
10008         }
10009
10010         state->acquire_ctx = ctx;
10011         restore_state->acquire_ctx = ctx;
10012
10013         connector_state = drm_atomic_get_connector_state(state, connector);
10014         if (IS_ERR(connector_state)) {
10015                 ret = PTR_ERR(connector_state);
10016                 goto fail;
10017         }
10018
10019         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10020         if (ret)
10021                 goto fail;
10022
10023         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10024         if (IS_ERR(crtc_state)) {
10025                 ret = PTR_ERR(crtc_state);
10026                 goto fail;
10027         }
10028
10029         crtc_state->base.active = crtc_state->base.enable = true;
10030
10031         if (!mode)
10032                 mode = &load_detect_mode;
10033
10034         /* We need a framebuffer large enough to accommodate all accesses
10035          * that the plane may generate whilst we perform load detection.
10036          * We can not rely on the fbcon either being present (we get called
10037          * during its initialisation to detect all boot displays, or it may
10038          * not even exist) or that it is large enough to satisfy the
10039          * requested mode.
10040          */
10041         fb = mode_fits_in_fbdev(dev, mode);
10042         if (fb == NULL) {
10043                 DRM_DEBUG_KMS("creating tmp fb for load-detection\n");
10044                 fb = intel_framebuffer_create_for_mode(dev, mode, 24, 32);
10045         } else
10046                 DRM_DEBUG_KMS("reusing fbdev for load-detection framebuffer\n");
10047         if (IS_ERR(fb)) {
10048                 DRM_DEBUG_KMS("failed to allocate framebuffer for load-detection\n");
10049                 ret = PTR_ERR(fb);
10050                 goto fail;
10051         }
10052
10053         ret = intel_modeset_setup_plane_state(state, crtc, mode, fb, 0, 0);
10054         if (ret)
10055                 goto fail;
10056
10057         drm_framebuffer_unreference(fb);
10058
10059         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10060         if (ret)
10061                 goto fail;
10062
10063         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10064         if (!ret)
10065                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10066         if (!ret)
10067                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_plane_state(restore_state, crtc->primary));
10068         if (ret) {
10069                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10070                 goto fail;
10071         }
10072
10073         ret = drm_atomic_commit(state);
10074         if (ret) {
10075                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10076                 goto fail;
10077         }
10078
10079         old->restore_state = restore_state;
10080         drm_atomic_state_put(state);
10081
10082         /* let the connector get through one full cycle before testing */
10083         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10084         return true;
10085
10086 fail:
10087         if (state) {
10088                 drm_atomic_state_put(state);
10089                 state = NULL;
10090         }
10091         if (restore_state) {
10092                 drm_atomic_state_put(restore_state);
10093                 restore_state = NULL;
10094         }
10095
10096         if (ret == -EDEADLK)
10097                 return ret;
10098
10099         return false;
10100 }
10101
10102 void intel_release_load_detect_pipe(struct drm_connector *connector,
10103                                     struct intel_load_detect_pipe *old,
10104                                     struct drm_modeset_acquire_ctx *ctx)
10105 {
10106         struct intel_encoder *intel_encoder =
10107                 intel_attached_encoder(connector);
10108         struct drm_encoder *encoder = &intel_encoder->base;
10109         struct drm_atomic_state *state = old->restore_state;
10110         int ret;
10111
10112         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10113                       connector->base.id, connector->name,
10114                       encoder->base.id, encoder->name);
10115
10116         if (!state)
10117                 return;
10118
10119         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10120         if (ret)
10121                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10122         drm_atomic_state_put(state);
10123 }
10124
10125 static int i9xx_pll_refclk(struct drm_device *dev,
10126                            const struct intel_crtc_state *pipe_config)
10127 {
10128         struct drm_i915_private *dev_priv = to_i915(dev);
10129         u32 dpll = pipe_config->dpll_hw_state.dpll;
10130
10131         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10132                 return dev_priv->vbt.lvds_ssc_freq;
10133         else if (HAS_PCH_SPLIT(dev_priv))
10134                 return 120000;
10135         else if (!IS_GEN2(dev_priv))
10136                 return 96000;
10137         else
10138                 return 48000;
10139 }
10140
10141 /* Returns the clock of the currently programmed mode of the given pipe. */
10142 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10143                                 struct intel_crtc_state *pipe_config)
10144 {
10145         struct drm_device *dev = crtc->base.dev;
10146         struct drm_i915_private *dev_priv = to_i915(dev);
10147         int pipe = pipe_config->cpu_transcoder;
10148         u32 dpll = pipe_config->dpll_hw_state.dpll;
10149         u32 fp;
10150         struct dpll clock;
10151         int port_clock;
10152         int refclk = i9xx_pll_refclk(dev, pipe_config);
10153
10154         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10155                 fp = pipe_config->dpll_hw_state.fp0;
10156         else
10157                 fp = pipe_config->dpll_hw_state.fp1;
10158
10159         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10160         if (IS_PINEVIEW(dev_priv)) {
10161                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10162                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10163         } else {
10164                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10165                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10166         }
10167
10168         if (!IS_GEN2(dev_priv)) {
10169                 if (IS_PINEVIEW(dev_priv))
10170                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10171                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10172                 else
10173                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10174                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10175
10176                 switch (dpll & DPLL_MODE_MASK) {
10177                 case DPLLB_MODE_DAC_SERIAL:
10178                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10179                                 5 : 10;
10180                         break;
10181                 case DPLLB_MODE_LVDS:
10182                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10183                                 7 : 14;
10184                         break;
10185                 default:
10186                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10187                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10188                         return;
10189                 }
10190
10191                 if (IS_PINEVIEW(dev_priv))
10192                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10193                 else
10194                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10195         } else {
10196                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10197                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10198
10199                 if (is_lvds) {
10200                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10201                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10202
10203                         if (lvds & LVDS_CLKB_POWER_UP)
10204                                 clock.p2 = 7;
10205                         else
10206                                 clock.p2 = 14;
10207                 } else {
10208                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10209                                 clock.p1 = 2;
10210                         else {
10211                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10212                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10213                         }
10214                         if (dpll & PLL_P2_DIVIDE_BY_4)
10215                                 clock.p2 = 4;
10216                         else
10217                                 clock.p2 = 2;
10218                 }
10219
10220                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10221         }
10222
10223         /*
10224          * This value includes pixel_multiplier. We will use
10225          * port_clock to compute adjusted_mode.crtc_clock in the
10226          * encoder's get_config() function.
10227          */
10228         pipe_config->port_clock = port_clock;
10229 }
10230
10231 int intel_dotclock_calculate(int link_freq,
10232                              const struct intel_link_m_n *m_n)
10233 {
10234         /*
10235          * The calculation for the data clock is:
10236          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10237          * But we want to avoid losing precison if possible, so:
10238          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10239          *
10240          * and the link clock is simpler:
10241          * link_clock = (m * link_clock) / n
10242          */
10243
10244         if (!m_n->link_n)
10245                 return 0;
10246
10247         return div_u64((u64)m_n->link_m * link_freq, m_n->link_n);
10248 }
10249
10250 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10251                                    struct intel_crtc_state *pipe_config)
10252 {
10253         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10254
10255         /* read out port_clock from the DPLL */
10256         i9xx_crtc_clock_get(crtc, pipe_config);
10257
10258         /*
10259          * In case there is an active pipe without active ports,
10260          * we may need some idea for the dotclock anyway.
10261          * Calculate one based on the FDI configuration.
10262          */
10263         pipe_config->base.adjusted_mode.crtc_clock =
10264                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10265                                          &pipe_config->fdi_m_n);
10266 }
10267
10268 /** Returns the currently programmed mode of the given pipe. */
10269 struct drm_display_mode *intel_crtc_mode_get(struct drm_device *dev,
10270                                              struct drm_crtc *crtc)
10271 {
10272         struct drm_i915_private *dev_priv = to_i915(dev);
10273         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10274         enum transcoder cpu_transcoder;
10275         struct drm_display_mode *mode;
10276         struct intel_crtc_state *pipe_config;
10277         u32 htot, hsync, vtot, vsync;
10278         enum pipe pipe = intel_crtc->pipe;
10279
10280         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10281         if (!mode)
10282                 return NULL;
10283
10284         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
10285         if (!pipe_config) {
10286                 kfree(mode);
10287                 return NULL;
10288         }
10289
10290         /*
10291          * Construct a pipe_config sufficient for getting the clock info
10292          * back out of crtc_clock_get.
10293          *
10294          * Note, if LVDS ever uses a non-1 pixel multiplier, we'll need
10295          * to use a real value here instead.
10296          */
10297         pipe_config->cpu_transcoder = (enum transcoder) pipe;
10298         pipe_config->pixel_multiplier = 1;
10299         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(pipe));
10300         pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(pipe));
10301         pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(pipe));
10302         i9xx_crtc_clock_get(intel_crtc, pipe_config);
10303
10304         mode->clock = pipe_config->port_clock / pipe_config->pixel_multiplier;
10305
10306         cpu_transcoder = pipe_config->cpu_transcoder;
10307         htot = I915_READ(HTOTAL(cpu_transcoder));
10308         hsync = I915_READ(HSYNC(cpu_transcoder));
10309         vtot = I915_READ(VTOTAL(cpu_transcoder));
10310         vsync = I915_READ(VSYNC(cpu_transcoder));
10311
10312         mode->hdisplay = (htot & 0xffff) + 1;
10313         mode->htotal = ((htot & 0xffff0000) >> 16) + 1;
10314         mode->hsync_start = (hsync & 0xffff) + 1;
10315         mode->hsync_end = ((hsync & 0xffff0000) >> 16) + 1;
10316         mode->vdisplay = (vtot & 0xffff) + 1;
10317         mode->vtotal = ((vtot & 0xffff0000) >> 16) + 1;
10318         mode->vsync_start = (vsync & 0xffff) + 1;
10319         mode->vsync_end = ((vsync & 0xffff0000) >> 16) + 1;
10320
10321         drm_mode_set_name(mode);
10322
10323         kfree(pipe_config);
10324
10325         return mode;
10326 }
10327
10328 static void intel_crtc_destroy(struct drm_crtc *crtc)
10329 {
10330         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10331
10332         drm_crtc_cleanup(crtc);
10333         kfree(intel_crtc);
10334 }
10335
10336 /**
10337  * intel_wm_need_update - Check whether watermarks need updating
10338  * @plane: drm plane
10339  * @state: new plane state
10340  *
10341  * Check current plane state versus the new one to determine whether
10342  * watermarks need to be recalculated.
10343  *
10344  * Returns true or false.
10345  */
10346 static bool intel_wm_need_update(struct drm_plane *plane,
10347                                  struct drm_plane_state *state)
10348 {
10349         struct intel_plane_state *new = to_intel_plane_state(state);
10350         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10351
10352         /* Update watermarks on tiling or size changes. */
10353         if (new->base.visible != cur->base.visible)
10354                 return true;
10355
10356         if (!cur->base.fb || !new->base.fb)
10357                 return false;
10358
10359         if (cur->base.fb->modifier != new->base.fb->modifier ||
10360             cur->base.rotation != new->base.rotation ||
10361             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10362             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10363             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10364             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10365                 return true;
10366
10367         return false;
10368 }
10369
10370 static bool needs_scaling(struct intel_plane_state *state)
10371 {
10372         int src_w = drm_rect_width(&state->base.src) >> 16;
10373         int src_h = drm_rect_height(&state->base.src) >> 16;
10374         int dst_w = drm_rect_width(&state->base.dst);
10375         int dst_h = drm_rect_height(&state->base.dst);
10376
10377         return (src_w != dst_w || src_h != dst_h);
10378 }
10379
10380 int intel_plane_atomic_calc_changes(struct drm_crtc_state *crtc_state,
10381                                     struct drm_plane_state *plane_state)
10382 {
10383         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10384         struct drm_crtc *crtc = crtc_state->crtc;
10385         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10386         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10387         struct drm_device *dev = crtc->dev;
10388         struct drm_i915_private *dev_priv = to_i915(dev);
10389         struct intel_plane_state *old_plane_state =
10390                 to_intel_plane_state(plane->base.state);
10391         bool mode_changed = needs_modeset(crtc_state);
10392         bool was_crtc_enabled = crtc->state->active;
10393         bool is_crtc_enabled = crtc_state->active;
10394         bool turn_off, turn_on, visible, was_visible;
10395         struct drm_framebuffer *fb = plane_state->fb;
10396         int ret;
10397
10398         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10399                 ret = skl_update_scaler_plane(
10400                         to_intel_crtc_state(crtc_state),
10401                         to_intel_plane_state(plane_state));
10402                 if (ret)
10403                         return ret;
10404         }
10405
10406         was_visible = old_plane_state->base.visible;
10407         visible = plane_state->visible;
10408
10409         if (!was_crtc_enabled && WARN_ON(was_visible))
10410                 was_visible = false;
10411
10412         /*
10413          * Visibility is calculated as if the crtc was on, but
10414          * after scaler setup everything depends on it being off
10415          * when the crtc isn't active.
10416          *
10417          * FIXME this is wrong for watermarks. Watermarks should also
10418          * be computed as if the pipe would be active. Perhaps move
10419          * per-plane wm computation to the .check_plane() hook, and
10420          * only combine the results from all planes in the current place?
10421          */
10422         if (!is_crtc_enabled) {
10423                 plane_state->visible = visible = false;
10424                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10425         }
10426
10427         if (!was_visible && !visible)
10428                 return 0;
10429
10430         if (fb != old_plane_state->base.fb)
10431                 pipe_config->fb_changed = true;
10432
10433         turn_off = was_visible && (!visible || mode_changed);
10434         turn_on = visible && (!was_visible || mode_changed);
10435
10436         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10437                          intel_crtc->base.base.id, intel_crtc->base.name,
10438                          plane->base.base.id, plane->base.name,
10439                          fb ? fb->base.id : -1);
10440
10441         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10442                          plane->base.base.id, plane->base.name,
10443                          was_visible, visible,
10444                          turn_off, turn_on, mode_changed);
10445
10446         if (turn_on) {
10447                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10448                         pipe_config->update_wm_pre = true;
10449
10450                 /* must disable cxsr around plane enable/disable */
10451                 if (plane->id != PLANE_CURSOR)
10452                         pipe_config->disable_cxsr = true;
10453         } else if (turn_off) {
10454                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10455                         pipe_config->update_wm_post = true;
10456
10457                 /* must disable cxsr around plane enable/disable */
10458                 if (plane->id != PLANE_CURSOR)
10459                         pipe_config->disable_cxsr = true;
10460         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10461                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10462                         /* FIXME bollocks */
10463                         pipe_config->update_wm_pre = true;
10464                         pipe_config->update_wm_post = true;
10465                 }
10466         }
10467
10468         if (visible || was_visible)
10469                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10470
10471         /*
10472          * WaCxSRDisabledForSpriteScaling:ivb
10473          *
10474          * cstate->update_wm was already set above, so this flag will
10475          * take effect when we commit and program watermarks.
10476          */
10477         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
10478             needs_scaling(to_intel_plane_state(plane_state)) &&
10479             !needs_scaling(old_plane_state))
10480                 pipe_config->disable_lp_wm = true;
10481
10482         return 0;
10483 }
10484
10485 static bool encoders_cloneable(const struct intel_encoder *a,
10486                                const struct intel_encoder *b)
10487 {
10488         /* masks could be asymmetric, so check both ways */
10489         return a == b || (a->cloneable & (1 << b->type) &&
10490                           b->cloneable & (1 << a->type));
10491 }
10492
10493 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10494                                          struct intel_crtc *crtc,
10495                                          struct intel_encoder *encoder)
10496 {
10497         struct intel_encoder *source_encoder;
10498         struct drm_connector *connector;
10499         struct drm_connector_state *connector_state;
10500         int i;
10501
10502         for_each_new_connector_in_state(state, connector, connector_state, i) {
10503                 if (connector_state->crtc != &crtc->base)
10504                         continue;
10505
10506                 source_encoder =
10507                         to_intel_encoder(connector_state->best_encoder);
10508                 if (!encoders_cloneable(encoder, source_encoder))
10509                         return false;
10510         }
10511
10512         return true;
10513 }
10514
10515 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10516                                    struct drm_crtc_state *crtc_state)
10517 {
10518         struct drm_device *dev = crtc->dev;
10519         struct drm_i915_private *dev_priv = to_i915(dev);
10520         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10521         struct intel_crtc_state *pipe_config =
10522                 to_intel_crtc_state(crtc_state);
10523         struct drm_atomic_state *state = crtc_state->state;
10524         int ret;
10525         bool mode_changed = needs_modeset(crtc_state);
10526
10527         if (mode_changed && !crtc_state->active)
10528                 pipe_config->update_wm_post = true;
10529
10530         if (mode_changed && crtc_state->enable &&
10531             dev_priv->display.crtc_compute_clock &&
10532             !WARN_ON(pipe_config->shared_dpll)) {
10533                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10534                                                            pipe_config);
10535                 if (ret)
10536                         return ret;
10537         }
10538
10539         if (crtc_state->color_mgmt_changed) {
10540                 ret = intel_color_check(crtc, crtc_state);
10541                 if (ret)
10542                         return ret;
10543
10544                 /*
10545                  * Changing color management on Intel hardware is
10546                  * handled as part of planes update.
10547                  */
10548                 crtc_state->planes_changed = true;
10549         }
10550
10551         ret = 0;
10552         if (dev_priv->display.compute_pipe_wm) {
10553                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10554                 if (ret) {
10555                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10556                         return ret;
10557                 }
10558         }
10559
10560         if (dev_priv->display.compute_intermediate_wm &&
10561             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10562                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10563                         return 0;
10564
10565                 /*
10566                  * Calculate 'intermediate' watermarks that satisfy both the
10567                  * old state and the new state.  We can program these
10568                  * immediately.
10569                  */
10570                 ret = dev_priv->display.compute_intermediate_wm(dev,
10571                                                                 intel_crtc,
10572                                                                 pipe_config);
10573                 if (ret) {
10574                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10575                         return ret;
10576                 }
10577         } else if (dev_priv->display.compute_intermediate_wm) {
10578                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10579                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10580         }
10581
10582         if (INTEL_GEN(dev_priv) >= 9) {
10583                 if (mode_changed)
10584                         ret = skl_update_scaler_crtc(pipe_config);
10585
10586                 if (!ret)
10587                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10588                                                             pipe_config);
10589                 if (!ret)
10590                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10591                                                          pipe_config);
10592         }
10593
10594         return ret;
10595 }
10596
10597 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10598         .atomic_begin = intel_begin_crtc_commit,
10599         .atomic_flush = intel_finish_crtc_commit,
10600         .atomic_check = intel_crtc_atomic_check,
10601 };
10602
10603 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10604 {
10605         struct intel_connector *connector;
10606         struct drm_connector_list_iter conn_iter;
10607
10608         drm_connector_list_iter_begin(dev, &conn_iter);
10609         for_each_intel_connector_iter(connector, &conn_iter) {
10610                 if (connector->base.state->crtc)
10611                         drm_connector_unreference(&connector->base);
10612
10613                 if (connector->base.encoder) {
10614                         connector->base.state->best_encoder =
10615                                 connector->base.encoder;
10616                         connector->base.state->crtc =
10617                                 connector->base.encoder->crtc;
10618
10619                         drm_connector_reference(&connector->base);
10620                 } else {
10621                         connector->base.state->best_encoder = NULL;
10622                         connector->base.state->crtc = NULL;
10623                 }
10624         }
10625         drm_connector_list_iter_end(&conn_iter);
10626 }
10627
10628 static void
10629 connected_sink_compute_bpp(struct intel_connector *connector,
10630                            struct intel_crtc_state *pipe_config)
10631 {
10632         const struct drm_display_info *info = &connector->base.display_info;
10633         int bpp = pipe_config->pipe_bpp;
10634
10635         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10636                       connector->base.base.id,
10637                       connector->base.name);
10638
10639         /* Don't use an invalid EDID bpc value */
10640         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10641                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10642                               bpp, info->bpc * 3);
10643                 pipe_config->pipe_bpp = info->bpc * 3;
10644         }
10645
10646         /* Clamp bpp to 8 on screens without EDID 1.4 */
10647         if (info->bpc == 0 && bpp > 24) {
10648                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10649                               bpp);
10650                 pipe_config->pipe_bpp = 24;
10651         }
10652 }
10653
10654 static int
10655 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10656                           struct intel_crtc_state *pipe_config)
10657 {
10658         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10659         struct drm_atomic_state *state;
10660         struct drm_connector *connector;
10661         struct drm_connector_state *connector_state;
10662         int bpp, i;
10663
10664         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10665             IS_CHERRYVIEW(dev_priv)))
10666                 bpp = 10*3;
10667         else if (INTEL_GEN(dev_priv) >= 5)
10668                 bpp = 12*3;
10669         else
10670                 bpp = 8*3;
10671
10672
10673         pipe_config->pipe_bpp = bpp;
10674
10675         state = pipe_config->base.state;
10676
10677         /* Clamp display bpp to EDID value */
10678         for_each_new_connector_in_state(state, connector, connector_state, i) {
10679                 if (connector_state->crtc != &crtc->base)
10680                         continue;
10681
10682                 connected_sink_compute_bpp(to_intel_connector(connector),
10683                                            pipe_config);
10684         }
10685
10686         return bpp;
10687 }
10688
10689 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10690 {
10691         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10692                         "type: 0x%x flags: 0x%x\n",
10693                 mode->crtc_clock,
10694                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10695                 mode->crtc_hsync_end, mode->crtc_htotal,
10696                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10697                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10698 }
10699
10700 static inline void
10701 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10702                       unsigned int lane_count, struct intel_link_m_n *m_n)
10703 {
10704         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10705                       id, lane_count,
10706                       m_n->gmch_m, m_n->gmch_n,
10707                       m_n->link_m, m_n->link_n, m_n->tu);
10708 }
10709
10710 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10711                                    struct intel_crtc_state *pipe_config,
10712                                    const char *context)
10713 {
10714         struct drm_device *dev = crtc->base.dev;
10715         struct drm_i915_private *dev_priv = to_i915(dev);
10716         struct drm_plane *plane;
10717         struct intel_plane *intel_plane;
10718         struct intel_plane_state *state;
10719         struct drm_framebuffer *fb;
10720
10721         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10722                       crtc->base.base.id, crtc->base.name, context);
10723
10724         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
10725                       transcoder_name(pipe_config->cpu_transcoder),
10726                       pipe_config->pipe_bpp, pipe_config->dither);
10727
10728         if (pipe_config->has_pch_encoder)
10729                 intel_dump_m_n_config(pipe_config, "fdi",
10730                                       pipe_config->fdi_lanes,
10731                                       &pipe_config->fdi_m_n);
10732
10733         if (pipe_config->ycbcr420)
10734                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
10735
10736         if (intel_crtc_has_dp_encoder(pipe_config)) {
10737                 intel_dump_m_n_config(pipe_config, "dp m_n",
10738                                 pipe_config->lane_count, &pipe_config->dp_m_n);
10739                 if (pipe_config->has_drrs)
10740                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
10741                                               pipe_config->lane_count,
10742                                               &pipe_config->dp_m2_n2);
10743         }
10744
10745         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10746                       pipe_config->has_audio, pipe_config->has_infoframe);
10747
10748         DRM_DEBUG_KMS("requested mode:\n");
10749         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10750         DRM_DEBUG_KMS("adjusted mode:\n");
10751         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10752         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10753         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
10754                       pipe_config->port_clock,
10755                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
10756                       pipe_config->pixel_rate);
10757
10758         if (INTEL_GEN(dev_priv) >= 9)
10759                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
10760                               crtc->num_scalers,
10761                               pipe_config->scaler_state.scaler_users,
10762                               pipe_config->scaler_state.scaler_id);
10763
10764         if (HAS_GMCH_DISPLAY(dev_priv))
10765                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10766                               pipe_config->gmch_pfit.control,
10767                               pipe_config->gmch_pfit.pgm_ratios,
10768                               pipe_config->gmch_pfit.lvds_border_bits);
10769         else
10770                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10771                               pipe_config->pch_pfit.pos,
10772                               pipe_config->pch_pfit.size,
10773                               enableddisabled(pipe_config->pch_pfit.enabled));
10774
10775         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
10776                       pipe_config->ips_enabled, pipe_config->double_wide);
10777
10778         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
10779
10780         DRM_DEBUG_KMS("planes on this crtc\n");
10781         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
10782                 struct drm_format_name_buf format_name;
10783                 intel_plane = to_intel_plane(plane);
10784                 if (intel_plane->pipe != crtc->pipe)
10785                         continue;
10786
10787                 state = to_intel_plane_state(plane->state);
10788                 fb = state->base.fb;
10789                 if (!fb) {
10790                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
10791                                       plane->base.id, plane->name, state->scaler_id);
10792                         continue;
10793                 }
10794
10795                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
10796                               plane->base.id, plane->name,
10797                               fb->base.id, fb->width, fb->height,
10798                               drm_get_format_name(fb->format->format, &format_name));
10799                 if (INTEL_GEN(dev_priv) >= 9)
10800                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
10801                                       state->scaler_id,
10802                                       state->base.src.x1 >> 16,
10803                                       state->base.src.y1 >> 16,
10804                                       drm_rect_width(&state->base.src) >> 16,
10805                                       drm_rect_height(&state->base.src) >> 16,
10806                                       state->base.dst.x1, state->base.dst.y1,
10807                                       drm_rect_width(&state->base.dst),
10808                                       drm_rect_height(&state->base.dst));
10809         }
10810 }
10811
10812 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
10813 {
10814         struct drm_device *dev = state->dev;
10815         struct drm_connector *connector;
10816         struct drm_connector_list_iter conn_iter;
10817         unsigned int used_ports = 0;
10818         unsigned int used_mst_ports = 0;
10819
10820         /*
10821          * Walk the connector list instead of the encoder
10822          * list to detect the problem on ddi platforms
10823          * where there's just one encoder per digital port.
10824          */
10825         drm_connector_list_iter_begin(dev, &conn_iter);
10826         drm_for_each_connector_iter(connector, &conn_iter) {
10827                 struct drm_connector_state *connector_state;
10828                 struct intel_encoder *encoder;
10829
10830                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
10831                 if (!connector_state)
10832                         connector_state = connector->state;
10833
10834                 if (!connector_state->best_encoder)
10835                         continue;
10836
10837                 encoder = to_intel_encoder(connector_state->best_encoder);
10838
10839                 WARN_ON(!connector_state->crtc);
10840
10841                 switch (encoder->type) {
10842                         unsigned int port_mask;
10843                 case INTEL_OUTPUT_UNKNOWN:
10844                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
10845                                 break;
10846                 case INTEL_OUTPUT_DP:
10847                 case INTEL_OUTPUT_HDMI:
10848                 case INTEL_OUTPUT_EDP:
10849                         port_mask = 1 << enc_to_dig_port(&encoder->base)->port;
10850
10851                         /* the same port mustn't appear more than once */
10852                         if (used_ports & port_mask)
10853                                 return false;
10854
10855                         used_ports |= port_mask;
10856                         break;
10857                 case INTEL_OUTPUT_DP_MST:
10858                         used_mst_ports |=
10859                                 1 << enc_to_mst(&encoder->base)->primary->port;
10860                         break;
10861                 default:
10862                         break;
10863                 }
10864         }
10865         drm_connector_list_iter_end(&conn_iter);
10866
10867         /* can't mix MST and SST/HDMI on the same port */
10868         if (used_ports & used_mst_ports)
10869                 return false;
10870
10871         return true;
10872 }
10873
10874 static void
10875 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
10876 {
10877         struct drm_i915_private *dev_priv =
10878                 to_i915(crtc_state->base.crtc->dev);
10879         struct intel_crtc_scaler_state scaler_state;
10880         struct intel_dpll_hw_state dpll_hw_state;
10881         struct intel_shared_dpll *shared_dpll;
10882         struct intel_crtc_wm_state wm_state;
10883         bool force_thru;
10884
10885         /* FIXME: before the switch to atomic started, a new pipe_config was
10886          * kzalloc'd. Code that depends on any field being zero should be
10887          * fixed, so that the crtc_state can be safely duplicated. For now,
10888          * only fields that are know to not cause problems are preserved. */
10889
10890         scaler_state = crtc_state->scaler_state;
10891         shared_dpll = crtc_state->shared_dpll;
10892         dpll_hw_state = crtc_state->dpll_hw_state;
10893         force_thru = crtc_state->pch_pfit.force_thru;
10894         if (IS_G4X(dev_priv) ||
10895             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10896                 wm_state = crtc_state->wm;
10897
10898         /* Keep base drm_crtc_state intact, only clear our extended struct */
10899         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
10900         memset(&crtc_state->base + 1, 0,
10901                sizeof(*crtc_state) - sizeof(crtc_state->base));
10902
10903         crtc_state->scaler_state = scaler_state;
10904         crtc_state->shared_dpll = shared_dpll;
10905         crtc_state->dpll_hw_state = dpll_hw_state;
10906         crtc_state->pch_pfit.force_thru = force_thru;
10907         if (IS_G4X(dev_priv) ||
10908             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10909                 crtc_state->wm = wm_state;
10910 }
10911
10912 static int
10913 intel_modeset_pipe_config(struct drm_crtc *crtc,
10914                           struct intel_crtc_state *pipe_config)
10915 {
10916         struct drm_atomic_state *state = pipe_config->base.state;
10917         struct intel_encoder *encoder;
10918         struct drm_connector *connector;
10919         struct drm_connector_state *connector_state;
10920         int base_bpp, ret = -EINVAL;
10921         int i;
10922         bool retry = true;
10923
10924         clear_intel_crtc_state(pipe_config);
10925
10926         pipe_config->cpu_transcoder =
10927                 (enum transcoder) to_intel_crtc(crtc)->pipe;
10928
10929         /*
10930          * Sanitize sync polarity flags based on requested ones. If neither
10931          * positive or negative polarity is requested, treat this as meaning
10932          * negative polarity.
10933          */
10934         if (!(pipe_config->base.adjusted_mode.flags &
10935               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
10936                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
10937
10938         if (!(pipe_config->base.adjusted_mode.flags &
10939               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
10940                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
10941
10942         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
10943                                              pipe_config);
10944         if (base_bpp < 0)
10945                 goto fail;
10946
10947         /*
10948          * Determine the real pipe dimensions. Note that stereo modes can
10949          * increase the actual pipe size due to the frame doubling and
10950          * insertion of additional space for blanks between the frame. This
10951          * is stored in the crtc timings. We use the requested mode to do this
10952          * computation to clearly distinguish it from the adjusted mode, which
10953          * can be changed by the connectors in the below retry loop.
10954          */
10955         drm_mode_get_hv_timing(&pipe_config->base.mode,
10956                                &pipe_config->pipe_src_w,
10957                                &pipe_config->pipe_src_h);
10958
10959         for_each_new_connector_in_state(state, connector, connector_state, i) {
10960                 if (connector_state->crtc != crtc)
10961                         continue;
10962
10963                 encoder = to_intel_encoder(connector_state->best_encoder);
10964
10965                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
10966                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
10967                         goto fail;
10968                 }
10969
10970                 /*
10971                  * Determine output_types before calling the .compute_config()
10972                  * hooks so that the hooks can use this information safely.
10973                  */
10974                 pipe_config->output_types |= 1 << encoder->type;
10975         }
10976
10977 encoder_retry:
10978         /* Ensure the port clock defaults are reset when retrying. */
10979         pipe_config->port_clock = 0;
10980         pipe_config->pixel_multiplier = 1;
10981
10982         /* Fill in default crtc timings, allow encoders to overwrite them. */
10983         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
10984                               CRTC_STEREO_DOUBLE);
10985
10986         /* Pass our mode to the connectors and the CRTC to give them a chance to
10987          * adjust it according to limitations or connector properties, and also
10988          * a chance to reject the mode entirely.
10989          */
10990         for_each_new_connector_in_state(state, connector, connector_state, i) {
10991                 if (connector_state->crtc != crtc)
10992                         continue;
10993
10994                 encoder = to_intel_encoder(connector_state->best_encoder);
10995
10996                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
10997                         DRM_DEBUG_KMS("Encoder config failure\n");
10998                         goto fail;
10999                 }
11000         }
11001
11002         /* Set default port clock if not overwritten by the encoder. Needs to be
11003          * done afterwards in case the encoder adjusts the mode. */
11004         if (!pipe_config->port_clock)
11005                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11006                         * pipe_config->pixel_multiplier;
11007
11008         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11009         if (ret < 0) {
11010                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11011                 goto fail;
11012         }
11013
11014         if (ret == RETRY) {
11015                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11016                         ret = -EINVAL;
11017                         goto fail;
11018                 }
11019
11020                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11021                 retry = false;
11022                 goto encoder_retry;
11023         }
11024
11025         /* Dithering seems to not pass-through bits correctly when it should, so
11026          * only enable it on 6bpc panels and when its not a compliance
11027          * test requesting 6bpc video pattern.
11028          */
11029         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11030                 !pipe_config->dither_force_disable;
11031         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11032                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11033
11034 fail:
11035         return ret;
11036 }
11037
11038 static void
11039 intel_modeset_update_crtc_state(struct drm_atomic_state *state)
11040 {
11041         struct drm_crtc *crtc;
11042         struct drm_crtc_state *new_crtc_state;
11043         int i;
11044
11045         /* Double check state. */
11046         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11047                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
11048
11049                 /*
11050                  * Update legacy state to satisfy fbc code. This can
11051                  * be removed when fbc uses the atomic state.
11052                  */
11053                 if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
11054                         struct drm_plane_state *plane_state = crtc->primary->state;
11055
11056                         crtc->primary->fb = plane_state->fb;
11057                         crtc->x = plane_state->src_x >> 16;
11058                         crtc->y = plane_state->src_y >> 16;
11059                 }
11060         }
11061 }
11062
11063 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11064 {
11065         int diff;
11066
11067         if (clock1 == clock2)
11068                 return true;
11069
11070         if (!clock1 || !clock2)
11071                 return false;
11072
11073         diff = abs(clock1 - clock2);
11074
11075         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11076                 return true;
11077
11078         return false;
11079 }
11080
11081 static bool
11082 intel_compare_m_n(unsigned int m, unsigned int n,
11083                   unsigned int m2, unsigned int n2,
11084                   bool exact)
11085 {
11086         if (m == m2 && n == n2)
11087                 return true;
11088
11089         if (exact || !m || !n || !m2 || !n2)
11090                 return false;
11091
11092         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11093
11094         if (n > n2) {
11095                 while (n > n2) {
11096                         m2 <<= 1;
11097                         n2 <<= 1;
11098                 }
11099         } else if (n < n2) {
11100                 while (n < n2) {
11101                         m <<= 1;
11102                         n <<= 1;
11103                 }
11104         }
11105
11106         if (n != n2)
11107                 return false;
11108
11109         return intel_fuzzy_clock_check(m, m2);
11110 }
11111
11112 static bool
11113 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11114                        struct intel_link_m_n *m2_n2,
11115                        bool adjust)
11116 {
11117         if (m_n->tu == m2_n2->tu &&
11118             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11119                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11120             intel_compare_m_n(m_n->link_m, m_n->link_n,
11121                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11122                 if (adjust)
11123                         *m2_n2 = *m_n;
11124
11125                 return true;
11126         }
11127
11128         return false;
11129 }
11130
11131 static void __printf(3, 4)
11132 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11133 {
11134         char *level;
11135         unsigned int category;
11136         struct va_format vaf;
11137         va_list args;
11138
11139         if (adjust) {
11140                 level = KERN_DEBUG;
11141                 category = DRM_UT_KMS;
11142         } else {
11143                 level = KERN_ERR;
11144                 category = DRM_UT_NONE;
11145         }
11146
11147         va_start(args, format);
11148         vaf.fmt = format;
11149         vaf.va = &args;
11150
11151         drm_printk(level, category, "mismatch in %s %pV", name, &vaf);
11152
11153         va_end(args);
11154 }
11155
11156 static bool
11157 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11158                           struct intel_crtc_state *current_config,
11159                           struct intel_crtc_state *pipe_config,
11160                           bool adjust)
11161 {
11162         bool ret = true;
11163
11164 #define PIPE_CONF_CHECK_X(name) \
11165         if (current_config->name != pipe_config->name) { \
11166                 pipe_config_err(adjust, __stringify(name), \
11167                           "(expected 0x%08x, found 0x%08x)\n", \
11168                           current_config->name, \
11169                           pipe_config->name); \
11170                 ret = false; \
11171         }
11172
11173 #define PIPE_CONF_CHECK_I(name) \
11174         if (current_config->name != pipe_config->name) { \
11175                 pipe_config_err(adjust, __stringify(name), \
11176                           "(expected %i, found %i)\n", \
11177                           current_config->name, \
11178                           pipe_config->name); \
11179                 ret = false; \
11180         }
11181
11182 #define PIPE_CONF_CHECK_P(name) \
11183         if (current_config->name != pipe_config->name) { \
11184                 pipe_config_err(adjust, __stringify(name), \
11185                           "(expected %p, found %p)\n", \
11186                           current_config->name, \
11187                           pipe_config->name); \
11188                 ret = false; \
11189         }
11190
11191 #define PIPE_CONF_CHECK_M_N(name) \
11192         if (!intel_compare_link_m_n(&current_config->name, \
11193                                     &pipe_config->name,\
11194                                     adjust)) { \
11195                 pipe_config_err(adjust, __stringify(name), \
11196                           "(expected tu %i gmch %i/%i link %i/%i, " \
11197                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11198                           current_config->name.tu, \
11199                           current_config->name.gmch_m, \
11200                           current_config->name.gmch_n, \
11201                           current_config->name.link_m, \
11202                           current_config->name.link_n, \
11203                           pipe_config->name.tu, \
11204                           pipe_config->name.gmch_m, \
11205                           pipe_config->name.gmch_n, \
11206                           pipe_config->name.link_m, \
11207                           pipe_config->name.link_n); \
11208                 ret = false; \
11209         }
11210
11211 /* This is required for BDW+ where there is only one set of registers for
11212  * switching between high and low RR.
11213  * This macro can be used whenever a comparison has to be made between one
11214  * hw state and multiple sw state variables.
11215  */
11216 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
11217         if (!intel_compare_link_m_n(&current_config->name, \
11218                                     &pipe_config->name, adjust) && \
11219             !intel_compare_link_m_n(&current_config->alt_name, \
11220                                     &pipe_config->name, adjust)) { \
11221                 pipe_config_err(adjust, __stringify(name), \
11222                           "(expected tu %i gmch %i/%i link %i/%i, " \
11223                           "or tu %i gmch %i/%i link %i/%i, " \
11224                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11225                           current_config->name.tu, \
11226                           current_config->name.gmch_m, \
11227                           current_config->name.gmch_n, \
11228                           current_config->name.link_m, \
11229                           current_config->name.link_n, \
11230                           current_config->alt_name.tu, \
11231                           current_config->alt_name.gmch_m, \
11232                           current_config->alt_name.gmch_n, \
11233                           current_config->alt_name.link_m, \
11234                           current_config->alt_name.link_n, \
11235                           pipe_config->name.tu, \
11236                           pipe_config->name.gmch_m, \
11237                           pipe_config->name.gmch_n, \
11238                           pipe_config->name.link_m, \
11239                           pipe_config->name.link_n); \
11240                 ret = false; \
11241         }
11242
11243 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
11244         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11245                 pipe_config_err(adjust, __stringify(name), \
11246                           "(%x) (expected %i, found %i)\n", \
11247                           (mask), \
11248                           current_config->name & (mask), \
11249                           pipe_config->name & (mask)); \
11250                 ret = false; \
11251         }
11252
11253 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
11254         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11255                 pipe_config_err(adjust, __stringify(name), \
11256                           "(expected %i, found %i)\n", \
11257                           current_config->name, \
11258                           pipe_config->name); \
11259                 ret = false; \
11260         }
11261
11262 #define PIPE_CONF_QUIRK(quirk)  \
11263         ((current_config->quirks | pipe_config->quirks) & (quirk))
11264
11265         PIPE_CONF_CHECK_I(cpu_transcoder);
11266
11267         PIPE_CONF_CHECK_I(has_pch_encoder);
11268         PIPE_CONF_CHECK_I(fdi_lanes);
11269         PIPE_CONF_CHECK_M_N(fdi_m_n);
11270
11271         PIPE_CONF_CHECK_I(lane_count);
11272         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11273
11274         if (INTEL_GEN(dev_priv) < 8) {
11275                 PIPE_CONF_CHECK_M_N(dp_m_n);
11276
11277                 if (current_config->has_drrs)
11278                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11279         } else
11280                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11281
11282         PIPE_CONF_CHECK_X(output_types);
11283
11284         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11285         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11286         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11287         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11288         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11289         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11290
11291         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11292         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11293         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11294         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11295         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11296         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11297
11298         PIPE_CONF_CHECK_I(pixel_multiplier);
11299         PIPE_CONF_CHECK_I(has_hdmi_sink);
11300         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11301             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11302                 PIPE_CONF_CHECK_I(limited_color_range);
11303
11304         PIPE_CONF_CHECK_I(hdmi_scrambling);
11305         PIPE_CONF_CHECK_I(hdmi_high_tmds_clock_ratio);
11306         PIPE_CONF_CHECK_I(has_infoframe);
11307         PIPE_CONF_CHECK_I(ycbcr420);
11308
11309         PIPE_CONF_CHECK_I(has_audio);
11310
11311         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11312                               DRM_MODE_FLAG_INTERLACE);
11313
11314         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11315                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11316                                       DRM_MODE_FLAG_PHSYNC);
11317                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11318                                       DRM_MODE_FLAG_NHSYNC);
11319                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11320                                       DRM_MODE_FLAG_PVSYNC);
11321                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11322                                       DRM_MODE_FLAG_NVSYNC);
11323         }
11324
11325         PIPE_CONF_CHECK_X(gmch_pfit.control);
11326         /* pfit ratios are autocomputed by the hw on gen4+ */
11327         if (INTEL_GEN(dev_priv) < 4)
11328                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11329         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11330
11331         if (!adjust) {
11332                 PIPE_CONF_CHECK_I(pipe_src_w);
11333                 PIPE_CONF_CHECK_I(pipe_src_h);
11334
11335                 PIPE_CONF_CHECK_I(pch_pfit.enabled);
11336                 if (current_config->pch_pfit.enabled) {
11337                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11338                         PIPE_CONF_CHECK_X(pch_pfit.size);
11339                 }
11340
11341                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11342                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11343         }
11344
11345         /* BDW+ don't expose a synchronous way to read the state */
11346         if (IS_HASWELL(dev_priv))
11347                 PIPE_CONF_CHECK_I(ips_enabled);
11348
11349         PIPE_CONF_CHECK_I(double_wide);
11350
11351         PIPE_CONF_CHECK_P(shared_dpll);
11352         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11353         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11354         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11355         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11356         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11357         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11358         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11359         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11360         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11361
11362         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11363         PIPE_CONF_CHECK_X(dsi_pll.div);
11364
11365         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11366                 PIPE_CONF_CHECK_I(pipe_bpp);
11367
11368         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11369         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11370
11371 #undef PIPE_CONF_CHECK_X
11372 #undef PIPE_CONF_CHECK_I
11373 #undef PIPE_CONF_CHECK_P
11374 #undef PIPE_CONF_CHECK_FLAGS
11375 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11376 #undef PIPE_CONF_QUIRK
11377
11378         return ret;
11379 }
11380
11381 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11382                                            const struct intel_crtc_state *pipe_config)
11383 {
11384         if (pipe_config->has_pch_encoder) {
11385                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11386                                                             &pipe_config->fdi_m_n);
11387                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11388
11389                 /*
11390                  * FDI already provided one idea for the dotclock.
11391                  * Yell if the encoder disagrees.
11392                  */
11393                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11394                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11395                      fdi_dotclock, dotclock);
11396         }
11397 }
11398
11399 static void verify_wm_state(struct drm_crtc *crtc,
11400                             struct drm_crtc_state *new_state)
11401 {
11402         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11403         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11404         struct skl_pipe_wm hw_wm, *sw_wm;
11405         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11406         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11407         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11408         const enum pipe pipe = intel_crtc->pipe;
11409         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11410
11411         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11412                 return;
11413
11414         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11415         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11416
11417         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11418         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11419
11420         /* planes */
11421         for_each_universal_plane(dev_priv, pipe, plane) {
11422                 hw_plane_wm = &hw_wm.planes[plane];
11423                 sw_plane_wm = &sw_wm->planes[plane];
11424
11425                 /* Watermarks */
11426                 for (level = 0; level <= max_level; level++) {
11427                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11428                                                 &sw_plane_wm->wm[level]))
11429                                 continue;
11430
11431                         DRM_ERROR("mismatch in WM pipe %c plane %d level %d (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11432                                   pipe_name(pipe), plane + 1, level,
11433                                   sw_plane_wm->wm[level].plane_en,
11434                                   sw_plane_wm->wm[level].plane_res_b,
11435                                   sw_plane_wm->wm[level].plane_res_l,
11436                                   hw_plane_wm->wm[level].plane_en,
11437                                   hw_plane_wm->wm[level].plane_res_b,
11438                                   hw_plane_wm->wm[level].plane_res_l);
11439                 }
11440
11441                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11442                                          &sw_plane_wm->trans_wm)) {
11443                         DRM_ERROR("mismatch in trans WM pipe %c plane %d (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11444                                   pipe_name(pipe), plane + 1,
11445                                   sw_plane_wm->trans_wm.plane_en,
11446                                   sw_plane_wm->trans_wm.plane_res_b,
11447                                   sw_plane_wm->trans_wm.plane_res_l,
11448                                   hw_plane_wm->trans_wm.plane_en,
11449                                   hw_plane_wm->trans_wm.plane_res_b,
11450                                   hw_plane_wm->trans_wm.plane_res_l);
11451                 }
11452
11453                 /* DDB */
11454                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11455                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11456
11457                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11458                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11459                                   pipe_name(pipe), plane + 1,
11460                                   sw_ddb_entry->start, sw_ddb_entry->end,
11461                                   hw_ddb_entry->start, hw_ddb_entry->end);
11462                 }
11463         }
11464
11465         /*
11466          * cursor
11467          * If the cursor plane isn't active, we may not have updated it's ddb
11468          * allocation. In that case since the ddb allocation will be updated
11469          * once the plane becomes visible, we can skip this check
11470          */
11471         if (1) {
11472                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11473                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11474
11475                 /* Watermarks */
11476                 for (level = 0; level <= max_level; level++) {
11477                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11478                                                 &sw_plane_wm->wm[level]))
11479                                 continue;
11480
11481                         DRM_ERROR("mismatch in WM pipe %c cursor level %d (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11482                                   pipe_name(pipe), level,
11483                                   sw_plane_wm->wm[level].plane_en,
11484                                   sw_plane_wm->wm[level].plane_res_b,
11485                                   sw_plane_wm->wm[level].plane_res_l,
11486                                   hw_plane_wm->wm[level].plane_en,
11487                                   hw_plane_wm->wm[level].plane_res_b,
11488                                   hw_plane_wm->wm[level].plane_res_l);
11489                 }
11490
11491                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11492                                          &sw_plane_wm->trans_wm)) {
11493                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11494                                   pipe_name(pipe),
11495                                   sw_plane_wm->trans_wm.plane_en,
11496                                   sw_plane_wm->trans_wm.plane_res_b,
11497                                   sw_plane_wm->trans_wm.plane_res_l,
11498                                   hw_plane_wm->trans_wm.plane_en,
11499                                   hw_plane_wm->trans_wm.plane_res_b,
11500                                   hw_plane_wm->trans_wm.plane_res_l);
11501                 }
11502
11503                 /* DDB */
11504                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11505                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11506
11507                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11508                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11509                                   pipe_name(pipe),
11510                                   sw_ddb_entry->start, sw_ddb_entry->end,
11511                                   hw_ddb_entry->start, hw_ddb_entry->end);
11512                 }
11513         }
11514 }
11515
11516 static void
11517 verify_connector_state(struct drm_device *dev,
11518                        struct drm_atomic_state *state,
11519                        struct drm_crtc *crtc)
11520 {
11521         struct drm_connector *connector;
11522         struct drm_connector_state *new_conn_state;
11523         int i;
11524
11525         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11526                 struct drm_encoder *encoder = connector->encoder;
11527                 struct drm_crtc_state *crtc_state = NULL;
11528
11529                 if (new_conn_state->crtc != crtc)
11530                         continue;
11531
11532                 if (crtc)
11533                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11534
11535                 intel_connector_verify_state(crtc_state, new_conn_state);
11536
11537                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11538                      "connector's atomic encoder doesn't match legacy encoder\n");
11539         }
11540 }
11541
11542 static void
11543 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11544 {
11545         struct intel_encoder *encoder;
11546         struct drm_connector *connector;
11547         struct drm_connector_state *old_conn_state, *new_conn_state;
11548         int i;
11549
11550         for_each_intel_encoder(dev, encoder) {
11551                 bool enabled = false, found = false;
11552                 enum pipe pipe;
11553
11554                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11555                               encoder->base.base.id,
11556                               encoder->base.name);
11557
11558                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11559                                                    new_conn_state, i) {
11560                         if (old_conn_state->best_encoder == &encoder->base)
11561                                 found = true;
11562
11563                         if (new_conn_state->best_encoder != &encoder->base)
11564                                 continue;
11565                         found = enabled = true;
11566
11567                         I915_STATE_WARN(new_conn_state->crtc !=
11568                                         encoder->base.crtc,
11569                              "connector's crtc doesn't match encoder crtc\n");
11570                 }
11571
11572                 if (!found)
11573                         continue;
11574
11575                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11576                      "encoder's enabled state mismatch "
11577                      "(expected %i, found %i)\n",
11578                      !!encoder->base.crtc, enabled);
11579
11580                 if (!encoder->base.crtc) {
11581                         bool active;
11582
11583                         active = encoder->get_hw_state(encoder, &pipe);
11584                         I915_STATE_WARN(active,
11585                              "encoder detached but still enabled on pipe %c.\n",
11586                              pipe_name(pipe));
11587                 }
11588         }
11589 }
11590
11591 static void
11592 verify_crtc_state(struct drm_crtc *crtc,
11593                   struct drm_crtc_state *old_crtc_state,
11594                   struct drm_crtc_state *new_crtc_state)
11595 {
11596         struct drm_device *dev = crtc->dev;
11597         struct drm_i915_private *dev_priv = to_i915(dev);
11598         struct intel_encoder *encoder;
11599         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11600         struct intel_crtc_state *pipe_config, *sw_config;
11601         struct drm_atomic_state *old_state;
11602         bool active;
11603
11604         old_state = old_crtc_state->state;
11605         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11606         pipe_config = to_intel_crtc_state(old_crtc_state);
11607         memset(pipe_config, 0, sizeof(*pipe_config));
11608         pipe_config->base.crtc = crtc;
11609         pipe_config->base.state = old_state;
11610
11611         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11612
11613         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11614
11615         /* we keep both pipes enabled on 830 */
11616         if (IS_I830(dev_priv))
11617                 active = new_crtc_state->active;
11618
11619         I915_STATE_WARN(new_crtc_state->active != active,
11620              "crtc active state doesn't match with hw state "
11621              "(expected %i, found %i)\n", new_crtc_state->active, active);
11622
11623         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11624              "transitional active state does not match atomic hw state "
11625              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11626
11627         for_each_encoder_on_crtc(dev, crtc, encoder) {
11628                 enum pipe pipe;
11629
11630                 active = encoder->get_hw_state(encoder, &pipe);
11631                 I915_STATE_WARN(active != new_crtc_state->active,
11632                         "[ENCODER:%i] active %i with crtc active %i\n",
11633                         encoder->base.base.id, active, new_crtc_state->active);
11634
11635                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11636                                 "Encoder connected to wrong pipe %c\n",
11637                                 pipe_name(pipe));
11638
11639                 if (active) {
11640                         pipe_config->output_types |= 1 << encoder->type;
11641                         encoder->get_config(encoder, pipe_config);
11642                 }
11643         }
11644
11645         intel_crtc_compute_pixel_rate(pipe_config);
11646
11647         if (!new_crtc_state->active)
11648                 return;
11649
11650         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11651
11652         sw_config = to_intel_crtc_state(new_crtc_state);
11653         if (!intel_pipe_config_compare(dev_priv, sw_config,
11654                                        pipe_config, false)) {
11655                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11656                 intel_dump_pipe_config(intel_crtc, pipe_config,
11657                                        "[hw state]");
11658                 intel_dump_pipe_config(intel_crtc, sw_config,
11659                                        "[sw state]");
11660         }
11661 }
11662
11663 static void
11664 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11665                          struct intel_shared_dpll *pll,
11666                          struct drm_crtc *crtc,
11667                          struct drm_crtc_state *new_state)
11668 {
11669         struct intel_dpll_hw_state dpll_hw_state;
11670         unsigned crtc_mask;
11671         bool active;
11672
11673         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11674
11675         DRM_DEBUG_KMS("%s\n", pll->name);
11676
11677         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
11678
11679         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
11680                 I915_STATE_WARN(!pll->on && pll->active_mask,
11681                      "pll in active use but not on in sw tracking\n");
11682                 I915_STATE_WARN(pll->on && !pll->active_mask,
11683                      "pll is on but not used by any active crtc\n");
11684                 I915_STATE_WARN(pll->on != active,
11685                      "pll on state mismatch (expected %i, found %i)\n",
11686                      pll->on, active);
11687         }
11688
11689         if (!crtc) {
11690                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
11691                                 "more active pll users than references: %x vs %x\n",
11692                                 pll->active_mask, pll->state.crtc_mask);
11693
11694                 return;
11695         }
11696
11697         crtc_mask = 1 << drm_crtc_index(crtc);
11698
11699         if (new_state->active)
11700                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
11701                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
11702                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11703         else
11704                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11705                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
11706                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11707
11708         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
11709                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
11710                         crtc_mask, pll->state.crtc_mask);
11711
11712         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
11713                                           &dpll_hw_state,
11714                                           sizeof(dpll_hw_state)),
11715                         "pll hw state mismatch\n");
11716 }
11717
11718 static void
11719 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
11720                          struct drm_crtc_state *old_crtc_state,
11721                          struct drm_crtc_state *new_crtc_state)
11722 {
11723         struct drm_i915_private *dev_priv = to_i915(dev);
11724         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
11725         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
11726
11727         if (new_state->shared_dpll)
11728                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
11729
11730         if (old_state->shared_dpll &&
11731             old_state->shared_dpll != new_state->shared_dpll) {
11732                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
11733                 struct intel_shared_dpll *pll = old_state->shared_dpll;
11734
11735                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11736                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
11737                                 pipe_name(drm_crtc_index(crtc)));
11738                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
11739                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
11740                                 pipe_name(drm_crtc_index(crtc)));
11741         }
11742 }
11743
11744 static void
11745 intel_modeset_verify_crtc(struct drm_crtc *crtc,
11746                           struct drm_atomic_state *state,
11747                           struct drm_crtc_state *old_state,
11748                           struct drm_crtc_state *new_state)
11749 {
11750         if (!needs_modeset(new_state) &&
11751             !to_intel_crtc_state(new_state)->update_pipe)
11752                 return;
11753
11754         verify_wm_state(crtc, new_state);
11755         verify_connector_state(crtc->dev, state, crtc);
11756         verify_crtc_state(crtc, old_state, new_state);
11757         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
11758 }
11759
11760 static void
11761 verify_disabled_dpll_state(struct drm_device *dev)
11762 {
11763         struct drm_i915_private *dev_priv = to_i915(dev);
11764         int i;
11765
11766         for (i = 0; i < dev_priv->num_shared_dpll; i++)
11767                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
11768 }
11769
11770 static void
11771 intel_modeset_verify_disabled(struct drm_device *dev,
11772                               struct drm_atomic_state *state)
11773 {
11774         verify_encoder_state(dev, state);
11775         verify_connector_state(dev, state, NULL);
11776         verify_disabled_dpll_state(dev);
11777 }
11778
11779 static void update_scanline_offset(struct intel_crtc *crtc)
11780 {
11781         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11782
11783         /*
11784          * The scanline counter increments at the leading edge of hsync.
11785          *
11786          * On most platforms it starts counting from vtotal-1 on the
11787          * first active line. That means the scanline counter value is
11788          * always one less than what we would expect. Ie. just after
11789          * start of vblank, which also occurs at start of hsync (on the
11790          * last active line), the scanline counter will read vblank_start-1.
11791          *
11792          * On gen2 the scanline counter starts counting from 1 instead
11793          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
11794          * to keep the value positive), instead of adding one.
11795          *
11796          * On HSW+ the behaviour of the scanline counter depends on the output
11797          * type. For DP ports it behaves like most other platforms, but on HDMI
11798          * there's an extra 1 line difference. So we need to add two instead of
11799          * one to the value.
11800          *
11801          * On VLV/CHV DSI the scanline counter would appear to increment
11802          * approx. 1/3 of a scanline before start of vblank. Unfortunately
11803          * that means we can't tell whether we're in vblank or not while
11804          * we're on that particular line. We must still set scanline_offset
11805          * to 1 so that the vblank timestamps come out correct when we query
11806          * the scanline counter from within the vblank interrupt handler.
11807          * However if queried just before the start of vblank we'll get an
11808          * answer that's slightly in the future.
11809          */
11810         if (IS_GEN2(dev_priv)) {
11811                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
11812                 int vtotal;
11813
11814                 vtotal = adjusted_mode->crtc_vtotal;
11815                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
11816                         vtotal /= 2;
11817
11818                 crtc->scanline_offset = vtotal - 1;
11819         } else if (HAS_DDI(dev_priv) &&
11820                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
11821                 crtc->scanline_offset = 2;
11822         } else
11823                 crtc->scanline_offset = 1;
11824 }
11825
11826 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
11827 {
11828         struct drm_device *dev = state->dev;
11829         struct drm_i915_private *dev_priv = to_i915(dev);
11830         struct drm_crtc *crtc;
11831         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11832         int i;
11833
11834         if (!dev_priv->display.crtc_compute_clock)
11835                 return;
11836
11837         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11838                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11839                 struct intel_shared_dpll *old_dpll =
11840                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
11841
11842                 if (!needs_modeset(new_crtc_state))
11843                         continue;
11844
11845                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
11846
11847                 if (!old_dpll)
11848                         continue;
11849
11850                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
11851         }
11852 }
11853
11854 /*
11855  * This implements the workaround described in the "notes" section of the mode
11856  * set sequence documentation. When going from no pipes or single pipe to
11857  * multiple pipes, and planes are enabled after the pipe, we need to wait at
11858  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
11859  */
11860 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
11861 {
11862         struct drm_crtc_state *crtc_state;
11863         struct intel_crtc *intel_crtc;
11864         struct drm_crtc *crtc;
11865         struct intel_crtc_state *first_crtc_state = NULL;
11866         struct intel_crtc_state *other_crtc_state = NULL;
11867         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
11868         int i;
11869
11870         /* look at all crtc's that are going to be enabled in during modeset */
11871         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
11872                 intel_crtc = to_intel_crtc(crtc);
11873
11874                 if (!crtc_state->active || !needs_modeset(crtc_state))
11875                         continue;
11876
11877                 if (first_crtc_state) {
11878                         other_crtc_state = to_intel_crtc_state(crtc_state);
11879                         break;
11880                 } else {
11881                         first_crtc_state = to_intel_crtc_state(crtc_state);
11882                         first_pipe = intel_crtc->pipe;
11883                 }
11884         }
11885
11886         /* No workaround needed? */
11887         if (!first_crtc_state)
11888                 return 0;
11889
11890         /* w/a possibly needed, check how many crtc's are already enabled. */
11891         for_each_intel_crtc(state->dev, intel_crtc) {
11892                 struct intel_crtc_state *pipe_config;
11893
11894                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
11895                 if (IS_ERR(pipe_config))
11896                         return PTR_ERR(pipe_config);
11897
11898                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
11899
11900                 if (!pipe_config->base.active ||
11901                     needs_modeset(&pipe_config->base))
11902                         continue;
11903
11904                 /* 2 or more enabled crtcs means no need for w/a */
11905                 if (enabled_pipe != INVALID_PIPE)
11906                         return 0;
11907
11908                 enabled_pipe = intel_crtc->pipe;
11909         }
11910
11911         if (enabled_pipe != INVALID_PIPE)
11912                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
11913         else if (other_crtc_state)
11914                 other_crtc_state->hsw_workaround_pipe = first_pipe;
11915
11916         return 0;
11917 }
11918
11919 static int intel_lock_all_pipes(struct drm_atomic_state *state)
11920 {
11921         struct drm_crtc *crtc;
11922
11923         /* Add all pipes to the state */
11924         for_each_crtc(state->dev, crtc) {
11925                 struct drm_crtc_state *crtc_state;
11926
11927                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11928                 if (IS_ERR(crtc_state))
11929                         return PTR_ERR(crtc_state);
11930         }
11931
11932         return 0;
11933 }
11934
11935 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
11936 {
11937         struct drm_crtc *crtc;
11938
11939         /*
11940          * Add all pipes to the state, and force
11941          * a modeset on all the active ones.
11942          */
11943         for_each_crtc(state->dev, crtc) {
11944                 struct drm_crtc_state *crtc_state;
11945                 int ret;
11946
11947                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11948                 if (IS_ERR(crtc_state))
11949                         return PTR_ERR(crtc_state);
11950
11951                 if (!crtc_state->active || needs_modeset(crtc_state))
11952                         continue;
11953
11954                 crtc_state->mode_changed = true;
11955
11956                 ret = drm_atomic_add_affected_connectors(state, crtc);
11957                 if (ret)
11958                         return ret;
11959
11960                 ret = drm_atomic_add_affected_planes(state, crtc);
11961                 if (ret)
11962                         return ret;
11963         }
11964
11965         return 0;
11966 }
11967
11968 static int intel_modeset_checks(struct drm_atomic_state *state)
11969 {
11970         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
11971         struct drm_i915_private *dev_priv = to_i915(state->dev);
11972         struct drm_crtc *crtc;
11973         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11974         int ret = 0, i;
11975
11976         if (!check_digital_port_conflicts(state)) {
11977                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
11978                 return -EINVAL;
11979         }
11980
11981         intel_state->modeset = true;
11982         intel_state->active_crtcs = dev_priv->active_crtcs;
11983         intel_state->cdclk.logical = dev_priv->cdclk.logical;
11984         intel_state->cdclk.actual = dev_priv->cdclk.actual;
11985
11986         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11987                 if (new_crtc_state->active)
11988                         intel_state->active_crtcs |= 1 << i;
11989                 else
11990                         intel_state->active_crtcs &= ~(1 << i);
11991
11992                 if (old_crtc_state->active != new_crtc_state->active)
11993                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
11994         }
11995
11996         /*
11997          * See if the config requires any additional preparation, e.g.
11998          * to adjust global state with pipes off.  We need to do this
11999          * here so we can get the modeset_pipe updated config for the new
12000          * mode set on this crtc.  For other crtcs we need to use the
12001          * adjusted_mode bits in the crtc directly.
12002          */
12003         if (dev_priv->display.modeset_calc_cdclk) {
12004                 ret = dev_priv->display.modeset_calc_cdclk(state);
12005                 if (ret < 0)
12006                         return ret;
12007
12008                 /*
12009                  * Writes to dev_priv->cdclk.logical must protected by
12010                  * holding all the crtc locks, even if we don't end up
12011                  * touching the hardware
12012                  */
12013                 if (!intel_cdclk_state_compare(&dev_priv->cdclk.logical,
12014                                                &intel_state->cdclk.logical)) {
12015                         ret = intel_lock_all_pipes(state);
12016                         if (ret < 0)
12017                                 return ret;
12018                 }
12019
12020                 /* All pipes must be switched off while we change the cdclk. */
12021                 if (!intel_cdclk_state_compare(&dev_priv->cdclk.actual,
12022                                                &intel_state->cdclk.actual)) {
12023                         ret = intel_modeset_all_pipes(state);
12024                         if (ret < 0)
12025                                 return ret;
12026                 }
12027
12028                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12029                               intel_state->cdclk.logical.cdclk,
12030                               intel_state->cdclk.actual.cdclk);
12031         } else {
12032                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12033         }
12034
12035         intel_modeset_clear_plls(state);
12036
12037         if (IS_HASWELL(dev_priv))
12038                 return haswell_mode_set_planes_workaround(state);
12039
12040         return 0;
12041 }
12042
12043 /*
12044  * Handle calculation of various watermark data at the end of the atomic check
12045  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12046  * handlers to ensure that all derived state has been updated.
12047  */
12048 static int calc_watermark_data(struct drm_atomic_state *state)
12049 {
12050         struct drm_device *dev = state->dev;
12051         struct drm_i915_private *dev_priv = to_i915(dev);
12052
12053         /* Is there platform-specific watermark information to calculate? */
12054         if (dev_priv->display.compute_global_watermarks)
12055                 return dev_priv->display.compute_global_watermarks(state);
12056
12057         return 0;
12058 }
12059
12060 /**
12061  * intel_atomic_check - validate state object
12062  * @dev: drm device
12063  * @state: state to validate
12064  */
12065 static int intel_atomic_check(struct drm_device *dev,
12066                               struct drm_atomic_state *state)
12067 {
12068         struct drm_i915_private *dev_priv = to_i915(dev);
12069         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12070         struct drm_crtc *crtc;
12071         struct drm_crtc_state *old_crtc_state, *crtc_state;
12072         int ret, i;
12073         bool any_ms = false;
12074
12075         ret = drm_atomic_helper_check_modeset(dev, state);
12076         if (ret)
12077                 return ret;
12078
12079         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12080                 struct intel_crtc_state *pipe_config =
12081                         to_intel_crtc_state(crtc_state);
12082
12083                 /* Catch I915_MODE_FLAG_INHERITED */
12084                 if (crtc_state->mode.private_flags != old_crtc_state->mode.private_flags)
12085                         crtc_state->mode_changed = true;
12086
12087                 if (!needs_modeset(crtc_state))
12088                         continue;
12089
12090                 if (!crtc_state->enable) {
12091                         any_ms = true;
12092                         continue;
12093                 }
12094
12095                 /* FIXME: For only active_changed we shouldn't need to do any
12096                  * state recomputation at all. */
12097
12098                 ret = drm_atomic_add_affected_connectors(state, crtc);
12099                 if (ret)
12100                         return ret;
12101
12102                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12103                 if (ret) {
12104                         intel_dump_pipe_config(to_intel_crtc(crtc),
12105                                                pipe_config, "[failed]");
12106                         return ret;
12107                 }
12108
12109                 if (i915.fastboot &&
12110                     intel_pipe_config_compare(dev_priv,
12111                                         to_intel_crtc_state(old_crtc_state),
12112                                         pipe_config, true)) {
12113                         crtc_state->mode_changed = false;
12114                         pipe_config->update_pipe = true;
12115                 }
12116
12117                 if (needs_modeset(crtc_state))
12118                         any_ms = true;
12119
12120                 ret = drm_atomic_add_affected_planes(state, crtc);
12121                 if (ret)
12122                         return ret;
12123
12124                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12125                                        needs_modeset(crtc_state) ?
12126                                        "[modeset]" : "[fastset]");
12127         }
12128
12129         if (any_ms) {
12130                 ret = intel_modeset_checks(state);
12131
12132                 if (ret)
12133                         return ret;
12134         } else {
12135                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12136         }
12137
12138         ret = drm_atomic_helper_check_planes(dev, state);
12139         if (ret)
12140                 return ret;
12141
12142         intel_fbc_choose_crtc(dev_priv, state);
12143         return calc_watermark_data(state);
12144 }
12145
12146 static int intel_atomic_prepare_commit(struct drm_device *dev,
12147                                        struct drm_atomic_state *state)
12148 {
12149         return drm_atomic_helper_prepare_planes(dev, state);
12150 }
12151
12152 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12153 {
12154         struct drm_device *dev = crtc->base.dev;
12155
12156         if (!dev->max_vblank_count)
12157                 return drm_crtc_accurate_vblank_count(&crtc->base);
12158
12159         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12160 }
12161
12162 static void intel_atomic_wait_for_vblanks(struct drm_device *dev,
12163                                           struct drm_i915_private *dev_priv,
12164                                           unsigned crtc_mask)
12165 {
12166         unsigned last_vblank_count[I915_MAX_PIPES];
12167         enum pipe pipe;
12168         int ret;
12169
12170         if (!crtc_mask)
12171                 return;
12172
12173         for_each_pipe(dev_priv, pipe) {
12174                 struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv,
12175                                                                   pipe);
12176
12177                 if (!((1 << pipe) & crtc_mask))
12178                         continue;
12179
12180                 ret = drm_crtc_vblank_get(&crtc->base);
12181                 if (WARN_ON(ret != 0)) {
12182                         crtc_mask &= ~(1 << pipe);
12183                         continue;
12184                 }
12185
12186                 last_vblank_count[pipe] = drm_crtc_vblank_count(&crtc->base);
12187         }
12188
12189         for_each_pipe(dev_priv, pipe) {
12190                 struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv,
12191                                                                   pipe);
12192                 long lret;
12193
12194                 if (!((1 << pipe) & crtc_mask))
12195                         continue;
12196
12197                 lret = wait_event_timeout(dev->vblank[pipe].queue,
12198                                 last_vblank_count[pipe] !=
12199                                         drm_crtc_vblank_count(&crtc->base),
12200                                 msecs_to_jiffies(50));
12201
12202                 WARN(!lret, "pipe %c vblank wait timed out\n", pipe_name(pipe));
12203
12204                 drm_crtc_vblank_put(&crtc->base);
12205         }
12206 }
12207
12208 static bool needs_vblank_wait(struct intel_crtc_state *crtc_state)
12209 {
12210         /* fb updated, need to unpin old fb */
12211         if (crtc_state->fb_changed)
12212                 return true;
12213
12214         /* wm changes, need vblank before final wm's */
12215         if (crtc_state->update_wm_post)
12216                 return true;
12217
12218         if (crtc_state->wm.need_postvbl_update)
12219                 return true;
12220
12221         return false;
12222 }
12223
12224 static void intel_update_crtc(struct drm_crtc *crtc,
12225                               struct drm_atomic_state *state,
12226                               struct drm_crtc_state *old_crtc_state,
12227                               struct drm_crtc_state *new_crtc_state,
12228                               unsigned int *crtc_vblank_mask)
12229 {
12230         struct drm_device *dev = crtc->dev;
12231         struct drm_i915_private *dev_priv = to_i915(dev);
12232         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12233         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12234         bool modeset = needs_modeset(new_crtc_state);
12235
12236         if (modeset) {
12237                 update_scanline_offset(intel_crtc);
12238                 dev_priv->display.crtc_enable(pipe_config, state);
12239         } else {
12240                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12241                                        pipe_config);
12242         }
12243
12244         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12245                 intel_fbc_enable(
12246                     intel_crtc, pipe_config,
12247                     to_intel_plane_state(crtc->primary->state));
12248         }
12249
12250         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12251
12252         if (needs_vblank_wait(pipe_config))
12253                 *crtc_vblank_mask |= drm_crtc_mask(crtc);
12254 }
12255
12256 static void intel_update_crtcs(struct drm_atomic_state *state,
12257                                unsigned int *crtc_vblank_mask)
12258 {
12259         struct drm_crtc *crtc;
12260         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12261         int i;
12262
12263         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12264                 if (!new_crtc_state->active)
12265                         continue;
12266
12267                 intel_update_crtc(crtc, state, old_crtc_state,
12268                                   new_crtc_state, crtc_vblank_mask);
12269         }
12270 }
12271
12272 static void skl_update_crtcs(struct drm_atomic_state *state,
12273                              unsigned int *crtc_vblank_mask)
12274 {
12275         struct drm_i915_private *dev_priv = to_i915(state->dev);
12276         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12277         struct drm_crtc *crtc;
12278         struct intel_crtc *intel_crtc;
12279         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12280         struct intel_crtc_state *cstate;
12281         unsigned int updated = 0;
12282         bool progress;
12283         enum pipe pipe;
12284         int i;
12285
12286         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12287
12288         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12289                 /* ignore allocations for crtc's that have been turned off. */
12290                 if (new_crtc_state->active)
12291                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12292
12293         /*
12294          * Whenever the number of active pipes changes, we need to make sure we
12295          * update the pipes in the right order so that their ddb allocations
12296          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12297          * cause pipe underruns and other bad stuff.
12298          */
12299         do {
12300                 progress = false;
12301
12302                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12303                         bool vbl_wait = false;
12304                         unsigned int cmask = drm_crtc_mask(crtc);
12305
12306                         intel_crtc = to_intel_crtc(crtc);
12307                         cstate = to_intel_crtc_state(crtc->state);
12308                         pipe = intel_crtc->pipe;
12309
12310                         if (updated & cmask || !cstate->base.active)
12311                                 continue;
12312
12313                         if (skl_ddb_allocation_overlaps(entries, &cstate->wm.skl.ddb, i))
12314                                 continue;
12315
12316                         updated |= cmask;
12317                         entries[i] = &cstate->wm.skl.ddb;
12318
12319                         /*
12320                          * If this is an already active pipe, it's DDB changed,
12321                          * and this isn't the last pipe that needs updating
12322                          * then we need to wait for a vblank to pass for the
12323                          * new ddb allocation to take effect.
12324                          */
12325                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12326                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12327                             !new_crtc_state->active_changed &&
12328                             intel_state->wm_results.dirty_pipes != updated)
12329                                 vbl_wait = true;
12330
12331                         intel_update_crtc(crtc, state, old_crtc_state,
12332                                           new_crtc_state, crtc_vblank_mask);
12333
12334                         if (vbl_wait)
12335                                 intel_wait_for_vblank(dev_priv, pipe);
12336
12337                         progress = true;
12338                 }
12339         } while (progress);
12340 }
12341
12342 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12343 {
12344         struct intel_atomic_state *state, *next;
12345         struct llist_node *freed;
12346
12347         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12348         llist_for_each_entry_safe(state, next, freed, freed)
12349                 drm_atomic_state_put(&state->base);
12350 }
12351
12352 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12353 {
12354         struct drm_i915_private *dev_priv =
12355                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12356
12357         intel_atomic_helper_free_state(dev_priv);
12358 }
12359
12360 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12361 {
12362         struct wait_queue_entry wait_fence, wait_reset;
12363         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12364
12365         init_wait_entry(&wait_fence, 0);
12366         init_wait_entry(&wait_reset, 0);
12367         for (;;) {
12368                 prepare_to_wait(&intel_state->commit_ready.wait,
12369                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12370                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12371                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12372
12373
12374                 if (i915_sw_fence_done(&intel_state->commit_ready)
12375                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12376                         break;
12377
12378                 schedule();
12379         }
12380         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12381         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12382 }
12383
12384 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12385 {
12386         struct drm_device *dev = state->dev;
12387         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12388         struct drm_i915_private *dev_priv = to_i915(dev);
12389         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12390         struct drm_crtc *crtc;
12391         struct intel_crtc_state *intel_cstate;
12392         u64 put_domains[I915_MAX_PIPES] = {};
12393         unsigned crtc_vblank_mask = 0;
12394         int i;
12395
12396         intel_atomic_commit_fence_wait(intel_state);
12397
12398         drm_atomic_helper_wait_for_dependencies(state);
12399
12400         if (intel_state->modeset)
12401                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12402
12403         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12404                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12405
12406                 if (needs_modeset(new_crtc_state) ||
12407                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12408
12409                         put_domains[to_intel_crtc(crtc)->pipe] =
12410                                 modeset_get_crtc_power_domains(crtc,
12411                                         to_intel_crtc_state(new_crtc_state));
12412                 }
12413
12414                 if (!needs_modeset(new_crtc_state))
12415                         continue;
12416
12417                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12418                                        to_intel_crtc_state(new_crtc_state));
12419
12420                 if (old_crtc_state->active) {
12421                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
12422                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
12423                         intel_crtc->active = false;
12424                         intel_fbc_disable(intel_crtc);
12425                         intel_disable_shared_dpll(intel_crtc);
12426
12427                         /*
12428                          * Underruns don't always raise
12429                          * interrupts, so check manually.
12430                          */
12431                         intel_check_cpu_fifo_underruns(dev_priv);
12432                         intel_check_pch_fifo_underruns(dev_priv);
12433
12434                         if (!crtc->state->active) {
12435                                 /*
12436                                  * Make sure we don't call initial_watermarks
12437                                  * for ILK-style watermark updates.
12438                                  *
12439                                  * No clue what this is supposed to achieve.
12440                                  */
12441                                 if (INTEL_GEN(dev_priv) >= 9)
12442                                         dev_priv->display.initial_watermarks(intel_state,
12443                                                                              to_intel_crtc_state(crtc->state));
12444                         }
12445                 }
12446         }
12447
12448         /* Only after disabling all output pipelines that will be changed can we
12449          * update the the output configuration. */
12450         intel_modeset_update_crtc_state(state);
12451
12452         if (intel_state->modeset) {
12453                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12454
12455                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12456
12457                 /*
12458                  * SKL workaround: bspec recommends we disable the SAGV when we
12459                  * have more then one pipe enabled
12460                  */
12461                 if (!intel_can_enable_sagv(state))
12462                         intel_disable_sagv(dev_priv);
12463
12464                 intel_modeset_verify_disabled(dev, state);
12465         }
12466
12467         /* Complete the events for pipes that have now been disabled */
12468         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12469                 bool modeset = needs_modeset(new_crtc_state);
12470
12471                 /* Complete events for now disable pipes here. */
12472                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12473                         spin_lock_irq(&dev->event_lock);
12474                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12475                         spin_unlock_irq(&dev->event_lock);
12476
12477                         new_crtc_state->event = NULL;
12478                 }
12479         }
12480
12481         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12482         dev_priv->display.update_crtcs(state, &crtc_vblank_mask);
12483
12484         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12485          * already, but still need the state for the delayed optimization. To
12486          * fix this:
12487          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12488          * - schedule that vblank worker _before_ calling hw_done
12489          * - at the start of commit_tail, cancel it _synchrously
12490          * - switch over to the vblank wait helper in the core after that since
12491          *   we don't need out special handling any more.
12492          */
12493         if (!state->legacy_cursor_update)
12494                 intel_atomic_wait_for_vblanks(dev, dev_priv, crtc_vblank_mask);
12495
12496         /*
12497          * Now that the vblank has passed, we can go ahead and program the
12498          * optimal watermarks on platforms that need two-step watermark
12499          * programming.
12500          *
12501          * TODO: Move this (and other cleanup) to an async worker eventually.
12502          */
12503         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12504                 intel_cstate = to_intel_crtc_state(new_crtc_state);
12505
12506                 if (dev_priv->display.optimize_watermarks)
12507                         dev_priv->display.optimize_watermarks(intel_state,
12508                                                               intel_cstate);
12509         }
12510
12511         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12512                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12513
12514                 if (put_domains[i])
12515                         modeset_put_power_domains(dev_priv, put_domains[i]);
12516
12517                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12518         }
12519
12520         if (intel_state->modeset && intel_can_enable_sagv(state))
12521                 intel_enable_sagv(dev_priv);
12522
12523         drm_atomic_helper_commit_hw_done(state);
12524
12525         if (intel_state->modeset) {
12526                 /* As one of the primary mmio accessors, KMS has a high
12527                  * likelihood of triggering bugs in unclaimed access. After we
12528                  * finish modesetting, see if an error has been flagged, and if
12529                  * so enable debugging for the next modeset - and hope we catch
12530                  * the culprit.
12531                  */
12532                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12533                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12534         }
12535
12536         drm_atomic_helper_cleanup_planes(dev, state);
12537
12538         drm_atomic_helper_commit_cleanup_done(state);
12539
12540         drm_atomic_state_put(state);
12541
12542         intel_atomic_helper_free_state(dev_priv);
12543 }
12544
12545 static void intel_atomic_commit_work(struct work_struct *work)
12546 {
12547         struct drm_atomic_state *state =
12548                 container_of(work, struct drm_atomic_state, commit_work);
12549
12550         intel_atomic_commit_tail(state);
12551 }
12552
12553 static int __i915_sw_fence_call
12554 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12555                           enum i915_sw_fence_notify notify)
12556 {
12557         struct intel_atomic_state *state =
12558                 container_of(fence, struct intel_atomic_state, commit_ready);
12559
12560         switch (notify) {
12561         case FENCE_COMPLETE:
12562                 /* we do blocking waits in the worker, nothing to do here */
12563                 break;
12564         case FENCE_FREE:
12565                 {
12566                         struct intel_atomic_helper *helper =
12567                                 &to_i915(state->base.dev)->atomic_helper;
12568
12569                         if (llist_add(&state->freed, &helper->free_list))
12570                                 schedule_work(&helper->free_work);
12571                         break;
12572                 }
12573         }
12574
12575         return NOTIFY_DONE;
12576 }
12577
12578 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12579 {
12580         struct drm_plane_state *old_plane_state, *new_plane_state;
12581         struct drm_plane *plane;
12582         int i;
12583
12584         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12585                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12586                                   intel_fb_obj(new_plane_state->fb),
12587                                   to_intel_plane(plane)->frontbuffer_bit);
12588 }
12589
12590 /**
12591  * intel_atomic_commit - commit validated state object
12592  * @dev: DRM device
12593  * @state: the top-level driver state object
12594  * @nonblock: nonblocking commit
12595  *
12596  * This function commits a top-level state object that has been validated
12597  * with drm_atomic_helper_check().
12598  *
12599  * RETURNS
12600  * Zero for success or -errno.
12601  */
12602 static int intel_atomic_commit(struct drm_device *dev,
12603                                struct drm_atomic_state *state,
12604                                bool nonblock)
12605 {
12606         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12607         struct drm_i915_private *dev_priv = to_i915(dev);
12608         int ret = 0;
12609
12610         ret = drm_atomic_helper_setup_commit(state, nonblock);
12611         if (ret)
12612                 return ret;
12613
12614         drm_atomic_state_get(state);
12615         i915_sw_fence_init(&intel_state->commit_ready,
12616                            intel_atomic_commit_ready);
12617
12618         ret = intel_atomic_prepare_commit(dev, state);
12619         if (ret) {
12620                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12621                 i915_sw_fence_commit(&intel_state->commit_ready);
12622                 return ret;
12623         }
12624
12625         /*
12626          * The intel_legacy_cursor_update() fast path takes care
12627          * of avoiding the vblank waits for simple cursor
12628          * movement and flips. For cursor on/off and size changes,
12629          * we want to perform the vblank waits so that watermark
12630          * updates happen during the correct frames. Gen9+ have
12631          * double buffered watermarks and so shouldn't need this.
12632          *
12633          * Do this after drm_atomic_helper_setup_commit() and
12634          * intel_atomic_prepare_commit() because we still want
12635          * to skip the flip and fb cleanup waits. Although that
12636          * does risk yanking the mapping from under the display
12637          * engine.
12638          *
12639          * FIXME doing watermarks and fb cleanup from a vblank worker
12640          * (assuming we had any) would solve these problems.
12641          */
12642         if (INTEL_GEN(dev_priv) < 9)
12643                 state->legacy_cursor_update = false;
12644
12645         ret = drm_atomic_helper_swap_state(state, true);
12646         if (ret) {
12647                 i915_sw_fence_commit(&intel_state->commit_ready);
12648
12649                 drm_atomic_helper_cleanup_planes(dev, state);
12650                 return ret;
12651         }
12652         dev_priv->wm.distrust_bios_wm = false;
12653         intel_shared_dpll_swap_state(state);
12654         intel_atomic_track_fbs(state);
12655
12656         if (intel_state->modeset) {
12657                 memcpy(dev_priv->min_pixclk, intel_state->min_pixclk,
12658                        sizeof(intel_state->min_pixclk));
12659                 dev_priv->active_crtcs = intel_state->active_crtcs;
12660                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12661                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12662         }
12663
12664         drm_atomic_state_get(state);
12665         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12666
12667         i915_sw_fence_commit(&intel_state->commit_ready);
12668         if (nonblock)
12669                 queue_work(system_unbound_wq, &state->commit_work);
12670         else
12671                 intel_atomic_commit_tail(state);
12672
12673
12674         return 0;
12675 }
12676
12677 static const struct drm_crtc_funcs intel_crtc_funcs = {
12678         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12679         .set_config = drm_atomic_helper_set_config,
12680         .destroy = intel_crtc_destroy,
12681         .page_flip = drm_atomic_helper_page_flip,
12682         .atomic_duplicate_state = intel_crtc_duplicate_state,
12683         .atomic_destroy_state = intel_crtc_destroy_state,
12684         .set_crc_source = intel_crtc_set_crc_source,
12685 };
12686
12687 /**
12688  * intel_prepare_plane_fb - Prepare fb for usage on plane
12689  * @plane: drm plane to prepare for
12690  * @fb: framebuffer to prepare for presentation
12691  *
12692  * Prepares a framebuffer for usage on a display plane.  Generally this
12693  * involves pinning the underlying object and updating the frontbuffer tracking
12694  * bits.  Some older platforms need special physical address handling for
12695  * cursor planes.
12696  *
12697  * Must be called with struct_mutex held.
12698  *
12699  * Returns 0 on success, negative error code on failure.
12700  */
12701 int
12702 intel_prepare_plane_fb(struct drm_plane *plane,
12703                        struct drm_plane_state *new_state)
12704 {
12705         struct intel_atomic_state *intel_state =
12706                 to_intel_atomic_state(new_state->state);
12707         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12708         struct drm_framebuffer *fb = new_state->fb;
12709         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12710         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
12711         int ret;
12712
12713         if (old_obj) {
12714                 struct drm_crtc_state *crtc_state =
12715                         drm_atomic_get_existing_crtc_state(new_state->state,
12716                                                            plane->state->crtc);
12717
12718                 /* Big Hammer, we also need to ensure that any pending
12719                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
12720                  * current scanout is retired before unpinning the old
12721                  * framebuffer. Note that we rely on userspace rendering
12722                  * into the buffer attached to the pipe they are waiting
12723                  * on. If not, userspace generates a GPU hang with IPEHR
12724                  * point to the MI_WAIT_FOR_EVENT.
12725                  *
12726                  * This should only fail upon a hung GPU, in which case we
12727                  * can safely continue.
12728                  */
12729                 if (needs_modeset(crtc_state)) {
12730                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12731                                                               old_obj->resv, NULL,
12732                                                               false, 0,
12733                                                               GFP_KERNEL);
12734                         if (ret < 0)
12735                                 return ret;
12736                 }
12737         }
12738
12739         if (new_state->fence) { /* explicit fencing */
12740                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
12741                                                     new_state->fence,
12742                                                     I915_FENCE_TIMEOUT,
12743                                                     GFP_KERNEL);
12744                 if (ret < 0)
12745                         return ret;
12746         }
12747
12748         if (!obj)
12749                 return 0;
12750
12751         ret = i915_gem_object_pin_pages(obj);
12752         if (ret)
12753                 return ret;
12754
12755         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
12756         if (ret) {
12757                 i915_gem_object_unpin_pages(obj);
12758                 return ret;
12759         }
12760
12761         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12762             INTEL_INFO(dev_priv)->cursor_needs_physical) {
12763                 const int align = intel_cursor_alignment(dev_priv);
12764
12765                 ret = i915_gem_object_attach_phys(obj, align);
12766         } else {
12767                 struct i915_vma *vma;
12768
12769                 vma = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
12770                 if (!IS_ERR(vma))
12771                         to_intel_plane_state(new_state)->vma = vma;
12772                 else
12773                         ret =  PTR_ERR(vma);
12774         }
12775
12776         i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
12777
12778         mutex_unlock(&dev_priv->drm.struct_mutex);
12779         i915_gem_object_unpin_pages(obj);
12780         if (ret)
12781                 return ret;
12782
12783         if (!new_state->fence) { /* implicit fencing */
12784                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12785                                                       obj->resv, NULL,
12786                                                       false, I915_FENCE_TIMEOUT,
12787                                                       GFP_KERNEL);
12788                 if (ret < 0)
12789                         return ret;
12790         }
12791
12792         return 0;
12793 }
12794
12795 /**
12796  * intel_cleanup_plane_fb - Cleans up an fb after plane use
12797  * @plane: drm plane to clean up for
12798  * @fb: old framebuffer that was on plane
12799  *
12800  * Cleans up a framebuffer that has just been removed from a plane.
12801  *
12802  * Must be called with struct_mutex held.
12803  */
12804 void
12805 intel_cleanup_plane_fb(struct drm_plane *plane,
12806                        struct drm_plane_state *old_state)
12807 {
12808         struct i915_vma *vma;
12809
12810         /* Should only be called after a successful intel_prepare_plane_fb()! */
12811         vma = fetch_and_zero(&to_intel_plane_state(old_state)->vma);
12812         if (vma) {
12813                 mutex_lock(&plane->dev->struct_mutex);
12814                 intel_unpin_fb_vma(vma);
12815                 mutex_unlock(&plane->dev->struct_mutex);
12816         }
12817 }
12818
12819 int
12820 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
12821 {
12822         struct drm_i915_private *dev_priv;
12823         int max_scale;
12824         int crtc_clock, max_dotclk;
12825
12826         if (!intel_crtc || !crtc_state->base.enable)
12827                 return DRM_PLANE_HELPER_NO_SCALING;
12828
12829         dev_priv = to_i915(intel_crtc->base.dev);
12830
12831         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
12832         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
12833
12834         if (IS_GEMINILAKE(dev_priv))
12835                 max_dotclk *= 2;
12836
12837         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
12838                 return DRM_PLANE_HELPER_NO_SCALING;
12839
12840         /*
12841          * skl max scale is lower of:
12842          *    close to 3 but not 3, -1 is for that purpose
12843          *            or
12844          *    cdclk/crtc_clock
12845          */
12846         max_scale = min((1 << 16) * 3 - 1,
12847                         (1 << 8) * ((max_dotclk << 8) / crtc_clock));
12848
12849         return max_scale;
12850 }
12851
12852 static int
12853 intel_check_primary_plane(struct intel_plane *plane,
12854                           struct intel_crtc_state *crtc_state,
12855                           struct intel_plane_state *state)
12856 {
12857         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12858         struct drm_crtc *crtc = state->base.crtc;
12859         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
12860         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
12861         bool can_position = false;
12862         int ret;
12863
12864         if (INTEL_GEN(dev_priv) >= 9) {
12865                 /* use scaler when colorkey is not required */
12866                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
12867                         min_scale = 1;
12868                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
12869                 }
12870                 can_position = true;
12871         }
12872
12873         ret = drm_plane_helper_check_state(&state->base,
12874                                            &state->clip,
12875                                            min_scale, max_scale,
12876                                            can_position, true);
12877         if (ret)
12878                 return ret;
12879
12880         if (!state->base.fb)
12881                 return 0;
12882
12883         if (INTEL_GEN(dev_priv) >= 9) {
12884                 ret = skl_check_plane_surface(state);
12885                 if (ret)
12886                         return ret;
12887
12888                 state->ctl = skl_plane_ctl(crtc_state, state);
12889         } else {
12890                 ret = i9xx_check_plane_surface(state);
12891                 if (ret)
12892                         return ret;
12893
12894                 state->ctl = i9xx_plane_ctl(crtc_state, state);
12895         }
12896
12897         return 0;
12898 }
12899
12900 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
12901                                     struct drm_crtc_state *old_crtc_state)
12902 {
12903         struct drm_device *dev = crtc->dev;
12904         struct drm_i915_private *dev_priv = to_i915(dev);
12905         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12906         struct intel_crtc_state *intel_cstate =
12907                 to_intel_crtc_state(crtc->state);
12908         struct intel_crtc_state *old_intel_cstate =
12909                 to_intel_crtc_state(old_crtc_state);
12910         struct intel_atomic_state *old_intel_state =
12911                 to_intel_atomic_state(old_crtc_state->state);
12912         bool modeset = needs_modeset(crtc->state);
12913
12914         if (!modeset &&
12915             (intel_cstate->base.color_mgmt_changed ||
12916              intel_cstate->update_pipe)) {
12917                 intel_color_set_csc(crtc->state);
12918                 intel_color_load_luts(crtc->state);
12919         }
12920
12921         /* Perform vblank evasion around commit operation */
12922         intel_pipe_update_start(intel_crtc);
12923
12924         if (modeset)
12925                 goto out;
12926
12927         if (intel_cstate->update_pipe)
12928                 intel_update_pipe_config(intel_crtc, old_intel_cstate);
12929         else if (INTEL_GEN(dev_priv) >= 9)
12930                 skl_detach_scalers(intel_crtc);
12931
12932 out:
12933         if (dev_priv->display.atomic_update_watermarks)
12934                 dev_priv->display.atomic_update_watermarks(old_intel_state,
12935                                                            intel_cstate);
12936 }
12937
12938 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
12939                                      struct drm_crtc_state *old_crtc_state)
12940 {
12941         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12942
12943         intel_pipe_update_end(intel_crtc);
12944 }
12945
12946 /**
12947  * intel_plane_destroy - destroy a plane
12948  * @plane: plane to destroy
12949  *
12950  * Common destruction function for all types of planes (primary, cursor,
12951  * sprite).
12952  */
12953 void intel_plane_destroy(struct drm_plane *plane)
12954 {
12955         drm_plane_cleanup(plane);
12956         kfree(to_intel_plane(plane));
12957 }
12958
12959 static bool i8xx_mod_supported(uint32_t format, uint64_t modifier)
12960 {
12961         switch (format) {
12962         case DRM_FORMAT_C8:
12963         case DRM_FORMAT_RGB565:
12964         case DRM_FORMAT_XRGB1555:
12965         case DRM_FORMAT_XRGB8888:
12966                 return modifier == DRM_FORMAT_MOD_LINEAR ||
12967                         modifier == I915_FORMAT_MOD_X_TILED;
12968         default:
12969                 return false;
12970         }
12971 }
12972
12973 static bool i965_mod_supported(uint32_t format, uint64_t modifier)
12974 {
12975         switch (format) {
12976         case DRM_FORMAT_C8:
12977         case DRM_FORMAT_RGB565:
12978         case DRM_FORMAT_XRGB8888:
12979         case DRM_FORMAT_XBGR8888:
12980         case DRM_FORMAT_XRGB2101010:
12981         case DRM_FORMAT_XBGR2101010:
12982                 return modifier == DRM_FORMAT_MOD_LINEAR ||
12983                         modifier == I915_FORMAT_MOD_X_TILED;
12984         default:
12985                 return false;
12986         }
12987 }
12988
12989 static bool skl_mod_supported(uint32_t format, uint64_t modifier)
12990 {
12991         switch (format) {
12992         case DRM_FORMAT_XRGB8888:
12993         case DRM_FORMAT_XBGR8888:
12994         case DRM_FORMAT_ARGB8888:
12995         case DRM_FORMAT_ABGR8888:
12996                 if (modifier == I915_FORMAT_MOD_Yf_TILED_CCS ||
12997                     modifier == I915_FORMAT_MOD_Y_TILED_CCS)
12998                         return true;
12999                 /* fall through */
13000         case DRM_FORMAT_RGB565:
13001         case DRM_FORMAT_XRGB2101010:
13002         case DRM_FORMAT_XBGR2101010:
13003         case DRM_FORMAT_YUYV:
13004         case DRM_FORMAT_YVYU:
13005         case DRM_FORMAT_UYVY:
13006         case DRM_FORMAT_VYUY:
13007                 if (modifier == I915_FORMAT_MOD_Yf_TILED)
13008                         return true;
13009                 /* fall through */
13010         case DRM_FORMAT_C8:
13011                 if (modifier == DRM_FORMAT_MOD_LINEAR ||
13012                     modifier == I915_FORMAT_MOD_X_TILED ||
13013                     modifier == I915_FORMAT_MOD_Y_TILED)
13014                         return true;
13015                 /* fall through */
13016         default:
13017                 return false;
13018         }
13019 }
13020
13021 static bool intel_primary_plane_format_mod_supported(struct drm_plane *plane,
13022                                                      uint32_t format,
13023                                                      uint64_t modifier)
13024 {
13025         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13026
13027         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13028                 return false;
13029
13030         if ((modifier >> 56) != DRM_FORMAT_MOD_VENDOR_INTEL &&
13031             modifier != DRM_FORMAT_MOD_LINEAR)
13032                 return false;
13033
13034         if (INTEL_GEN(dev_priv) >= 9)
13035                 return skl_mod_supported(format, modifier);
13036         else if (INTEL_GEN(dev_priv) >= 4)
13037                 return i965_mod_supported(format, modifier);
13038         else
13039                 return i8xx_mod_supported(format, modifier);
13040
13041         unreachable();
13042 }
13043
13044 static bool intel_cursor_plane_format_mod_supported(struct drm_plane *plane,
13045                                                     uint32_t format,
13046                                                     uint64_t modifier)
13047 {
13048         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13049                 return false;
13050
13051         return modifier == DRM_FORMAT_MOD_LINEAR && format == DRM_FORMAT_ARGB8888;
13052 }
13053
13054 static struct drm_plane_funcs intel_plane_funcs = {
13055         .update_plane = drm_atomic_helper_update_plane,
13056         .disable_plane = drm_atomic_helper_disable_plane,
13057         .destroy = intel_plane_destroy,
13058         .atomic_get_property = intel_plane_atomic_get_property,
13059         .atomic_set_property = intel_plane_atomic_set_property,
13060         .atomic_duplicate_state = intel_plane_duplicate_state,
13061         .atomic_destroy_state = intel_plane_destroy_state,
13062         .format_mod_supported = intel_primary_plane_format_mod_supported,
13063 };
13064
13065 static int
13066 intel_legacy_cursor_update(struct drm_plane *plane,
13067                            struct drm_crtc *crtc,
13068                            struct drm_framebuffer *fb,
13069                            int crtc_x, int crtc_y,
13070                            unsigned int crtc_w, unsigned int crtc_h,
13071                            uint32_t src_x, uint32_t src_y,
13072                            uint32_t src_w, uint32_t src_h,
13073                            struct drm_modeset_acquire_ctx *ctx)
13074 {
13075         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13076         int ret;
13077         struct drm_plane_state *old_plane_state, *new_plane_state;
13078         struct intel_plane *intel_plane = to_intel_plane(plane);
13079         struct drm_framebuffer *old_fb;
13080         struct drm_crtc_state *crtc_state = crtc->state;
13081         struct i915_vma *old_vma, *vma;
13082
13083         /*
13084          * When crtc is inactive or there is a modeset pending,
13085          * wait for it to complete in the slowpath
13086          */
13087         if (!crtc_state->active || needs_modeset(crtc_state) ||
13088             to_intel_crtc_state(crtc_state)->update_pipe)
13089                 goto slow;
13090
13091         old_plane_state = plane->state;
13092
13093         /*
13094          * If any parameters change that may affect watermarks,
13095          * take the slowpath. Only changing fb or position should be
13096          * in the fastpath.
13097          */
13098         if (old_plane_state->crtc != crtc ||
13099             old_plane_state->src_w != src_w ||
13100             old_plane_state->src_h != src_h ||
13101             old_plane_state->crtc_w != crtc_w ||
13102             old_plane_state->crtc_h != crtc_h ||
13103             !old_plane_state->fb != !fb)
13104                 goto slow;
13105
13106         new_plane_state = intel_plane_duplicate_state(plane);
13107         if (!new_plane_state)
13108                 return -ENOMEM;
13109
13110         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13111
13112         new_plane_state->src_x = src_x;
13113         new_plane_state->src_y = src_y;
13114         new_plane_state->src_w = src_w;
13115         new_plane_state->src_h = src_h;
13116         new_plane_state->crtc_x = crtc_x;
13117         new_plane_state->crtc_y = crtc_y;
13118         new_plane_state->crtc_w = crtc_w;
13119         new_plane_state->crtc_h = crtc_h;
13120
13121         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13122                                                   to_intel_plane_state(new_plane_state));
13123         if (ret)
13124                 goto out_free;
13125
13126         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13127         if (ret)
13128                 goto out_free;
13129
13130         if (INTEL_INFO(dev_priv)->cursor_needs_physical) {
13131                 int align = intel_cursor_alignment(dev_priv);
13132
13133                 ret = i915_gem_object_attach_phys(intel_fb_obj(fb), align);
13134                 if (ret) {
13135                         DRM_DEBUG_KMS("failed to attach phys object\n");
13136                         goto out_unlock;
13137                 }
13138         } else {
13139                 vma = intel_pin_and_fence_fb_obj(fb, new_plane_state->rotation);
13140                 if (IS_ERR(vma)) {
13141                         DRM_DEBUG_KMS("failed to pin object\n");
13142
13143                         ret = PTR_ERR(vma);
13144                         goto out_unlock;
13145                 }
13146
13147                 to_intel_plane_state(new_plane_state)->vma = vma;
13148         }
13149
13150         old_fb = old_plane_state->fb;
13151         old_vma = to_intel_plane_state(old_plane_state)->vma;
13152
13153         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13154                           intel_plane->frontbuffer_bit);
13155
13156         /* Swap plane state */
13157         new_plane_state->fence = old_plane_state->fence;
13158         *to_intel_plane_state(old_plane_state) = *to_intel_plane_state(new_plane_state);
13159         new_plane_state->fence = NULL;
13160         new_plane_state->fb = old_fb;
13161         to_intel_plane_state(new_plane_state)->vma = NULL;
13162
13163         if (plane->state->visible) {
13164                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13165                 intel_plane->update_plane(intel_plane,
13166                                           to_intel_crtc_state(crtc->state),
13167                                           to_intel_plane_state(plane->state));
13168         } else {
13169                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13170                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13171         }
13172
13173         if (old_vma)
13174                 intel_unpin_fb_vma(old_vma);
13175
13176 out_unlock:
13177         mutex_unlock(&dev_priv->drm.struct_mutex);
13178 out_free:
13179         intel_plane_destroy_state(plane, new_plane_state);
13180         return ret;
13181
13182 slow:
13183         return drm_atomic_helper_update_plane(plane, crtc, fb,
13184                                               crtc_x, crtc_y, crtc_w, crtc_h,
13185                                               src_x, src_y, src_w, src_h, ctx);
13186 }
13187
13188 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13189         .update_plane = intel_legacy_cursor_update,
13190         .disable_plane = drm_atomic_helper_disable_plane,
13191         .destroy = intel_plane_destroy,
13192         .atomic_get_property = intel_plane_atomic_get_property,
13193         .atomic_set_property = intel_plane_atomic_set_property,
13194         .atomic_duplicate_state = intel_plane_duplicate_state,
13195         .atomic_destroy_state = intel_plane_destroy_state,
13196         .format_mod_supported = intel_cursor_plane_format_mod_supported,
13197 };
13198
13199 static struct intel_plane *
13200 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13201 {
13202         struct intel_plane *primary = NULL;
13203         struct intel_plane_state *state = NULL;
13204         const uint32_t *intel_primary_formats;
13205         unsigned int supported_rotations;
13206         unsigned int num_formats;
13207         const uint64_t *modifiers;
13208         int ret;
13209
13210         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13211         if (!primary) {
13212                 ret = -ENOMEM;
13213                 goto fail;
13214         }
13215
13216         state = intel_create_plane_state(&primary->base);
13217         if (!state) {
13218                 ret = -ENOMEM;
13219                 goto fail;
13220         }
13221
13222         primary->base.state = &state->base;
13223
13224         primary->can_scale = false;
13225         primary->max_downscale = 1;
13226         if (INTEL_GEN(dev_priv) >= 9) {
13227                 primary->can_scale = true;
13228                 state->scaler_id = -1;
13229         }
13230         primary->pipe = pipe;
13231         /*
13232          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13233          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13234          */
13235         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13236                 primary->plane = (enum plane) !pipe;
13237         else
13238                 primary->plane = (enum plane) pipe;
13239         primary->id = PLANE_PRIMARY;
13240         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13241         primary->check_plane = intel_check_primary_plane;
13242
13243         if (INTEL_GEN(dev_priv) >= 10) {
13244                 intel_primary_formats = skl_primary_formats;
13245                 num_formats = ARRAY_SIZE(skl_primary_formats);
13246                 modifiers = skl_format_modifiers_ccs;
13247
13248                 primary->update_plane = skylake_update_primary_plane;
13249                 primary->disable_plane = skylake_disable_primary_plane;
13250                 primary->get_hw_state = skl_plane_get_hw_state;
13251         } else if (INTEL_GEN(dev_priv) >= 9) {
13252                 intel_primary_formats = skl_primary_formats;
13253                 num_formats = ARRAY_SIZE(skl_primary_formats);
13254                 if (pipe < PIPE_C)
13255                         modifiers = skl_format_modifiers_ccs;
13256                 else
13257                         modifiers = skl_format_modifiers_noccs;
13258
13259                 primary->update_plane = skylake_update_primary_plane;
13260                 primary->disable_plane = skylake_disable_primary_plane;
13261                 primary->get_hw_state = skl_plane_get_hw_state;
13262         } else if (INTEL_GEN(dev_priv) >= 4) {
13263                 intel_primary_formats = i965_primary_formats;
13264                 num_formats = ARRAY_SIZE(i965_primary_formats);
13265                 modifiers = i9xx_format_modifiers;
13266
13267                 primary->update_plane = i9xx_update_primary_plane;
13268                 primary->disable_plane = i9xx_disable_primary_plane;
13269                 primary->get_hw_state = i9xx_plane_get_hw_state;
13270         } else {
13271                 intel_primary_formats = i8xx_primary_formats;
13272                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13273                 modifiers = i9xx_format_modifiers;
13274
13275                 primary->update_plane = i9xx_update_primary_plane;
13276                 primary->disable_plane = i9xx_disable_primary_plane;
13277                 primary->get_hw_state = i9xx_plane_get_hw_state;
13278         }
13279
13280         if (INTEL_GEN(dev_priv) >= 9)
13281                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13282                                                0, &intel_plane_funcs,
13283                                                intel_primary_formats, num_formats,
13284                                                modifiers,
13285                                                DRM_PLANE_TYPE_PRIMARY,
13286                                                "plane 1%c", pipe_name(pipe));
13287         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13288                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13289                                                0, &intel_plane_funcs,
13290                                                intel_primary_formats, num_formats,
13291                                                modifiers,
13292                                                DRM_PLANE_TYPE_PRIMARY,
13293                                                "primary %c", pipe_name(pipe));
13294         else
13295                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13296                                                0, &intel_plane_funcs,
13297                                                intel_primary_formats, num_formats,
13298                                                modifiers,
13299                                                DRM_PLANE_TYPE_PRIMARY,
13300                                                "plane %c", plane_name(primary->plane));
13301         if (ret)
13302                 goto fail;
13303
13304         if (INTEL_GEN(dev_priv) >= 9) {
13305                 supported_rotations =
13306                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13307                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13308         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13309                 supported_rotations =
13310                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13311                         DRM_MODE_REFLECT_X;
13312         } else if (INTEL_GEN(dev_priv) >= 4) {
13313                 supported_rotations =
13314                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13315         } else {
13316                 supported_rotations = DRM_MODE_ROTATE_0;
13317         }
13318
13319         if (INTEL_GEN(dev_priv) >= 4)
13320                 drm_plane_create_rotation_property(&primary->base,
13321                                                    DRM_MODE_ROTATE_0,
13322                                                    supported_rotations);
13323
13324         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13325
13326         return primary;
13327
13328 fail:
13329         kfree(state);
13330         kfree(primary);
13331
13332         return ERR_PTR(ret);
13333 }
13334
13335 static struct intel_plane *
13336 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13337                           enum pipe pipe)
13338 {
13339         struct intel_plane *cursor = NULL;
13340         struct intel_plane_state *state = NULL;
13341         int ret;
13342
13343         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13344         if (!cursor) {
13345                 ret = -ENOMEM;
13346                 goto fail;
13347         }
13348
13349         state = intel_create_plane_state(&cursor->base);
13350         if (!state) {
13351                 ret = -ENOMEM;
13352                 goto fail;
13353         }
13354
13355         cursor->base.state = &state->base;
13356
13357         cursor->can_scale = false;
13358         cursor->max_downscale = 1;
13359         cursor->pipe = pipe;
13360         cursor->plane = pipe;
13361         cursor->id = PLANE_CURSOR;
13362         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
13363
13364         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13365                 cursor->update_plane = i845_update_cursor;
13366                 cursor->disable_plane = i845_disable_cursor;
13367                 cursor->get_hw_state = i845_cursor_get_hw_state;
13368                 cursor->check_plane = i845_check_cursor;
13369         } else {
13370                 cursor->update_plane = i9xx_update_cursor;
13371                 cursor->disable_plane = i9xx_disable_cursor;
13372                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13373                 cursor->check_plane = i9xx_check_cursor;
13374         }
13375
13376         cursor->cursor.base = ~0;
13377         cursor->cursor.cntl = ~0;
13378
13379         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13380                 cursor->cursor.size = ~0;
13381
13382         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13383                                        0, &intel_cursor_plane_funcs,
13384                                        intel_cursor_formats,
13385                                        ARRAY_SIZE(intel_cursor_formats),
13386                                        cursor_format_modifiers,
13387                                        DRM_PLANE_TYPE_CURSOR,
13388                                        "cursor %c", pipe_name(pipe));
13389         if (ret)
13390                 goto fail;
13391
13392         if (INTEL_GEN(dev_priv) >= 4)
13393                 drm_plane_create_rotation_property(&cursor->base,
13394                                                    DRM_MODE_ROTATE_0,
13395                                                    DRM_MODE_ROTATE_0 |
13396                                                    DRM_MODE_ROTATE_180);
13397
13398         if (INTEL_GEN(dev_priv) >= 9)
13399                 state->scaler_id = -1;
13400
13401         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13402
13403         return cursor;
13404
13405 fail:
13406         kfree(state);
13407         kfree(cursor);
13408
13409         return ERR_PTR(ret);
13410 }
13411
13412 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13413                                     struct intel_crtc_state *crtc_state)
13414 {
13415         struct intel_crtc_scaler_state *scaler_state =
13416                 &crtc_state->scaler_state;
13417         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13418         int i;
13419
13420         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13421         if (!crtc->num_scalers)
13422                 return;
13423
13424         for (i = 0; i < crtc->num_scalers; i++) {
13425                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13426
13427                 scaler->in_use = 0;
13428                 scaler->mode = PS_SCALER_MODE_DYN;
13429         }
13430
13431         scaler_state->scaler_id = -1;
13432 }
13433
13434 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13435 {
13436         struct intel_crtc *intel_crtc;
13437         struct intel_crtc_state *crtc_state = NULL;
13438         struct intel_plane *primary = NULL;
13439         struct intel_plane *cursor = NULL;
13440         int sprite, ret;
13441
13442         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13443         if (!intel_crtc)
13444                 return -ENOMEM;
13445
13446         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13447         if (!crtc_state) {
13448                 ret = -ENOMEM;
13449                 goto fail;
13450         }
13451         intel_crtc->config = crtc_state;
13452         intel_crtc->base.state = &crtc_state->base;
13453         crtc_state->base.crtc = &intel_crtc->base;
13454
13455         primary = intel_primary_plane_create(dev_priv, pipe);
13456         if (IS_ERR(primary)) {
13457                 ret = PTR_ERR(primary);
13458                 goto fail;
13459         }
13460         intel_crtc->plane_ids_mask |= BIT(primary->id);
13461
13462         for_each_sprite(dev_priv, pipe, sprite) {
13463                 struct intel_plane *plane;
13464
13465                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13466                 if (IS_ERR(plane)) {
13467                         ret = PTR_ERR(plane);
13468                         goto fail;
13469                 }
13470                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13471         }
13472
13473         cursor = intel_cursor_plane_create(dev_priv, pipe);
13474         if (IS_ERR(cursor)) {
13475                 ret = PTR_ERR(cursor);
13476                 goto fail;
13477         }
13478         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13479
13480         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13481                                         &primary->base, &cursor->base,
13482                                         &intel_crtc_funcs,
13483                                         "pipe %c", pipe_name(pipe));
13484         if (ret)
13485                 goto fail;
13486
13487         intel_crtc->pipe = pipe;
13488         intel_crtc->plane = primary->plane;
13489
13490         /* initialize shared scalers */
13491         intel_crtc_init_scalers(intel_crtc, crtc_state);
13492
13493         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13494                dev_priv->plane_to_crtc_mapping[intel_crtc->plane] != NULL);
13495         dev_priv->plane_to_crtc_mapping[intel_crtc->plane] = intel_crtc;
13496         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = intel_crtc;
13497
13498         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13499
13500         intel_color_init(&intel_crtc->base);
13501
13502         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13503
13504         return 0;
13505
13506 fail:
13507         /*
13508          * drm_mode_config_cleanup() will free up any
13509          * crtcs/planes already initialized.
13510          */
13511         kfree(crtc_state);
13512         kfree(intel_crtc);
13513
13514         return ret;
13515 }
13516
13517 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13518 {
13519         struct drm_device *dev = connector->base.dev;
13520
13521         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13522
13523         if (!connector->base.state->crtc)
13524                 return INVALID_PIPE;
13525
13526         return to_intel_crtc(connector->base.state->crtc)->pipe;
13527 }
13528
13529 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
13530                                 struct drm_file *file)
13531 {
13532         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13533         struct drm_crtc *drmmode_crtc;
13534         struct intel_crtc *crtc;
13535
13536         drmmode_crtc = drm_crtc_find(dev, pipe_from_crtc_id->crtc_id);
13537         if (!drmmode_crtc)
13538                 return -ENOENT;
13539
13540         crtc = to_intel_crtc(drmmode_crtc);
13541         pipe_from_crtc_id->pipe = crtc->pipe;
13542
13543         return 0;
13544 }
13545
13546 static int intel_encoder_clones(struct intel_encoder *encoder)
13547 {
13548         struct drm_device *dev = encoder->base.dev;
13549         struct intel_encoder *source_encoder;
13550         int index_mask = 0;
13551         int entry = 0;
13552
13553         for_each_intel_encoder(dev, source_encoder) {
13554                 if (encoders_cloneable(encoder, source_encoder))
13555                         index_mask |= (1 << entry);
13556
13557                 entry++;
13558         }
13559
13560         return index_mask;
13561 }
13562
13563 static bool has_edp_a(struct drm_i915_private *dev_priv)
13564 {
13565         if (!IS_MOBILE(dev_priv))
13566                 return false;
13567
13568         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13569                 return false;
13570
13571         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13572                 return false;
13573
13574         return true;
13575 }
13576
13577 static bool intel_crt_present(struct drm_i915_private *dev_priv)
13578 {
13579         if (INTEL_GEN(dev_priv) >= 9)
13580                 return false;
13581
13582         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
13583                 return false;
13584
13585         if (IS_CHERRYVIEW(dev_priv))
13586                 return false;
13587
13588         if (HAS_PCH_LPT_H(dev_priv) &&
13589             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
13590                 return false;
13591
13592         /* DDI E can't be used if DDI A requires 4 lanes */
13593         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
13594                 return false;
13595
13596         if (!dev_priv->vbt.int_crt_support)
13597                 return false;
13598
13599         return true;
13600 }
13601
13602 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
13603 {
13604         int pps_num;
13605         int pps_idx;
13606
13607         if (HAS_DDI(dev_priv))
13608                 return;
13609         /*
13610          * This w/a is needed at least on CPT/PPT, but to be sure apply it
13611          * everywhere where registers can be write protected.
13612          */
13613         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13614                 pps_num = 2;
13615         else
13616                 pps_num = 1;
13617
13618         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
13619                 u32 val = I915_READ(PP_CONTROL(pps_idx));
13620
13621                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
13622                 I915_WRITE(PP_CONTROL(pps_idx), val);
13623         }
13624 }
13625
13626 static void intel_pps_init(struct drm_i915_private *dev_priv)
13627 {
13628         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
13629                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
13630         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13631                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
13632         else
13633                 dev_priv->pps_mmio_base = PPS_BASE;
13634
13635         intel_pps_unlock_regs_wa(dev_priv);
13636 }
13637
13638 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
13639 {
13640         struct intel_encoder *encoder;
13641         bool dpd_is_edp = false;
13642
13643         intel_pps_init(dev_priv);
13644
13645         /*
13646          * intel_edp_init_connector() depends on this completing first, to
13647          * prevent the registeration of both eDP and LVDS and the incorrect
13648          * sharing of the PPS.
13649          */
13650         intel_lvds_init(dev_priv);
13651
13652         if (intel_crt_present(dev_priv))
13653                 intel_crt_init(dev_priv);
13654
13655         if (IS_GEN9_LP(dev_priv)) {
13656                 /*
13657                  * FIXME: Broxton doesn't support port detection via the
13658                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13659                  * detect the ports.
13660                  */
13661                 intel_ddi_init(dev_priv, PORT_A);
13662                 intel_ddi_init(dev_priv, PORT_B);
13663                 intel_ddi_init(dev_priv, PORT_C);
13664
13665                 intel_dsi_init(dev_priv);
13666         } else if (HAS_DDI(dev_priv)) {
13667                 int found;
13668
13669                 /*
13670                  * Haswell uses DDI functions to detect digital outputs.
13671                  * On SKL pre-D0 the strap isn't connected, so we assume
13672                  * it's there.
13673                  */
13674                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
13675                 /* WaIgnoreDDIAStrap: skl */
13676                 if (found || IS_GEN9_BC(dev_priv))
13677                         intel_ddi_init(dev_priv, PORT_A);
13678
13679                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
13680                  * register */
13681                 found = I915_READ(SFUSE_STRAP);
13682
13683                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13684                         intel_ddi_init(dev_priv, PORT_B);
13685                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13686                         intel_ddi_init(dev_priv, PORT_C);
13687                 if (found & SFUSE_STRAP_DDID_DETECTED)
13688                         intel_ddi_init(dev_priv, PORT_D);
13689                 /*
13690                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
13691                  */
13692                 if (IS_GEN9_BC(dev_priv) &&
13693                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
13694                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
13695                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
13696                         intel_ddi_init(dev_priv, PORT_E);
13697
13698         } else if (HAS_PCH_SPLIT(dev_priv)) {
13699                 int found;
13700                 dpd_is_edp = intel_dp_is_edp(dev_priv, PORT_D);
13701
13702                 if (has_edp_a(dev_priv))
13703                         intel_dp_init(dev_priv, DP_A, PORT_A);
13704
13705                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13706                         /* PCH SDVOB multiplex with HDMIB */
13707                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
13708                         if (!found)
13709                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
13710                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13711                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
13712                 }
13713
13714                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13715                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
13716
13717                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13718                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
13719
13720                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13721                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
13722
13723                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13724                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
13725         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
13726                 bool has_edp, has_port;
13727
13728                 /*
13729                  * The DP_DETECTED bit is the latched state of the DDC
13730                  * SDA pin at boot. However since eDP doesn't require DDC
13731                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13732                  * eDP ports may have been muxed to an alternate function.
13733                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13734                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13735                  * detect eDP ports.
13736                  *
13737                  * Sadly the straps seem to be missing sometimes even for HDMI
13738                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
13739                  * and VBT for the presence of the port. Additionally we can't
13740                  * trust the port type the VBT declares as we've seen at least
13741                  * HDMI ports that the VBT claim are DP or eDP.
13742                  */
13743                 has_edp = intel_dp_is_edp(dev_priv, PORT_B);
13744                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
13745                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
13746                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
13747                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
13748                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
13749
13750                 has_edp = intel_dp_is_edp(dev_priv, PORT_C);
13751                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
13752                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
13753                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
13754                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
13755                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
13756
13757                 if (IS_CHERRYVIEW(dev_priv)) {
13758                         /*
13759                          * eDP not supported on port D,
13760                          * so no need to worry about it
13761                          */
13762                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
13763                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
13764                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
13765                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
13766                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
13767                 }
13768
13769                 intel_dsi_init(dev_priv);
13770         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
13771                 bool found = false;
13772
13773                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13774                         DRM_DEBUG_KMS("probing SDVOB\n");
13775                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
13776                         if (!found && IS_G4X(dev_priv)) {
13777                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
13778                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
13779                         }
13780
13781                         if (!found && IS_G4X(dev_priv))
13782                                 intel_dp_init(dev_priv, DP_B, PORT_B);
13783                 }
13784
13785                 /* Before G4X SDVOC doesn't have its own detect register */
13786
13787                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13788                         DRM_DEBUG_KMS("probing SDVOC\n");
13789                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
13790                 }
13791
13792                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
13793
13794                         if (IS_G4X(dev_priv)) {
13795                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
13796                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
13797                         }
13798                         if (IS_G4X(dev_priv))
13799                                 intel_dp_init(dev_priv, DP_C, PORT_C);
13800                 }
13801
13802                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
13803                         intel_dp_init(dev_priv, DP_D, PORT_D);
13804         } else if (IS_GEN2(dev_priv))
13805                 intel_dvo_init(dev_priv);
13806
13807         if (SUPPORTS_TV(dev_priv))
13808                 intel_tv_init(dev_priv);
13809
13810         intel_psr_init(dev_priv);
13811
13812         for_each_intel_encoder(&dev_priv->drm, encoder) {
13813                 encoder->base.possible_crtcs = encoder->crtc_mask;
13814                 encoder->base.possible_clones =
13815                         intel_encoder_clones(encoder);
13816         }
13817
13818         intel_init_pch_refclk(dev_priv);
13819
13820         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
13821 }
13822
13823 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
13824 {
13825         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13826
13827         drm_framebuffer_cleanup(fb);
13828
13829         i915_gem_object_lock(intel_fb->obj);
13830         WARN_ON(!intel_fb->obj->framebuffer_references--);
13831         i915_gem_object_unlock(intel_fb->obj);
13832
13833         i915_gem_object_put(intel_fb->obj);
13834
13835         kfree(intel_fb);
13836 }
13837
13838 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
13839                                                 struct drm_file *file,
13840                                                 unsigned int *handle)
13841 {
13842         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13843         struct drm_i915_gem_object *obj = intel_fb->obj;
13844
13845         if (obj->userptr.mm) {
13846                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
13847                 return -EINVAL;
13848         }
13849
13850         return drm_gem_handle_create(file, &obj->base, handle);
13851 }
13852
13853 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
13854                                         struct drm_file *file,
13855                                         unsigned flags, unsigned color,
13856                                         struct drm_clip_rect *clips,
13857                                         unsigned num_clips)
13858 {
13859         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13860
13861         i915_gem_object_flush_if_display(obj);
13862         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13863
13864         return 0;
13865 }
13866
13867 static const struct drm_framebuffer_funcs intel_fb_funcs = {
13868         .destroy = intel_user_framebuffer_destroy,
13869         .create_handle = intel_user_framebuffer_create_handle,
13870         .dirty = intel_user_framebuffer_dirty,
13871 };
13872
13873 static
13874 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
13875                          uint64_t fb_modifier, uint32_t pixel_format)
13876 {
13877         u32 gen = INTEL_GEN(dev_priv);
13878
13879         if (gen >= 9) {
13880                 int cpp = drm_format_plane_cpp(pixel_format, 0);
13881
13882                 /* "The stride in bytes must not exceed the of the size of 8K
13883                  *  pixels and 32K bytes."
13884                  */
13885                 return min(8192 * cpp, 32768);
13886         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
13887                 return 32*1024;
13888         } else if (gen >= 4) {
13889                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13890                         return 16*1024;
13891                 else
13892                         return 32*1024;
13893         } else if (gen >= 3) {
13894                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13895                         return 8*1024;
13896                 else
13897                         return 16*1024;
13898         } else {
13899                 /* XXX DSPC is limited to 4k tiled */
13900                 return 8*1024;
13901         }
13902 }
13903
13904 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
13905                                   struct drm_i915_gem_object *obj,
13906                                   struct drm_mode_fb_cmd2 *mode_cmd)
13907 {
13908         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
13909         struct drm_framebuffer *fb = &intel_fb->base;
13910         struct drm_format_name_buf format_name;
13911         u32 pitch_limit;
13912         unsigned int tiling, stride;
13913         int ret = -EINVAL;
13914         int i;
13915
13916         i915_gem_object_lock(obj);
13917         obj->framebuffer_references++;
13918         tiling = i915_gem_object_get_tiling(obj);
13919         stride = i915_gem_object_get_stride(obj);
13920         i915_gem_object_unlock(obj);
13921
13922         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
13923                 /*
13924                  * If there's a fence, enforce that
13925                  * the fb modifier and tiling mode match.
13926                  */
13927                 if (tiling != I915_TILING_NONE &&
13928                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
13929                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
13930                         goto err;
13931                 }
13932         } else {
13933                 if (tiling == I915_TILING_X) {
13934                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
13935                 } else if (tiling == I915_TILING_Y) {
13936                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
13937                         goto err;
13938                 }
13939         }
13940
13941         /* Passed in modifier sanity checking. */
13942         switch (mode_cmd->modifier[0]) {
13943         case I915_FORMAT_MOD_Y_TILED_CCS:
13944         case I915_FORMAT_MOD_Yf_TILED_CCS:
13945                 switch (mode_cmd->pixel_format) {
13946                 case DRM_FORMAT_XBGR8888:
13947                 case DRM_FORMAT_ABGR8888:
13948                 case DRM_FORMAT_XRGB8888:
13949                 case DRM_FORMAT_ARGB8888:
13950                         break;
13951                 default:
13952                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
13953                         goto err;
13954                 }
13955                 /* fall through */
13956         case I915_FORMAT_MOD_Y_TILED:
13957         case I915_FORMAT_MOD_Yf_TILED:
13958                 if (INTEL_GEN(dev_priv) < 9) {
13959                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
13960                                       mode_cmd->modifier[0]);
13961                         goto err;
13962                 }
13963         case DRM_FORMAT_MOD_LINEAR:
13964         case I915_FORMAT_MOD_X_TILED:
13965                 break;
13966         default:
13967                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
13968                               mode_cmd->modifier[0]);
13969                 goto err;
13970         }
13971
13972         /*
13973          * gen2/3 display engine uses the fence if present,
13974          * so the tiling mode must match the fb modifier exactly.
13975          */
13976         if (INTEL_INFO(dev_priv)->gen < 4 &&
13977             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
13978                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
13979                 goto err;
13980         }
13981
13982         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
13983                                            mode_cmd->pixel_format);
13984         if (mode_cmd->pitches[0] > pitch_limit) {
13985                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
13986                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
13987                               "tiled" : "linear",
13988                               mode_cmd->pitches[0], pitch_limit);
13989                 goto err;
13990         }
13991
13992         /*
13993          * If there's a fence, enforce that
13994          * the fb pitch and fence stride match.
13995          */
13996         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
13997                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
13998                               mode_cmd->pitches[0], stride);
13999                 goto err;
14000         }
14001
14002         /* Reject formats not supported by any plane early. */
14003         switch (mode_cmd->pixel_format) {
14004         case DRM_FORMAT_C8:
14005         case DRM_FORMAT_RGB565:
14006         case DRM_FORMAT_XRGB8888:
14007         case DRM_FORMAT_ARGB8888:
14008                 break;
14009         case DRM_FORMAT_XRGB1555:
14010                 if (INTEL_GEN(dev_priv) > 3) {
14011                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14012                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14013                         goto err;
14014                 }
14015                 break;
14016         case DRM_FORMAT_ABGR8888:
14017                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14018                     INTEL_GEN(dev_priv) < 9) {
14019                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14020                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14021                         goto err;
14022                 }
14023                 break;
14024         case DRM_FORMAT_XBGR8888:
14025         case DRM_FORMAT_XRGB2101010:
14026         case DRM_FORMAT_XBGR2101010:
14027                 if (INTEL_GEN(dev_priv) < 4) {
14028                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14029                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14030                         goto err;
14031                 }
14032                 break;
14033         case DRM_FORMAT_ABGR2101010:
14034                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14035                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14036                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14037                         goto err;
14038                 }
14039                 break;
14040         case DRM_FORMAT_YUYV:
14041         case DRM_FORMAT_UYVY:
14042         case DRM_FORMAT_YVYU:
14043         case DRM_FORMAT_VYUY:
14044                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14045                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14046                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14047                         goto err;
14048                 }
14049                 break;
14050         default:
14051                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14052                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14053                 goto err;
14054         }
14055
14056         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14057         if (mode_cmd->offsets[0] != 0)
14058                 goto err;
14059
14060         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14061
14062         for (i = 0; i < fb->format->num_planes; i++) {
14063                 u32 stride_alignment;
14064
14065                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14066                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14067                         goto err;
14068                 }
14069
14070                 stride_alignment = intel_fb_stride_alignment(fb, i);
14071
14072                 /*
14073                  * Display WA #0531: skl,bxt,kbl,glk
14074                  *
14075                  * Render decompression and plane width > 3840
14076                  * combined with horizontal panning requires the
14077                  * plane stride to be a multiple of 4. We'll just
14078                  * require the entire fb to accommodate that to avoid
14079                  * potential runtime errors at plane configuration time.
14080                  */
14081                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14082                     (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
14083                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS))
14084                         stride_alignment *= 4;
14085
14086                 if (fb->pitches[i] & (stride_alignment - 1)) {
14087                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14088                                       i, fb->pitches[i], stride_alignment);
14089                         goto err;
14090                 }
14091         }
14092
14093         intel_fb->obj = obj;
14094
14095         ret = intel_fill_fb_info(dev_priv, fb);
14096         if (ret)
14097                 goto err;
14098
14099         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14100         if (ret) {
14101                 DRM_ERROR("framebuffer init failed %d\n", ret);
14102                 goto err;
14103         }
14104
14105         return 0;
14106
14107 err:
14108         i915_gem_object_lock(obj);
14109         obj->framebuffer_references--;
14110         i915_gem_object_unlock(obj);
14111         return ret;
14112 }
14113
14114 static struct drm_framebuffer *
14115 intel_user_framebuffer_create(struct drm_device *dev,
14116                               struct drm_file *filp,
14117                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14118 {
14119         struct drm_framebuffer *fb;
14120         struct drm_i915_gem_object *obj;
14121         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14122
14123         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14124         if (!obj)
14125                 return ERR_PTR(-ENOENT);
14126
14127         fb = intel_framebuffer_create(obj, &mode_cmd);
14128         if (IS_ERR(fb))
14129                 i915_gem_object_put(obj);
14130
14131         return fb;
14132 }
14133
14134 static void intel_atomic_state_free(struct drm_atomic_state *state)
14135 {
14136         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14137
14138         drm_atomic_state_default_release(state);
14139
14140         i915_sw_fence_fini(&intel_state->commit_ready);
14141
14142         kfree(state);
14143 }
14144
14145 static const struct drm_mode_config_funcs intel_mode_funcs = {
14146         .fb_create = intel_user_framebuffer_create,
14147         .get_format_info = intel_get_format_info,
14148         .output_poll_changed = intel_fbdev_output_poll_changed,
14149         .atomic_check = intel_atomic_check,
14150         .atomic_commit = intel_atomic_commit,
14151         .atomic_state_alloc = intel_atomic_state_alloc,
14152         .atomic_state_clear = intel_atomic_state_clear,
14153         .atomic_state_free = intel_atomic_state_free,
14154 };
14155
14156 /**
14157  * intel_init_display_hooks - initialize the display modesetting hooks
14158  * @dev_priv: device private
14159  */
14160 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14161 {
14162         intel_init_cdclk_hooks(dev_priv);
14163
14164         if (INTEL_INFO(dev_priv)->gen >= 9) {
14165                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14166                 dev_priv->display.get_initial_plane_config =
14167                         skylake_get_initial_plane_config;
14168                 dev_priv->display.crtc_compute_clock =
14169                         haswell_crtc_compute_clock;
14170                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14171                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14172         } else if (HAS_DDI(dev_priv)) {
14173                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14174                 dev_priv->display.get_initial_plane_config =
14175                         ironlake_get_initial_plane_config;
14176                 dev_priv->display.crtc_compute_clock =
14177                         haswell_crtc_compute_clock;
14178                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14179                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14180         } else if (HAS_PCH_SPLIT(dev_priv)) {
14181                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14182                 dev_priv->display.get_initial_plane_config =
14183                         ironlake_get_initial_plane_config;
14184                 dev_priv->display.crtc_compute_clock =
14185                         ironlake_crtc_compute_clock;
14186                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14187                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14188         } else if (IS_CHERRYVIEW(dev_priv)) {
14189                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14190                 dev_priv->display.get_initial_plane_config =
14191                         i9xx_get_initial_plane_config;
14192                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14193                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14194                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14195         } else if (IS_VALLEYVIEW(dev_priv)) {
14196                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14197                 dev_priv->display.get_initial_plane_config =
14198                         i9xx_get_initial_plane_config;
14199                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14200                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14201                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14202         } else if (IS_G4X(dev_priv)) {
14203                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14204                 dev_priv->display.get_initial_plane_config =
14205                         i9xx_get_initial_plane_config;
14206                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14207                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14208                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14209         } else if (IS_PINEVIEW(dev_priv)) {
14210                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14211                 dev_priv->display.get_initial_plane_config =
14212                         i9xx_get_initial_plane_config;
14213                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14214                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14215                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14216         } else if (!IS_GEN2(dev_priv)) {
14217                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14218                 dev_priv->display.get_initial_plane_config =
14219                         i9xx_get_initial_plane_config;
14220                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14221                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14222                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14223         } else {
14224                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14225                 dev_priv->display.get_initial_plane_config =
14226                         i9xx_get_initial_plane_config;
14227                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14228                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14229                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14230         }
14231
14232         if (IS_GEN5(dev_priv)) {
14233                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14234         } else if (IS_GEN6(dev_priv)) {
14235                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14236         } else if (IS_IVYBRIDGE(dev_priv)) {
14237                 /* FIXME: detect B0+ stepping and use auto training */
14238                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14239         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14240                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14241         }
14242
14243         if (dev_priv->info.gen >= 9)
14244                 dev_priv->display.update_crtcs = skl_update_crtcs;
14245         else
14246                 dev_priv->display.update_crtcs = intel_update_crtcs;
14247 }
14248
14249 /*
14250  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14251  */
14252 static void quirk_ssc_force_disable(struct drm_device *dev)
14253 {
14254         struct drm_i915_private *dev_priv = to_i915(dev);
14255         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14256         DRM_INFO("applying lvds SSC disable quirk\n");
14257 }
14258
14259 /*
14260  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14261  * brightness value
14262  */
14263 static void quirk_invert_brightness(struct drm_device *dev)
14264 {
14265         struct drm_i915_private *dev_priv = to_i915(dev);
14266         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14267         DRM_INFO("applying inverted panel brightness quirk\n");
14268 }
14269
14270 /* Some VBT's incorrectly indicate no backlight is present */
14271 static void quirk_backlight_present(struct drm_device *dev)
14272 {
14273         struct drm_i915_private *dev_priv = to_i915(dev);
14274         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14275         DRM_INFO("applying backlight present quirk\n");
14276 }
14277
14278 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14279  * which is 300 ms greater than eDP spec T12 min.
14280  */
14281 static void quirk_increase_t12_delay(struct drm_device *dev)
14282 {
14283         struct drm_i915_private *dev_priv = to_i915(dev);
14284
14285         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14286         DRM_INFO("Applying T12 delay quirk\n");
14287 }
14288
14289 /*
14290  * GeminiLake NUC HDMI outputs require additional off time
14291  * this allows the onboard retimer to correctly sync to signal
14292  */
14293 static void quirk_increase_ddi_disabled_time(struct drm_device *dev)
14294 {
14295         struct drm_i915_private *dev_priv = to_i915(dev);
14296
14297         dev_priv->quirks |= QUIRK_INCREASE_DDI_DISABLED_TIME;
14298         DRM_INFO("Applying Increase DDI Disabled quirk\n");
14299 }
14300
14301 struct intel_quirk {
14302         int device;
14303         int subsystem_vendor;
14304         int subsystem_device;
14305         void (*hook)(struct drm_device *dev);
14306 };
14307
14308 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14309 struct intel_dmi_quirk {
14310         void (*hook)(struct drm_device *dev);
14311         const struct dmi_system_id (*dmi_id_list)[];
14312 };
14313
14314 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14315 {
14316         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14317         return 1;
14318 }
14319
14320 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14321         {
14322                 .dmi_id_list = &(const struct dmi_system_id[]) {
14323                         {
14324                                 .callback = intel_dmi_reverse_brightness,
14325                                 .ident = "NCR Corporation",
14326                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14327                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14328                                 },
14329                         },
14330                         { }  /* terminating entry */
14331                 },
14332                 .hook = quirk_invert_brightness,
14333         },
14334 };
14335
14336 static struct intel_quirk intel_quirks[] = {
14337         /* Lenovo U160 cannot use SSC on LVDS */
14338         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14339
14340         /* Sony Vaio Y cannot use SSC on LVDS */
14341         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14342
14343         /* Acer Aspire 5734Z must invert backlight brightness */
14344         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14345
14346         /* Acer/eMachines G725 */
14347         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14348
14349         /* Acer/eMachines e725 */
14350         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14351
14352         /* Acer/Packard Bell NCL20 */
14353         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14354
14355         /* Acer Aspire 4736Z */
14356         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14357
14358         /* Acer Aspire 5336 */
14359         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14360
14361         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14362         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14363
14364         /* Acer C720 Chromebook (Core i3 4005U) */
14365         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14366
14367         /* Apple Macbook 2,1 (Core 2 T7400) */
14368         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14369
14370         /* Apple Macbook 4,1 */
14371         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14372
14373         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14374         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14375
14376         /* HP Chromebook 14 (Celeron 2955U) */
14377         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14378
14379         /* Dell Chromebook 11 */
14380         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14381
14382         /* Dell Chromebook 11 (2015 version) */
14383         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14384
14385         /* Toshiba Satellite P50-C-18C */
14386         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14387
14388         /* GeminiLake NUC */
14389         { 0x3185, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14390         { 0x3184, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14391         /* ASRock ITX*/
14392         { 0x3185, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14393         { 0x3184, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14394 };
14395
14396 static void intel_init_quirks(struct drm_device *dev)
14397 {
14398         struct pci_dev *d = dev->pdev;
14399         int i;
14400
14401         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14402                 struct intel_quirk *q = &intel_quirks[i];
14403
14404                 if (d->device == q->device &&
14405                     (d->subsystem_vendor == q->subsystem_vendor ||
14406                      q->subsystem_vendor == PCI_ANY_ID) &&
14407                     (d->subsystem_device == q->subsystem_device ||
14408                      q->subsystem_device == PCI_ANY_ID))
14409                         q->hook(dev);
14410         }
14411         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14412                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14413                         intel_dmi_quirks[i].hook(dev);
14414         }
14415 }
14416
14417 /* Disable the VGA plane that we never use */
14418 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14419 {
14420         struct pci_dev *pdev = dev_priv->drm.pdev;
14421         u8 sr1;
14422         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14423
14424         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14425         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14426         outb(SR01, VGA_SR_INDEX);
14427         sr1 = inb(VGA_SR_DATA);
14428         outb(sr1 | 1<<5, VGA_SR_DATA);
14429         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14430         udelay(300);
14431
14432         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14433         POSTING_READ(vga_reg);
14434 }
14435
14436 void intel_modeset_init_hw(struct drm_device *dev)
14437 {
14438         struct drm_i915_private *dev_priv = to_i915(dev);
14439
14440         intel_update_cdclk(dev_priv);
14441         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14442 }
14443
14444 /*
14445  * Calculate what we think the watermarks should be for the state we've read
14446  * out of the hardware and then immediately program those watermarks so that
14447  * we ensure the hardware settings match our internal state.
14448  *
14449  * We can calculate what we think WM's should be by creating a duplicate of the
14450  * current state (which was constructed during hardware readout) and running it
14451  * through the atomic check code to calculate new watermark values in the
14452  * state object.
14453  */
14454 static void sanitize_watermarks(struct drm_device *dev)
14455 {
14456         struct drm_i915_private *dev_priv = to_i915(dev);
14457         struct drm_atomic_state *state;
14458         struct intel_atomic_state *intel_state;
14459         struct drm_crtc *crtc;
14460         struct drm_crtc_state *cstate;
14461         struct drm_modeset_acquire_ctx ctx;
14462         int ret;
14463         int i;
14464
14465         /* Only supported on platforms that use atomic watermark design */
14466         if (!dev_priv->display.optimize_watermarks)
14467                 return;
14468
14469         /*
14470          * We need to hold connection_mutex before calling duplicate_state so
14471          * that the connector loop is protected.
14472          */
14473         drm_modeset_acquire_init(&ctx, 0);
14474 retry:
14475         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14476         if (ret == -EDEADLK) {
14477                 drm_modeset_backoff(&ctx);
14478                 goto retry;
14479         } else if (WARN_ON(ret)) {
14480                 goto fail;
14481         }
14482
14483         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14484         if (WARN_ON(IS_ERR(state)))
14485                 goto fail;
14486
14487         intel_state = to_intel_atomic_state(state);
14488
14489         /*
14490          * Hardware readout is the only time we don't want to calculate
14491          * intermediate watermarks (since we don't trust the current
14492          * watermarks).
14493          */
14494         if (!HAS_GMCH_DISPLAY(dev_priv))
14495                 intel_state->skip_intermediate_wm = true;
14496
14497         ret = intel_atomic_check(dev, state);
14498         if (ret) {
14499                 /*
14500                  * If we fail here, it means that the hardware appears to be
14501                  * programmed in a way that shouldn't be possible, given our
14502                  * understanding of watermark requirements.  This might mean a
14503                  * mistake in the hardware readout code or a mistake in the
14504                  * watermark calculations for a given platform.  Raise a WARN
14505                  * so that this is noticeable.
14506                  *
14507                  * If this actually happens, we'll have to just leave the
14508                  * BIOS-programmed watermarks untouched and hope for the best.
14509                  */
14510                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14511                 goto put_state;
14512         }
14513
14514         /* Write calculated watermark values back */
14515         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14516                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14517
14518                 cs->wm.need_postvbl_update = true;
14519                 dev_priv->display.optimize_watermarks(intel_state, cs);
14520
14521                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
14522         }
14523
14524 put_state:
14525         drm_atomic_state_put(state);
14526 fail:
14527         drm_modeset_drop_locks(&ctx);
14528         drm_modeset_acquire_fini(&ctx);
14529 }
14530
14531 int intel_modeset_init(struct drm_device *dev)
14532 {
14533         struct drm_i915_private *dev_priv = to_i915(dev);
14534         struct i915_ggtt *ggtt = &dev_priv->ggtt;
14535         enum pipe pipe;
14536         struct intel_crtc *crtc;
14537
14538         drm_mode_config_init(dev);
14539
14540         dev->mode_config.min_width = 0;
14541         dev->mode_config.min_height = 0;
14542
14543         dev->mode_config.preferred_depth = 24;
14544         dev->mode_config.prefer_shadow = 1;
14545
14546         dev->mode_config.allow_fb_modifiers = true;
14547
14548         dev->mode_config.funcs = &intel_mode_funcs;
14549
14550         init_llist_head(&dev_priv->atomic_helper.free_list);
14551         INIT_WORK(&dev_priv->atomic_helper.free_work,
14552                   intel_atomic_helper_free_state_worker);
14553
14554         intel_init_quirks(dev);
14555
14556         intel_init_pm(dev_priv);
14557
14558         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14559                 return 0;
14560
14561         /*
14562          * There may be no VBT; and if the BIOS enabled SSC we can
14563          * just keep using it to avoid unnecessary flicker.  Whereas if the
14564          * BIOS isn't using it, don't assume it will work even if the VBT
14565          * indicates as much.
14566          */
14567         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
14568                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14569                                             DREF_SSC1_ENABLE);
14570
14571                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
14572                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
14573                                      bios_lvds_use_ssc ? "en" : "dis",
14574                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
14575                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
14576                 }
14577         }
14578
14579         if (IS_GEN2(dev_priv)) {
14580                 dev->mode_config.max_width = 2048;
14581                 dev->mode_config.max_height = 2048;
14582         } else if (IS_GEN3(dev_priv)) {
14583                 dev->mode_config.max_width = 4096;
14584                 dev->mode_config.max_height = 4096;
14585         } else {
14586                 dev->mode_config.max_width = 8192;
14587                 dev->mode_config.max_height = 8192;
14588         }
14589
14590         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14591                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
14592                 dev->mode_config.cursor_height = 1023;
14593         } else if (IS_GEN2(dev_priv)) {
14594                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14595                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14596         } else {
14597                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14598                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14599         }
14600
14601         dev->mode_config.fb_base = ggtt->mappable_base;
14602
14603         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14604                       INTEL_INFO(dev_priv)->num_pipes,
14605                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
14606
14607         for_each_pipe(dev_priv, pipe) {
14608                 int ret;
14609
14610                 ret = intel_crtc_init(dev_priv, pipe);
14611                 if (ret) {
14612                         drm_mode_config_cleanup(dev);
14613                         return ret;
14614                 }
14615         }
14616
14617         intel_shared_dpll_init(dev);
14618
14619         intel_update_czclk(dev_priv);
14620         intel_modeset_init_hw(dev);
14621
14622         if (dev_priv->max_cdclk_freq == 0)
14623                 intel_update_max_cdclk(dev_priv);
14624
14625         /* Just disable it once at startup */
14626         i915_disable_vga(dev_priv);
14627         intel_setup_outputs(dev_priv);
14628
14629         drm_modeset_lock_all(dev);
14630         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
14631         drm_modeset_unlock_all(dev);
14632
14633         for_each_intel_crtc(dev, crtc) {
14634                 struct intel_initial_plane_config plane_config = {};
14635
14636                 if (!crtc->active)
14637                         continue;
14638
14639                 /*
14640                  * Note that reserving the BIOS fb up front prevents us
14641                  * from stuffing other stolen allocations like the ring
14642                  * on top.  This prevents some ugliness at boot time, and
14643                  * can even allow for smooth boot transitions if the BIOS
14644                  * fb is large enough for the active pipe configuration.
14645                  */
14646                 dev_priv->display.get_initial_plane_config(crtc,
14647                                                            &plane_config);
14648
14649                 /*
14650                  * If the fb is shared between multiple heads, we'll
14651                  * just get the first one.
14652                  */
14653                 intel_find_initial_plane_obj(crtc, &plane_config);
14654         }
14655
14656         /*
14657          * Make sure hardware watermarks really match the state we read out.
14658          * Note that we need to do this after reconstructing the BIOS fb's
14659          * since the watermark calculation done here will use pstate->fb.
14660          */
14661         if (!HAS_GMCH_DISPLAY(dev_priv))
14662                 sanitize_watermarks(dev);
14663
14664         return 0;
14665 }
14666
14667 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14668 {
14669         /* 640x480@60Hz, ~25175 kHz */
14670         struct dpll clock = {
14671                 .m1 = 18,
14672                 .m2 = 7,
14673                 .p1 = 13,
14674                 .p2 = 4,
14675                 .n = 2,
14676         };
14677         u32 dpll, fp;
14678         int i;
14679
14680         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
14681
14682         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
14683                       pipe_name(pipe), clock.vco, clock.dot);
14684
14685         fp = i9xx_dpll_compute_fp(&clock);
14686         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
14687                 DPLL_VGA_MODE_DIS |
14688                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
14689                 PLL_P2_DIVIDE_BY_4 |
14690                 PLL_REF_INPUT_DREFCLK |
14691                 DPLL_VCO_ENABLE;
14692
14693         I915_WRITE(FP0(pipe), fp);
14694         I915_WRITE(FP1(pipe), fp);
14695
14696         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
14697         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
14698         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
14699         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
14700         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
14701         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
14702         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
14703
14704         /*
14705          * Apparently we need to have VGA mode enabled prior to changing
14706          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
14707          * dividers, even though the register value does change.
14708          */
14709         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
14710         I915_WRITE(DPLL(pipe), dpll);
14711
14712         /* Wait for the clocks to stabilize. */
14713         POSTING_READ(DPLL(pipe));
14714         udelay(150);
14715
14716         /* The pixel multiplier can only be updated once the
14717          * DPLL is enabled and the clocks are stable.
14718          *
14719          * So write it again.
14720          */
14721         I915_WRITE(DPLL(pipe), dpll);
14722
14723         /* We do this three times for luck */
14724         for (i = 0; i < 3 ; i++) {
14725                 I915_WRITE(DPLL(pipe), dpll);
14726                 POSTING_READ(DPLL(pipe));
14727                 udelay(150); /* wait for warmup */
14728         }
14729
14730         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
14731         POSTING_READ(PIPECONF(pipe));
14732 }
14733
14734 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14735 {
14736         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14737
14738         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
14739                       pipe_name(pipe));
14740
14741         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
14742         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
14743         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
14744         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & CURSOR_MODE);
14745         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & CURSOR_MODE);
14746
14747         I915_WRITE(PIPECONF(pipe), 0);
14748         POSTING_READ(PIPECONF(pipe));
14749
14750         intel_wait_for_pipe_scanline_stopped(crtc);
14751
14752         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
14753         POSTING_READ(DPLL(pipe));
14754 }
14755
14756 static bool intel_plane_mapping_ok(struct intel_crtc *crtc,
14757                                    struct intel_plane *primary)
14758 {
14759         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14760         enum plane plane = primary->plane;
14761         u32 val = I915_READ(DSPCNTR(plane));
14762
14763         return (val & DISPLAY_PLANE_ENABLE) == 0 ||
14764                 (val & DISPPLANE_SEL_PIPE_MASK) == DISPPLANE_SEL_PIPE(crtc->pipe);
14765 }
14766
14767 static void
14768 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
14769 {
14770         struct intel_crtc *crtc;
14771
14772         if (INTEL_GEN(dev_priv) >= 4)
14773                 return;
14774
14775         for_each_intel_crtc(&dev_priv->drm, crtc) {
14776                 struct intel_plane *plane =
14777                         to_intel_plane(crtc->base.primary);
14778
14779                 if (intel_plane_mapping_ok(crtc, plane))
14780                         continue;
14781
14782                 DRM_DEBUG_KMS("%s attached to the wrong pipe, disabling plane\n",
14783                               plane->base.name);
14784                 intel_plane_disable_noatomic(crtc, plane);
14785         }
14786 }
14787
14788 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
14789 {
14790         struct drm_device *dev = crtc->base.dev;
14791         struct intel_encoder *encoder;
14792
14793         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14794                 return true;
14795
14796         return false;
14797 }
14798
14799 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
14800 {
14801         struct drm_device *dev = encoder->base.dev;
14802         struct intel_connector *connector;
14803
14804         for_each_connector_on_encoder(dev, &encoder->base, connector)
14805                 return connector;
14806
14807         return NULL;
14808 }
14809
14810 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
14811                               enum transcoder pch_transcoder)
14812 {
14813         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
14814                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == TRANSCODER_A);
14815 }
14816
14817 static void intel_sanitize_crtc(struct intel_crtc *crtc,
14818                                 struct drm_modeset_acquire_ctx *ctx)
14819 {
14820         struct drm_device *dev = crtc->base.dev;
14821         struct drm_i915_private *dev_priv = to_i915(dev);
14822         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
14823
14824         /* Clear any frame start delays used for debugging left by the BIOS */
14825         if (!transcoder_is_dsi(cpu_transcoder)) {
14826                 i915_reg_t reg = PIPECONF(cpu_transcoder);
14827
14828                 I915_WRITE(reg,
14829                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14830         }
14831
14832         if (crtc->active) {
14833                 struct intel_plane *plane;
14834
14835                 /* Disable everything but the primary plane */
14836                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
14837                         const struct intel_plane_state *plane_state =
14838                                 to_intel_plane_state(plane->base.state);
14839
14840                         if (plane_state->base.visible &&
14841                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
14842                                 intel_plane_disable_noatomic(crtc, plane);
14843                 }
14844         }
14845
14846         /* Adjust the state of the output pipe according to whether we
14847          * have active connectors/encoders. */
14848         if (crtc->active && !intel_crtc_has_encoders(crtc))
14849                 intel_crtc_disable_noatomic(&crtc->base, ctx);
14850
14851         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
14852                 /*
14853                  * We start out with underrun reporting disabled to avoid races.
14854                  * For correct bookkeeping mark this on active crtcs.
14855                  *
14856                  * Also on gmch platforms we dont have any hardware bits to
14857                  * disable the underrun reporting. Which means we need to start
14858                  * out with underrun reporting disabled also on inactive pipes,
14859                  * since otherwise we'll complain about the garbage we read when
14860                  * e.g. coming up after runtime pm.
14861                  *
14862                  * No protection against concurrent access is required - at
14863                  * worst a fifo underrun happens which also sets this to false.
14864                  */
14865                 crtc->cpu_fifo_underrun_disabled = true;
14866                 /*
14867                  * We track the PCH trancoder underrun reporting state
14868                  * within the crtc. With crtc for pipe A housing the underrun
14869                  * reporting state for PCH transcoder A, crtc for pipe B housing
14870                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
14871                  * and marking underrun reporting as disabled for the non-existing
14872                  * PCH transcoders B and C would prevent enabling the south
14873                  * error interrupt (see cpt_can_enable_serr_int()).
14874                  */
14875                 if (has_pch_trancoder(dev_priv, (enum transcoder)crtc->pipe))
14876                         crtc->pch_fifo_underrun_disabled = true;
14877         }
14878 }
14879
14880 static void intel_sanitize_encoder(struct intel_encoder *encoder)
14881 {
14882         struct intel_connector *connector;
14883
14884         /* We need to check both for a crtc link (meaning that the
14885          * encoder is active and trying to read from a pipe) and the
14886          * pipe itself being active. */
14887         bool has_active_crtc = encoder->base.crtc &&
14888                 to_intel_crtc(encoder->base.crtc)->active;
14889
14890         connector = intel_encoder_find_connector(encoder);
14891         if (connector && !has_active_crtc) {
14892                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
14893                               encoder->base.base.id,
14894                               encoder->base.name);
14895
14896                 /* Connector is active, but has no active pipe. This is
14897                  * fallout from our resume register restoring. Disable
14898                  * the encoder manually again. */
14899                 if (encoder->base.crtc) {
14900                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
14901
14902                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
14903                                       encoder->base.base.id,
14904                                       encoder->base.name);
14905                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
14906                         if (encoder->post_disable)
14907                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
14908                 }
14909                 encoder->base.crtc = NULL;
14910
14911                 /* Inconsistent output/port/pipe state happens presumably due to
14912                  * a bug in one of the get_hw_state functions. Or someplace else
14913                  * in our code, like the register restore mess on resume. Clamp
14914                  * things to off as a safer default. */
14915
14916                 connector->base.dpms = DRM_MODE_DPMS_OFF;
14917                 connector->base.encoder = NULL;
14918         }
14919         /* Enabled encoders without active connectors will be fixed in
14920          * the crtc fixup. */
14921 }
14922
14923 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
14924 {
14925         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14926
14927         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
14928                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
14929                 i915_disable_vga(dev_priv);
14930         }
14931 }
14932
14933 void i915_redisable_vga(struct drm_i915_private *dev_priv)
14934 {
14935         /* This function can be called both from intel_modeset_setup_hw_state or
14936          * at a very early point in our resume sequence, where the power well
14937          * structures are not yet restored. Since this function is at a very
14938          * paranoid "someone might have enabled VGA while we were not looking"
14939          * level, just check if the power well is enabled instead of trying to
14940          * follow the "don't touch the power well if we don't need it" policy
14941          * the rest of the driver uses. */
14942         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
14943                 return;
14944
14945         i915_redisable_vga_power_on(dev_priv);
14946
14947         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
14948 }
14949
14950 /* FIXME read out full plane state for all planes */
14951 static void readout_plane_state(struct intel_crtc *crtc)
14952 {
14953         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14954         struct intel_crtc_state *crtc_state =
14955                 to_intel_crtc_state(crtc->base.state);
14956         struct intel_plane *plane;
14957
14958         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
14959                 struct intel_plane_state *plane_state =
14960                         to_intel_plane_state(plane->base.state);
14961                 bool visible = plane->get_hw_state(plane);
14962
14963                 intel_set_plane_visible(crtc_state, plane_state, visible);
14964         }
14965 }
14966
14967 static void intel_modeset_readout_hw_state(struct drm_device *dev)
14968 {
14969         struct drm_i915_private *dev_priv = to_i915(dev);
14970         enum pipe pipe;
14971         struct intel_crtc *crtc;
14972         struct intel_encoder *encoder;
14973         struct intel_connector *connector;
14974         struct drm_connector_list_iter conn_iter;
14975         int i;
14976
14977         dev_priv->active_crtcs = 0;
14978
14979         for_each_intel_crtc(dev, crtc) {
14980                 struct intel_crtc_state *crtc_state =
14981                         to_intel_crtc_state(crtc->base.state);
14982
14983                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
14984                 memset(crtc_state, 0, sizeof(*crtc_state));
14985                 crtc_state->base.crtc = &crtc->base;
14986
14987                 crtc_state->base.active = crtc_state->base.enable =
14988                         dev_priv->display.get_pipe_config(crtc, crtc_state);
14989
14990                 crtc->base.enabled = crtc_state->base.enable;
14991                 crtc->active = crtc_state->base.active;
14992
14993                 if (crtc_state->base.active)
14994                         dev_priv->active_crtcs |= 1 << crtc->pipe;
14995
14996                 readout_plane_state(crtc);
14997
14998                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
14999                               crtc->base.base.id, crtc->base.name,
15000                               enableddisabled(crtc_state->base.active));
15001         }
15002
15003         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15004                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15005
15006                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15007                                                   &pll->state.hw_state);
15008                 pll->state.crtc_mask = 0;
15009                 for_each_intel_crtc(dev, crtc) {
15010                         struct intel_crtc_state *crtc_state =
15011                                 to_intel_crtc_state(crtc->base.state);
15012
15013                         if (crtc_state->base.active &&
15014                             crtc_state->shared_dpll == pll)
15015                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15016                 }
15017                 pll->active_mask = pll->state.crtc_mask;
15018
15019                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15020                               pll->name, pll->state.crtc_mask, pll->on);
15021         }
15022
15023         for_each_intel_encoder(dev, encoder) {
15024                 pipe = 0;
15025
15026                 if (encoder->get_hw_state(encoder, &pipe)) {
15027                         struct intel_crtc_state *crtc_state;
15028
15029                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15030                         crtc_state = to_intel_crtc_state(crtc->base.state);
15031
15032                         encoder->base.crtc = &crtc->base;
15033                         crtc_state->output_types |= 1 << encoder->type;
15034                         encoder->get_config(encoder, crtc_state);
15035                 } else {
15036                         encoder->base.crtc = NULL;
15037                 }
15038
15039                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15040                               encoder->base.base.id, encoder->base.name,
15041                               enableddisabled(encoder->base.crtc),
15042                               pipe_name(pipe));
15043         }
15044
15045         drm_connector_list_iter_begin(dev, &conn_iter);
15046         for_each_intel_connector_iter(connector, &conn_iter) {
15047                 if (connector->get_hw_state(connector)) {
15048                         connector->base.dpms = DRM_MODE_DPMS_ON;
15049
15050                         encoder = connector->encoder;
15051                         connector->base.encoder = &encoder->base;
15052
15053                         if (encoder->base.crtc &&
15054                             encoder->base.crtc->state->active) {
15055                                 /*
15056                                  * This has to be done during hardware readout
15057                                  * because anything calling .crtc_disable may
15058                                  * rely on the connector_mask being accurate.
15059                                  */
15060                                 encoder->base.crtc->state->connector_mask |=
15061                                         1 << drm_connector_index(&connector->base);
15062                                 encoder->base.crtc->state->encoder_mask |=
15063                                         1 << drm_encoder_index(&encoder->base);
15064                         }
15065
15066                 } else {
15067                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15068                         connector->base.encoder = NULL;
15069                 }
15070                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15071                               connector->base.base.id, connector->base.name,
15072                               enableddisabled(connector->base.encoder));
15073         }
15074         drm_connector_list_iter_end(&conn_iter);
15075
15076         for_each_intel_crtc(dev, crtc) {
15077                 struct intel_crtc_state *crtc_state =
15078                         to_intel_crtc_state(crtc->base.state);
15079                 int pixclk = 0;
15080
15081                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15082                 if (crtc_state->base.active) {
15083                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15084                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15085                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15086
15087                         /*
15088                          * The initial mode needs to be set in order to keep
15089                          * the atomic core happy. It wants a valid mode if the
15090                          * crtc's enabled, so we do the above call.
15091                          *
15092                          * But we don't set all the derived state fully, hence
15093                          * set a flag to indicate that a full recalculation is
15094                          * needed on the next commit.
15095                          */
15096                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15097
15098                         intel_crtc_compute_pixel_rate(crtc_state);
15099
15100                         if (INTEL_GEN(dev_priv) >= 9 || IS_BROADWELL(dev_priv) ||
15101                             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
15102                                 pixclk = crtc_state->pixel_rate;
15103                         else
15104                                 WARN_ON(dev_priv->display.modeset_calc_cdclk);
15105
15106                         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
15107                         if (IS_BROADWELL(dev_priv) && crtc_state->ips_enabled)
15108                                 pixclk = DIV_ROUND_UP(pixclk * 100, 95);
15109
15110                         drm_calc_timestamping_constants(&crtc->base,
15111                                                         &crtc_state->base.adjusted_mode);
15112                         update_scanline_offset(crtc);
15113                 }
15114
15115                 dev_priv->min_pixclk[crtc->pipe] = pixclk;
15116
15117                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15118         }
15119 }
15120
15121 static void
15122 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15123 {
15124         struct intel_encoder *encoder;
15125
15126         for_each_intel_encoder(&dev_priv->drm, encoder) {
15127                 u64 get_domains;
15128                 enum intel_display_power_domain domain;
15129
15130                 if (!encoder->get_power_domains)
15131                         continue;
15132
15133                 get_domains = encoder->get_power_domains(encoder);
15134                 for_each_power_domain(domain, get_domains)
15135                         intel_display_power_get(dev_priv, domain);
15136         }
15137 }
15138
15139 /* Scan out the current hw modeset state,
15140  * and sanitizes it to the current state
15141  */
15142 static void
15143 intel_modeset_setup_hw_state(struct drm_device *dev,
15144                              struct drm_modeset_acquire_ctx *ctx)
15145 {
15146         struct drm_i915_private *dev_priv = to_i915(dev);
15147         struct intel_crtc *crtc;
15148         struct intel_encoder *encoder;
15149         int i;
15150
15151         if (IS_HASWELL(dev_priv)) {
15152                 /*
15153                  * WaRsPkgCStateDisplayPMReq:hsw
15154                  * System hang if this isn't done before disabling all planes!
15155                  */
15156                 I915_WRITE(CHICKEN_PAR1_1,
15157                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15158         }
15159
15160         intel_modeset_readout_hw_state(dev);
15161
15162         /* HW state is read out, now we need to sanitize this mess. */
15163         get_encoder_power_domains(dev_priv);
15164
15165         /*
15166          * intel_sanitize_plane_mapping() may need to do vblank
15167          * waits, so we need vblank interrupts restored beforehand.
15168          */
15169         for_each_intel_crtc(&dev_priv->drm, crtc) {
15170                 drm_crtc_vblank_reset(&crtc->base);
15171
15172                 if (crtc->active)
15173                         drm_crtc_vblank_on(&crtc->base);
15174         }
15175
15176         intel_sanitize_plane_mapping(dev_priv);
15177
15178         for_each_intel_encoder(dev, encoder)
15179                 intel_sanitize_encoder(encoder);
15180
15181         for_each_intel_crtc(&dev_priv->drm, crtc) {
15182                 intel_sanitize_crtc(crtc, ctx);
15183                 intel_dump_pipe_config(crtc, crtc->config,
15184                                        "[setup_hw_state]");
15185         }
15186
15187         intel_modeset_update_connector_atomic_state(dev);
15188
15189         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15190                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15191
15192                 if (!pll->on || pll->active_mask)
15193                         continue;
15194
15195                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15196
15197                 pll->funcs.disable(dev_priv, pll);
15198                 pll->on = false;
15199         }
15200
15201         if (IS_G4X(dev_priv)) {
15202                 g4x_wm_get_hw_state(dev);
15203                 g4x_wm_sanitize(dev_priv);
15204         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15205                 vlv_wm_get_hw_state(dev);
15206                 vlv_wm_sanitize(dev_priv);
15207         } else if (INTEL_GEN(dev_priv) >= 9) {
15208                 skl_wm_get_hw_state(dev);
15209         } else if (HAS_PCH_SPLIT(dev_priv)) {
15210                 ilk_wm_get_hw_state(dev);
15211         }
15212
15213         for_each_intel_crtc(dev, crtc) {
15214                 u64 put_domains;
15215
15216                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15217                 if (WARN_ON(put_domains))
15218                         modeset_put_power_domains(dev_priv, put_domains);
15219         }
15220         intel_display_set_init_power(dev_priv, false);
15221
15222         intel_power_domains_verify_state(dev_priv);
15223
15224         intel_fbc_init_pipe_state(dev_priv);
15225 }
15226
15227 void intel_display_resume(struct drm_device *dev)
15228 {
15229         struct drm_i915_private *dev_priv = to_i915(dev);
15230         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15231         struct drm_modeset_acquire_ctx ctx;
15232         int ret;
15233
15234         dev_priv->modeset_restore_state = NULL;
15235         if (state)
15236                 state->acquire_ctx = &ctx;
15237
15238         drm_modeset_acquire_init(&ctx, 0);
15239
15240         while (1) {
15241                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15242                 if (ret != -EDEADLK)
15243                         break;
15244
15245                 drm_modeset_backoff(&ctx);
15246         }
15247
15248         if (!ret)
15249                 ret = __intel_display_resume(dev, state, &ctx);
15250
15251         drm_modeset_drop_locks(&ctx);
15252         drm_modeset_acquire_fini(&ctx);
15253
15254         if (ret)
15255                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15256         if (state)
15257                 drm_atomic_state_put(state);
15258 }
15259
15260 void intel_modeset_gem_init(struct drm_device *dev)
15261 {
15262         struct drm_i915_private *dev_priv = to_i915(dev);
15263
15264         intel_init_gt_powersave(dev_priv);
15265
15266         intel_init_clock_gating(dev_priv);
15267
15268         intel_setup_overlay(dev_priv);
15269 }
15270
15271 int intel_connector_register(struct drm_connector *connector)
15272 {
15273         struct intel_connector *intel_connector = to_intel_connector(connector);
15274         int ret;
15275
15276         ret = intel_backlight_device_register(intel_connector);
15277         if (ret)
15278                 goto err;
15279
15280         return 0;
15281
15282 err:
15283         return ret;
15284 }
15285
15286 void intel_connector_unregister(struct drm_connector *connector)
15287 {
15288         struct intel_connector *intel_connector = to_intel_connector(connector);
15289
15290         intel_backlight_device_unregister(intel_connector);
15291         intel_panel_destroy_backlight(connector);
15292 }
15293
15294 static void intel_hpd_poll_fini(struct drm_device *dev)
15295 {
15296         struct intel_connector *connector;
15297         struct drm_connector_list_iter conn_iter;
15298
15299         /* First disable polling... */
15300         drm_kms_helper_poll_fini(dev);
15301
15302         /* Then kill the work that may have been queued by hpd. */
15303         drm_connector_list_iter_begin(dev, &conn_iter);
15304         for_each_intel_connector_iter(connector, &conn_iter) {
15305                 if (connector->modeset_retry_work.func)
15306                         cancel_work_sync(&connector->modeset_retry_work);
15307         }
15308         drm_connector_list_iter_end(&conn_iter);
15309 }
15310
15311 void intel_modeset_cleanup(struct drm_device *dev)
15312 {
15313         struct drm_i915_private *dev_priv = to_i915(dev);
15314
15315         flush_work(&dev_priv->atomic_helper.free_work);
15316         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15317
15318         intel_disable_gt_powersave(dev_priv);
15319
15320         /*
15321          * Interrupts and polling as the first thing to avoid creating havoc.
15322          * Too much stuff here (turning of connectors, ...) would
15323          * experience fancy races otherwise.
15324          */
15325         intel_irq_uninstall(dev_priv);
15326
15327         /*
15328          * Due to the hpd irq storm handling the hotplug work can re-arm the
15329          * poll handlers. Hence disable polling after hpd handling is shut down.
15330          */
15331         intel_hpd_poll_fini(dev);
15332
15333         /* poll work can call into fbdev, hence clean that up afterwards */
15334         intel_fbdev_fini(dev_priv);
15335
15336         intel_unregister_dsm_handler();
15337
15338         intel_fbc_global_disable(dev_priv);
15339
15340         /* flush any delayed tasks or pending work */
15341         flush_scheduled_work();
15342
15343         drm_mode_config_cleanup(dev);
15344
15345         intel_cleanup_overlay(dev_priv);
15346
15347         intel_cleanup_gt_powersave(dev_priv);
15348
15349         intel_teardown_gmbus(dev_priv);
15350 }
15351
15352 void intel_connector_attach_encoder(struct intel_connector *connector,
15353                                     struct intel_encoder *encoder)
15354 {
15355         connector->encoder = encoder;
15356         drm_mode_connector_attach_encoder(&connector->base,
15357                                           &encoder->base);
15358 }
15359
15360 /*
15361  * set vga decode state - true == enable VGA decode
15362  */
15363 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15364 {
15365         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15366         u16 gmch_ctrl;
15367
15368         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15369                 DRM_ERROR("failed to read control word\n");
15370                 return -EIO;
15371         }
15372
15373         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15374                 return 0;
15375
15376         if (state)
15377                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15378         else
15379                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15380
15381         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15382                 DRM_ERROR("failed to write control word\n");
15383                 return -EIO;
15384         }
15385
15386         return 0;
15387 }
15388
15389 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15390
15391 struct intel_display_error_state {
15392
15393         u32 power_well_driver;
15394
15395         int num_transcoders;
15396
15397         struct intel_cursor_error_state {
15398                 u32 control;
15399                 u32 position;
15400                 u32 base;
15401                 u32 size;
15402         } cursor[I915_MAX_PIPES];
15403
15404         struct intel_pipe_error_state {
15405                 bool power_domain_on;
15406                 u32 source;
15407                 u32 stat;
15408         } pipe[I915_MAX_PIPES];
15409
15410         struct intel_plane_error_state {
15411                 u32 control;
15412                 u32 stride;
15413                 u32 size;
15414                 u32 pos;
15415                 u32 addr;
15416                 u32 surface;
15417                 u32 tile_offset;
15418         } plane[I915_MAX_PIPES];
15419
15420         struct intel_transcoder_error_state {
15421                 bool power_domain_on;
15422                 enum transcoder cpu_transcoder;
15423
15424                 u32 conf;
15425
15426                 u32 htotal;
15427                 u32 hblank;
15428                 u32 hsync;
15429                 u32 vtotal;
15430                 u32 vblank;
15431                 u32 vsync;
15432         } transcoder[4];
15433 };
15434
15435 struct intel_display_error_state *
15436 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15437 {
15438         struct intel_display_error_state *error;
15439         int transcoders[] = {
15440                 TRANSCODER_A,
15441                 TRANSCODER_B,
15442                 TRANSCODER_C,
15443                 TRANSCODER_EDP,
15444         };
15445         int i;
15446
15447         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15448                 return NULL;
15449
15450         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15451         if (error == NULL)
15452                 return NULL;
15453
15454         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15455                 error->power_well_driver =
15456                         I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL));
15457
15458         for_each_pipe(dev_priv, i) {
15459                 error->pipe[i].power_domain_on =
15460                         __intel_display_power_is_enabled(dev_priv,
15461                                                          POWER_DOMAIN_PIPE(i));
15462                 if (!error->pipe[i].power_domain_on)
15463                         continue;
15464
15465                 error->cursor[i].control = I915_READ(CURCNTR(i));
15466                 error->cursor[i].position = I915_READ(CURPOS(i));
15467                 error->cursor[i].base = I915_READ(CURBASE(i));
15468
15469                 error->plane[i].control = I915_READ(DSPCNTR(i));
15470                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15471                 if (INTEL_GEN(dev_priv) <= 3) {
15472                         error->plane[i].size = I915_READ(DSPSIZE(i));
15473                         error->plane[i].pos = I915_READ(DSPPOS(i));
15474                 }
15475                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15476                         error->plane[i].addr = I915_READ(DSPADDR(i));
15477                 if (INTEL_GEN(dev_priv) >= 4) {
15478                         error->plane[i].surface = I915_READ(DSPSURF(i));
15479                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15480                 }
15481
15482                 error->pipe[i].source = I915_READ(PIPESRC(i));
15483
15484                 if (HAS_GMCH_DISPLAY(dev_priv))
15485                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15486         }
15487
15488         /* Note: this does not include DSI transcoders. */
15489         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15490         if (HAS_DDI(dev_priv))
15491                 error->num_transcoders++; /* Account for eDP. */
15492
15493         for (i = 0; i < error->num_transcoders; i++) {
15494                 enum transcoder cpu_transcoder = transcoders[i];
15495
15496                 error->transcoder[i].power_domain_on =
15497                         __intel_display_power_is_enabled(dev_priv,
15498                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15499                 if (!error->transcoder[i].power_domain_on)
15500                         continue;
15501
15502                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15503
15504                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15505                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15506                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15507                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15508                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15509                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15510                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15511         }
15512
15513         return error;
15514 }
15515
15516 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15517
15518 void
15519 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15520                                 struct intel_display_error_state *error)
15521 {
15522         struct drm_i915_private *dev_priv = m->i915;
15523         int i;
15524
15525         if (!error)
15526                 return;
15527
15528         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
15529         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15530                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15531                            error->power_well_driver);
15532         for_each_pipe(dev_priv, i) {
15533                 err_printf(m, "Pipe [%d]:\n", i);
15534                 err_printf(m, "  Power: %s\n",
15535                            onoff(error->pipe[i].power_domain_on));
15536                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15537                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15538
15539                 err_printf(m, "Plane [%d]:\n", i);
15540                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15541                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15542                 if (INTEL_GEN(dev_priv) <= 3) {
15543                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15544                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15545                 }
15546                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15547                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15548                 if (INTEL_GEN(dev_priv) >= 4) {
15549                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15550                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15551                 }
15552
15553                 err_printf(m, "Cursor [%d]:\n", i);
15554                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15555                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15556                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15557         }
15558
15559         for (i = 0; i < error->num_transcoders; i++) {
15560                 err_printf(m, "CPU transcoder: %s\n",
15561                            transcoder_name(error->transcoder[i].cpu_transcoder));
15562                 err_printf(m, "  Power: %s\n",
15563                            onoff(error->transcoder[i].power_domain_on));
15564                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15565                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15566                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15567                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15568                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15569                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15570                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15571         }
15572 }
15573
15574 #endif