]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/gpu/drm/i915/intel_display.c
drm/i915: Unwind vma pinning for intel_pin_and_fence_fb_obj error path
[linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "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
223                 return dev_priv->fdi_pll_freq;
224 }
225
226 static const struct intel_limit intel_limits_i8xx_dac = {
227         .dot = { .min = 25000, .max = 350000 },
228         .vco = { .min = 908000, .max = 1512000 },
229         .n = { .min = 2, .max = 16 },
230         .m = { .min = 96, .max = 140 },
231         .m1 = { .min = 18, .max = 26 },
232         .m2 = { .min = 6, .max = 16 },
233         .p = { .min = 4, .max = 128 },
234         .p1 = { .min = 2, .max = 33 },
235         .p2 = { .dot_limit = 165000,
236                 .p2_slow = 4, .p2_fast = 2 },
237 };
238
239 static const struct intel_limit intel_limits_i8xx_dvo = {
240         .dot = { .min = 25000, .max = 350000 },
241         .vco = { .min = 908000, .max = 1512000 },
242         .n = { .min = 2, .max = 16 },
243         .m = { .min = 96, .max = 140 },
244         .m1 = { .min = 18, .max = 26 },
245         .m2 = { .min = 6, .max = 16 },
246         .p = { .min = 4, .max = 128 },
247         .p1 = { .min = 2, .max = 33 },
248         .p2 = { .dot_limit = 165000,
249                 .p2_slow = 4, .p2_fast = 4 },
250 };
251
252 static const struct intel_limit intel_limits_i8xx_lvds = {
253         .dot = { .min = 25000, .max = 350000 },
254         .vco = { .min = 908000, .max = 1512000 },
255         .n = { .min = 2, .max = 16 },
256         .m = { .min = 96, .max = 140 },
257         .m1 = { .min = 18, .max = 26 },
258         .m2 = { .min = 6, .max = 16 },
259         .p = { .min = 4, .max = 128 },
260         .p1 = { .min = 1, .max = 6 },
261         .p2 = { .dot_limit = 165000,
262                 .p2_slow = 14, .p2_fast = 7 },
263 };
264
265 static const struct intel_limit intel_limits_i9xx_sdvo = {
266         .dot = { .min = 20000, .max = 400000 },
267         .vco = { .min = 1400000, .max = 2800000 },
268         .n = { .min = 1, .max = 6 },
269         .m = { .min = 70, .max = 120 },
270         .m1 = { .min = 8, .max = 18 },
271         .m2 = { .min = 3, .max = 7 },
272         .p = { .min = 5, .max = 80 },
273         .p1 = { .min = 1, .max = 8 },
274         .p2 = { .dot_limit = 200000,
275                 .p2_slow = 10, .p2_fast = 5 },
276 };
277
278 static const struct intel_limit intel_limits_i9xx_lvds = {
279         .dot = { .min = 20000, .max = 400000 },
280         .vco = { .min = 1400000, .max = 2800000 },
281         .n = { .min = 1, .max = 6 },
282         .m = { .min = 70, .max = 120 },
283         .m1 = { .min = 8, .max = 18 },
284         .m2 = { .min = 3, .max = 7 },
285         .p = { .min = 7, .max = 98 },
286         .p1 = { .min = 1, .max = 8 },
287         .p2 = { .dot_limit = 112000,
288                 .p2_slow = 14, .p2_fast = 7 },
289 };
290
291
292 static const struct intel_limit intel_limits_g4x_sdvo = {
293         .dot = { .min = 25000, .max = 270000 },
294         .vco = { .min = 1750000, .max = 3500000},
295         .n = { .min = 1, .max = 4 },
296         .m = { .min = 104, .max = 138 },
297         .m1 = { .min = 17, .max = 23 },
298         .m2 = { .min = 5, .max = 11 },
299         .p = { .min = 10, .max = 30 },
300         .p1 = { .min = 1, .max = 3},
301         .p2 = { .dot_limit = 270000,
302                 .p2_slow = 10,
303                 .p2_fast = 10
304         },
305 };
306
307 static const struct intel_limit intel_limits_g4x_hdmi = {
308         .dot = { .min = 22000, .max = 400000 },
309         .vco = { .min = 1750000, .max = 3500000},
310         .n = { .min = 1, .max = 4 },
311         .m = { .min = 104, .max = 138 },
312         .m1 = { .min = 16, .max = 23 },
313         .m2 = { .min = 5, .max = 11 },
314         .p = { .min = 5, .max = 80 },
315         .p1 = { .min = 1, .max = 8},
316         .p2 = { .dot_limit = 165000,
317                 .p2_slow = 10, .p2_fast = 5 },
318 };
319
320 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
321         .dot = { .min = 20000, .max = 115000 },
322         .vco = { .min = 1750000, .max = 3500000 },
323         .n = { .min = 1, .max = 3 },
324         .m = { .min = 104, .max = 138 },
325         .m1 = { .min = 17, .max = 23 },
326         .m2 = { .min = 5, .max = 11 },
327         .p = { .min = 28, .max = 112 },
328         .p1 = { .min = 2, .max = 8 },
329         .p2 = { .dot_limit = 0,
330                 .p2_slow = 14, .p2_fast = 14
331         },
332 };
333
334 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
335         .dot = { .min = 80000, .max = 224000 },
336         .vco = { .min = 1750000, .max = 3500000 },
337         .n = { .min = 1, .max = 3 },
338         .m = { .min = 104, .max = 138 },
339         .m1 = { .min = 17, .max = 23 },
340         .m2 = { .min = 5, .max = 11 },
341         .p = { .min = 14, .max = 42 },
342         .p1 = { .min = 2, .max = 6 },
343         .p2 = { .dot_limit = 0,
344                 .p2_slow = 7, .p2_fast = 7
345         },
346 };
347
348 static const struct intel_limit intel_limits_pineview_sdvo = {
349         .dot = { .min = 20000, .max = 400000},
350         .vco = { .min = 1700000, .max = 3500000 },
351         /* Pineview's Ncounter is a ring counter */
352         .n = { .min = 3, .max = 6 },
353         .m = { .min = 2, .max = 256 },
354         /* Pineview only has one combined m divider, which we treat as m2. */
355         .m1 = { .min = 0, .max = 0 },
356         .m2 = { .min = 0, .max = 254 },
357         .p = { .min = 5, .max = 80 },
358         .p1 = { .min = 1, .max = 8 },
359         .p2 = { .dot_limit = 200000,
360                 .p2_slow = 10, .p2_fast = 5 },
361 };
362
363 static const struct intel_limit intel_limits_pineview_lvds = {
364         .dot = { .min = 20000, .max = 400000 },
365         .vco = { .min = 1700000, .max = 3500000 },
366         .n = { .min = 3, .max = 6 },
367         .m = { .min = 2, .max = 256 },
368         .m1 = { .min = 0, .max = 0 },
369         .m2 = { .min = 0, .max = 254 },
370         .p = { .min = 7, .max = 112 },
371         .p1 = { .min = 1, .max = 8 },
372         .p2 = { .dot_limit = 112000,
373                 .p2_slow = 14, .p2_fast = 14 },
374 };
375
376 /* Ironlake / Sandybridge
377  *
378  * We calculate clock using (register_value + 2) for N/M1/M2, so here
379  * the range value for them is (actual_value - 2).
380  */
381 static const struct intel_limit intel_limits_ironlake_dac = {
382         .dot = { .min = 25000, .max = 350000 },
383         .vco = { .min = 1760000, .max = 3510000 },
384         .n = { .min = 1, .max = 5 },
385         .m = { .min = 79, .max = 127 },
386         .m1 = { .min = 12, .max = 22 },
387         .m2 = { .min = 5, .max = 9 },
388         .p = { .min = 5, .max = 80 },
389         .p1 = { .min = 1, .max = 8 },
390         .p2 = { .dot_limit = 225000,
391                 .p2_slow = 10, .p2_fast = 5 },
392 };
393
394 static const struct intel_limit intel_limits_ironlake_single_lvds = {
395         .dot = { .min = 25000, .max = 350000 },
396         .vco = { .min = 1760000, .max = 3510000 },
397         .n = { .min = 1, .max = 3 },
398         .m = { .min = 79, .max = 118 },
399         .m1 = { .min = 12, .max = 22 },
400         .m2 = { .min = 5, .max = 9 },
401         .p = { .min = 28, .max = 112 },
402         .p1 = { .min = 2, .max = 8 },
403         .p2 = { .dot_limit = 225000,
404                 .p2_slow = 14, .p2_fast = 14 },
405 };
406
407 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
408         .dot = { .min = 25000, .max = 350000 },
409         .vco = { .min = 1760000, .max = 3510000 },
410         .n = { .min = 1, .max = 3 },
411         .m = { .min = 79, .max = 127 },
412         .m1 = { .min = 12, .max = 22 },
413         .m2 = { .min = 5, .max = 9 },
414         .p = { .min = 14, .max = 56 },
415         .p1 = { .min = 2, .max = 8 },
416         .p2 = { .dot_limit = 225000,
417                 .p2_slow = 7, .p2_fast = 7 },
418 };
419
420 /* LVDS 100mhz refclk limits. */
421 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
422         .dot = { .min = 25000, .max = 350000 },
423         .vco = { .min = 1760000, .max = 3510000 },
424         .n = { .min = 1, .max = 2 },
425         .m = { .min = 79, .max = 126 },
426         .m1 = { .min = 12, .max = 22 },
427         .m2 = { .min = 5, .max = 9 },
428         .p = { .min = 28, .max = 112 },
429         .p1 = { .min = 2, .max = 8 },
430         .p2 = { .dot_limit = 225000,
431                 .p2_slow = 14, .p2_fast = 14 },
432 };
433
434 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
435         .dot = { .min = 25000, .max = 350000 },
436         .vco = { .min = 1760000, .max = 3510000 },
437         .n = { .min = 1, .max = 3 },
438         .m = { .min = 79, .max = 126 },
439         .m1 = { .min = 12, .max = 22 },
440         .m2 = { .min = 5, .max = 9 },
441         .p = { .min = 14, .max = 42 },
442         .p1 = { .min = 2, .max = 6 },
443         .p2 = { .dot_limit = 225000,
444                 .p2_slow = 7, .p2_fast = 7 },
445 };
446
447 static const struct intel_limit intel_limits_vlv = {
448          /*
449           * These are the data rate limits (measured in fast clocks)
450           * since those are the strictest limits we have. The fast
451           * clock and actual rate limits are more relaxed, so checking
452           * them would make no difference.
453           */
454         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
455         .vco = { .min = 4000000, .max = 6000000 },
456         .n = { .min = 1, .max = 7 },
457         .m1 = { .min = 2, .max = 3 },
458         .m2 = { .min = 11, .max = 156 },
459         .p1 = { .min = 2, .max = 3 },
460         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
461 };
462
463 static const struct intel_limit intel_limits_chv = {
464         /*
465          * These are the data rate limits (measured in fast clocks)
466          * since those are the strictest limits we have.  The fast
467          * clock and actual rate limits are more relaxed, so checking
468          * them would make no difference.
469          */
470         .dot = { .min = 25000 * 5, .max = 540000 * 5},
471         .vco = { .min = 4800000, .max = 6480000 },
472         .n = { .min = 1, .max = 1 },
473         .m1 = { .min = 2, .max = 2 },
474         .m2 = { .min = 24 << 22, .max = 175 << 22 },
475         .p1 = { .min = 2, .max = 4 },
476         .p2 = { .p2_slow = 1, .p2_fast = 14 },
477 };
478
479 static const struct intel_limit intel_limits_bxt = {
480         /* FIXME: find real dot limits */
481         .dot = { .min = 0, .max = INT_MAX },
482         .vco = { .min = 4800000, .max = 6700000 },
483         .n = { .min = 1, .max = 1 },
484         .m1 = { .min = 2, .max = 2 },
485         /* FIXME: find real m2 limits */
486         .m2 = { .min = 2 << 22, .max = 255 << 22 },
487         .p1 = { .min = 2, .max = 4 },
488         .p2 = { .p2_slow = 1, .p2_fast = 20 },
489 };
490
491 static bool
492 needs_modeset(const struct drm_crtc_state *state)
493 {
494         return drm_atomic_crtc_needs_modeset(state);
495 }
496
497 /*
498  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
499  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
500  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
501  * The helpers' return value is the rate of the clock that is fed to the
502  * display engine's pipe which can be the above fast dot clock rate or a
503  * divided-down version of it.
504  */
505 /* m1 is reserved as 0 in Pineview, n is a ring counter */
506 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
507 {
508         clock->m = clock->m2 + 2;
509         clock->p = clock->p1 * clock->p2;
510         if (WARN_ON(clock->n == 0 || clock->p == 0))
511                 return 0;
512         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
513         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
514
515         return clock->dot;
516 }
517
518 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
519 {
520         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
521 }
522
523 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
524 {
525         clock->m = i9xx_dpll_compute_m(clock);
526         clock->p = clock->p1 * clock->p2;
527         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
528                 return 0;
529         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
530         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
531
532         return clock->dot;
533 }
534
535 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
536 {
537         clock->m = clock->m1 * clock->m2;
538         clock->p = clock->p1 * clock->p2;
539         if (WARN_ON(clock->n == 0 || clock->p == 0))
540                 return 0;
541         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
542         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
543
544         return clock->dot / 5;
545 }
546
547 int chv_calc_dpll_params(int refclk, struct dpll *clock)
548 {
549         clock->m = clock->m1 * clock->m2;
550         clock->p = clock->p1 * clock->p2;
551         if (WARN_ON(clock->n == 0 || clock->p == 0))
552                 return 0;
553         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
554                         clock->n << 22);
555         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
556
557         return clock->dot / 5;
558 }
559
560 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
561
562 /*
563  * Returns whether the given set of divisors are valid for a given refclk with
564  * the given connectors.
565  */
566 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
567                                const struct intel_limit *limit,
568                                const struct dpll *clock)
569 {
570         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
571                 INTELPllInvalid("n out of range\n");
572         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
573                 INTELPllInvalid("p1 out of range\n");
574         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
575                 INTELPllInvalid("m2 out of range\n");
576         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
577                 INTELPllInvalid("m1 out of range\n");
578
579         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
580             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
581                 if (clock->m1 <= clock->m2)
582                         INTELPllInvalid("m1 <= m2\n");
583
584         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
585             !IS_GEN9_LP(dev_priv)) {
586                 if (clock->p < limit->p.min || limit->p.max < clock->p)
587                         INTELPllInvalid("p out of range\n");
588                 if (clock->m < limit->m.min || limit->m.max < clock->m)
589                         INTELPllInvalid("m out of range\n");
590         }
591
592         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
593                 INTELPllInvalid("vco out of range\n");
594         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
595          * connector, etc., rather than just a single range.
596          */
597         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
598                 INTELPllInvalid("dot out of range\n");
599
600         return true;
601 }
602
603 static int
604 i9xx_select_p2_div(const struct intel_limit *limit,
605                    const struct intel_crtc_state *crtc_state,
606                    int target)
607 {
608         struct drm_device *dev = crtc_state->base.crtc->dev;
609
610         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
611                 /*
612                  * For LVDS just rely on its current settings for dual-channel.
613                  * We haven't figured out how to reliably set up different
614                  * single/dual channel state, if we even can.
615                  */
616                 if (intel_is_dual_link_lvds(dev))
617                         return limit->p2.p2_fast;
618                 else
619                         return limit->p2.p2_slow;
620         } else {
621                 if (target < limit->p2.dot_limit)
622                         return limit->p2.p2_slow;
623                 else
624                         return limit->p2.p2_fast;
625         }
626 }
627
628 /*
629  * Returns a set of divisors for the desired target clock with the given
630  * refclk, or FALSE.  The returned values represent the clock equation:
631  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
632  *
633  * Target and reference clocks are specified in kHz.
634  *
635  * If match_clock is provided, then best_clock P divider must match the P
636  * divider from @match_clock used for LVDS downclocking.
637  */
638 static bool
639 i9xx_find_best_dpll(const struct intel_limit *limit,
640                     struct intel_crtc_state *crtc_state,
641                     int target, int refclk, struct dpll *match_clock,
642                     struct dpll *best_clock)
643 {
644         struct drm_device *dev = crtc_state->base.crtc->dev;
645         struct dpll clock;
646         int err = target;
647
648         memset(best_clock, 0, sizeof(*best_clock));
649
650         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
651
652         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
653              clock.m1++) {
654                 for (clock.m2 = limit->m2.min;
655                      clock.m2 <= limit->m2.max; clock.m2++) {
656                         if (clock.m2 >= clock.m1)
657                                 break;
658                         for (clock.n = limit->n.min;
659                              clock.n <= limit->n.max; clock.n++) {
660                                 for (clock.p1 = limit->p1.min;
661                                         clock.p1 <= limit->p1.max; clock.p1++) {
662                                         int this_err;
663
664                                         i9xx_calc_dpll_params(refclk, &clock);
665                                         if (!intel_PLL_is_valid(to_i915(dev),
666                                                                 limit,
667                                                                 &clock))
668                                                 continue;
669                                         if (match_clock &&
670                                             clock.p != match_clock->p)
671                                                 continue;
672
673                                         this_err = abs(clock.dot - target);
674                                         if (this_err < err) {
675                                                 *best_clock = clock;
676                                                 err = this_err;
677                                         }
678                                 }
679                         }
680                 }
681         }
682
683         return (err != target);
684 }
685
686 /*
687  * Returns a set of divisors for the desired target clock with the given
688  * refclk, or FALSE.  The returned values represent the clock equation:
689  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
690  *
691  * Target and reference clocks are specified in kHz.
692  *
693  * If match_clock is provided, then best_clock P divider must match the P
694  * divider from @match_clock used for LVDS downclocking.
695  */
696 static bool
697 pnv_find_best_dpll(const struct intel_limit *limit,
698                    struct intel_crtc_state *crtc_state,
699                    int target, int refclk, struct dpll *match_clock,
700                    struct dpll *best_clock)
701 {
702         struct drm_device *dev = crtc_state->base.crtc->dev;
703         struct dpll clock;
704         int err = target;
705
706         memset(best_clock, 0, sizeof(*best_clock));
707
708         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
709
710         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
711              clock.m1++) {
712                 for (clock.m2 = limit->m2.min;
713                      clock.m2 <= limit->m2.max; clock.m2++) {
714                         for (clock.n = limit->n.min;
715                              clock.n <= limit->n.max; clock.n++) {
716                                 for (clock.p1 = limit->p1.min;
717                                         clock.p1 <= limit->p1.max; clock.p1++) {
718                                         int this_err;
719
720                                         pnv_calc_dpll_params(refclk, &clock);
721                                         if (!intel_PLL_is_valid(to_i915(dev),
722                                                                 limit,
723                                                                 &clock))
724                                                 continue;
725                                         if (match_clock &&
726                                             clock.p != match_clock->p)
727                                                 continue;
728
729                                         this_err = abs(clock.dot - target);
730                                         if (this_err < err) {
731                                                 *best_clock = clock;
732                                                 err = this_err;
733                                         }
734                                 }
735                         }
736                 }
737         }
738
739         return (err != target);
740 }
741
742 /*
743  * Returns a set of divisors for the desired target clock with the given
744  * refclk, or FALSE.  The returned values represent the clock equation:
745  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
746  *
747  * Target and reference clocks are specified in kHz.
748  *
749  * If match_clock is provided, then best_clock P divider must match the P
750  * divider from @match_clock used for LVDS downclocking.
751  */
752 static bool
753 g4x_find_best_dpll(const struct intel_limit *limit,
754                    struct intel_crtc_state *crtc_state,
755                    int target, int refclk, struct dpll *match_clock,
756                    struct dpll *best_clock)
757 {
758         struct drm_device *dev = crtc_state->base.crtc->dev;
759         struct dpll clock;
760         int max_n;
761         bool found = false;
762         /* approximately equals target * 0.00585 */
763         int err_most = (target >> 8) + (target >> 9);
764
765         memset(best_clock, 0, sizeof(*best_clock));
766
767         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
768
769         max_n = limit->n.max;
770         /* based on hardware requirement, prefer smaller n to precision */
771         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
772                 /* based on hardware requirement, prefere larger m1,m2 */
773                 for (clock.m1 = limit->m1.max;
774                      clock.m1 >= limit->m1.min; clock.m1--) {
775                         for (clock.m2 = limit->m2.max;
776                              clock.m2 >= limit->m2.min; clock.m2--) {
777                                 for (clock.p1 = limit->p1.max;
778                                      clock.p1 >= limit->p1.min; clock.p1--) {
779                                         int this_err;
780
781                                         i9xx_calc_dpll_params(refclk, &clock);
782                                         if (!intel_PLL_is_valid(to_i915(dev),
783                                                                 limit,
784                                                                 &clock))
785                                                 continue;
786
787                                         this_err = abs(clock.dot - target);
788                                         if (this_err < err_most) {
789                                                 *best_clock = clock;
790                                                 err_most = this_err;
791                                                 max_n = clock.n;
792                                                 found = true;
793                                         }
794                                 }
795                         }
796                 }
797         }
798         return found;
799 }
800
801 /*
802  * Check if the calculated PLL configuration is more optimal compared to the
803  * best configuration and error found so far. Return the calculated error.
804  */
805 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
806                                const struct dpll *calculated_clock,
807                                const struct dpll *best_clock,
808                                unsigned int best_error_ppm,
809                                unsigned int *error_ppm)
810 {
811         /*
812          * For CHV ignore the error and consider only the P value.
813          * Prefer a bigger P value based on HW requirements.
814          */
815         if (IS_CHERRYVIEW(to_i915(dev))) {
816                 *error_ppm = 0;
817
818                 return calculated_clock->p > best_clock->p;
819         }
820
821         if (WARN_ON_ONCE(!target_freq))
822                 return false;
823
824         *error_ppm = div_u64(1000000ULL *
825                                 abs(target_freq - calculated_clock->dot),
826                              target_freq);
827         /*
828          * Prefer a better P value over a better (smaller) error if the error
829          * is small. Ensure this preference for future configurations too by
830          * setting the error to 0.
831          */
832         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
833                 *error_ppm = 0;
834
835                 return true;
836         }
837
838         return *error_ppm + 10 < best_error_ppm;
839 }
840
841 /*
842  * Returns a set of divisors for the desired target clock with the given
843  * refclk, or FALSE.  The returned values represent the clock equation:
844  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
845  */
846 static bool
847 vlv_find_best_dpll(const struct intel_limit *limit,
848                    struct intel_crtc_state *crtc_state,
849                    int target, int refclk, struct dpll *match_clock,
850                    struct dpll *best_clock)
851 {
852         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
853         struct drm_device *dev = crtc->base.dev;
854         struct dpll clock;
855         unsigned int bestppm = 1000000;
856         /* min update 19.2 MHz */
857         int max_n = min(limit->n.max, refclk / 19200);
858         bool found = false;
859
860         target *= 5; /* fast clock */
861
862         memset(best_clock, 0, sizeof(*best_clock));
863
864         /* based on hardware requirement, prefer smaller n to precision */
865         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
866                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
867                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
868                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
869                                 clock.p = clock.p1 * clock.p2;
870                                 /* based on hardware requirement, prefer bigger m1,m2 values */
871                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
872                                         unsigned int ppm;
873
874                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
875                                                                      refclk * clock.m1);
876
877                                         vlv_calc_dpll_params(refclk, &clock);
878
879                                         if (!intel_PLL_is_valid(to_i915(dev),
880                                                                 limit,
881                                                                 &clock))
882                                                 continue;
883
884                                         if (!vlv_PLL_is_optimal(dev, target,
885                                                                 &clock,
886                                                                 best_clock,
887                                                                 bestppm, &ppm))
888                                                 continue;
889
890                                         *best_clock = clock;
891                                         bestppm = ppm;
892                                         found = true;
893                                 }
894                         }
895                 }
896         }
897
898         return found;
899 }
900
901 /*
902  * Returns a set of divisors for the desired target clock with the given
903  * refclk, or FALSE.  The returned values represent the clock equation:
904  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
905  */
906 static bool
907 chv_find_best_dpll(const struct intel_limit *limit,
908                    struct intel_crtc_state *crtc_state,
909                    int target, int refclk, struct dpll *match_clock,
910                    struct dpll *best_clock)
911 {
912         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
913         struct drm_device *dev = crtc->base.dev;
914         unsigned int best_error_ppm;
915         struct dpll clock;
916         uint64_t m2;
917         int found = false;
918
919         memset(best_clock, 0, sizeof(*best_clock));
920         best_error_ppm = 1000000;
921
922         /*
923          * Based on hardware doc, the n always set to 1, and m1 always
924          * set to 2.  If requires to support 200Mhz refclk, we need to
925          * revisit this because n may not 1 anymore.
926          */
927         clock.n = 1, clock.m1 = 2;
928         target *= 5;    /* fast clock */
929
930         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
931                 for (clock.p2 = limit->p2.p2_fast;
932                                 clock.p2 >= limit->p2.p2_slow;
933                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
934                         unsigned int error_ppm;
935
936                         clock.p = clock.p1 * clock.p2;
937
938                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
939                                         clock.n) << 22, refclk * clock.m1);
940
941                         if (m2 > INT_MAX/clock.m1)
942                                 continue;
943
944                         clock.m2 = m2;
945
946                         chv_calc_dpll_params(refclk, &clock);
947
948                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
949                                 continue;
950
951                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
952                                                 best_error_ppm, &error_ppm))
953                                 continue;
954
955                         *best_clock = clock;
956                         best_error_ppm = error_ppm;
957                         found = true;
958                 }
959         }
960
961         return found;
962 }
963
964 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
965                         struct dpll *best_clock)
966 {
967         int refclk = 100000;
968         const struct intel_limit *limit = &intel_limits_bxt;
969
970         return chv_find_best_dpll(limit, crtc_state,
971                                   target_clock, refclk, NULL, best_clock);
972 }
973
974 bool intel_crtc_active(struct intel_crtc *crtc)
975 {
976         /* Be paranoid as we can arrive here with only partial
977          * state retrieved from the hardware during setup.
978          *
979          * We can ditch the adjusted_mode.crtc_clock check as soon
980          * as Haswell has gained clock readout/fastboot support.
981          *
982          * We can ditch the crtc->primary->fb check as soon as we can
983          * properly reconstruct framebuffers.
984          *
985          * FIXME: The intel_crtc->active here should be switched to
986          * crtc->state->active once we have proper CRTC states wired up
987          * for atomic.
988          */
989         return crtc->active && crtc->base.primary->state->fb &&
990                 crtc->config->base.adjusted_mode.crtc_clock;
991 }
992
993 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
994                                              enum pipe pipe)
995 {
996         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
997
998         return crtc->config->cpu_transcoder;
999 }
1000
1001 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
1002                                     enum pipe pipe)
1003 {
1004         i915_reg_t reg = PIPEDSL(pipe);
1005         u32 line1, line2;
1006         u32 line_mask;
1007
1008         if (IS_GEN2(dev_priv))
1009                 line_mask = DSL_LINEMASK_GEN2;
1010         else
1011                 line_mask = DSL_LINEMASK_GEN3;
1012
1013         line1 = I915_READ(reg) & line_mask;
1014         msleep(5);
1015         line2 = I915_READ(reg) & line_mask;
1016
1017         return line1 != line2;
1018 }
1019
1020 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1021 {
1022         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1023         enum pipe pipe = crtc->pipe;
1024
1025         /* Wait for the display line to settle/start moving */
1026         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1027                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1028                           pipe_name(pipe), onoff(state));
1029 }
1030
1031 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1032 {
1033         wait_for_pipe_scanline_moving(crtc, false);
1034 }
1035
1036 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1037 {
1038         wait_for_pipe_scanline_moving(crtc, true);
1039 }
1040
1041 static void
1042 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1043 {
1044         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1045         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1046
1047         if (INTEL_GEN(dev_priv) >= 4) {
1048                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1049                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1050
1051                 /* Wait for the Pipe State to go off */
1052                 if (intel_wait_for_register(dev_priv,
1053                                             reg, I965_PIPECONF_ACTIVE, 0,
1054                                             100))
1055                         WARN(1, "pipe_off wait timed out\n");
1056         } else {
1057                 intel_wait_for_pipe_scanline_stopped(crtc);
1058         }
1059 }
1060
1061 /* Only for pre-ILK configs */
1062 void assert_pll(struct drm_i915_private *dev_priv,
1063                 enum pipe pipe, bool state)
1064 {
1065         u32 val;
1066         bool cur_state;
1067
1068         val = I915_READ(DPLL(pipe));
1069         cur_state = !!(val & DPLL_VCO_ENABLE);
1070         I915_STATE_WARN(cur_state != state,
1071              "PLL state assertion failure (expected %s, current %s)\n",
1072                         onoff(state), onoff(cur_state));
1073 }
1074
1075 /* XXX: the dsi pll is shared between MIPI DSI ports */
1076 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1077 {
1078         u32 val;
1079         bool cur_state;
1080
1081         mutex_lock(&dev_priv->sb_lock);
1082         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1083         mutex_unlock(&dev_priv->sb_lock);
1084
1085         cur_state = val & DSI_PLL_VCO_EN;
1086         I915_STATE_WARN(cur_state != state,
1087              "DSI PLL state assertion failure (expected %s, current %s)\n",
1088                         onoff(state), onoff(cur_state));
1089 }
1090
1091 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1092                           enum pipe pipe, bool state)
1093 {
1094         bool cur_state;
1095         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1096                                                                       pipe);
1097
1098         if (HAS_DDI(dev_priv)) {
1099                 /* DDI does not have a specific FDI_TX register */
1100                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1101                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1102         } else {
1103                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1104                 cur_state = !!(val & FDI_TX_ENABLE);
1105         }
1106         I915_STATE_WARN(cur_state != state,
1107              "FDI TX state assertion failure (expected %s, current %s)\n",
1108                         onoff(state), onoff(cur_state));
1109 }
1110 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1111 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1112
1113 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1114                           enum pipe pipe, bool state)
1115 {
1116         u32 val;
1117         bool cur_state;
1118
1119         val = I915_READ(FDI_RX_CTL(pipe));
1120         cur_state = !!(val & FDI_RX_ENABLE);
1121         I915_STATE_WARN(cur_state != state,
1122              "FDI RX state assertion failure (expected %s, current %s)\n",
1123                         onoff(state), onoff(cur_state));
1124 }
1125 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1126 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1127
1128 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1129                                       enum pipe pipe)
1130 {
1131         u32 val;
1132
1133         /* ILK FDI PLL is always enabled */
1134         if (IS_GEN5(dev_priv))
1135                 return;
1136
1137         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1138         if (HAS_DDI(dev_priv))
1139                 return;
1140
1141         val = I915_READ(FDI_TX_CTL(pipe));
1142         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1143 }
1144
1145 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1146                        enum pipe pipe, bool state)
1147 {
1148         u32 val;
1149         bool cur_state;
1150
1151         val = I915_READ(FDI_RX_CTL(pipe));
1152         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1153         I915_STATE_WARN(cur_state != state,
1154              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1155                         onoff(state), onoff(cur_state));
1156 }
1157
1158 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1159 {
1160         i915_reg_t pp_reg;
1161         u32 val;
1162         enum pipe panel_pipe = PIPE_A;
1163         bool locked = true;
1164
1165         if (WARN_ON(HAS_DDI(dev_priv)))
1166                 return;
1167
1168         if (HAS_PCH_SPLIT(dev_priv)) {
1169                 u32 port_sel;
1170
1171                 pp_reg = PP_CONTROL(0);
1172                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1173
1174                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1175                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1176                         panel_pipe = PIPE_B;
1177                 /* XXX: else fix for eDP */
1178         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1179                 /* presumably write lock depends on pipe, not port select */
1180                 pp_reg = PP_CONTROL(pipe);
1181                 panel_pipe = pipe;
1182         } else {
1183                 pp_reg = PP_CONTROL(0);
1184                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1185                         panel_pipe = PIPE_B;
1186         }
1187
1188         val = I915_READ(pp_reg);
1189         if (!(val & PANEL_POWER_ON) ||
1190             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1191                 locked = false;
1192
1193         I915_STATE_WARN(panel_pipe == pipe && locked,
1194              "panel assertion failure, pipe %c regs locked\n",
1195              pipe_name(pipe));
1196 }
1197
1198 void assert_pipe(struct drm_i915_private *dev_priv,
1199                  enum pipe pipe, bool state)
1200 {
1201         bool cur_state;
1202         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1203                                                                       pipe);
1204         enum intel_display_power_domain power_domain;
1205
1206         /* we keep both pipes enabled on 830 */
1207         if (IS_I830(dev_priv))
1208                 state = true;
1209
1210         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1211         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1212                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1213                 cur_state = !!(val & PIPECONF_ENABLE);
1214
1215                 intel_display_power_put(dev_priv, power_domain);
1216         } else {
1217                 cur_state = false;
1218         }
1219
1220         I915_STATE_WARN(cur_state != state,
1221              "pipe %c assertion failure (expected %s, current %s)\n",
1222                         pipe_name(pipe), onoff(state), onoff(cur_state));
1223 }
1224
1225 static void assert_plane(struct intel_plane *plane, bool state)
1226 {
1227         bool cur_state = plane->get_hw_state(plane);
1228
1229         I915_STATE_WARN(cur_state != state,
1230                         "%s assertion failure (expected %s, current %s)\n",
1231                         plane->base.name, onoff(state), onoff(cur_state));
1232 }
1233
1234 #define assert_plane_enabled(p) assert_plane(p, true)
1235 #define assert_plane_disabled(p) assert_plane(p, false)
1236
1237 static void assert_planes_disabled(struct intel_crtc *crtc)
1238 {
1239         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1240         struct intel_plane *plane;
1241
1242         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1243                 assert_plane_disabled(plane);
1244 }
1245
1246 static void assert_vblank_disabled(struct drm_crtc *crtc)
1247 {
1248         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1249                 drm_crtc_vblank_put(crtc);
1250 }
1251
1252 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1253                                     enum pipe pipe)
1254 {
1255         u32 val;
1256         bool enabled;
1257
1258         val = I915_READ(PCH_TRANSCONF(pipe));
1259         enabled = !!(val & TRANS_ENABLE);
1260         I915_STATE_WARN(enabled,
1261              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1262              pipe_name(pipe));
1263 }
1264
1265 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1266                             enum pipe pipe, u32 port_sel, u32 val)
1267 {
1268         if ((val & DP_PORT_EN) == 0)
1269                 return false;
1270
1271         if (HAS_PCH_CPT(dev_priv)) {
1272                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1273                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1274                         return false;
1275         } else if (IS_CHERRYVIEW(dev_priv)) {
1276                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1277                         return false;
1278         } else {
1279                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1280                         return false;
1281         }
1282         return true;
1283 }
1284
1285 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1286                               enum pipe pipe, u32 val)
1287 {
1288         if ((val & SDVO_ENABLE) == 0)
1289                 return false;
1290
1291         if (HAS_PCH_CPT(dev_priv)) {
1292                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1293                         return false;
1294         } else if (IS_CHERRYVIEW(dev_priv)) {
1295                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1296                         return false;
1297         } else {
1298                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1299                         return false;
1300         }
1301         return true;
1302 }
1303
1304 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1305                               enum pipe pipe, u32 val)
1306 {
1307         if ((val & LVDS_PORT_EN) == 0)
1308                 return false;
1309
1310         if (HAS_PCH_CPT(dev_priv)) {
1311                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1312                         return false;
1313         } else {
1314                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1315                         return false;
1316         }
1317         return true;
1318 }
1319
1320 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1321                               enum pipe pipe, u32 val)
1322 {
1323         if ((val & ADPA_DAC_ENABLE) == 0)
1324                 return false;
1325         if (HAS_PCH_CPT(dev_priv)) {
1326                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1327                         return false;
1328         } else {
1329                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1330                         return false;
1331         }
1332         return true;
1333 }
1334
1335 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1336                                    enum pipe pipe, i915_reg_t reg,
1337                                    u32 port_sel)
1338 {
1339         u32 val = I915_READ(reg);
1340         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1341              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1342              i915_mmio_reg_offset(reg), pipe_name(pipe));
1343
1344         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1345              && (val & DP_PIPEB_SELECT),
1346              "IBX PCH dp port still using transcoder B\n");
1347 }
1348
1349 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1350                                      enum pipe pipe, i915_reg_t reg)
1351 {
1352         u32 val = I915_READ(reg);
1353         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1354              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1355              i915_mmio_reg_offset(reg), pipe_name(pipe));
1356
1357         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1358              && (val & SDVO_PIPE_B_SELECT),
1359              "IBX PCH hdmi port still using transcoder B\n");
1360 }
1361
1362 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1363                                       enum pipe pipe)
1364 {
1365         u32 val;
1366
1367         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1368         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1369         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1370
1371         val = I915_READ(PCH_ADPA);
1372         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1373              "PCH VGA enabled on transcoder %c, should be disabled\n",
1374              pipe_name(pipe));
1375
1376         val = I915_READ(PCH_LVDS);
1377         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1378              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1379              pipe_name(pipe));
1380
1381         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1382         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1383         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1384 }
1385
1386 static void _vlv_enable_pll(struct intel_crtc *crtc,
1387                             const struct intel_crtc_state *pipe_config)
1388 {
1389         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1390         enum pipe pipe = crtc->pipe;
1391
1392         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1393         POSTING_READ(DPLL(pipe));
1394         udelay(150);
1395
1396         if (intel_wait_for_register(dev_priv,
1397                                     DPLL(pipe),
1398                                     DPLL_LOCK_VLV,
1399                                     DPLL_LOCK_VLV,
1400                                     1))
1401                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1402 }
1403
1404 static void vlv_enable_pll(struct intel_crtc *crtc,
1405                            const struct intel_crtc_state *pipe_config)
1406 {
1407         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1408         enum pipe pipe = crtc->pipe;
1409
1410         assert_pipe_disabled(dev_priv, pipe);
1411
1412         /* PLL is protected by panel, make sure we can write it */
1413         assert_panel_unlocked(dev_priv, pipe);
1414
1415         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1416                 _vlv_enable_pll(crtc, pipe_config);
1417
1418         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1419         POSTING_READ(DPLL_MD(pipe));
1420 }
1421
1422
1423 static void _chv_enable_pll(struct intel_crtc *crtc,
1424                             const struct intel_crtc_state *pipe_config)
1425 {
1426         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1427         enum pipe pipe = crtc->pipe;
1428         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1429         u32 tmp;
1430
1431         mutex_lock(&dev_priv->sb_lock);
1432
1433         /* Enable back the 10bit clock to display controller */
1434         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1435         tmp |= DPIO_DCLKP_EN;
1436         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1437
1438         mutex_unlock(&dev_priv->sb_lock);
1439
1440         /*
1441          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1442          */
1443         udelay(1);
1444
1445         /* Enable PLL */
1446         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1447
1448         /* Check PLL is locked */
1449         if (intel_wait_for_register(dev_priv,
1450                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1451                                     1))
1452                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1453 }
1454
1455 static void chv_enable_pll(struct intel_crtc *crtc,
1456                            const struct intel_crtc_state *pipe_config)
1457 {
1458         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1459         enum pipe pipe = crtc->pipe;
1460
1461         assert_pipe_disabled(dev_priv, pipe);
1462
1463         /* PLL is protected by panel, make sure we can write it */
1464         assert_panel_unlocked(dev_priv, pipe);
1465
1466         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1467                 _chv_enable_pll(crtc, pipe_config);
1468
1469         if (pipe != PIPE_A) {
1470                 /*
1471                  * WaPixelRepeatModeFixForC0:chv
1472                  *
1473                  * DPLLCMD is AWOL. Use chicken bits to propagate
1474                  * the value from DPLLBMD to either pipe B or C.
1475                  */
1476                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1477                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1478                 I915_WRITE(CBR4_VLV, 0);
1479                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1480
1481                 /*
1482                  * DPLLB VGA mode also seems to cause problems.
1483                  * We should always have it disabled.
1484                  */
1485                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1486         } else {
1487                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1488                 POSTING_READ(DPLL_MD(pipe));
1489         }
1490 }
1491
1492 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1493 {
1494         struct intel_crtc *crtc;
1495         int count = 0;
1496
1497         for_each_intel_crtc(&dev_priv->drm, crtc) {
1498                 count += crtc->base.state->active &&
1499                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1500         }
1501
1502         return count;
1503 }
1504
1505 static void i9xx_enable_pll(struct intel_crtc *crtc,
1506                             const struct intel_crtc_state *crtc_state)
1507 {
1508         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1509         i915_reg_t reg = DPLL(crtc->pipe);
1510         u32 dpll = crtc_state->dpll_hw_state.dpll;
1511         int i;
1512
1513         assert_pipe_disabled(dev_priv, crtc->pipe);
1514
1515         /* PLL is protected by panel, make sure we can write it */
1516         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1517                 assert_panel_unlocked(dev_priv, crtc->pipe);
1518
1519         /* Enable DVO 2x clock on both PLLs if necessary */
1520         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1521                 /*
1522                  * It appears to be important that we don't enable this
1523                  * for the current pipe before otherwise configuring the
1524                  * PLL. No idea how this should be handled if multiple
1525                  * DVO outputs are enabled simultaneosly.
1526                  */
1527                 dpll |= DPLL_DVO_2X_MODE;
1528                 I915_WRITE(DPLL(!crtc->pipe),
1529                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1530         }
1531
1532         /*
1533          * Apparently we need to have VGA mode enabled prior to changing
1534          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1535          * dividers, even though the register value does change.
1536          */
1537         I915_WRITE(reg, 0);
1538
1539         I915_WRITE(reg, dpll);
1540
1541         /* Wait for the clocks to stabilize. */
1542         POSTING_READ(reg);
1543         udelay(150);
1544
1545         if (INTEL_GEN(dev_priv) >= 4) {
1546                 I915_WRITE(DPLL_MD(crtc->pipe),
1547                            crtc_state->dpll_hw_state.dpll_md);
1548         } else {
1549                 /* The pixel multiplier can only be updated once the
1550                  * DPLL is enabled and the clocks are stable.
1551                  *
1552                  * So write it again.
1553                  */
1554                 I915_WRITE(reg, dpll);
1555         }
1556
1557         /* We do this three times for luck */
1558         for (i = 0; i < 3; i++) {
1559                 I915_WRITE(reg, dpll);
1560                 POSTING_READ(reg);
1561                 udelay(150); /* wait for warmup */
1562         }
1563 }
1564
1565 static void i9xx_disable_pll(struct intel_crtc *crtc)
1566 {
1567         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1568         enum pipe pipe = crtc->pipe;
1569
1570         /* Disable DVO 2x clock on both PLLs if necessary */
1571         if (IS_I830(dev_priv) &&
1572             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1573             !intel_num_dvo_pipes(dev_priv)) {
1574                 I915_WRITE(DPLL(PIPE_B),
1575                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1576                 I915_WRITE(DPLL(PIPE_A),
1577                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1578         }
1579
1580         /* Don't disable pipe or pipe PLLs if needed */
1581         if (IS_I830(dev_priv))
1582                 return;
1583
1584         /* Make sure the pipe isn't still relying on us */
1585         assert_pipe_disabled(dev_priv, pipe);
1586
1587         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1588         POSTING_READ(DPLL(pipe));
1589 }
1590
1591 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1592 {
1593         u32 val;
1594
1595         /* Make sure the pipe isn't still relying on us */
1596         assert_pipe_disabled(dev_priv, pipe);
1597
1598         val = DPLL_INTEGRATED_REF_CLK_VLV |
1599                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1600         if (pipe != PIPE_A)
1601                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1602
1603         I915_WRITE(DPLL(pipe), val);
1604         POSTING_READ(DPLL(pipe));
1605 }
1606
1607 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1608 {
1609         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1610         u32 val;
1611
1612         /* Make sure the pipe isn't still relying on us */
1613         assert_pipe_disabled(dev_priv, pipe);
1614
1615         val = DPLL_SSC_REF_CLK_CHV |
1616                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1617         if (pipe != PIPE_A)
1618                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1619
1620         I915_WRITE(DPLL(pipe), val);
1621         POSTING_READ(DPLL(pipe));
1622
1623         mutex_lock(&dev_priv->sb_lock);
1624
1625         /* Disable 10bit clock to display controller */
1626         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1627         val &= ~DPIO_DCLKP_EN;
1628         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1629
1630         mutex_unlock(&dev_priv->sb_lock);
1631 }
1632
1633 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1634                          struct intel_digital_port *dport,
1635                          unsigned int expected_mask)
1636 {
1637         u32 port_mask;
1638         i915_reg_t dpll_reg;
1639
1640         switch (dport->base.port) {
1641         case PORT_B:
1642                 port_mask = DPLL_PORTB_READY_MASK;
1643                 dpll_reg = DPLL(0);
1644                 break;
1645         case PORT_C:
1646                 port_mask = DPLL_PORTC_READY_MASK;
1647                 dpll_reg = DPLL(0);
1648                 expected_mask <<= 4;
1649                 break;
1650         case PORT_D:
1651                 port_mask = DPLL_PORTD_READY_MASK;
1652                 dpll_reg = DPIO_PHY_STATUS;
1653                 break;
1654         default:
1655                 BUG();
1656         }
1657
1658         if (intel_wait_for_register(dev_priv,
1659                                     dpll_reg, port_mask, expected_mask,
1660                                     1000))
1661                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1662                      port_name(dport->base.port),
1663                      I915_READ(dpll_reg) & port_mask, expected_mask);
1664 }
1665
1666 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1667                                            enum pipe pipe)
1668 {
1669         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1670                                                                 pipe);
1671         i915_reg_t reg;
1672         uint32_t val, pipeconf_val;
1673
1674         /* Make sure PCH DPLL is enabled */
1675         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1676
1677         /* FDI must be feeding us bits for PCH ports */
1678         assert_fdi_tx_enabled(dev_priv, pipe);
1679         assert_fdi_rx_enabled(dev_priv, pipe);
1680
1681         if (HAS_PCH_CPT(dev_priv)) {
1682                 /* Workaround: Set the timing override bit before enabling the
1683                  * pch transcoder. */
1684                 reg = TRANS_CHICKEN2(pipe);
1685                 val = I915_READ(reg);
1686                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1687                 I915_WRITE(reg, val);
1688         }
1689
1690         reg = PCH_TRANSCONF(pipe);
1691         val = I915_READ(reg);
1692         pipeconf_val = I915_READ(PIPECONF(pipe));
1693
1694         if (HAS_PCH_IBX(dev_priv)) {
1695                 /*
1696                  * Make the BPC in transcoder be consistent with
1697                  * that in pipeconf reg. For HDMI we must use 8bpc
1698                  * here for both 8bpc and 12bpc.
1699                  */
1700                 val &= ~PIPECONF_BPC_MASK;
1701                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1702                         val |= PIPECONF_8BPC;
1703                 else
1704                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1705         }
1706
1707         val &= ~TRANS_INTERLACE_MASK;
1708         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1709                 if (HAS_PCH_IBX(dev_priv) &&
1710                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1711                         val |= TRANS_LEGACY_INTERLACED_ILK;
1712                 else
1713                         val |= TRANS_INTERLACED;
1714         else
1715                 val |= TRANS_PROGRESSIVE;
1716
1717         I915_WRITE(reg, val | TRANS_ENABLE);
1718         if (intel_wait_for_register(dev_priv,
1719                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1720                                     100))
1721                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1722 }
1723
1724 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1725                                       enum transcoder cpu_transcoder)
1726 {
1727         u32 val, pipeconf_val;
1728
1729         /* FDI must be feeding us bits for PCH ports */
1730         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1731         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1732
1733         /* Workaround: set timing override bit. */
1734         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1735         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1736         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1737
1738         val = TRANS_ENABLE;
1739         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1740
1741         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1742             PIPECONF_INTERLACED_ILK)
1743                 val |= TRANS_INTERLACED;
1744         else
1745                 val |= TRANS_PROGRESSIVE;
1746
1747         I915_WRITE(LPT_TRANSCONF, val);
1748         if (intel_wait_for_register(dev_priv,
1749                                     LPT_TRANSCONF,
1750                                     TRANS_STATE_ENABLE,
1751                                     TRANS_STATE_ENABLE,
1752                                     100))
1753                 DRM_ERROR("Failed to enable PCH transcoder\n");
1754 }
1755
1756 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1757                                             enum pipe pipe)
1758 {
1759         i915_reg_t reg;
1760         uint32_t val;
1761
1762         /* FDI relies on the transcoder */
1763         assert_fdi_tx_disabled(dev_priv, pipe);
1764         assert_fdi_rx_disabled(dev_priv, pipe);
1765
1766         /* Ports must be off as well */
1767         assert_pch_ports_disabled(dev_priv, pipe);
1768
1769         reg = PCH_TRANSCONF(pipe);
1770         val = I915_READ(reg);
1771         val &= ~TRANS_ENABLE;
1772         I915_WRITE(reg, val);
1773         /* wait for PCH transcoder off, transcoder state */
1774         if (intel_wait_for_register(dev_priv,
1775                                     reg, TRANS_STATE_ENABLE, 0,
1776                                     50))
1777                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1778
1779         if (HAS_PCH_CPT(dev_priv)) {
1780                 /* Workaround: Clear the timing override chicken bit again. */
1781                 reg = TRANS_CHICKEN2(pipe);
1782                 val = I915_READ(reg);
1783                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1784                 I915_WRITE(reg, val);
1785         }
1786 }
1787
1788 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1789 {
1790         u32 val;
1791
1792         val = I915_READ(LPT_TRANSCONF);
1793         val &= ~TRANS_ENABLE;
1794         I915_WRITE(LPT_TRANSCONF, val);
1795         /* wait for PCH transcoder off, transcoder state */
1796         if (intel_wait_for_register(dev_priv,
1797                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1798                                     50))
1799                 DRM_ERROR("Failed to disable PCH transcoder\n");
1800
1801         /* Workaround: clear timing override bit. */
1802         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1803         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1804         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1805 }
1806
1807 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1808 {
1809         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1810
1811         if (HAS_PCH_LPT(dev_priv))
1812                 return PIPE_A;
1813         else
1814                 return crtc->pipe;
1815 }
1816
1817 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1818 {
1819         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1820         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1821         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1822         enum pipe pipe = crtc->pipe;
1823         i915_reg_t reg;
1824         u32 val;
1825
1826         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1827
1828         assert_planes_disabled(crtc);
1829
1830         /*
1831          * A pipe without a PLL won't actually be able to drive bits from
1832          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1833          * need the check.
1834          */
1835         if (HAS_GMCH_DISPLAY(dev_priv)) {
1836                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1837                         assert_dsi_pll_enabled(dev_priv);
1838                 else
1839                         assert_pll_enabled(dev_priv, pipe);
1840         } else {
1841                 if (new_crtc_state->has_pch_encoder) {
1842                         /* if driving the PCH, we need FDI enabled */
1843                         assert_fdi_rx_pll_enabled(dev_priv,
1844                                                   intel_crtc_pch_transcoder(crtc));
1845                         assert_fdi_tx_pll_enabled(dev_priv,
1846                                                   (enum pipe) cpu_transcoder);
1847                 }
1848                 /* FIXME: assert CPU port conditions for SNB+ */
1849         }
1850
1851         reg = PIPECONF(cpu_transcoder);
1852         val = I915_READ(reg);
1853         if (val & PIPECONF_ENABLE) {
1854                 /* we keep both pipes enabled on 830 */
1855                 WARN_ON(!IS_I830(dev_priv));
1856                 return;
1857         }
1858
1859         I915_WRITE(reg, val | PIPECONF_ENABLE);
1860         POSTING_READ(reg);
1861
1862         /*
1863          * Until the pipe starts PIPEDSL reads will return a stale value,
1864          * which causes an apparent vblank timestamp jump when PIPEDSL
1865          * resets to its proper value. That also messes up the frame count
1866          * when it's derived from the timestamps. So let's wait for the
1867          * pipe to start properly before we call drm_crtc_vblank_on()
1868          */
1869         if (dev_priv->drm.max_vblank_count == 0)
1870                 intel_wait_for_pipe_scanline_moving(crtc);
1871 }
1872
1873 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1874 {
1875         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1876         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1877         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1878         enum pipe pipe = crtc->pipe;
1879         i915_reg_t reg;
1880         u32 val;
1881
1882         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1883
1884         /*
1885          * Make sure planes won't keep trying to pump pixels to us,
1886          * or we might hang the display.
1887          */
1888         assert_planes_disabled(crtc);
1889
1890         reg = PIPECONF(cpu_transcoder);
1891         val = I915_READ(reg);
1892         if ((val & PIPECONF_ENABLE) == 0)
1893                 return;
1894
1895         /*
1896          * Double wide has implications for planes
1897          * so best keep it disabled when not needed.
1898          */
1899         if (old_crtc_state->double_wide)
1900                 val &= ~PIPECONF_DOUBLE_WIDE;
1901
1902         /* Don't disable pipe or pipe PLLs if needed */
1903         if (!IS_I830(dev_priv))
1904                 val &= ~PIPECONF_ENABLE;
1905
1906         I915_WRITE(reg, val);
1907         if ((val & PIPECONF_ENABLE) == 0)
1908                 intel_wait_for_pipe_off(old_crtc_state);
1909 }
1910
1911 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1912 {
1913         return IS_GEN2(dev_priv) ? 2048 : 4096;
1914 }
1915
1916 static unsigned int
1917 intel_tile_width_bytes(const struct drm_framebuffer *fb, int plane)
1918 {
1919         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1920         unsigned int cpp = fb->format->cpp[plane];
1921
1922         switch (fb->modifier) {
1923         case DRM_FORMAT_MOD_LINEAR:
1924                 return cpp;
1925         case I915_FORMAT_MOD_X_TILED:
1926                 if (IS_GEN2(dev_priv))
1927                         return 128;
1928                 else
1929                         return 512;
1930         case I915_FORMAT_MOD_Y_TILED_CCS:
1931                 if (plane == 1)
1932                         return 128;
1933                 /* fall through */
1934         case I915_FORMAT_MOD_Y_TILED:
1935                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
1936                         return 128;
1937                 else
1938                         return 512;
1939         case I915_FORMAT_MOD_Yf_TILED_CCS:
1940                 if (plane == 1)
1941                         return 128;
1942                 /* fall through */
1943         case I915_FORMAT_MOD_Yf_TILED:
1944                 switch (cpp) {
1945                 case 1:
1946                         return 64;
1947                 case 2:
1948                 case 4:
1949                         return 128;
1950                 case 8:
1951                 case 16:
1952                         return 256;
1953                 default:
1954                         MISSING_CASE(cpp);
1955                         return cpp;
1956                 }
1957                 break;
1958         default:
1959                 MISSING_CASE(fb->modifier);
1960                 return cpp;
1961         }
1962 }
1963
1964 static unsigned int
1965 intel_tile_height(const struct drm_framebuffer *fb, int plane)
1966 {
1967         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
1968                 return 1;
1969         else
1970                 return intel_tile_size(to_i915(fb->dev)) /
1971                         intel_tile_width_bytes(fb, plane);
1972 }
1973
1974 /* Return the tile dimensions in pixel units */
1975 static void intel_tile_dims(const struct drm_framebuffer *fb, int plane,
1976                             unsigned int *tile_width,
1977                             unsigned int *tile_height)
1978 {
1979         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, plane);
1980         unsigned int cpp = fb->format->cpp[plane];
1981
1982         *tile_width = tile_width_bytes / cpp;
1983         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1984 }
1985
1986 unsigned int
1987 intel_fb_align_height(const struct drm_framebuffer *fb,
1988                       int plane, unsigned int height)
1989 {
1990         unsigned int tile_height = intel_tile_height(fb, plane);
1991
1992         return ALIGN(height, tile_height);
1993 }
1994
1995 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
1996 {
1997         unsigned int size = 0;
1998         int i;
1999
2000         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2001                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2002
2003         return size;
2004 }
2005
2006 static void
2007 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2008                         const struct drm_framebuffer *fb,
2009                         unsigned int rotation)
2010 {
2011         view->type = I915_GGTT_VIEW_NORMAL;
2012         if (drm_rotation_90_or_270(rotation)) {
2013                 view->type = I915_GGTT_VIEW_ROTATED;
2014                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2015         }
2016 }
2017
2018 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2019 {
2020         if (IS_I830(dev_priv))
2021                 return 16 * 1024;
2022         else if (IS_I85X(dev_priv))
2023                 return 256;
2024         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2025                 return 32;
2026         else
2027                 return 4 * 1024;
2028 }
2029
2030 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2031 {
2032         if (INTEL_GEN(dev_priv) >= 9)
2033                 return 256 * 1024;
2034         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2035                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2036                 return 128 * 1024;
2037         else if (INTEL_GEN(dev_priv) >= 4)
2038                 return 4 * 1024;
2039         else
2040                 return 0;
2041 }
2042
2043 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2044                                          int plane)
2045 {
2046         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2047
2048         /* AUX_DIST needs only 4K alignment */
2049         if (plane == 1)
2050                 return 4096;
2051
2052         switch (fb->modifier) {
2053         case DRM_FORMAT_MOD_LINEAR:
2054                 return intel_linear_alignment(dev_priv);
2055         case I915_FORMAT_MOD_X_TILED:
2056                 if (INTEL_GEN(dev_priv) >= 9)
2057                         return 256 * 1024;
2058                 return 0;
2059         case I915_FORMAT_MOD_Y_TILED_CCS:
2060         case I915_FORMAT_MOD_Yf_TILED_CCS:
2061         case I915_FORMAT_MOD_Y_TILED:
2062         case I915_FORMAT_MOD_Yf_TILED:
2063                 return 1 * 1024 * 1024;
2064         default:
2065                 MISSING_CASE(fb->modifier);
2066                 return 0;
2067         }
2068 }
2069
2070 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2071 {
2072         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2073         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2074
2075         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2076 }
2077
2078 struct i915_vma *
2079 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2080                            unsigned int rotation,
2081                            bool uses_fence,
2082                            unsigned long *out_flags)
2083 {
2084         struct drm_device *dev = fb->dev;
2085         struct drm_i915_private *dev_priv = to_i915(dev);
2086         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2087         struct i915_ggtt_view view;
2088         struct i915_vma *vma;
2089         unsigned int pinctl;
2090         u32 alignment;
2091
2092         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2093
2094         alignment = intel_surf_alignment(fb, 0);
2095
2096         intel_fill_fb_ggtt_view(&view, fb, rotation);
2097
2098         /* Note that the w/a also requires 64 PTE of padding following the
2099          * bo. We currently fill all unused PTE with the shadow page and so
2100          * we should always have valid PTE following the scanout preventing
2101          * the VT-d warning.
2102          */
2103         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2104                 alignment = 256 * 1024;
2105
2106         /*
2107          * Global gtt pte registers are special registers which actually forward
2108          * writes to a chunk of system memory. Which means that there is no risk
2109          * that the register values disappear as soon as we call
2110          * intel_runtime_pm_put(), so it is correct to wrap only the
2111          * pin/unpin/fence and not more.
2112          */
2113         intel_runtime_pm_get(dev_priv);
2114
2115         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2116
2117         pinctl = 0;
2118
2119         /* Valleyview is definitely limited to scanning out the first
2120          * 512MiB. Lets presume this behaviour was inherited from the
2121          * g4x display engine and that all earlier gen are similarly
2122          * limited. Testing suggests that it is a little more
2123          * complicated than this. For example, Cherryview appears quite
2124          * happy to scanout from anywhere within its global aperture.
2125          */
2126         if (HAS_GMCH_DISPLAY(dev_priv))
2127                 pinctl |= PIN_MAPPABLE;
2128
2129         vma = i915_gem_object_pin_to_display_plane(obj,
2130                                                    alignment, &view, pinctl);
2131         if (IS_ERR(vma))
2132                 goto err;
2133
2134         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2135                 int ret;
2136
2137                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2138                  * fence, whereas 965+ only requires a fence if using
2139                  * framebuffer compression.  For simplicity, we always, when
2140                  * possible, install a fence as the cost is not that onerous.
2141                  *
2142                  * If we fail to fence the tiled scanout, then either the
2143                  * modeset will reject the change (which is highly unlikely as
2144                  * the affected systems, all but one, do not have unmappable
2145                  * space) or we will not be able to enable full powersaving
2146                  * techniques (also likely not to apply due to various limits
2147                  * FBC and the like impose on the size of the buffer, which
2148                  * presumably we violated anyway with this unmappable buffer).
2149                  * Anyway, it is presumably better to stumble onwards with
2150                  * something and try to run the system in a "less than optimal"
2151                  * mode that matches the user configuration.
2152                  */
2153                 ret = i915_vma_pin_fence(vma);
2154                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2155                         i915_gem_object_unpin_from_display_plane(vma);
2156                         vma = ERR_PTR(ret);
2157                         goto err;
2158                 }
2159
2160                 if (ret == 0 && vma->fence)
2161                         *out_flags |= PLANE_HAS_FENCE;
2162         }
2163
2164         i915_vma_get(vma);
2165 err:
2166         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2167
2168         intel_runtime_pm_put(dev_priv);
2169         return vma;
2170 }
2171
2172 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2173 {
2174         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2175
2176         if (flags & PLANE_HAS_FENCE)
2177                 i915_vma_unpin_fence(vma);
2178         i915_gem_object_unpin_from_display_plane(vma);
2179         i915_vma_put(vma);
2180 }
2181
2182 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2183                           unsigned int rotation)
2184 {
2185         if (drm_rotation_90_or_270(rotation))
2186                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2187         else
2188                 return fb->pitches[plane];
2189 }
2190
2191 /*
2192  * Convert the x/y offsets into a linear offset.
2193  * Only valid with 0/180 degree rotation, which is fine since linear
2194  * offset is only used with linear buffers on pre-hsw and tiled buffers
2195  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2196  */
2197 u32 intel_fb_xy_to_linear(int x, int y,
2198                           const struct intel_plane_state *state,
2199                           int plane)
2200 {
2201         const struct drm_framebuffer *fb = state->base.fb;
2202         unsigned int cpp = fb->format->cpp[plane];
2203         unsigned int pitch = fb->pitches[plane];
2204
2205         return y * pitch + x * cpp;
2206 }
2207
2208 /*
2209  * Add the x/y offsets derived from fb->offsets[] to the user
2210  * specified plane src x/y offsets. The resulting x/y offsets
2211  * specify the start of scanout from the beginning of the gtt mapping.
2212  */
2213 void intel_add_fb_offsets(int *x, int *y,
2214                           const struct intel_plane_state *state,
2215                           int plane)
2216
2217 {
2218         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2219         unsigned int rotation = state->base.rotation;
2220
2221         if (drm_rotation_90_or_270(rotation)) {
2222                 *x += intel_fb->rotated[plane].x;
2223                 *y += intel_fb->rotated[plane].y;
2224         } else {
2225                 *x += intel_fb->normal[plane].x;
2226                 *y += intel_fb->normal[plane].y;
2227         }
2228 }
2229
2230 static u32 __intel_adjust_tile_offset(int *x, int *y,
2231                                       unsigned int tile_width,
2232                                       unsigned int tile_height,
2233                                       unsigned int tile_size,
2234                                       unsigned int pitch_tiles,
2235                                       u32 old_offset,
2236                                       u32 new_offset)
2237 {
2238         unsigned int pitch_pixels = pitch_tiles * tile_width;
2239         unsigned int tiles;
2240
2241         WARN_ON(old_offset & (tile_size - 1));
2242         WARN_ON(new_offset & (tile_size - 1));
2243         WARN_ON(new_offset > old_offset);
2244
2245         tiles = (old_offset - new_offset) / tile_size;
2246
2247         *y += tiles / pitch_tiles * tile_height;
2248         *x += tiles % pitch_tiles * tile_width;
2249
2250         /* minimize x in case it got needlessly big */
2251         *y += *x / pitch_pixels * tile_height;
2252         *x %= pitch_pixels;
2253
2254         return new_offset;
2255 }
2256
2257 static u32 _intel_adjust_tile_offset(int *x, int *y,
2258                                      const struct drm_framebuffer *fb, int plane,
2259                                      unsigned int rotation,
2260                                      u32 old_offset, u32 new_offset)
2261 {
2262         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2263         unsigned int cpp = fb->format->cpp[plane];
2264         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2265
2266         WARN_ON(new_offset > old_offset);
2267
2268         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2269                 unsigned int tile_size, tile_width, tile_height;
2270                 unsigned int pitch_tiles;
2271
2272                 tile_size = intel_tile_size(dev_priv);
2273                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2274
2275                 if (drm_rotation_90_or_270(rotation)) {
2276                         pitch_tiles = pitch / tile_height;
2277                         swap(tile_width, tile_height);
2278                 } else {
2279                         pitch_tiles = pitch / (tile_width * cpp);
2280                 }
2281
2282                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2283                                            tile_size, pitch_tiles,
2284                                            old_offset, new_offset);
2285         } else {
2286                 old_offset += *y * pitch + *x * cpp;
2287
2288                 *y = (old_offset - new_offset) / pitch;
2289                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2290         }
2291
2292         return new_offset;
2293 }
2294
2295 /*
2296  * Adjust the tile offset by moving the difference into
2297  * the x/y offsets.
2298  */
2299 static u32 intel_adjust_tile_offset(int *x, int *y,
2300                                     const struct intel_plane_state *state, int plane,
2301                                     u32 old_offset, u32 new_offset)
2302 {
2303         return _intel_adjust_tile_offset(x, y, state->base.fb, plane,
2304                                          state->base.rotation,
2305                                          old_offset, new_offset);
2306 }
2307
2308 /*
2309  * Computes the linear offset to the base tile and adjusts
2310  * x, y. bytes per pixel is assumed to be a power-of-two.
2311  *
2312  * In the 90/270 rotated case, x and y are assumed
2313  * to be already rotated to match the rotated GTT view, and
2314  * pitch is the tile_height aligned framebuffer height.
2315  *
2316  * This function is used when computing the derived information
2317  * under intel_framebuffer, so using any of that information
2318  * here is not allowed. Anything under drm_framebuffer can be
2319  * used. This is why the user has to pass in the pitch since it
2320  * is specified in the rotated orientation.
2321  */
2322 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2323                                       int *x, int *y,
2324                                       const struct drm_framebuffer *fb, int plane,
2325                                       unsigned int pitch,
2326                                       unsigned int rotation,
2327                                       u32 alignment)
2328 {
2329         uint64_t fb_modifier = fb->modifier;
2330         unsigned int cpp = fb->format->cpp[plane];
2331         u32 offset, offset_aligned;
2332
2333         if (alignment)
2334                 alignment--;
2335
2336         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2337                 unsigned int tile_size, tile_width, tile_height;
2338                 unsigned int tile_rows, tiles, pitch_tiles;
2339
2340                 tile_size = intel_tile_size(dev_priv);
2341                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2342
2343                 if (drm_rotation_90_or_270(rotation)) {
2344                         pitch_tiles = pitch / tile_height;
2345                         swap(tile_width, tile_height);
2346                 } else {
2347                         pitch_tiles = pitch / (tile_width * cpp);
2348                 }
2349
2350                 tile_rows = *y / tile_height;
2351                 *y %= tile_height;
2352
2353                 tiles = *x / tile_width;
2354                 *x %= tile_width;
2355
2356                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2357                 offset_aligned = offset & ~alignment;
2358
2359                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2360                                            tile_size, pitch_tiles,
2361                                            offset, offset_aligned);
2362         } else {
2363                 offset = *y * pitch + *x * cpp;
2364                 offset_aligned = offset & ~alignment;
2365
2366                 *y = (offset & alignment) / pitch;
2367                 *x = ((offset & alignment) - *y * pitch) / cpp;
2368         }
2369
2370         return offset_aligned;
2371 }
2372
2373 u32 intel_compute_tile_offset(int *x, int *y,
2374                               const struct intel_plane_state *state,
2375                               int plane)
2376 {
2377         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2378         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2379         const struct drm_framebuffer *fb = state->base.fb;
2380         unsigned int rotation = state->base.rotation;
2381         int pitch = intel_fb_pitch(fb, plane, rotation);
2382         u32 alignment;
2383
2384         if (intel_plane->id == PLANE_CURSOR)
2385                 alignment = intel_cursor_alignment(dev_priv);
2386         else
2387                 alignment = intel_surf_alignment(fb, plane);
2388
2389         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2390                                           rotation, alignment);
2391 }
2392
2393 /* Convert the fb->offset[] into x/y offsets */
2394 static int intel_fb_offset_to_xy(int *x, int *y,
2395                                  const struct drm_framebuffer *fb, int plane)
2396 {
2397         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2398
2399         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2400             fb->offsets[plane] % intel_tile_size(dev_priv))
2401                 return -EINVAL;
2402
2403         *x = 0;
2404         *y = 0;
2405
2406         _intel_adjust_tile_offset(x, y,
2407                                   fb, plane, DRM_MODE_ROTATE_0,
2408                                   fb->offsets[plane], 0);
2409
2410         return 0;
2411 }
2412
2413 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2414 {
2415         switch (fb_modifier) {
2416         case I915_FORMAT_MOD_X_TILED:
2417                 return I915_TILING_X;
2418         case I915_FORMAT_MOD_Y_TILED:
2419         case I915_FORMAT_MOD_Y_TILED_CCS:
2420                 return I915_TILING_Y;
2421         default:
2422                 return I915_TILING_NONE;
2423         }
2424 }
2425
2426 /*
2427  * From the Sky Lake PRM:
2428  * "The Color Control Surface (CCS) contains the compression status of
2429  *  the cache-line pairs. The compression state of the cache-line pair
2430  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2431  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2432  *  cache-line-pairs. CCS is always Y tiled."
2433  *
2434  * Since cache line pairs refers to horizontally adjacent cache lines,
2435  * each cache line in the CCS corresponds to an area of 32x16 cache
2436  * lines on the main surface. Since each pixel is 4 bytes, this gives
2437  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2438  * main surface.
2439  */
2440 static const struct drm_format_info ccs_formats[] = {
2441         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2442         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2443         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2444         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2445 };
2446
2447 static const struct drm_format_info *
2448 lookup_format_info(const struct drm_format_info formats[],
2449                    int num_formats, u32 format)
2450 {
2451         int i;
2452
2453         for (i = 0; i < num_formats; i++) {
2454                 if (formats[i].format == format)
2455                         return &formats[i];
2456         }
2457
2458         return NULL;
2459 }
2460
2461 static const struct drm_format_info *
2462 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2463 {
2464         switch (cmd->modifier[0]) {
2465         case I915_FORMAT_MOD_Y_TILED_CCS:
2466         case I915_FORMAT_MOD_Yf_TILED_CCS:
2467                 return lookup_format_info(ccs_formats,
2468                                           ARRAY_SIZE(ccs_formats),
2469                                           cmd->pixel_format);
2470         default:
2471                 return NULL;
2472         }
2473 }
2474
2475 static int
2476 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2477                    struct drm_framebuffer *fb)
2478 {
2479         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2480         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2481         u32 gtt_offset_rotated = 0;
2482         unsigned int max_size = 0;
2483         int i, num_planes = fb->format->num_planes;
2484         unsigned int tile_size = intel_tile_size(dev_priv);
2485
2486         for (i = 0; i < num_planes; i++) {
2487                 unsigned int width, height;
2488                 unsigned int cpp, size;
2489                 u32 offset;
2490                 int x, y;
2491                 int ret;
2492
2493                 cpp = fb->format->cpp[i];
2494                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2495                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2496
2497                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2498                 if (ret) {
2499                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2500                                       i, fb->offsets[i]);
2501                         return ret;
2502                 }
2503
2504                 if ((fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2505                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) && i == 1) {
2506                         int hsub = fb->format->hsub;
2507                         int vsub = fb->format->vsub;
2508                         int tile_width, tile_height;
2509                         int main_x, main_y;
2510                         int ccs_x, ccs_y;
2511
2512                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2513                         tile_width *= hsub;
2514                         tile_height *= vsub;
2515
2516                         ccs_x = (x * hsub) % tile_width;
2517                         ccs_y = (y * vsub) % tile_height;
2518                         main_x = intel_fb->normal[0].x % tile_width;
2519                         main_y = intel_fb->normal[0].y % tile_height;
2520
2521                         /*
2522                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2523                          * x/y offsets must match between CCS and the main surface.
2524                          */
2525                         if (main_x != ccs_x || main_y != ccs_y) {
2526                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2527                                               main_x, main_y,
2528                                               ccs_x, ccs_y,
2529                                               intel_fb->normal[0].x,
2530                                               intel_fb->normal[0].y,
2531                                               x, y);
2532                                 return -EINVAL;
2533                         }
2534                 }
2535
2536                 /*
2537                  * The fence (if used) is aligned to the start of the object
2538                  * so having the framebuffer wrap around across the edge of the
2539                  * fenced region doesn't really work. We have no API to configure
2540                  * the fence start offset within the object (nor could we probably
2541                  * on gen2/3). So it's just easier if we just require that the
2542                  * fb layout agrees with the fence layout. We already check that the
2543                  * fb stride matches the fence stride elsewhere.
2544                  */
2545                 if (i == 0 && i915_gem_object_is_tiled(intel_fb->obj) &&
2546                     (x + width) * cpp > fb->pitches[i]) {
2547                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2548                                       i, fb->offsets[i]);
2549                         return -EINVAL;
2550                 }
2551
2552                 /*
2553                  * First pixel of the framebuffer from
2554                  * the start of the normal gtt mapping.
2555                  */
2556                 intel_fb->normal[i].x = x;
2557                 intel_fb->normal[i].y = y;
2558
2559                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2560                                                     fb, i, fb->pitches[i],
2561                                                     DRM_MODE_ROTATE_0, tile_size);
2562                 offset /= tile_size;
2563
2564                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2565                         unsigned int tile_width, tile_height;
2566                         unsigned int pitch_tiles;
2567                         struct drm_rect r;
2568
2569                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2570
2571                         rot_info->plane[i].offset = offset;
2572                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2573                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2574                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2575
2576                         intel_fb->rotated[i].pitch =
2577                                 rot_info->plane[i].height * tile_height;
2578
2579                         /* how many tiles does this plane need */
2580                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2581                         /*
2582                          * If the plane isn't horizontally tile aligned,
2583                          * we need one more tile.
2584                          */
2585                         if (x != 0)
2586                                 size++;
2587
2588                         /* rotate the x/y offsets to match the GTT view */
2589                         r.x1 = x;
2590                         r.y1 = y;
2591                         r.x2 = x + width;
2592                         r.y2 = y + height;
2593                         drm_rect_rotate(&r,
2594                                         rot_info->plane[i].width * tile_width,
2595                                         rot_info->plane[i].height * tile_height,
2596                                         DRM_MODE_ROTATE_270);
2597                         x = r.x1;
2598                         y = r.y1;
2599
2600                         /* rotate the tile dimensions to match the GTT view */
2601                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2602                         swap(tile_width, tile_height);
2603
2604                         /*
2605                          * We only keep the x/y offsets, so push all of the
2606                          * gtt offset into the x/y offsets.
2607                          */
2608                         __intel_adjust_tile_offset(&x, &y,
2609                                                    tile_width, tile_height,
2610                                                    tile_size, pitch_tiles,
2611                                                    gtt_offset_rotated * tile_size, 0);
2612
2613                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2614
2615                         /*
2616                          * First pixel of the framebuffer from
2617                          * the start of the rotated gtt mapping.
2618                          */
2619                         intel_fb->rotated[i].x = x;
2620                         intel_fb->rotated[i].y = y;
2621                 } else {
2622                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2623                                             x * cpp, tile_size);
2624                 }
2625
2626                 /* how many tiles in total needed in the bo */
2627                 max_size = max(max_size, offset + size);
2628         }
2629
2630         if (max_size * tile_size > intel_fb->obj->base.size) {
2631                 DRM_DEBUG_KMS("fb too big for bo (need %u bytes, have %zu bytes)\n",
2632                               max_size * tile_size, intel_fb->obj->base.size);
2633                 return -EINVAL;
2634         }
2635
2636         return 0;
2637 }
2638
2639 static int i9xx_format_to_fourcc(int format)
2640 {
2641         switch (format) {
2642         case DISPPLANE_8BPP:
2643                 return DRM_FORMAT_C8;
2644         case DISPPLANE_BGRX555:
2645                 return DRM_FORMAT_XRGB1555;
2646         case DISPPLANE_BGRX565:
2647                 return DRM_FORMAT_RGB565;
2648         default:
2649         case DISPPLANE_BGRX888:
2650                 return DRM_FORMAT_XRGB8888;
2651         case DISPPLANE_RGBX888:
2652                 return DRM_FORMAT_XBGR8888;
2653         case DISPPLANE_BGRX101010:
2654                 return DRM_FORMAT_XRGB2101010;
2655         case DISPPLANE_RGBX101010:
2656                 return DRM_FORMAT_XBGR2101010;
2657         }
2658 }
2659
2660 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2661 {
2662         switch (format) {
2663         case PLANE_CTL_FORMAT_RGB_565:
2664                 return DRM_FORMAT_RGB565;
2665         default:
2666         case PLANE_CTL_FORMAT_XRGB_8888:
2667                 if (rgb_order) {
2668                         if (alpha)
2669                                 return DRM_FORMAT_ABGR8888;
2670                         else
2671                                 return DRM_FORMAT_XBGR8888;
2672                 } else {
2673                         if (alpha)
2674                                 return DRM_FORMAT_ARGB8888;
2675                         else
2676                                 return DRM_FORMAT_XRGB8888;
2677                 }
2678         case PLANE_CTL_FORMAT_XRGB_2101010:
2679                 if (rgb_order)
2680                         return DRM_FORMAT_XBGR2101010;
2681                 else
2682                         return DRM_FORMAT_XRGB2101010;
2683         }
2684 }
2685
2686 static bool
2687 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2688                               struct intel_initial_plane_config *plane_config)
2689 {
2690         struct drm_device *dev = crtc->base.dev;
2691         struct drm_i915_private *dev_priv = to_i915(dev);
2692         struct drm_i915_gem_object *obj = NULL;
2693         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2694         struct drm_framebuffer *fb = &plane_config->fb->base;
2695         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2696         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2697                                     PAGE_SIZE);
2698
2699         size_aligned -= base_aligned;
2700
2701         if (plane_config->size == 0)
2702                 return false;
2703
2704         /* If the FB is too big, just don't use it since fbdev is not very
2705          * important and we should probably use that space with FBC or other
2706          * features. */
2707         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2708                 return false;
2709
2710         mutex_lock(&dev->struct_mutex);
2711         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2712                                                              base_aligned,
2713                                                              base_aligned,
2714                                                              size_aligned);
2715         mutex_unlock(&dev->struct_mutex);
2716         if (!obj)
2717                 return false;
2718
2719         if (plane_config->tiling == I915_TILING_X)
2720                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2721
2722         mode_cmd.pixel_format = fb->format->format;
2723         mode_cmd.width = fb->width;
2724         mode_cmd.height = fb->height;
2725         mode_cmd.pitches[0] = fb->pitches[0];
2726         mode_cmd.modifier[0] = fb->modifier;
2727         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2728
2729         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2730                 DRM_DEBUG_KMS("intel fb init failed\n");
2731                 goto out_unref_obj;
2732         }
2733
2734
2735         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2736         return true;
2737
2738 out_unref_obj:
2739         i915_gem_object_put(obj);
2740         return false;
2741 }
2742
2743 static void
2744 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2745                         struct intel_plane_state *plane_state,
2746                         bool visible)
2747 {
2748         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2749
2750         plane_state->base.visible = visible;
2751
2752         /* FIXME pre-g4x don't work like this */
2753         if (visible) {
2754                 crtc_state->base.plane_mask |= BIT(drm_plane_index(&plane->base));
2755                 crtc_state->active_planes |= BIT(plane->id);
2756         } else {
2757                 crtc_state->base.plane_mask &= ~BIT(drm_plane_index(&plane->base));
2758                 crtc_state->active_planes &= ~BIT(plane->id);
2759         }
2760
2761         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2762                       crtc_state->base.crtc->name,
2763                       crtc_state->active_planes);
2764 }
2765
2766 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2767                                          struct intel_plane *plane)
2768 {
2769         struct intel_crtc_state *crtc_state =
2770                 to_intel_crtc_state(crtc->base.state);
2771         struct intel_plane_state *plane_state =
2772                 to_intel_plane_state(plane->base.state);
2773
2774         intel_set_plane_visible(crtc_state, plane_state, false);
2775
2776         if (plane->id == PLANE_PRIMARY)
2777                 intel_pre_disable_primary_noatomic(&crtc->base);
2778
2779         trace_intel_disable_plane(&plane->base, crtc);
2780         plane->disable_plane(plane, crtc);
2781 }
2782
2783 static void
2784 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2785                              struct intel_initial_plane_config *plane_config)
2786 {
2787         struct drm_device *dev = intel_crtc->base.dev;
2788         struct drm_i915_private *dev_priv = to_i915(dev);
2789         struct drm_crtc *c;
2790         struct drm_i915_gem_object *obj;
2791         struct drm_plane *primary = intel_crtc->base.primary;
2792         struct drm_plane_state *plane_state = primary->state;
2793         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2794         struct intel_plane *intel_plane = to_intel_plane(primary);
2795         struct intel_plane_state *intel_state =
2796                 to_intel_plane_state(plane_state);
2797         struct drm_framebuffer *fb;
2798
2799         if (!plane_config->fb)
2800                 return;
2801
2802         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2803                 fb = &plane_config->fb->base;
2804                 goto valid_fb;
2805         }
2806
2807         kfree(plane_config->fb);
2808
2809         /*
2810          * Failed to alloc the obj, check to see if we should share
2811          * an fb with another CRTC instead
2812          */
2813         for_each_crtc(dev, c) {
2814                 struct intel_plane_state *state;
2815
2816                 if (c == &intel_crtc->base)
2817                         continue;
2818
2819                 if (!to_intel_crtc(c)->active)
2820                         continue;
2821
2822                 state = to_intel_plane_state(c->primary->state);
2823                 if (!state->vma)
2824                         continue;
2825
2826                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2827                         fb = c->primary->fb;
2828                         drm_framebuffer_get(fb);
2829                         goto valid_fb;
2830                 }
2831         }
2832
2833         /*
2834          * We've failed to reconstruct the BIOS FB.  Current display state
2835          * indicates that the primary plane is visible, but has a NULL FB,
2836          * which will lead to problems later if we don't fix it up.  The
2837          * simplest solution is to just disable the primary plane now and
2838          * pretend the BIOS never had it enabled.
2839          */
2840         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2841
2842         return;
2843
2844 valid_fb:
2845         mutex_lock(&dev->struct_mutex);
2846         intel_state->vma =
2847                 intel_pin_and_fence_fb_obj(fb,
2848                                            primary->state->rotation,
2849                                            intel_plane_uses_fence(intel_state),
2850                                            &intel_state->flags);
2851         mutex_unlock(&dev->struct_mutex);
2852         if (IS_ERR(intel_state->vma)) {
2853                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2854                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2855
2856                 intel_state->vma = NULL;
2857                 drm_framebuffer_put(fb);
2858                 return;
2859         }
2860
2861         plane_state->src_x = 0;
2862         plane_state->src_y = 0;
2863         plane_state->src_w = fb->width << 16;
2864         plane_state->src_h = fb->height << 16;
2865
2866         plane_state->crtc_x = 0;
2867         plane_state->crtc_y = 0;
2868         plane_state->crtc_w = fb->width;
2869         plane_state->crtc_h = fb->height;
2870
2871         intel_state->base.src = drm_plane_state_src(plane_state);
2872         intel_state->base.dst = drm_plane_state_dest(plane_state);
2873
2874         obj = intel_fb_obj(fb);
2875         if (i915_gem_object_is_tiled(obj))
2876                 dev_priv->preserve_bios_swizzle = true;
2877
2878         drm_framebuffer_get(fb);
2879         primary->fb = primary->state->fb = fb;
2880         primary->crtc = primary->state->crtc = &intel_crtc->base;
2881
2882         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2883                                 to_intel_plane_state(plane_state),
2884                                 true);
2885
2886         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2887                   &obj->frontbuffer_bits);
2888 }
2889
2890 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2891                                unsigned int rotation)
2892 {
2893         int cpp = fb->format->cpp[plane];
2894
2895         switch (fb->modifier) {
2896         case DRM_FORMAT_MOD_LINEAR:
2897         case I915_FORMAT_MOD_X_TILED:
2898                 switch (cpp) {
2899                 case 8:
2900                         return 4096;
2901                 case 4:
2902                 case 2:
2903                 case 1:
2904                         return 8192;
2905                 default:
2906                         MISSING_CASE(cpp);
2907                         break;
2908                 }
2909                 break;
2910         case I915_FORMAT_MOD_Y_TILED_CCS:
2911         case I915_FORMAT_MOD_Yf_TILED_CCS:
2912                 /* FIXME AUX plane? */
2913         case I915_FORMAT_MOD_Y_TILED:
2914         case I915_FORMAT_MOD_Yf_TILED:
2915                 switch (cpp) {
2916                 case 8:
2917                         return 2048;
2918                 case 4:
2919                         return 4096;
2920                 case 2:
2921                 case 1:
2922                         return 8192;
2923                 default:
2924                         MISSING_CASE(cpp);
2925                         break;
2926                 }
2927                 break;
2928         default:
2929                 MISSING_CASE(fb->modifier);
2930         }
2931
2932         return 2048;
2933 }
2934
2935 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2936                                            int main_x, int main_y, u32 main_offset)
2937 {
2938         const struct drm_framebuffer *fb = plane_state->base.fb;
2939         int hsub = fb->format->hsub;
2940         int vsub = fb->format->vsub;
2941         int aux_x = plane_state->aux.x;
2942         int aux_y = plane_state->aux.y;
2943         u32 aux_offset = plane_state->aux.offset;
2944         u32 alignment = intel_surf_alignment(fb, 1);
2945
2946         while (aux_offset >= main_offset && aux_y <= main_y) {
2947                 int x, y;
2948
2949                 if (aux_x == main_x && aux_y == main_y)
2950                         break;
2951
2952                 if (aux_offset == 0)
2953                         break;
2954
2955                 x = aux_x / hsub;
2956                 y = aux_y / vsub;
2957                 aux_offset = intel_adjust_tile_offset(&x, &y, plane_state, 1,
2958                                                       aux_offset, aux_offset - alignment);
2959                 aux_x = x * hsub + aux_x % hsub;
2960                 aux_y = y * vsub + aux_y % vsub;
2961         }
2962
2963         if (aux_x != main_x || aux_y != main_y)
2964                 return false;
2965
2966         plane_state->aux.offset = aux_offset;
2967         plane_state->aux.x = aux_x;
2968         plane_state->aux.y = aux_y;
2969
2970         return true;
2971 }
2972
2973 static int skl_check_main_surface(const struct intel_crtc_state *crtc_state,
2974                                   struct intel_plane_state *plane_state)
2975 {
2976         struct drm_i915_private *dev_priv =
2977                 to_i915(plane_state->base.plane->dev);
2978         const struct drm_framebuffer *fb = plane_state->base.fb;
2979         unsigned int rotation = plane_state->base.rotation;
2980         int x = plane_state->base.src.x1 >> 16;
2981         int y = plane_state->base.src.y1 >> 16;
2982         int w = drm_rect_width(&plane_state->base.src) >> 16;
2983         int h = drm_rect_height(&plane_state->base.src) >> 16;
2984         int dst_x = plane_state->base.dst.x1;
2985         int pipe_src_w = crtc_state->pipe_src_w;
2986         int max_width = skl_max_plane_width(fb, 0, rotation);
2987         int max_height = 4096;
2988         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2989
2990         if (w > max_width || h > max_height) {
2991                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2992                               w, h, max_width, max_height);
2993                 return -EINVAL;
2994         }
2995
2996         /*
2997          * Display WA #1175: cnl,glk
2998          * Planes other than the cursor may cause FIFO underflow and display
2999          * corruption if starting less than 4 pixels from the right edge of
3000          * the screen.
3001          * Besides the above WA fix the similar problem, where planes other
3002          * than the cursor ending less than 4 pixels from the left edge of the
3003          * screen may cause FIFO underflow and display corruption.
3004          */
3005         if ((IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
3006             (dst_x + w < 4 || dst_x > pipe_src_w - 4)) {
3007                 DRM_DEBUG_KMS("requested plane X %s position %d invalid (valid range %d-%d)\n",
3008                               dst_x + w < 4 ? "end" : "start",
3009                               dst_x + w < 4 ? dst_x + w : dst_x,
3010                               4, pipe_src_w - 4);
3011                 return -ERANGE;
3012         }
3013
3014         intel_add_fb_offsets(&x, &y, plane_state, 0);
3015         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
3016         alignment = intel_surf_alignment(fb, 0);
3017
3018         /*
3019          * AUX surface offset is specified as the distance from the
3020          * main surface offset, and it must be non-negative. Make
3021          * sure that is what we will get.
3022          */
3023         if (offset > aux_offset)
3024                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3025                                                   offset, aux_offset & ~(alignment - 1));
3026
3027         /*
3028          * When using an X-tiled surface, the plane blows up
3029          * if the x offset + width exceed the stride.
3030          *
3031          * TODO: linear and Y-tiled seem fine, Yf untested,
3032          */
3033         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3034                 int cpp = fb->format->cpp[0];
3035
3036                 while ((x + w) * cpp > fb->pitches[0]) {
3037                         if (offset == 0) {
3038                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3039                                 return -EINVAL;
3040                         }
3041
3042                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3043                                                           offset, offset - alignment);
3044                 }
3045         }
3046
3047         /*
3048          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3049          * they match with the main surface x/y offsets.
3050          */
3051         if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3052             fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3053                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3054                         if (offset == 0)
3055                                 break;
3056
3057                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3058                                                           offset, offset - alignment);
3059                 }
3060
3061                 if (x != plane_state->aux.x || y != plane_state->aux.y) {
3062                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3063                         return -EINVAL;
3064                 }
3065         }
3066
3067         plane_state->main.offset = offset;
3068         plane_state->main.x = x;
3069         plane_state->main.y = y;
3070
3071         return 0;
3072 }
3073
3074 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3075 {
3076         const struct drm_framebuffer *fb = plane_state->base.fb;
3077         unsigned int rotation = plane_state->base.rotation;
3078         int max_width = skl_max_plane_width(fb, 1, rotation);
3079         int max_height = 4096;
3080         int x = plane_state->base.src.x1 >> 17;
3081         int y = plane_state->base.src.y1 >> 17;
3082         int w = drm_rect_width(&plane_state->base.src) >> 17;
3083         int h = drm_rect_height(&plane_state->base.src) >> 17;
3084         u32 offset;
3085
3086         intel_add_fb_offsets(&x, &y, plane_state, 1);
3087         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3088
3089         /* FIXME not quite sure how/if these apply to the chroma plane */
3090         if (w > max_width || h > max_height) {
3091                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3092                               w, h, max_width, max_height);
3093                 return -EINVAL;
3094         }
3095
3096         plane_state->aux.offset = offset;
3097         plane_state->aux.x = x;
3098         plane_state->aux.y = y;
3099
3100         return 0;
3101 }
3102
3103 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3104 {
3105         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3106         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3107         struct intel_crtc *crtc = to_intel_crtc(plane_state->base.crtc);
3108         const struct drm_framebuffer *fb = plane_state->base.fb;
3109         int src_x = plane_state->base.src.x1 >> 16;
3110         int src_y = plane_state->base.src.y1 >> 16;
3111         int hsub = fb->format->hsub;
3112         int vsub = fb->format->vsub;
3113         int x = src_x / hsub;
3114         int y = src_y / vsub;
3115         u32 offset;
3116
3117         if (!skl_plane_has_ccs(dev_priv, crtc->pipe, plane->id)) {
3118                 DRM_DEBUG_KMS("No RC support on %s\n", plane->base.name);
3119                 return -EINVAL;
3120         }
3121
3122         if (plane_state->base.rotation & ~(DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180)) {
3123                 DRM_DEBUG_KMS("RC support only with 0/180 degree rotation %x\n",
3124                               plane_state->base.rotation);
3125                 return -EINVAL;
3126         }
3127
3128         intel_add_fb_offsets(&x, &y, plane_state, 1);
3129         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3130
3131         plane_state->aux.offset = offset;
3132         plane_state->aux.x = x * hsub + src_x % hsub;
3133         plane_state->aux.y = y * vsub + src_y % vsub;
3134
3135         return 0;
3136 }
3137
3138 int skl_check_plane_surface(const struct intel_crtc_state *crtc_state,
3139                             struct intel_plane_state *plane_state)
3140 {
3141         const struct drm_framebuffer *fb = plane_state->base.fb;
3142         unsigned int rotation = plane_state->base.rotation;
3143         int ret;
3144
3145         if (rotation & DRM_MODE_REFLECT_X &&
3146             fb->modifier == DRM_FORMAT_MOD_LINEAR) {
3147                 DRM_DEBUG_KMS("horizontal flip is not supported with linear surface formats\n");
3148                 return -EINVAL;
3149         }
3150
3151         if (!plane_state->base.visible)
3152                 return 0;
3153
3154         /* Rotate src coordinates to match rotated GTT view */
3155         if (drm_rotation_90_or_270(rotation))
3156                 drm_rect_rotate(&plane_state->base.src,
3157                                 fb->width << 16, fb->height << 16,
3158                                 DRM_MODE_ROTATE_270);
3159
3160         /*
3161          * Handle the AUX surface first since
3162          * the main surface setup depends on it.
3163          */
3164         if (fb->format->format == DRM_FORMAT_NV12) {
3165                 ret = skl_check_nv12_aux_surface(plane_state);
3166                 if (ret)
3167                         return ret;
3168         } else if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3169                    fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3170                 ret = skl_check_ccs_aux_surface(plane_state);
3171                 if (ret)
3172                         return ret;
3173         } else {
3174                 plane_state->aux.offset = ~0xfff;
3175                 plane_state->aux.x = 0;
3176                 plane_state->aux.y = 0;
3177         }
3178
3179         ret = skl_check_main_surface(crtc_state, plane_state);
3180         if (ret)
3181                 return ret;
3182
3183         return 0;
3184 }
3185
3186 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3187                           const struct intel_plane_state *plane_state)
3188 {
3189         struct drm_i915_private *dev_priv =
3190                 to_i915(plane_state->base.plane->dev);
3191         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3192         const struct drm_framebuffer *fb = plane_state->base.fb;
3193         unsigned int rotation = plane_state->base.rotation;
3194         u32 dspcntr;
3195
3196         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3197
3198         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3199             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3200                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3201
3202         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3203                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3204
3205         if (INTEL_GEN(dev_priv) < 5)
3206                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3207
3208         switch (fb->format->format) {
3209         case DRM_FORMAT_C8:
3210                 dspcntr |= DISPPLANE_8BPP;
3211                 break;
3212         case DRM_FORMAT_XRGB1555:
3213                 dspcntr |= DISPPLANE_BGRX555;
3214                 break;
3215         case DRM_FORMAT_RGB565:
3216                 dspcntr |= DISPPLANE_BGRX565;
3217                 break;
3218         case DRM_FORMAT_XRGB8888:
3219                 dspcntr |= DISPPLANE_BGRX888;
3220                 break;
3221         case DRM_FORMAT_XBGR8888:
3222                 dspcntr |= DISPPLANE_RGBX888;
3223                 break;
3224         case DRM_FORMAT_XRGB2101010:
3225                 dspcntr |= DISPPLANE_BGRX101010;
3226                 break;
3227         case DRM_FORMAT_XBGR2101010:
3228                 dspcntr |= DISPPLANE_RGBX101010;
3229                 break;
3230         default:
3231                 MISSING_CASE(fb->format->format);
3232                 return 0;
3233         }
3234
3235         if (INTEL_GEN(dev_priv) >= 4 &&
3236             fb->modifier == I915_FORMAT_MOD_X_TILED)
3237                 dspcntr |= DISPPLANE_TILED;
3238
3239         if (rotation & DRM_MODE_ROTATE_180)
3240                 dspcntr |= DISPPLANE_ROTATE_180;
3241
3242         if (rotation & DRM_MODE_REFLECT_X)
3243                 dspcntr |= DISPPLANE_MIRROR;
3244
3245         return dspcntr;
3246 }
3247
3248 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3249 {
3250         struct drm_i915_private *dev_priv =
3251                 to_i915(plane_state->base.plane->dev);
3252         int src_x = plane_state->base.src.x1 >> 16;
3253         int src_y = plane_state->base.src.y1 >> 16;
3254         u32 offset;
3255
3256         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3257
3258         if (INTEL_GEN(dev_priv) >= 4)
3259                 offset = intel_compute_tile_offset(&src_x, &src_y,
3260                                                    plane_state, 0);
3261         else
3262                 offset = 0;
3263
3264         /* HSW/BDW do this automagically in hardware */
3265         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3266                 unsigned int rotation = plane_state->base.rotation;
3267                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3268                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3269
3270                 if (rotation & DRM_MODE_ROTATE_180) {
3271                         src_x += src_w - 1;
3272                         src_y += src_h - 1;
3273                 } else if (rotation & DRM_MODE_REFLECT_X) {
3274                         src_x += src_w - 1;
3275                 }
3276         }
3277
3278         plane_state->main.offset = offset;
3279         plane_state->main.x = src_x;
3280         plane_state->main.y = src_y;
3281
3282         return 0;
3283 }
3284
3285 static void i9xx_update_plane(struct intel_plane *plane,
3286                               const struct intel_crtc_state *crtc_state,
3287                               const struct intel_plane_state *plane_state)
3288 {
3289         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3290         const struct drm_framebuffer *fb = plane_state->base.fb;
3291         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3292         u32 linear_offset;
3293         u32 dspcntr = plane_state->ctl;
3294         i915_reg_t reg = DSPCNTR(i9xx_plane);
3295         int x = plane_state->main.x;
3296         int y = plane_state->main.y;
3297         unsigned long irqflags;
3298         u32 dspaddr_offset;
3299
3300         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3301
3302         if (INTEL_GEN(dev_priv) >= 4)
3303                 dspaddr_offset = plane_state->main.offset;
3304         else
3305                 dspaddr_offset = linear_offset;
3306
3307         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3308
3309         if (INTEL_GEN(dev_priv) < 4) {
3310                 /* pipesrc and dspsize control the size that is scaled from,
3311                  * which should always be the user's requested size.
3312                  */
3313                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3314                               ((crtc_state->pipe_src_h - 1) << 16) |
3315                               (crtc_state->pipe_src_w - 1));
3316                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3317         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3318                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3319                               ((crtc_state->pipe_src_h - 1) << 16) |
3320                               (crtc_state->pipe_src_w - 1));
3321                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3322                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3323         }
3324
3325         I915_WRITE_FW(reg, dspcntr);
3326
3327         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), fb->pitches[0]);
3328         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3329                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3330                               intel_plane_ggtt_offset(plane_state) +
3331                               dspaddr_offset);
3332                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3333         } else if (INTEL_GEN(dev_priv) >= 4) {
3334                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3335                               intel_plane_ggtt_offset(plane_state) +
3336                               dspaddr_offset);
3337                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3338                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3339         } else {
3340                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3341                               intel_plane_ggtt_offset(plane_state) +
3342                               dspaddr_offset);
3343         }
3344         POSTING_READ_FW(reg);
3345
3346         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3347 }
3348
3349 static void i9xx_disable_plane(struct intel_plane *plane,
3350                                struct intel_crtc *crtc)
3351 {
3352         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3353         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3354         unsigned long irqflags;
3355
3356         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3357
3358         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3359         if (INTEL_GEN(dev_priv) >= 4)
3360                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3361         else
3362                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3363         POSTING_READ_FW(DSPCNTR(i9xx_plane));
3364
3365         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3366 }
3367
3368 static bool i9xx_plane_get_hw_state(struct intel_plane *plane)
3369 {
3370         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3371         enum intel_display_power_domain power_domain;
3372         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3373         enum pipe pipe = plane->pipe;
3374         bool ret;
3375
3376         /*
3377          * Not 100% correct for planes that can move between pipes,
3378          * but that's only the case for gen2-4 which don't have any
3379          * display power wells.
3380          */
3381         power_domain = POWER_DOMAIN_PIPE(pipe);
3382         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3383                 return false;
3384
3385         ret = I915_READ(DSPCNTR(i9xx_plane)) & DISPLAY_PLANE_ENABLE;
3386
3387         intel_display_power_put(dev_priv, power_domain);
3388
3389         return ret;
3390 }
3391
3392 static u32
3393 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int plane)
3394 {
3395         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3396                 return 64;
3397         else
3398                 return intel_tile_width_bytes(fb, plane);
3399 }
3400
3401 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3402 {
3403         struct drm_device *dev = intel_crtc->base.dev;
3404         struct drm_i915_private *dev_priv = to_i915(dev);
3405
3406         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3407         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3408         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3409 }
3410
3411 /*
3412  * This function detaches (aka. unbinds) unused scalers in hardware
3413  */
3414 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3415 {
3416         struct intel_crtc_scaler_state *scaler_state;
3417         int i;
3418
3419         scaler_state = &intel_crtc->config->scaler_state;
3420
3421         /* loop through and disable scalers that aren't in use */
3422         for (i = 0; i < intel_crtc->num_scalers; i++) {
3423                 if (!scaler_state->scalers[i].in_use)
3424                         skl_detach_scaler(intel_crtc, i);
3425         }
3426 }
3427
3428 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3429                      unsigned int rotation)
3430 {
3431         u32 stride;
3432
3433         if (plane >= fb->format->num_planes)
3434                 return 0;
3435
3436         stride = intel_fb_pitch(fb, plane, rotation);
3437
3438         /*
3439          * The stride is either expressed as a multiple of 64 bytes chunks for
3440          * linear buffers or in number of tiles for tiled buffers.
3441          */
3442         if (drm_rotation_90_or_270(rotation))
3443                 stride /= intel_tile_height(fb, plane);
3444         else
3445                 stride /= intel_fb_stride_alignment(fb, plane);
3446
3447         return stride;
3448 }
3449
3450 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3451 {
3452         switch (pixel_format) {
3453         case DRM_FORMAT_C8:
3454                 return PLANE_CTL_FORMAT_INDEXED;
3455         case DRM_FORMAT_RGB565:
3456                 return PLANE_CTL_FORMAT_RGB_565;
3457         case DRM_FORMAT_XBGR8888:
3458         case DRM_FORMAT_ABGR8888:
3459                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3460         case DRM_FORMAT_XRGB8888:
3461         case DRM_FORMAT_ARGB8888:
3462                 return PLANE_CTL_FORMAT_XRGB_8888;
3463         case DRM_FORMAT_XRGB2101010:
3464                 return PLANE_CTL_FORMAT_XRGB_2101010;
3465         case DRM_FORMAT_XBGR2101010:
3466                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3467         case DRM_FORMAT_YUYV:
3468                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3469         case DRM_FORMAT_YVYU:
3470                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3471         case DRM_FORMAT_UYVY:
3472                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3473         case DRM_FORMAT_VYUY:
3474                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3475         default:
3476                 MISSING_CASE(pixel_format);
3477         }
3478
3479         return 0;
3480 }
3481
3482 /*
3483  * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3484  * to be already pre-multiplied. We need to add a knob (or a different
3485  * DRM_FORMAT) for user-space to configure that.
3486  */
3487 static u32 skl_plane_ctl_alpha(uint32_t pixel_format)
3488 {
3489         switch (pixel_format) {
3490         case DRM_FORMAT_ABGR8888:
3491         case DRM_FORMAT_ARGB8888:
3492                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3493         default:
3494                 return PLANE_CTL_ALPHA_DISABLE;
3495         }
3496 }
3497
3498 static u32 glk_plane_color_ctl_alpha(uint32_t pixel_format)
3499 {
3500         switch (pixel_format) {
3501         case DRM_FORMAT_ABGR8888:
3502         case DRM_FORMAT_ARGB8888:
3503                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3504         default:
3505                 return PLANE_COLOR_ALPHA_DISABLE;
3506         }
3507 }
3508
3509 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3510 {
3511         switch (fb_modifier) {
3512         case DRM_FORMAT_MOD_LINEAR:
3513                 break;
3514         case I915_FORMAT_MOD_X_TILED:
3515                 return PLANE_CTL_TILED_X;
3516         case I915_FORMAT_MOD_Y_TILED:
3517                 return PLANE_CTL_TILED_Y;
3518         case I915_FORMAT_MOD_Y_TILED_CCS:
3519                 return PLANE_CTL_TILED_Y | PLANE_CTL_DECOMPRESSION_ENABLE;
3520         case I915_FORMAT_MOD_Yf_TILED:
3521                 return PLANE_CTL_TILED_YF;
3522         case I915_FORMAT_MOD_Yf_TILED_CCS:
3523                 return PLANE_CTL_TILED_YF | PLANE_CTL_DECOMPRESSION_ENABLE;
3524         default:
3525                 MISSING_CASE(fb_modifier);
3526         }
3527
3528         return 0;
3529 }
3530
3531 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3532 {
3533         switch (rotate) {
3534         case DRM_MODE_ROTATE_0:
3535                 break;
3536         /*
3537          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3538          * while i915 HW rotation is clockwise, thats why this swapping.
3539          */
3540         case DRM_MODE_ROTATE_90:
3541                 return PLANE_CTL_ROTATE_270;
3542         case DRM_MODE_ROTATE_180:
3543                 return PLANE_CTL_ROTATE_180;
3544         case DRM_MODE_ROTATE_270:
3545                 return PLANE_CTL_ROTATE_90;
3546         default:
3547                 MISSING_CASE(rotate);
3548         }
3549
3550         return 0;
3551 }
3552
3553 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3554 {
3555         switch (reflect) {
3556         case 0:
3557                 break;
3558         case DRM_MODE_REFLECT_X:
3559                 return PLANE_CTL_FLIP_HORIZONTAL;
3560         case DRM_MODE_REFLECT_Y:
3561         default:
3562                 MISSING_CASE(reflect);
3563         }
3564
3565         return 0;
3566 }
3567
3568 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3569                   const struct intel_plane_state *plane_state)
3570 {
3571         struct drm_i915_private *dev_priv =
3572                 to_i915(plane_state->base.plane->dev);
3573         const struct drm_framebuffer *fb = plane_state->base.fb;
3574         unsigned int rotation = plane_state->base.rotation;
3575         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3576         u32 plane_ctl;
3577
3578         plane_ctl = PLANE_CTL_ENABLE;
3579
3580         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3581                 plane_ctl |= skl_plane_ctl_alpha(fb->format->format);
3582                 plane_ctl |=
3583                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3584                         PLANE_CTL_PIPE_CSC_ENABLE |
3585                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3586         }
3587
3588         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3589         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3590         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3591
3592         if (INTEL_GEN(dev_priv) >= 10)
3593                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3594                                                 DRM_MODE_REFLECT_MASK);
3595
3596         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3597                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3598         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3599                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3600
3601         return plane_ctl;
3602 }
3603
3604 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3605                         const struct intel_plane_state *plane_state)
3606 {
3607         const struct drm_framebuffer *fb = plane_state->base.fb;
3608         u32 plane_color_ctl = 0;
3609
3610         plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3611         plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3612         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3613         plane_color_ctl |= glk_plane_color_ctl_alpha(fb->format->format);
3614
3615         return plane_color_ctl;
3616 }
3617
3618 static int
3619 __intel_display_resume(struct drm_device *dev,
3620                        struct drm_atomic_state *state,
3621                        struct drm_modeset_acquire_ctx *ctx)
3622 {
3623         struct drm_crtc_state *crtc_state;
3624         struct drm_crtc *crtc;
3625         int i, ret;
3626
3627         intel_modeset_setup_hw_state(dev, ctx);
3628         i915_redisable_vga(to_i915(dev));
3629
3630         if (!state)
3631                 return 0;
3632
3633         /*
3634          * We've duplicated the state, pointers to the old state are invalid.
3635          *
3636          * Don't attempt to use the old state until we commit the duplicated state.
3637          */
3638         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3639                 /*
3640                  * Force recalculation even if we restore
3641                  * current state. With fast modeset this may not result
3642                  * in a modeset when the state is compatible.
3643                  */
3644                 crtc_state->mode_changed = true;
3645         }
3646
3647         /* ignore any reset values/BIOS leftovers in the WM registers */
3648         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3649                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3650
3651         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3652
3653         WARN_ON(ret == -EDEADLK);
3654         return ret;
3655 }
3656
3657 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3658 {
3659         return intel_has_gpu_reset(dev_priv) &&
3660                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3661 }
3662
3663 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3664 {
3665         struct drm_device *dev = &dev_priv->drm;
3666         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3667         struct drm_atomic_state *state;
3668         int ret;
3669
3670
3671         /* reset doesn't touch the display */
3672         if (!i915_modparams.force_reset_modeset_test &&
3673             !gpu_reset_clobbers_display(dev_priv))
3674                 return;
3675
3676         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3677         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3678         wake_up_all(&dev_priv->gpu_error.wait_queue);
3679
3680         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3681                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3682                 i915_gem_set_wedged(dev_priv);
3683         }
3684
3685         /*
3686          * Need mode_config.mutex so that we don't
3687          * trample ongoing ->detect() and whatnot.
3688          */
3689         mutex_lock(&dev->mode_config.mutex);
3690         drm_modeset_acquire_init(ctx, 0);
3691         while (1) {
3692                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3693                 if (ret != -EDEADLK)
3694                         break;
3695
3696                 drm_modeset_backoff(ctx);
3697         }
3698         /*
3699          * Disabling the crtcs gracefully seems nicer. Also the
3700          * g33 docs say we should at least disable all the planes.
3701          */
3702         state = drm_atomic_helper_duplicate_state(dev, ctx);
3703         if (IS_ERR(state)) {
3704                 ret = PTR_ERR(state);
3705                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3706                 return;
3707         }
3708
3709         ret = drm_atomic_helper_disable_all(dev, ctx);
3710         if (ret) {
3711                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3712                 drm_atomic_state_put(state);
3713                 return;
3714         }
3715
3716         dev_priv->modeset_restore_state = state;
3717         state->acquire_ctx = ctx;
3718 }
3719
3720 void intel_finish_reset(struct drm_i915_private *dev_priv)
3721 {
3722         struct drm_device *dev = &dev_priv->drm;
3723         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3724         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3725         int ret;
3726
3727         /* reset doesn't touch the display */
3728         if (!i915_modparams.force_reset_modeset_test &&
3729             !gpu_reset_clobbers_display(dev_priv))
3730                 return;
3731
3732         if (!state)
3733                 goto unlock;
3734
3735         dev_priv->modeset_restore_state = NULL;
3736
3737         /* reset doesn't touch the display */
3738         if (!gpu_reset_clobbers_display(dev_priv)) {
3739                 /* for testing only restore the display */
3740                 ret = __intel_display_resume(dev, state, ctx);
3741                 if (ret)
3742                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3743         } else {
3744                 /*
3745                  * The display has been reset as well,
3746                  * so need a full re-initialization.
3747                  */
3748                 intel_runtime_pm_disable_interrupts(dev_priv);
3749                 intel_runtime_pm_enable_interrupts(dev_priv);
3750
3751                 intel_pps_unlock_regs_wa(dev_priv);
3752                 intel_modeset_init_hw(dev);
3753                 intel_init_clock_gating(dev_priv);
3754
3755                 spin_lock_irq(&dev_priv->irq_lock);
3756                 if (dev_priv->display.hpd_irq_setup)
3757                         dev_priv->display.hpd_irq_setup(dev_priv);
3758                 spin_unlock_irq(&dev_priv->irq_lock);
3759
3760                 ret = __intel_display_resume(dev, state, ctx);
3761                 if (ret)
3762                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3763
3764                 intel_hpd_init(dev_priv);
3765         }
3766
3767         drm_atomic_state_put(state);
3768 unlock:
3769         drm_modeset_drop_locks(ctx);
3770         drm_modeset_acquire_fini(ctx);
3771         mutex_unlock(&dev->mode_config.mutex);
3772
3773         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3774 }
3775
3776 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3777                                      const struct intel_crtc_state *new_crtc_state)
3778 {
3779         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3780         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3781
3782         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3783         crtc->base.mode = new_crtc_state->base.mode;
3784
3785         /*
3786          * Update pipe size and adjust fitter if needed: the reason for this is
3787          * that in compute_mode_changes we check the native mode (not the pfit
3788          * mode) to see if we can flip rather than do a full mode set. In the
3789          * fastboot case, we'll flip, but if we don't update the pipesrc and
3790          * pfit state, we'll end up with a big fb scanned out into the wrong
3791          * sized surface.
3792          */
3793
3794         I915_WRITE(PIPESRC(crtc->pipe),
3795                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3796                    (new_crtc_state->pipe_src_h - 1));
3797
3798         /* on skylake this is done by detaching scalers */
3799         if (INTEL_GEN(dev_priv) >= 9) {
3800                 skl_detach_scalers(crtc);
3801
3802                 if (new_crtc_state->pch_pfit.enabled)
3803                         skylake_pfit_enable(crtc);
3804         } else if (HAS_PCH_SPLIT(dev_priv)) {
3805                 if (new_crtc_state->pch_pfit.enabled)
3806                         ironlake_pfit_enable(crtc);
3807                 else if (old_crtc_state->pch_pfit.enabled)
3808                         ironlake_pfit_disable(crtc, true);
3809         }
3810 }
3811
3812 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3813 {
3814         struct drm_device *dev = crtc->base.dev;
3815         struct drm_i915_private *dev_priv = to_i915(dev);
3816         int pipe = crtc->pipe;
3817         i915_reg_t reg;
3818         u32 temp;
3819
3820         /* enable normal train */
3821         reg = FDI_TX_CTL(pipe);
3822         temp = I915_READ(reg);
3823         if (IS_IVYBRIDGE(dev_priv)) {
3824                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3825                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3826         } else {
3827                 temp &= ~FDI_LINK_TRAIN_NONE;
3828                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3829         }
3830         I915_WRITE(reg, temp);
3831
3832         reg = FDI_RX_CTL(pipe);
3833         temp = I915_READ(reg);
3834         if (HAS_PCH_CPT(dev_priv)) {
3835                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3836                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3837         } else {
3838                 temp &= ~FDI_LINK_TRAIN_NONE;
3839                 temp |= FDI_LINK_TRAIN_NONE;
3840         }
3841         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3842
3843         /* wait one idle pattern time */
3844         POSTING_READ(reg);
3845         udelay(1000);
3846
3847         /* IVB wants error correction enabled */
3848         if (IS_IVYBRIDGE(dev_priv))
3849                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3850                            FDI_FE_ERRC_ENABLE);
3851 }
3852
3853 /* The FDI link training functions for ILK/Ibexpeak. */
3854 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3855                                     const struct intel_crtc_state *crtc_state)
3856 {
3857         struct drm_device *dev = crtc->base.dev;
3858         struct drm_i915_private *dev_priv = to_i915(dev);
3859         int pipe = crtc->pipe;
3860         i915_reg_t reg;
3861         u32 temp, tries;
3862
3863         /* FDI needs bits from pipe first */
3864         assert_pipe_enabled(dev_priv, pipe);
3865
3866         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3867            for train result */
3868         reg = FDI_RX_IMR(pipe);
3869         temp = I915_READ(reg);
3870         temp &= ~FDI_RX_SYMBOL_LOCK;
3871         temp &= ~FDI_RX_BIT_LOCK;
3872         I915_WRITE(reg, temp);
3873         I915_READ(reg);
3874         udelay(150);
3875
3876         /* enable CPU FDI TX and PCH FDI RX */
3877         reg = FDI_TX_CTL(pipe);
3878         temp = I915_READ(reg);
3879         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3880         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3881         temp &= ~FDI_LINK_TRAIN_NONE;
3882         temp |= FDI_LINK_TRAIN_PATTERN_1;
3883         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3884
3885         reg = FDI_RX_CTL(pipe);
3886         temp = I915_READ(reg);
3887         temp &= ~FDI_LINK_TRAIN_NONE;
3888         temp |= FDI_LINK_TRAIN_PATTERN_1;
3889         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3890
3891         POSTING_READ(reg);
3892         udelay(150);
3893
3894         /* Ironlake workaround, enable clock pointer after FDI enable*/
3895         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3896         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3897                    FDI_RX_PHASE_SYNC_POINTER_EN);
3898
3899         reg = FDI_RX_IIR(pipe);
3900         for (tries = 0; tries < 5; tries++) {
3901                 temp = I915_READ(reg);
3902                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3903
3904                 if ((temp & FDI_RX_BIT_LOCK)) {
3905                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3906                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3907                         break;
3908                 }
3909         }
3910         if (tries == 5)
3911                 DRM_ERROR("FDI train 1 fail!\n");
3912
3913         /* Train 2 */
3914         reg = FDI_TX_CTL(pipe);
3915         temp = I915_READ(reg);
3916         temp &= ~FDI_LINK_TRAIN_NONE;
3917         temp |= FDI_LINK_TRAIN_PATTERN_2;
3918         I915_WRITE(reg, temp);
3919
3920         reg = FDI_RX_CTL(pipe);
3921         temp = I915_READ(reg);
3922         temp &= ~FDI_LINK_TRAIN_NONE;
3923         temp |= FDI_LINK_TRAIN_PATTERN_2;
3924         I915_WRITE(reg, temp);
3925
3926         POSTING_READ(reg);
3927         udelay(150);
3928
3929         reg = FDI_RX_IIR(pipe);
3930         for (tries = 0; tries < 5; tries++) {
3931                 temp = I915_READ(reg);
3932                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3933
3934                 if (temp & FDI_RX_SYMBOL_LOCK) {
3935                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3936                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3937                         break;
3938                 }
3939         }
3940         if (tries == 5)
3941                 DRM_ERROR("FDI train 2 fail!\n");
3942
3943         DRM_DEBUG_KMS("FDI train done\n");
3944
3945 }
3946
3947 static const int snb_b_fdi_train_param[] = {
3948         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3949         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3950         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3951         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3952 };
3953
3954 /* The FDI link training functions for SNB/Cougarpoint. */
3955 static void gen6_fdi_link_train(struct intel_crtc *crtc,
3956                                 const struct intel_crtc_state *crtc_state)
3957 {
3958         struct drm_device *dev = crtc->base.dev;
3959         struct drm_i915_private *dev_priv = to_i915(dev);
3960         int pipe = crtc->pipe;
3961         i915_reg_t reg;
3962         u32 temp, i, retry;
3963
3964         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3965            for train result */
3966         reg = FDI_RX_IMR(pipe);
3967         temp = I915_READ(reg);
3968         temp &= ~FDI_RX_SYMBOL_LOCK;
3969         temp &= ~FDI_RX_BIT_LOCK;
3970         I915_WRITE(reg, temp);
3971
3972         POSTING_READ(reg);
3973         udelay(150);
3974
3975         /* enable CPU FDI TX and PCH FDI RX */
3976         reg = FDI_TX_CTL(pipe);
3977         temp = I915_READ(reg);
3978         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3979         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3980         temp &= ~FDI_LINK_TRAIN_NONE;
3981         temp |= FDI_LINK_TRAIN_PATTERN_1;
3982         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3983         /* SNB-B */
3984         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3985         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3986
3987         I915_WRITE(FDI_RX_MISC(pipe),
3988                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3989
3990         reg = FDI_RX_CTL(pipe);
3991         temp = I915_READ(reg);
3992         if (HAS_PCH_CPT(dev_priv)) {
3993                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3994                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3995         } else {
3996                 temp &= ~FDI_LINK_TRAIN_NONE;
3997                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3998         }
3999         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4000
4001         POSTING_READ(reg);
4002         udelay(150);
4003
4004         for (i = 0; i < 4; i++) {
4005                 reg = FDI_TX_CTL(pipe);
4006                 temp = I915_READ(reg);
4007                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4008                 temp |= snb_b_fdi_train_param[i];
4009                 I915_WRITE(reg, temp);
4010
4011                 POSTING_READ(reg);
4012                 udelay(500);
4013
4014                 for (retry = 0; retry < 5; retry++) {
4015                         reg = FDI_RX_IIR(pipe);
4016                         temp = I915_READ(reg);
4017                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4018                         if (temp & FDI_RX_BIT_LOCK) {
4019                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4020                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4021                                 break;
4022                         }
4023                         udelay(50);
4024                 }
4025                 if (retry < 5)
4026                         break;
4027         }
4028         if (i == 4)
4029                 DRM_ERROR("FDI train 1 fail!\n");
4030
4031         /* Train 2 */
4032         reg = FDI_TX_CTL(pipe);
4033         temp = I915_READ(reg);
4034         temp &= ~FDI_LINK_TRAIN_NONE;
4035         temp |= FDI_LINK_TRAIN_PATTERN_2;
4036         if (IS_GEN6(dev_priv)) {
4037                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4038                 /* SNB-B */
4039                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4040         }
4041         I915_WRITE(reg, temp);
4042
4043         reg = FDI_RX_CTL(pipe);
4044         temp = I915_READ(reg);
4045         if (HAS_PCH_CPT(dev_priv)) {
4046                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4047                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4048         } else {
4049                 temp &= ~FDI_LINK_TRAIN_NONE;
4050                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4051         }
4052         I915_WRITE(reg, temp);
4053
4054         POSTING_READ(reg);
4055         udelay(150);
4056
4057         for (i = 0; i < 4; i++) {
4058                 reg = FDI_TX_CTL(pipe);
4059                 temp = I915_READ(reg);
4060                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4061                 temp |= snb_b_fdi_train_param[i];
4062                 I915_WRITE(reg, temp);
4063
4064                 POSTING_READ(reg);
4065                 udelay(500);
4066
4067                 for (retry = 0; retry < 5; retry++) {
4068                         reg = FDI_RX_IIR(pipe);
4069                         temp = I915_READ(reg);
4070                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4071                         if (temp & FDI_RX_SYMBOL_LOCK) {
4072                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4073                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4074                                 break;
4075                         }
4076                         udelay(50);
4077                 }
4078                 if (retry < 5)
4079                         break;
4080         }
4081         if (i == 4)
4082                 DRM_ERROR("FDI train 2 fail!\n");
4083
4084         DRM_DEBUG_KMS("FDI train done.\n");
4085 }
4086
4087 /* Manual link training for Ivy Bridge A0 parts */
4088 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4089                                       const struct intel_crtc_state *crtc_state)
4090 {
4091         struct drm_device *dev = crtc->base.dev;
4092         struct drm_i915_private *dev_priv = to_i915(dev);
4093         int pipe = crtc->pipe;
4094         i915_reg_t reg;
4095         u32 temp, i, j;
4096
4097         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4098            for train result */
4099         reg = FDI_RX_IMR(pipe);
4100         temp = I915_READ(reg);
4101         temp &= ~FDI_RX_SYMBOL_LOCK;
4102         temp &= ~FDI_RX_BIT_LOCK;
4103         I915_WRITE(reg, temp);
4104
4105         POSTING_READ(reg);
4106         udelay(150);
4107
4108         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4109                       I915_READ(FDI_RX_IIR(pipe)));
4110
4111         /* Try each vswing and preemphasis setting twice before moving on */
4112         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4113                 /* disable first in case we need to retry */
4114                 reg = FDI_TX_CTL(pipe);
4115                 temp = I915_READ(reg);
4116                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4117                 temp &= ~FDI_TX_ENABLE;
4118                 I915_WRITE(reg, temp);
4119
4120                 reg = FDI_RX_CTL(pipe);
4121                 temp = I915_READ(reg);
4122                 temp &= ~FDI_LINK_TRAIN_AUTO;
4123                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4124                 temp &= ~FDI_RX_ENABLE;
4125                 I915_WRITE(reg, temp);
4126
4127                 /* enable CPU FDI TX and PCH FDI RX */
4128                 reg = FDI_TX_CTL(pipe);
4129                 temp = I915_READ(reg);
4130                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4131                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4132                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4133                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4134                 temp |= snb_b_fdi_train_param[j/2];
4135                 temp |= FDI_COMPOSITE_SYNC;
4136                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4137
4138                 I915_WRITE(FDI_RX_MISC(pipe),
4139                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4140
4141                 reg = FDI_RX_CTL(pipe);
4142                 temp = I915_READ(reg);
4143                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4144                 temp |= FDI_COMPOSITE_SYNC;
4145                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4146
4147                 POSTING_READ(reg);
4148                 udelay(1); /* should be 0.5us */
4149
4150                 for (i = 0; i < 4; i++) {
4151                         reg = FDI_RX_IIR(pipe);
4152                         temp = I915_READ(reg);
4153                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4154
4155                         if (temp & FDI_RX_BIT_LOCK ||
4156                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4157                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4158                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4159                                               i);
4160                                 break;
4161                         }
4162                         udelay(1); /* should be 0.5us */
4163                 }
4164                 if (i == 4) {
4165                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4166                         continue;
4167                 }
4168
4169                 /* Train 2 */
4170                 reg = FDI_TX_CTL(pipe);
4171                 temp = I915_READ(reg);
4172                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4173                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4174                 I915_WRITE(reg, temp);
4175
4176                 reg = FDI_RX_CTL(pipe);
4177                 temp = I915_READ(reg);
4178                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4179                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4180                 I915_WRITE(reg, temp);
4181
4182                 POSTING_READ(reg);
4183                 udelay(2); /* should be 1.5us */
4184
4185                 for (i = 0; i < 4; i++) {
4186                         reg = FDI_RX_IIR(pipe);
4187                         temp = I915_READ(reg);
4188                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4189
4190                         if (temp & FDI_RX_SYMBOL_LOCK ||
4191                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4192                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4193                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4194                                               i);
4195                                 goto train_done;
4196                         }
4197                         udelay(2); /* should be 1.5us */
4198                 }
4199                 if (i == 4)
4200                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4201         }
4202
4203 train_done:
4204         DRM_DEBUG_KMS("FDI train done.\n");
4205 }
4206
4207 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4208 {
4209         struct drm_device *dev = intel_crtc->base.dev;
4210         struct drm_i915_private *dev_priv = to_i915(dev);
4211         int pipe = intel_crtc->pipe;
4212         i915_reg_t reg;
4213         u32 temp;
4214
4215         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4216         reg = FDI_RX_CTL(pipe);
4217         temp = I915_READ(reg);
4218         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4219         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4220         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4221         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4222
4223         POSTING_READ(reg);
4224         udelay(200);
4225
4226         /* Switch from Rawclk to PCDclk */
4227         temp = I915_READ(reg);
4228         I915_WRITE(reg, temp | FDI_PCDCLK);
4229
4230         POSTING_READ(reg);
4231         udelay(200);
4232
4233         /* Enable CPU FDI TX PLL, always on for Ironlake */
4234         reg = FDI_TX_CTL(pipe);
4235         temp = I915_READ(reg);
4236         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4237                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4238
4239                 POSTING_READ(reg);
4240                 udelay(100);
4241         }
4242 }
4243
4244 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4245 {
4246         struct drm_device *dev = intel_crtc->base.dev;
4247         struct drm_i915_private *dev_priv = to_i915(dev);
4248         int pipe = intel_crtc->pipe;
4249         i915_reg_t reg;
4250         u32 temp;
4251
4252         /* Switch from PCDclk to Rawclk */
4253         reg = FDI_RX_CTL(pipe);
4254         temp = I915_READ(reg);
4255         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4256
4257         /* Disable CPU FDI TX PLL */
4258         reg = FDI_TX_CTL(pipe);
4259         temp = I915_READ(reg);
4260         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4261
4262         POSTING_READ(reg);
4263         udelay(100);
4264
4265         reg = FDI_RX_CTL(pipe);
4266         temp = I915_READ(reg);
4267         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4268
4269         /* Wait for the clocks to turn off. */
4270         POSTING_READ(reg);
4271         udelay(100);
4272 }
4273
4274 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4275 {
4276         struct drm_device *dev = crtc->dev;
4277         struct drm_i915_private *dev_priv = to_i915(dev);
4278         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4279         int pipe = intel_crtc->pipe;
4280         i915_reg_t reg;
4281         u32 temp;
4282
4283         /* disable CPU FDI tx and PCH FDI rx */
4284         reg = FDI_TX_CTL(pipe);
4285         temp = I915_READ(reg);
4286         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4287         POSTING_READ(reg);
4288
4289         reg = FDI_RX_CTL(pipe);
4290         temp = I915_READ(reg);
4291         temp &= ~(0x7 << 16);
4292         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4293         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4294
4295         POSTING_READ(reg);
4296         udelay(100);
4297
4298         /* Ironlake workaround, disable clock pointer after downing FDI */
4299         if (HAS_PCH_IBX(dev_priv))
4300                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4301
4302         /* still set train pattern 1 */
4303         reg = FDI_TX_CTL(pipe);
4304         temp = I915_READ(reg);
4305         temp &= ~FDI_LINK_TRAIN_NONE;
4306         temp |= FDI_LINK_TRAIN_PATTERN_1;
4307         I915_WRITE(reg, temp);
4308
4309         reg = FDI_RX_CTL(pipe);
4310         temp = I915_READ(reg);
4311         if (HAS_PCH_CPT(dev_priv)) {
4312                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4313                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4314         } else {
4315                 temp &= ~FDI_LINK_TRAIN_NONE;
4316                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4317         }
4318         /* BPC in FDI rx is consistent with that in PIPECONF */
4319         temp &= ~(0x07 << 16);
4320         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4321         I915_WRITE(reg, temp);
4322
4323         POSTING_READ(reg);
4324         udelay(100);
4325 }
4326
4327 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4328 {
4329         struct drm_crtc *crtc;
4330         bool cleanup_done;
4331
4332         drm_for_each_crtc(crtc, &dev_priv->drm) {
4333                 struct drm_crtc_commit *commit;
4334                 spin_lock(&crtc->commit_lock);
4335                 commit = list_first_entry_or_null(&crtc->commit_list,
4336                                                   struct drm_crtc_commit, commit_entry);
4337                 cleanup_done = commit ?
4338                         try_wait_for_completion(&commit->cleanup_done) : true;
4339                 spin_unlock(&crtc->commit_lock);
4340
4341                 if (cleanup_done)
4342                         continue;
4343
4344                 drm_crtc_wait_one_vblank(crtc);
4345
4346                 return true;
4347         }
4348
4349         return false;
4350 }
4351
4352 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4353 {
4354         u32 temp;
4355
4356         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4357
4358         mutex_lock(&dev_priv->sb_lock);
4359
4360         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4361         temp |= SBI_SSCCTL_DISABLE;
4362         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4363
4364         mutex_unlock(&dev_priv->sb_lock);
4365 }
4366
4367 /* Program iCLKIP clock to the desired frequency */
4368 static void lpt_program_iclkip(struct intel_crtc *crtc)
4369 {
4370         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4371         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4372         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4373         u32 temp;
4374
4375         lpt_disable_iclkip(dev_priv);
4376
4377         /* The iCLK virtual clock root frequency is in MHz,
4378          * but the adjusted_mode->crtc_clock in in KHz. To get the
4379          * divisors, it is necessary to divide one by another, so we
4380          * convert the virtual clock precision to KHz here for higher
4381          * precision.
4382          */
4383         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4384                 u32 iclk_virtual_root_freq = 172800 * 1000;
4385                 u32 iclk_pi_range = 64;
4386                 u32 desired_divisor;
4387
4388                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4389                                                     clock << auxdiv);
4390                 divsel = (desired_divisor / iclk_pi_range) - 2;
4391                 phaseinc = desired_divisor % iclk_pi_range;
4392
4393                 /*
4394                  * Near 20MHz is a corner case which is
4395                  * out of range for the 7-bit divisor
4396                  */
4397                 if (divsel <= 0x7f)
4398                         break;
4399         }
4400
4401         /* This should not happen with any sane values */
4402         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4403                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4404         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4405                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4406
4407         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4408                         clock,
4409                         auxdiv,
4410                         divsel,
4411                         phasedir,
4412                         phaseinc);
4413
4414         mutex_lock(&dev_priv->sb_lock);
4415
4416         /* Program SSCDIVINTPHASE6 */
4417         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4418         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4419         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4420         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4421         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4422         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4423         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4424         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4425
4426         /* Program SSCAUXDIV */
4427         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4428         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4429         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4430         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4431
4432         /* Enable modulator and associated divider */
4433         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4434         temp &= ~SBI_SSCCTL_DISABLE;
4435         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4436
4437         mutex_unlock(&dev_priv->sb_lock);
4438
4439         /* Wait for initialization time */
4440         udelay(24);
4441
4442         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4443 }
4444
4445 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4446 {
4447         u32 divsel, phaseinc, auxdiv;
4448         u32 iclk_virtual_root_freq = 172800 * 1000;
4449         u32 iclk_pi_range = 64;
4450         u32 desired_divisor;
4451         u32 temp;
4452
4453         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4454                 return 0;
4455
4456         mutex_lock(&dev_priv->sb_lock);
4457
4458         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4459         if (temp & SBI_SSCCTL_DISABLE) {
4460                 mutex_unlock(&dev_priv->sb_lock);
4461                 return 0;
4462         }
4463
4464         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4465         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4466                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4467         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4468                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4469
4470         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4471         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4472                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4473
4474         mutex_unlock(&dev_priv->sb_lock);
4475
4476         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4477
4478         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4479                                  desired_divisor << auxdiv);
4480 }
4481
4482 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4483                                                 enum pipe pch_transcoder)
4484 {
4485         struct drm_device *dev = crtc->base.dev;
4486         struct drm_i915_private *dev_priv = to_i915(dev);
4487         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4488
4489         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4490                    I915_READ(HTOTAL(cpu_transcoder)));
4491         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4492                    I915_READ(HBLANK(cpu_transcoder)));
4493         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4494                    I915_READ(HSYNC(cpu_transcoder)));
4495
4496         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4497                    I915_READ(VTOTAL(cpu_transcoder)));
4498         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4499                    I915_READ(VBLANK(cpu_transcoder)));
4500         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4501                    I915_READ(VSYNC(cpu_transcoder)));
4502         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4503                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4504 }
4505
4506 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4507 {
4508         struct drm_i915_private *dev_priv = to_i915(dev);
4509         uint32_t temp;
4510
4511         temp = I915_READ(SOUTH_CHICKEN1);
4512         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4513                 return;
4514
4515         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4516         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4517
4518         temp &= ~FDI_BC_BIFURCATION_SELECT;
4519         if (enable)
4520                 temp |= FDI_BC_BIFURCATION_SELECT;
4521
4522         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4523         I915_WRITE(SOUTH_CHICKEN1, temp);
4524         POSTING_READ(SOUTH_CHICKEN1);
4525 }
4526
4527 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4528 {
4529         struct drm_device *dev = intel_crtc->base.dev;
4530
4531         switch (intel_crtc->pipe) {
4532         case PIPE_A:
4533                 break;
4534         case PIPE_B:
4535                 if (intel_crtc->config->fdi_lanes > 2)
4536                         cpt_set_fdi_bc_bifurcation(dev, false);
4537                 else
4538                         cpt_set_fdi_bc_bifurcation(dev, true);
4539
4540                 break;
4541         case PIPE_C:
4542                 cpt_set_fdi_bc_bifurcation(dev, true);
4543
4544                 break;
4545         default:
4546                 BUG();
4547         }
4548 }
4549
4550 /* Return which DP Port should be selected for Transcoder DP control */
4551 static enum port
4552 intel_trans_dp_port_sel(struct intel_crtc *crtc)
4553 {
4554         struct drm_device *dev = crtc->base.dev;
4555         struct intel_encoder *encoder;
4556
4557         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
4558                 if (encoder->type == INTEL_OUTPUT_DP ||
4559                     encoder->type == INTEL_OUTPUT_EDP)
4560                         return encoder->port;
4561         }
4562
4563         return -1;
4564 }
4565
4566 /*
4567  * Enable PCH resources required for PCH ports:
4568  *   - PCH PLLs
4569  *   - FDI training & RX/TX
4570  *   - update transcoder timings
4571  *   - DP transcoding bits
4572  *   - transcoder
4573  */
4574 static void ironlake_pch_enable(const struct intel_crtc_state *crtc_state)
4575 {
4576         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4577         struct drm_device *dev = crtc->base.dev;
4578         struct drm_i915_private *dev_priv = to_i915(dev);
4579         int pipe = crtc->pipe;
4580         u32 temp;
4581
4582         assert_pch_transcoder_disabled(dev_priv, pipe);
4583
4584         if (IS_IVYBRIDGE(dev_priv))
4585                 ivybridge_update_fdi_bc_bifurcation(crtc);
4586
4587         /* Write the TU size bits before fdi link training, so that error
4588          * detection works. */
4589         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4590                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4591
4592         /* For PCH output, training FDI link */
4593         dev_priv->display.fdi_link_train(crtc, crtc_state);
4594
4595         /* We need to program the right clock selection before writing the pixel
4596          * mutliplier into the DPLL. */
4597         if (HAS_PCH_CPT(dev_priv)) {
4598                 u32 sel;
4599
4600                 temp = I915_READ(PCH_DPLL_SEL);
4601                 temp |= TRANS_DPLL_ENABLE(pipe);
4602                 sel = TRANS_DPLLB_SEL(pipe);
4603                 if (crtc_state->shared_dpll ==
4604                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4605                         temp |= sel;
4606                 else
4607                         temp &= ~sel;
4608                 I915_WRITE(PCH_DPLL_SEL, temp);
4609         }
4610
4611         /* XXX: pch pll's can be enabled any time before we enable the PCH
4612          * transcoder, and we actually should do this to not upset any PCH
4613          * transcoder that already use the clock when we share it.
4614          *
4615          * Note that enable_shared_dpll tries to do the right thing, but
4616          * get_shared_dpll unconditionally resets the pll - we need that to have
4617          * the right LVDS enable sequence. */
4618         intel_enable_shared_dpll(crtc);
4619
4620         /* set transcoder timing, panel must allow it */
4621         assert_panel_unlocked(dev_priv, pipe);
4622         ironlake_pch_transcoder_set_timings(crtc, pipe);
4623
4624         intel_fdi_normal_train(crtc);
4625
4626         /* For PCH DP, enable TRANS_DP_CTL */
4627         if (HAS_PCH_CPT(dev_priv) &&
4628             intel_crtc_has_dp_encoder(crtc_state)) {
4629                 const struct drm_display_mode *adjusted_mode =
4630                         &crtc_state->base.adjusted_mode;
4631                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4632                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4633                 temp = I915_READ(reg);
4634                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4635                           TRANS_DP_SYNC_MASK |
4636                           TRANS_DP_BPC_MASK);
4637                 temp |= TRANS_DP_OUTPUT_ENABLE;
4638                 temp |= bpc << 9; /* same format but at 11:9 */
4639
4640                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4641                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4642                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4643                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4644
4645                 switch (intel_trans_dp_port_sel(crtc)) {
4646                 case PORT_B:
4647                         temp |= TRANS_DP_PORT_SEL_B;
4648                         break;
4649                 case PORT_C:
4650                         temp |= TRANS_DP_PORT_SEL_C;
4651                         break;
4652                 case PORT_D:
4653                         temp |= TRANS_DP_PORT_SEL_D;
4654                         break;
4655                 default:
4656                         BUG();
4657                 }
4658
4659                 I915_WRITE(reg, temp);
4660         }
4661
4662         ironlake_enable_pch_transcoder(dev_priv, pipe);
4663 }
4664
4665 static void lpt_pch_enable(const struct intel_crtc_state *crtc_state)
4666 {
4667         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4668         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4669         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4670
4671         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4672
4673         lpt_program_iclkip(crtc);
4674
4675         /* Set transcoder timing. */
4676         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4677
4678         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4679 }
4680
4681 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4682 {
4683         struct drm_i915_private *dev_priv = to_i915(dev);
4684         i915_reg_t dslreg = PIPEDSL(pipe);
4685         u32 temp;
4686
4687         temp = I915_READ(dslreg);
4688         udelay(500);
4689         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4690                 if (wait_for(I915_READ(dslreg) != temp, 5))
4691                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4692         }
4693 }
4694
4695 static int
4696 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4697                   unsigned int scaler_user, int *scaler_id,
4698                   int src_w, int src_h, int dst_w, int dst_h)
4699 {
4700         struct intel_crtc_scaler_state *scaler_state =
4701                 &crtc_state->scaler_state;
4702         struct intel_crtc *intel_crtc =
4703                 to_intel_crtc(crtc_state->base.crtc);
4704         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4705         const struct drm_display_mode *adjusted_mode =
4706                 &crtc_state->base.adjusted_mode;
4707         int need_scaling;
4708
4709         /*
4710          * Src coordinates are already rotated by 270 degrees for
4711          * the 90/270 degree plane rotation cases (to match the
4712          * GTT mapping), hence no need to account for rotation here.
4713          */
4714         need_scaling = src_w != dst_w || src_h != dst_h;
4715
4716         if (crtc_state->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4717                 need_scaling = true;
4718
4719         /*
4720          * Scaling/fitting not supported in IF-ID mode in GEN9+
4721          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4722          * Once NV12 is enabled, handle it here while allocating scaler
4723          * for NV12.
4724          */
4725         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4726             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4727                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4728                 return -EINVAL;
4729         }
4730
4731         /*
4732          * if plane is being disabled or scaler is no more required or force detach
4733          *  - free scaler binded to this plane/crtc
4734          *  - in order to do this, update crtc->scaler_usage
4735          *
4736          * Here scaler state in crtc_state is set free so that
4737          * scaler can be assigned to other user. Actual register
4738          * update to free the scaler is done in plane/panel-fit programming.
4739          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4740          */
4741         if (force_detach || !need_scaling) {
4742                 if (*scaler_id >= 0) {
4743                         scaler_state->scaler_users &= ~(1 << scaler_user);
4744                         scaler_state->scalers[*scaler_id].in_use = 0;
4745
4746                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4747                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4748                                 intel_crtc->pipe, scaler_user, *scaler_id,
4749                                 scaler_state->scaler_users);
4750                         *scaler_id = -1;
4751                 }
4752                 return 0;
4753         }
4754
4755         /* range checks */
4756         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4757                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4758
4759                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4760                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4761                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4762                         "size is out of scaler range\n",
4763                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4764                 return -EINVAL;
4765         }
4766
4767         /* mark this plane as a scaler user in crtc_state */
4768         scaler_state->scaler_users |= (1 << scaler_user);
4769         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4770                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4771                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4772                 scaler_state->scaler_users);
4773
4774         return 0;
4775 }
4776
4777 /**
4778  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4779  *
4780  * @state: crtc's scaler state
4781  *
4782  * Return
4783  *     0 - scaler_usage updated successfully
4784  *    error - requested scaling cannot be supported or other error condition
4785  */
4786 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4787 {
4788         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4789
4790         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4791                 &state->scaler_state.scaler_id,
4792                 state->pipe_src_w, state->pipe_src_h,
4793                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4794 }
4795
4796 /**
4797  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4798  * @crtc_state: crtc's scaler state
4799  * @plane_state: atomic plane state to update
4800  *
4801  * Return
4802  *     0 - scaler_usage updated successfully
4803  *    error - requested scaling cannot be supported or other error condition
4804  */
4805 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4806                                    struct intel_plane_state *plane_state)
4807 {
4808
4809         struct intel_plane *intel_plane =
4810                 to_intel_plane(plane_state->base.plane);
4811         struct drm_framebuffer *fb = plane_state->base.fb;
4812         int ret;
4813
4814         bool force_detach = !fb || !plane_state->base.visible;
4815
4816         ret = skl_update_scaler(crtc_state, force_detach,
4817                                 drm_plane_index(&intel_plane->base),
4818                                 &plane_state->scaler_id,
4819                                 drm_rect_width(&plane_state->base.src) >> 16,
4820                                 drm_rect_height(&plane_state->base.src) >> 16,
4821                                 drm_rect_width(&plane_state->base.dst),
4822                                 drm_rect_height(&plane_state->base.dst));
4823
4824         if (ret || plane_state->scaler_id < 0)
4825                 return ret;
4826
4827         /* check colorkey */
4828         if (plane_state->ckey.flags) {
4829                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4830                               intel_plane->base.base.id,
4831                               intel_plane->base.name);
4832                 return -EINVAL;
4833         }
4834
4835         /* Check src format */
4836         switch (fb->format->format) {
4837         case DRM_FORMAT_RGB565:
4838         case DRM_FORMAT_XBGR8888:
4839         case DRM_FORMAT_XRGB8888:
4840         case DRM_FORMAT_ABGR8888:
4841         case DRM_FORMAT_ARGB8888:
4842         case DRM_FORMAT_XRGB2101010:
4843         case DRM_FORMAT_XBGR2101010:
4844         case DRM_FORMAT_YUYV:
4845         case DRM_FORMAT_YVYU:
4846         case DRM_FORMAT_UYVY:
4847         case DRM_FORMAT_VYUY:
4848                 break;
4849         default:
4850                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4851                               intel_plane->base.base.id, intel_plane->base.name,
4852                               fb->base.id, fb->format->format);
4853                 return -EINVAL;
4854         }
4855
4856         return 0;
4857 }
4858
4859 static void skylake_scaler_disable(struct intel_crtc *crtc)
4860 {
4861         int i;
4862
4863         for (i = 0; i < crtc->num_scalers; i++)
4864                 skl_detach_scaler(crtc, i);
4865 }
4866
4867 static void skylake_pfit_enable(struct intel_crtc *crtc)
4868 {
4869         struct drm_device *dev = crtc->base.dev;
4870         struct drm_i915_private *dev_priv = to_i915(dev);
4871         int pipe = crtc->pipe;
4872         struct intel_crtc_scaler_state *scaler_state =
4873                 &crtc->config->scaler_state;
4874
4875         if (crtc->config->pch_pfit.enabled) {
4876                 int id;
4877
4878                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4879                         return;
4880
4881                 id = scaler_state->scaler_id;
4882                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4883                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4884                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4885                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4886         }
4887 }
4888
4889 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4890 {
4891         struct drm_device *dev = crtc->base.dev;
4892         struct drm_i915_private *dev_priv = to_i915(dev);
4893         int pipe = crtc->pipe;
4894
4895         if (crtc->config->pch_pfit.enabled) {
4896                 /* Force use of hard-coded filter coefficients
4897                  * as some pre-programmed values are broken,
4898                  * e.g. x201.
4899                  */
4900                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4901                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4902                                                  PF_PIPE_SEL_IVB(pipe));
4903                 else
4904                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4905                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4906                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4907         }
4908 }
4909
4910 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
4911 {
4912         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4913         struct drm_device *dev = crtc->base.dev;
4914         struct drm_i915_private *dev_priv = to_i915(dev);
4915
4916         if (!crtc_state->ips_enabled)
4917                 return;
4918
4919         /*
4920          * We can only enable IPS after we enable a plane and wait for a vblank
4921          * This function is called from post_plane_update, which is run after
4922          * a vblank wait.
4923          */
4924         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
4925
4926         if (IS_BROADWELL(dev_priv)) {
4927                 mutex_lock(&dev_priv->pcu_lock);
4928                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
4929                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
4930                 mutex_unlock(&dev_priv->pcu_lock);
4931                 /* Quoting Art Runyan: "its not safe to expect any particular
4932                  * value in IPS_CTL bit 31 after enabling IPS through the
4933                  * mailbox." Moreover, the mailbox may return a bogus state,
4934                  * so we need to just enable it and continue on.
4935                  */
4936         } else {
4937                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4938                 /* The bit only becomes 1 in the next vblank, so this wait here
4939                  * is essentially intel_wait_for_vblank. If we don't have this
4940                  * and don't wait for vblanks until the end of crtc_enable, then
4941                  * the HW state readout code will complain that the expected
4942                  * IPS_CTL value is not the one we read. */
4943                 if (intel_wait_for_register(dev_priv,
4944                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4945                                             50))
4946                         DRM_ERROR("Timed out waiting for IPS enable\n");
4947         }
4948 }
4949
4950 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
4951 {
4952         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4953         struct drm_device *dev = crtc->base.dev;
4954         struct drm_i915_private *dev_priv = to_i915(dev);
4955
4956         if (!crtc_state->ips_enabled)
4957                 return;
4958
4959         if (IS_BROADWELL(dev_priv)) {
4960                 mutex_lock(&dev_priv->pcu_lock);
4961                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4962                 mutex_unlock(&dev_priv->pcu_lock);
4963                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4964                 if (intel_wait_for_register(dev_priv,
4965                                             IPS_CTL, IPS_ENABLE, 0,
4966                                             42))
4967                         DRM_ERROR("Timed out waiting for IPS disable\n");
4968         } else {
4969                 I915_WRITE(IPS_CTL, 0);
4970                 POSTING_READ(IPS_CTL);
4971         }
4972
4973         /* We need to wait for a vblank before we can disable the plane. */
4974         intel_wait_for_vblank(dev_priv, crtc->pipe);
4975 }
4976
4977 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4978 {
4979         if (intel_crtc->overlay) {
4980                 struct drm_device *dev = intel_crtc->base.dev;
4981
4982                 mutex_lock(&dev->struct_mutex);
4983                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4984                 mutex_unlock(&dev->struct_mutex);
4985         }
4986
4987         /* Let userspace switch the overlay on again. In most cases userspace
4988          * has to recompute where to put it anyway.
4989          */
4990 }
4991
4992 /**
4993  * intel_post_enable_primary - Perform operations after enabling primary plane
4994  * @crtc: the CRTC whose primary plane was just enabled
4995  * @new_crtc_state: the enabling state
4996  *
4997  * Performs potentially sleeping operations that must be done after the primary
4998  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4999  * called due to an explicit primary plane update, or due to an implicit
5000  * re-enable that is caused when a sprite plane is updated to no longer
5001  * completely hide the primary plane.
5002  */
5003 static void
5004 intel_post_enable_primary(struct drm_crtc *crtc,
5005                           const struct intel_crtc_state *new_crtc_state)
5006 {
5007         struct drm_device *dev = crtc->dev;
5008         struct drm_i915_private *dev_priv = to_i915(dev);
5009         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5010         int pipe = intel_crtc->pipe;
5011
5012         /*
5013          * Gen2 reports pipe underruns whenever all planes are disabled.
5014          * So don't enable underrun reporting before at least some planes
5015          * are enabled.
5016          * FIXME: Need to fix the logic to work when we turn off all planes
5017          * but leave the pipe running.
5018          */
5019         if (IS_GEN2(dev_priv))
5020                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5021
5022         /* Underruns don't always raise interrupts, so check manually. */
5023         intel_check_cpu_fifo_underruns(dev_priv);
5024         intel_check_pch_fifo_underruns(dev_priv);
5025 }
5026
5027 /* FIXME get rid of this and use pre_plane_update */
5028 static void
5029 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5030 {
5031         struct drm_device *dev = crtc->dev;
5032         struct drm_i915_private *dev_priv = to_i915(dev);
5033         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5034         int pipe = intel_crtc->pipe;
5035
5036         /*
5037          * Gen2 reports pipe underruns whenever all planes are disabled.
5038          * So disable underrun reporting before all the planes get disabled.
5039          */
5040         if (IS_GEN2(dev_priv))
5041                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5042
5043         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5044
5045         /*
5046          * Vblank time updates from the shadow to live plane control register
5047          * are blocked if the memory self-refresh mode is active at that
5048          * moment. So to make sure the plane gets truly disabled, disable
5049          * first the self-refresh mode. The self-refresh enable bit in turn
5050          * will be checked/applied by the HW only at the next frame start
5051          * event which is after the vblank start event, so we need to have a
5052          * wait-for-vblank between disabling the plane and the pipe.
5053          */
5054         if (HAS_GMCH_DISPLAY(dev_priv) &&
5055             intel_set_memory_cxsr(dev_priv, false))
5056                 intel_wait_for_vblank(dev_priv, pipe);
5057 }
5058
5059 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5060                                        const struct intel_crtc_state *new_crtc_state)
5061 {
5062         if (!old_crtc_state->ips_enabled)
5063                 return false;
5064
5065         if (needs_modeset(&new_crtc_state->base))
5066                 return true;
5067
5068         return !new_crtc_state->ips_enabled;
5069 }
5070
5071 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5072                                        const struct intel_crtc_state *new_crtc_state)
5073 {
5074         if (!new_crtc_state->ips_enabled)
5075                 return false;
5076
5077         if (needs_modeset(&new_crtc_state->base))
5078                 return true;
5079
5080         /*
5081          * We can't read out IPS on broadwell, assume the worst and
5082          * forcibly enable IPS on the first fastset.
5083          */
5084         if (new_crtc_state->update_pipe &&
5085             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5086                 return true;
5087
5088         return !old_crtc_state->ips_enabled;
5089 }
5090
5091 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5092 {
5093         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5094         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5095         struct intel_crtc_state *pipe_config =
5096                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5097                                                 crtc);
5098         struct drm_plane *primary = crtc->base.primary;
5099         struct drm_plane_state *old_pri_state =
5100                 drm_atomic_get_existing_plane_state(old_state, primary);
5101
5102         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5103
5104         if (pipe_config->update_wm_post && pipe_config->base.active)
5105                 intel_update_watermarks(crtc);
5106
5107         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5108                 hsw_enable_ips(pipe_config);
5109
5110         if (old_pri_state) {
5111                 struct intel_plane_state *primary_state =
5112                         intel_atomic_get_new_plane_state(to_intel_atomic_state(old_state),
5113                                                          to_intel_plane(primary));
5114                 struct intel_plane_state *old_primary_state =
5115                         to_intel_plane_state(old_pri_state);
5116
5117                 intel_fbc_post_update(crtc);
5118
5119                 if (primary_state->base.visible &&
5120                     (needs_modeset(&pipe_config->base) ||
5121                      !old_primary_state->base.visible))
5122                         intel_post_enable_primary(&crtc->base, pipe_config);
5123         }
5124 }
5125
5126 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5127                                    struct intel_crtc_state *pipe_config)
5128 {
5129         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5130         struct drm_device *dev = crtc->base.dev;
5131         struct drm_i915_private *dev_priv = to_i915(dev);
5132         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5133         struct drm_plane *primary = crtc->base.primary;
5134         struct drm_plane_state *old_pri_state =
5135                 drm_atomic_get_existing_plane_state(old_state, primary);
5136         bool modeset = needs_modeset(&pipe_config->base);
5137         struct intel_atomic_state *old_intel_state =
5138                 to_intel_atomic_state(old_state);
5139
5140         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5141                 hsw_disable_ips(old_crtc_state);
5142
5143         if (old_pri_state) {
5144                 struct intel_plane_state *primary_state =
5145                         intel_atomic_get_new_plane_state(old_intel_state,
5146                                                          to_intel_plane(primary));
5147                 struct intel_plane_state *old_primary_state =
5148                         to_intel_plane_state(old_pri_state);
5149
5150                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5151                 /*
5152                  * Gen2 reports pipe underruns whenever all planes are disabled.
5153                  * So disable underrun reporting before all the planes get disabled.
5154                  */
5155                 if (IS_GEN2(dev_priv) && old_primary_state->base.visible &&
5156                     (modeset || !primary_state->base.visible))
5157                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5158         }
5159
5160         /*
5161          * Vblank time updates from the shadow to live plane control register
5162          * are blocked if the memory self-refresh mode is active at that
5163          * moment. So to make sure the plane gets truly disabled, disable
5164          * first the self-refresh mode. The self-refresh enable bit in turn
5165          * will be checked/applied by the HW only at the next frame start
5166          * event which is after the vblank start event, so we need to have a
5167          * wait-for-vblank between disabling the plane and the pipe.
5168          */
5169         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5170             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5171                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5172
5173         /*
5174          * IVB workaround: must disable low power watermarks for at least
5175          * one frame before enabling scaling.  LP watermarks can be re-enabled
5176          * when scaling is disabled.
5177          *
5178          * WaCxSRDisabledForSpriteScaling:ivb
5179          */
5180         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5181                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5182
5183         /*
5184          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5185          * watermark programming here.
5186          */
5187         if (needs_modeset(&pipe_config->base))
5188                 return;
5189
5190         /*
5191          * For platforms that support atomic watermarks, program the
5192          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5193          * will be the intermediate values that are safe for both pre- and
5194          * post- vblank; when vblank happens, the 'active' values will be set
5195          * to the final 'target' values and we'll do this again to get the
5196          * optimal watermarks.  For gen9+ platforms, the values we program here
5197          * will be the final target values which will get automatically latched
5198          * at vblank time; no further programming will be necessary.
5199          *
5200          * If a platform hasn't been transitioned to atomic watermarks yet,
5201          * we'll continue to update watermarks the old way, if flags tell
5202          * us to.
5203          */
5204         if (dev_priv->display.initial_watermarks != NULL)
5205                 dev_priv->display.initial_watermarks(old_intel_state,
5206                                                      pipe_config);
5207         else if (pipe_config->update_wm_pre)
5208                 intel_update_watermarks(crtc);
5209 }
5210
5211 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5212 {
5213         struct drm_device *dev = crtc->dev;
5214         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5215         struct drm_plane *p;
5216         int pipe = intel_crtc->pipe;
5217
5218         intel_crtc_dpms_overlay_disable(intel_crtc);
5219
5220         drm_for_each_plane_mask(p, dev, plane_mask)
5221                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5222
5223         /*
5224          * FIXME: Once we grow proper nuclear flip support out of this we need
5225          * to compute the mask of flip planes precisely. For the time being
5226          * consider this a flip to a NULL plane.
5227          */
5228         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5229 }
5230
5231 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5232                                           struct intel_crtc_state *crtc_state,
5233                                           struct drm_atomic_state *old_state)
5234 {
5235         struct drm_connector_state *conn_state;
5236         struct drm_connector *conn;
5237         int i;
5238
5239         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5240                 struct intel_encoder *encoder =
5241                         to_intel_encoder(conn_state->best_encoder);
5242
5243                 if (conn_state->crtc != crtc)
5244                         continue;
5245
5246                 if (encoder->pre_pll_enable)
5247                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5248         }
5249 }
5250
5251 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5252                                       struct intel_crtc_state *crtc_state,
5253                                       struct drm_atomic_state *old_state)
5254 {
5255         struct drm_connector_state *conn_state;
5256         struct drm_connector *conn;
5257         int i;
5258
5259         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5260                 struct intel_encoder *encoder =
5261                         to_intel_encoder(conn_state->best_encoder);
5262
5263                 if (conn_state->crtc != crtc)
5264                         continue;
5265
5266                 if (encoder->pre_enable)
5267                         encoder->pre_enable(encoder, crtc_state, conn_state);
5268         }
5269 }
5270
5271 static void intel_encoders_enable(struct drm_crtc *crtc,
5272                                   struct intel_crtc_state *crtc_state,
5273                                   struct drm_atomic_state *old_state)
5274 {
5275         struct drm_connector_state *conn_state;
5276         struct drm_connector *conn;
5277         int i;
5278
5279         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5280                 struct intel_encoder *encoder =
5281                         to_intel_encoder(conn_state->best_encoder);
5282
5283                 if (conn_state->crtc != crtc)
5284                         continue;
5285
5286                 encoder->enable(encoder, crtc_state, conn_state);
5287                 intel_opregion_notify_encoder(encoder, true);
5288         }
5289 }
5290
5291 static void intel_encoders_disable(struct drm_crtc *crtc,
5292                                    struct intel_crtc_state *old_crtc_state,
5293                                    struct drm_atomic_state *old_state)
5294 {
5295         struct drm_connector_state *old_conn_state;
5296         struct drm_connector *conn;
5297         int i;
5298
5299         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5300                 struct intel_encoder *encoder =
5301                         to_intel_encoder(old_conn_state->best_encoder);
5302
5303                 if (old_conn_state->crtc != crtc)
5304                         continue;
5305
5306                 intel_opregion_notify_encoder(encoder, false);
5307                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5308         }
5309 }
5310
5311 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5312                                         struct intel_crtc_state *old_crtc_state,
5313                                         struct drm_atomic_state *old_state)
5314 {
5315         struct drm_connector_state *old_conn_state;
5316         struct drm_connector *conn;
5317         int i;
5318
5319         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5320                 struct intel_encoder *encoder =
5321                         to_intel_encoder(old_conn_state->best_encoder);
5322
5323                 if (old_conn_state->crtc != crtc)
5324                         continue;
5325
5326                 if (encoder->post_disable)
5327                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5328         }
5329 }
5330
5331 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5332                                             struct intel_crtc_state *old_crtc_state,
5333                                             struct drm_atomic_state *old_state)
5334 {
5335         struct drm_connector_state *old_conn_state;
5336         struct drm_connector *conn;
5337         int i;
5338
5339         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5340                 struct intel_encoder *encoder =
5341                         to_intel_encoder(old_conn_state->best_encoder);
5342
5343                 if (old_conn_state->crtc != crtc)
5344                         continue;
5345
5346                 if (encoder->post_pll_disable)
5347                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5348         }
5349 }
5350
5351 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5352                                  struct drm_atomic_state *old_state)
5353 {
5354         struct drm_crtc *crtc = pipe_config->base.crtc;
5355         struct drm_device *dev = crtc->dev;
5356         struct drm_i915_private *dev_priv = to_i915(dev);
5357         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5358         int pipe = intel_crtc->pipe;
5359         struct intel_atomic_state *old_intel_state =
5360                 to_intel_atomic_state(old_state);
5361
5362         if (WARN_ON(intel_crtc->active))
5363                 return;
5364
5365         /*
5366          * Sometimes spurious CPU pipe underruns happen during FDI
5367          * training, at least with VGA+HDMI cloning. Suppress them.
5368          *
5369          * On ILK we get an occasional spurious CPU pipe underruns
5370          * between eDP port A enable and vdd enable. Also PCH port
5371          * enable seems to result in the occasional CPU pipe underrun.
5372          *
5373          * Spurious PCH underruns also occur during PCH enabling.
5374          */
5375         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5376                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5377         if (intel_crtc->config->has_pch_encoder)
5378                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5379
5380         if (intel_crtc->config->has_pch_encoder)
5381                 intel_prepare_shared_dpll(intel_crtc);
5382
5383         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5384                 intel_dp_set_m_n(intel_crtc, M1_N1);
5385
5386         intel_set_pipe_timings(intel_crtc);
5387         intel_set_pipe_src_size(intel_crtc);
5388
5389         if (intel_crtc->config->has_pch_encoder) {
5390                 intel_cpu_transcoder_set_m_n(intel_crtc,
5391                                      &intel_crtc->config->fdi_m_n, NULL);
5392         }
5393
5394         ironlake_set_pipeconf(crtc);
5395
5396         intel_crtc->active = true;
5397
5398         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5399
5400         if (intel_crtc->config->has_pch_encoder) {
5401                 /* Note: FDI PLL enabling _must_ be done before we enable the
5402                  * cpu pipes, hence this is separate from all the other fdi/pch
5403                  * enabling. */
5404                 ironlake_fdi_pll_enable(intel_crtc);
5405         } else {
5406                 assert_fdi_tx_disabled(dev_priv, pipe);
5407                 assert_fdi_rx_disabled(dev_priv, pipe);
5408         }
5409
5410         ironlake_pfit_enable(intel_crtc);
5411
5412         /*
5413          * On ILK+ LUT must be loaded before the pipe is running but with
5414          * clocks enabled
5415          */
5416         intel_color_load_luts(&pipe_config->base);
5417
5418         if (dev_priv->display.initial_watermarks != NULL)
5419                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5420         intel_enable_pipe(pipe_config);
5421
5422         if (intel_crtc->config->has_pch_encoder)
5423                 ironlake_pch_enable(pipe_config);
5424
5425         assert_vblank_disabled(crtc);
5426         drm_crtc_vblank_on(crtc);
5427
5428         intel_encoders_enable(crtc, pipe_config, old_state);
5429
5430         if (HAS_PCH_CPT(dev_priv))
5431                 cpt_verify_modeset(dev, intel_crtc->pipe);
5432
5433         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5434         if (intel_crtc->config->has_pch_encoder)
5435                 intel_wait_for_vblank(dev_priv, pipe);
5436         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5437         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5438 }
5439
5440 /* IPS only exists on ULT machines and is tied to pipe A. */
5441 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5442 {
5443         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5444 }
5445
5446 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5447                                             enum pipe pipe, bool apply)
5448 {
5449         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5450         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5451
5452         if (apply)
5453                 val |= mask;
5454         else
5455                 val &= ~mask;
5456
5457         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5458 }
5459
5460 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5461 {
5462         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5463         enum pipe pipe = crtc->pipe;
5464         uint32_t val;
5465
5466         val = MBUS_DBOX_BW_CREDIT(1) | MBUS_DBOX_A_CREDIT(2);
5467
5468         /* Program B credit equally to all pipes */
5469         val |= MBUS_DBOX_B_CREDIT(24 / INTEL_INFO(dev_priv)->num_pipes);
5470
5471         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5472 }
5473
5474 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5475                                 struct drm_atomic_state *old_state)
5476 {
5477         struct drm_crtc *crtc = pipe_config->base.crtc;
5478         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5479         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5480         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5481         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5482         struct intel_atomic_state *old_intel_state =
5483                 to_intel_atomic_state(old_state);
5484         bool psl_clkgate_wa;
5485
5486         if (WARN_ON(intel_crtc->active))
5487                 return;
5488
5489         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5490
5491         if (intel_crtc->config->shared_dpll)
5492                 intel_enable_shared_dpll(intel_crtc);
5493
5494         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5495                 intel_dp_set_m_n(intel_crtc, M1_N1);
5496
5497         if (!transcoder_is_dsi(cpu_transcoder))
5498                 intel_set_pipe_timings(intel_crtc);
5499
5500         intel_set_pipe_src_size(intel_crtc);
5501
5502         if (cpu_transcoder != TRANSCODER_EDP &&
5503             !transcoder_is_dsi(cpu_transcoder)) {
5504                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5505                            intel_crtc->config->pixel_multiplier - 1);
5506         }
5507
5508         if (intel_crtc->config->has_pch_encoder) {
5509                 intel_cpu_transcoder_set_m_n(intel_crtc,
5510                                      &intel_crtc->config->fdi_m_n, NULL);
5511         }
5512
5513         if (!transcoder_is_dsi(cpu_transcoder))
5514                 haswell_set_pipeconf(crtc);
5515
5516         haswell_set_pipemisc(crtc);
5517
5518         intel_color_set_csc(&pipe_config->base);
5519
5520         intel_crtc->active = true;
5521
5522         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5523
5524         if (!transcoder_is_dsi(cpu_transcoder))
5525                 intel_ddi_enable_pipe_clock(pipe_config);
5526
5527         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5528         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5529                          intel_crtc->config->pch_pfit.enabled;
5530         if (psl_clkgate_wa)
5531                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5532
5533         if (INTEL_GEN(dev_priv) >= 9)
5534                 skylake_pfit_enable(intel_crtc);
5535         else
5536                 ironlake_pfit_enable(intel_crtc);
5537
5538         /*
5539          * On ILK+ LUT must be loaded before the pipe is running but with
5540          * clocks enabled
5541          */
5542         intel_color_load_luts(&pipe_config->base);
5543
5544         intel_ddi_set_pipe_settings(pipe_config);
5545         if (!transcoder_is_dsi(cpu_transcoder))
5546                 intel_ddi_enable_transcoder_func(pipe_config);
5547
5548         if (dev_priv->display.initial_watermarks != NULL)
5549                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5550
5551         if (INTEL_GEN(dev_priv) >= 11)
5552                 icl_pipe_mbus_enable(intel_crtc);
5553
5554         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5555         if (!transcoder_is_dsi(cpu_transcoder))
5556                 intel_enable_pipe(pipe_config);
5557
5558         if (intel_crtc->config->has_pch_encoder)
5559                 lpt_pch_enable(pipe_config);
5560
5561         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5562                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5563
5564         assert_vblank_disabled(crtc);
5565         drm_crtc_vblank_on(crtc);
5566
5567         intel_encoders_enable(crtc, pipe_config, old_state);
5568
5569         if (psl_clkgate_wa) {
5570                 intel_wait_for_vblank(dev_priv, pipe);
5571                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5572         }
5573
5574         /* If we change the relative order between pipe/planes enabling, we need
5575          * to change the workaround. */
5576         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5577         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5578                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5579                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5580         }
5581 }
5582
5583 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5584 {
5585         struct drm_device *dev = crtc->base.dev;
5586         struct drm_i915_private *dev_priv = to_i915(dev);
5587         int pipe = crtc->pipe;
5588
5589         /* To avoid upsetting the power well on haswell only disable the pfit if
5590          * it's in use. The hw state code will make sure we get this right. */
5591         if (force || crtc->config->pch_pfit.enabled) {
5592                 I915_WRITE(PF_CTL(pipe), 0);
5593                 I915_WRITE(PF_WIN_POS(pipe), 0);
5594                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5595         }
5596 }
5597
5598 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5599                                   struct drm_atomic_state *old_state)
5600 {
5601         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5602         struct drm_device *dev = crtc->dev;
5603         struct drm_i915_private *dev_priv = to_i915(dev);
5604         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5605         int pipe = intel_crtc->pipe;
5606
5607         /*
5608          * Sometimes spurious CPU pipe underruns happen when the
5609          * pipe is already disabled, but FDI RX/TX is still enabled.
5610          * Happens at least with VGA+HDMI cloning. Suppress them.
5611          */
5612         if (intel_crtc->config->has_pch_encoder) {
5613                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5614                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5615         }
5616
5617         intel_encoders_disable(crtc, old_crtc_state, old_state);
5618
5619         drm_crtc_vblank_off(crtc);
5620         assert_vblank_disabled(crtc);
5621
5622         intel_disable_pipe(old_crtc_state);
5623
5624         ironlake_pfit_disable(intel_crtc, false);
5625
5626         if (intel_crtc->config->has_pch_encoder)
5627                 ironlake_fdi_disable(crtc);
5628
5629         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5630
5631         if (intel_crtc->config->has_pch_encoder) {
5632                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5633
5634                 if (HAS_PCH_CPT(dev_priv)) {
5635                         i915_reg_t reg;
5636                         u32 temp;
5637
5638                         /* disable TRANS_DP_CTL */
5639                         reg = TRANS_DP_CTL(pipe);
5640                         temp = I915_READ(reg);
5641                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5642                                   TRANS_DP_PORT_SEL_MASK);
5643                         temp |= TRANS_DP_PORT_SEL_NONE;
5644                         I915_WRITE(reg, temp);
5645
5646                         /* disable DPLL_SEL */
5647                         temp = I915_READ(PCH_DPLL_SEL);
5648                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5649                         I915_WRITE(PCH_DPLL_SEL, temp);
5650                 }
5651
5652                 ironlake_fdi_pll_disable(intel_crtc);
5653         }
5654
5655         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5656         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5657 }
5658
5659 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5660                                  struct drm_atomic_state *old_state)
5661 {
5662         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5663         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5664         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5665         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5666
5667         intel_encoders_disable(crtc, old_crtc_state, old_state);
5668
5669         drm_crtc_vblank_off(crtc);
5670         assert_vblank_disabled(crtc);
5671
5672         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5673         if (!transcoder_is_dsi(cpu_transcoder))
5674                 intel_disable_pipe(old_crtc_state);
5675
5676         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5677                 intel_ddi_set_vc_payload_alloc(intel_crtc->config, false);
5678
5679         if (!transcoder_is_dsi(cpu_transcoder))
5680                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5681
5682         if (INTEL_GEN(dev_priv) >= 9)
5683                 skylake_scaler_disable(intel_crtc);
5684         else
5685                 ironlake_pfit_disable(intel_crtc, false);
5686
5687         if (!transcoder_is_dsi(cpu_transcoder))
5688                 intel_ddi_disable_pipe_clock(intel_crtc->config);
5689
5690         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5691 }
5692
5693 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5694 {
5695         struct drm_device *dev = crtc->base.dev;
5696         struct drm_i915_private *dev_priv = to_i915(dev);
5697         struct intel_crtc_state *pipe_config = crtc->config;
5698
5699         if (!pipe_config->gmch_pfit.control)
5700                 return;
5701
5702         /*
5703          * The panel fitter should only be adjusted whilst the pipe is disabled,
5704          * according to register description and PRM.
5705          */
5706         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5707         assert_pipe_disabled(dev_priv, crtc->pipe);
5708
5709         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5710         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5711
5712         /* Border color in case we don't scale up to the full screen. Black by
5713          * default, change to something else for debugging. */
5714         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5715 }
5716
5717 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5718 {
5719         switch (port) {
5720         case PORT_A:
5721                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5722         case PORT_B:
5723                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5724         case PORT_C:
5725                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5726         case PORT_D:
5727                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5728         case PORT_E:
5729                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5730         case PORT_F:
5731                 return POWER_DOMAIN_PORT_DDI_F_LANES;
5732         default:
5733                 MISSING_CASE(port);
5734                 return POWER_DOMAIN_PORT_OTHER;
5735         }
5736 }
5737
5738 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5739                                   struct intel_crtc_state *crtc_state)
5740 {
5741         struct drm_device *dev = crtc->dev;
5742         struct drm_i915_private *dev_priv = to_i915(dev);
5743         struct drm_encoder *encoder;
5744         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5745         enum pipe pipe = intel_crtc->pipe;
5746         u64 mask;
5747         enum transcoder transcoder = crtc_state->cpu_transcoder;
5748
5749         if (!crtc_state->base.active)
5750                 return 0;
5751
5752         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
5753         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
5754         if (crtc_state->pch_pfit.enabled ||
5755             crtc_state->pch_pfit.force_thru)
5756                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5757
5758         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5759                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5760
5761                 mask |= BIT_ULL(intel_encoder->power_domain);
5762         }
5763
5764         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5765                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
5766
5767         if (crtc_state->shared_dpll)
5768                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5769
5770         return mask;
5771 }
5772
5773 static u64
5774 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5775                                struct intel_crtc_state *crtc_state)
5776 {
5777         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5778         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5779         enum intel_display_power_domain domain;
5780         u64 domains, new_domains, old_domains;
5781
5782         old_domains = intel_crtc->enabled_power_domains;
5783         intel_crtc->enabled_power_domains = new_domains =
5784                 get_crtc_power_domains(crtc, crtc_state);
5785
5786         domains = new_domains & ~old_domains;
5787
5788         for_each_power_domain(domain, domains)
5789                 intel_display_power_get(dev_priv, domain);
5790
5791         return old_domains & ~new_domains;
5792 }
5793
5794 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5795                                       u64 domains)
5796 {
5797         enum intel_display_power_domain domain;
5798
5799         for_each_power_domain(domain, domains)
5800                 intel_display_power_put(dev_priv, domain);
5801 }
5802
5803 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5804                                    struct drm_atomic_state *old_state)
5805 {
5806         struct intel_atomic_state *old_intel_state =
5807                 to_intel_atomic_state(old_state);
5808         struct drm_crtc *crtc = pipe_config->base.crtc;
5809         struct drm_device *dev = crtc->dev;
5810         struct drm_i915_private *dev_priv = to_i915(dev);
5811         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5812         int pipe = intel_crtc->pipe;
5813
5814         if (WARN_ON(intel_crtc->active))
5815                 return;
5816
5817         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5818                 intel_dp_set_m_n(intel_crtc, M1_N1);
5819
5820         intel_set_pipe_timings(intel_crtc);
5821         intel_set_pipe_src_size(intel_crtc);
5822
5823         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
5824                 struct drm_i915_private *dev_priv = to_i915(dev);
5825
5826                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5827                 I915_WRITE(CHV_CANVAS(pipe), 0);
5828         }
5829
5830         i9xx_set_pipeconf(intel_crtc);
5831
5832         intel_crtc->active = true;
5833
5834         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5835
5836         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5837
5838         if (IS_CHERRYVIEW(dev_priv)) {
5839                 chv_prepare_pll(intel_crtc, intel_crtc->config);
5840                 chv_enable_pll(intel_crtc, intel_crtc->config);
5841         } else {
5842                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
5843                 vlv_enable_pll(intel_crtc, intel_crtc->config);
5844         }
5845
5846         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5847
5848         i9xx_pfit_enable(intel_crtc);
5849
5850         intel_color_load_luts(&pipe_config->base);
5851
5852         dev_priv->display.initial_watermarks(old_intel_state,
5853                                              pipe_config);
5854         intel_enable_pipe(pipe_config);
5855
5856         assert_vblank_disabled(crtc);
5857         drm_crtc_vblank_on(crtc);
5858
5859         intel_encoders_enable(crtc, pipe_config, old_state);
5860 }
5861
5862 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5863 {
5864         struct drm_device *dev = crtc->base.dev;
5865         struct drm_i915_private *dev_priv = to_i915(dev);
5866
5867         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5868         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5869 }
5870
5871 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
5872                              struct drm_atomic_state *old_state)
5873 {
5874         struct intel_atomic_state *old_intel_state =
5875                 to_intel_atomic_state(old_state);
5876         struct drm_crtc *crtc = pipe_config->base.crtc;
5877         struct drm_device *dev = crtc->dev;
5878         struct drm_i915_private *dev_priv = to_i915(dev);
5879         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5880         enum pipe pipe = intel_crtc->pipe;
5881
5882         if (WARN_ON(intel_crtc->active))
5883                 return;
5884
5885         i9xx_set_pll_dividers(intel_crtc);
5886
5887         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5888                 intel_dp_set_m_n(intel_crtc, M1_N1);
5889
5890         intel_set_pipe_timings(intel_crtc);
5891         intel_set_pipe_src_size(intel_crtc);
5892
5893         i9xx_set_pipeconf(intel_crtc);
5894
5895         intel_crtc->active = true;
5896
5897         if (!IS_GEN2(dev_priv))
5898                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5899
5900         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5901
5902         i9xx_enable_pll(intel_crtc, pipe_config);
5903
5904         i9xx_pfit_enable(intel_crtc);
5905
5906         intel_color_load_luts(&pipe_config->base);
5907
5908         if (dev_priv->display.initial_watermarks != NULL)
5909                 dev_priv->display.initial_watermarks(old_intel_state,
5910                                                      intel_crtc->config);
5911         else
5912                 intel_update_watermarks(intel_crtc);
5913         intel_enable_pipe(pipe_config);
5914
5915         assert_vblank_disabled(crtc);
5916         drm_crtc_vblank_on(crtc);
5917
5918         intel_encoders_enable(crtc, pipe_config, old_state);
5919 }
5920
5921 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5922 {
5923         struct drm_device *dev = crtc->base.dev;
5924         struct drm_i915_private *dev_priv = to_i915(dev);
5925
5926         if (!crtc->config->gmch_pfit.control)
5927                 return;
5928
5929         assert_pipe_disabled(dev_priv, crtc->pipe);
5930
5931         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5932                          I915_READ(PFIT_CONTROL));
5933         I915_WRITE(PFIT_CONTROL, 0);
5934 }
5935
5936 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
5937                               struct drm_atomic_state *old_state)
5938 {
5939         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5940         struct drm_device *dev = crtc->dev;
5941         struct drm_i915_private *dev_priv = to_i915(dev);
5942         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5943         int pipe = intel_crtc->pipe;
5944
5945         /*
5946          * On gen2 planes are double buffered but the pipe isn't, so we must
5947          * wait for planes to fully turn off before disabling the pipe.
5948          */
5949         if (IS_GEN2(dev_priv))
5950                 intel_wait_for_vblank(dev_priv, pipe);
5951
5952         intel_encoders_disable(crtc, old_crtc_state, old_state);
5953
5954         drm_crtc_vblank_off(crtc);
5955         assert_vblank_disabled(crtc);
5956
5957         intel_disable_pipe(old_crtc_state);
5958
5959         i9xx_pfit_disable(intel_crtc);
5960
5961         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5962
5963         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
5964                 if (IS_CHERRYVIEW(dev_priv))
5965                         chv_disable_pll(dev_priv, pipe);
5966                 else if (IS_VALLEYVIEW(dev_priv))
5967                         vlv_disable_pll(dev_priv, pipe);
5968                 else
5969                         i9xx_disable_pll(intel_crtc);
5970         }
5971
5972         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
5973
5974         if (!IS_GEN2(dev_priv))
5975                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5976
5977         if (!dev_priv->display.initial_watermarks)
5978                 intel_update_watermarks(intel_crtc);
5979
5980         /* clock the pipe down to 640x480@60 to potentially save power */
5981         if (IS_I830(dev_priv))
5982                 i830_enable_pipe(dev_priv, pipe);
5983 }
5984
5985 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
5986                                         struct drm_modeset_acquire_ctx *ctx)
5987 {
5988         struct intel_encoder *encoder;
5989         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5990         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5991         enum intel_display_power_domain domain;
5992         struct intel_plane *plane;
5993         u64 domains;
5994         struct drm_atomic_state *state;
5995         struct intel_crtc_state *crtc_state;
5996         int ret;
5997
5998         if (!intel_crtc->active)
5999                 return;
6000
6001         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6002                 const struct intel_plane_state *plane_state =
6003                         to_intel_plane_state(plane->base.state);
6004
6005                 if (plane_state->base.visible)
6006                         intel_plane_disable_noatomic(intel_crtc, plane);
6007         }
6008
6009         state = drm_atomic_state_alloc(crtc->dev);
6010         if (!state) {
6011                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6012                               crtc->base.id, crtc->name);
6013                 return;
6014         }
6015
6016         state->acquire_ctx = ctx;
6017
6018         /* Everything's already locked, -EDEADLK can't happen. */
6019         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6020         ret = drm_atomic_add_affected_connectors(state, crtc);
6021
6022         WARN_ON(IS_ERR(crtc_state) || ret);
6023
6024         dev_priv->display.crtc_disable(crtc_state, state);
6025
6026         drm_atomic_state_put(state);
6027
6028         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6029                       crtc->base.id, crtc->name);
6030
6031         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6032         crtc->state->active = false;
6033         intel_crtc->active = false;
6034         crtc->enabled = false;
6035         crtc->state->connector_mask = 0;
6036         crtc->state->encoder_mask = 0;
6037
6038         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6039                 encoder->base.crtc = NULL;
6040
6041         intel_fbc_disable(intel_crtc);
6042         intel_update_watermarks(intel_crtc);
6043         intel_disable_shared_dpll(intel_crtc);
6044
6045         domains = intel_crtc->enabled_power_domains;
6046         for_each_power_domain(domain, domains)
6047                 intel_display_power_put(dev_priv, domain);
6048         intel_crtc->enabled_power_domains = 0;
6049
6050         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6051         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6052         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6053 }
6054
6055 /*
6056  * turn all crtc's off, but do not adjust state
6057  * This has to be paired with a call to intel_modeset_setup_hw_state.
6058  */
6059 int intel_display_suspend(struct drm_device *dev)
6060 {
6061         struct drm_i915_private *dev_priv = to_i915(dev);
6062         struct drm_atomic_state *state;
6063         int ret;
6064
6065         state = drm_atomic_helper_suspend(dev);
6066         ret = PTR_ERR_OR_ZERO(state);
6067         if (ret)
6068                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6069         else
6070                 dev_priv->modeset_restore_state = state;
6071         return ret;
6072 }
6073
6074 void intel_encoder_destroy(struct drm_encoder *encoder)
6075 {
6076         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6077
6078         drm_encoder_cleanup(encoder);
6079         kfree(intel_encoder);
6080 }
6081
6082 /* Cross check the actual hw state with our own modeset state tracking (and it's
6083  * internal consistency). */
6084 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6085                                          struct drm_connector_state *conn_state)
6086 {
6087         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6088
6089         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6090                       connector->base.base.id,
6091                       connector->base.name);
6092
6093         if (connector->get_hw_state(connector)) {
6094                 struct intel_encoder *encoder = connector->encoder;
6095
6096                 I915_STATE_WARN(!crtc_state,
6097                          "connector enabled without attached crtc\n");
6098
6099                 if (!crtc_state)
6100                         return;
6101
6102                 I915_STATE_WARN(!crtc_state->active,
6103                       "connector is active, but attached crtc isn't\n");
6104
6105                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6106                         return;
6107
6108                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6109                         "atomic encoder doesn't match attached encoder\n");
6110
6111                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6112                         "attached encoder crtc differs from connector crtc\n");
6113         } else {
6114                 I915_STATE_WARN(crtc_state && crtc_state->active,
6115                         "attached crtc is active, but connector isn't\n");
6116                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6117                         "best encoder set without crtc!\n");
6118         }
6119 }
6120
6121 int intel_connector_init(struct intel_connector *connector)
6122 {
6123         struct intel_digital_connector_state *conn_state;
6124
6125         /*
6126          * Allocate enough memory to hold intel_digital_connector_state,
6127          * This might be a few bytes too many, but for connectors that don't
6128          * need it we'll free the state and allocate a smaller one on the first
6129          * succesful commit anyway.
6130          */
6131         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
6132         if (!conn_state)
6133                 return -ENOMEM;
6134
6135         __drm_atomic_helper_connector_reset(&connector->base,
6136                                             &conn_state->base);
6137
6138         return 0;
6139 }
6140
6141 struct intel_connector *intel_connector_alloc(void)
6142 {
6143         struct intel_connector *connector;
6144
6145         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6146         if (!connector)
6147                 return NULL;
6148
6149         if (intel_connector_init(connector) < 0) {
6150                 kfree(connector);
6151                 return NULL;
6152         }
6153
6154         return connector;
6155 }
6156
6157 /*
6158  * Free the bits allocated by intel_connector_alloc.
6159  * This should only be used after intel_connector_alloc has returned
6160  * successfully, and before drm_connector_init returns successfully.
6161  * Otherwise the destroy callbacks for the connector and the state should
6162  * take care of proper cleanup/free
6163  */
6164 void intel_connector_free(struct intel_connector *connector)
6165 {
6166         kfree(to_intel_digital_connector_state(connector->base.state));
6167         kfree(connector);
6168 }
6169
6170 /* Simple connector->get_hw_state implementation for encoders that support only
6171  * one connector and no cloning and hence the encoder state determines the state
6172  * of the connector. */
6173 bool intel_connector_get_hw_state(struct intel_connector *connector)
6174 {
6175         enum pipe pipe = 0;
6176         struct intel_encoder *encoder = connector->encoder;
6177
6178         return encoder->get_hw_state(encoder, &pipe);
6179 }
6180
6181 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6182 {
6183         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6184                 return crtc_state->fdi_lanes;
6185
6186         return 0;
6187 }
6188
6189 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6190                                      struct intel_crtc_state *pipe_config)
6191 {
6192         struct drm_i915_private *dev_priv = to_i915(dev);
6193         struct drm_atomic_state *state = pipe_config->base.state;
6194         struct intel_crtc *other_crtc;
6195         struct intel_crtc_state *other_crtc_state;
6196
6197         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6198                       pipe_name(pipe), pipe_config->fdi_lanes);
6199         if (pipe_config->fdi_lanes > 4) {
6200                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6201                               pipe_name(pipe), pipe_config->fdi_lanes);
6202                 return -EINVAL;
6203         }
6204
6205         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6206                 if (pipe_config->fdi_lanes > 2) {
6207                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6208                                       pipe_config->fdi_lanes);
6209                         return -EINVAL;
6210                 } else {
6211                         return 0;
6212                 }
6213         }
6214
6215         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6216                 return 0;
6217
6218         /* Ivybridge 3 pipe is really complicated */
6219         switch (pipe) {
6220         case PIPE_A:
6221                 return 0;
6222         case PIPE_B:
6223                 if (pipe_config->fdi_lanes <= 2)
6224                         return 0;
6225
6226                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6227                 other_crtc_state =
6228                         intel_atomic_get_crtc_state(state, other_crtc);
6229                 if (IS_ERR(other_crtc_state))
6230                         return PTR_ERR(other_crtc_state);
6231
6232                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6233                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6234                                       pipe_name(pipe), pipe_config->fdi_lanes);
6235                         return -EINVAL;
6236                 }
6237                 return 0;
6238         case PIPE_C:
6239                 if (pipe_config->fdi_lanes > 2) {
6240                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6241                                       pipe_name(pipe), pipe_config->fdi_lanes);
6242                         return -EINVAL;
6243                 }
6244
6245                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6246                 other_crtc_state =
6247                         intel_atomic_get_crtc_state(state, other_crtc);
6248                 if (IS_ERR(other_crtc_state))
6249                         return PTR_ERR(other_crtc_state);
6250
6251                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6252                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6253                         return -EINVAL;
6254                 }
6255                 return 0;
6256         default:
6257                 BUG();
6258         }
6259 }
6260
6261 #define RETRY 1
6262 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6263                                        struct intel_crtc_state *pipe_config)
6264 {
6265         struct drm_device *dev = intel_crtc->base.dev;
6266         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6267         int lane, link_bw, fdi_dotclock, ret;
6268         bool needs_recompute = false;
6269
6270 retry:
6271         /* FDI is a binary signal running at ~2.7GHz, encoding
6272          * each output octet as 10 bits. The actual frequency
6273          * is stored as a divider into a 100MHz clock, and the
6274          * mode pixel clock is stored in units of 1KHz.
6275          * Hence the bw of each lane in terms of the mode signal
6276          * is:
6277          */
6278         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6279
6280         fdi_dotclock = adjusted_mode->crtc_clock;
6281
6282         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6283                                            pipe_config->pipe_bpp);
6284
6285         pipe_config->fdi_lanes = lane;
6286
6287         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6288                                link_bw, &pipe_config->fdi_m_n, false);
6289
6290         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6291         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6292                 pipe_config->pipe_bpp -= 2*3;
6293                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6294                               pipe_config->pipe_bpp);
6295                 needs_recompute = true;
6296                 pipe_config->bw_constrained = true;
6297
6298                 goto retry;
6299         }
6300
6301         if (needs_recompute)
6302                 return RETRY;
6303
6304         return ret;
6305 }
6306
6307 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6308 {
6309         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6310         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6311
6312         /* IPS only exists on ULT machines and is tied to pipe A. */
6313         if (!hsw_crtc_supports_ips(crtc))
6314                 return false;
6315
6316         if (!i915_modparams.enable_ips)
6317                 return false;
6318
6319         if (crtc_state->pipe_bpp > 24)
6320                 return false;
6321
6322         /*
6323          * We compare against max which means we must take
6324          * the increased cdclk requirement into account when
6325          * calculating the new cdclk.
6326          *
6327          * Should measure whether using a lower cdclk w/o IPS
6328          */
6329         if (IS_BROADWELL(dev_priv) &&
6330             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6331                 return false;
6332
6333         return true;
6334 }
6335
6336 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6337 {
6338         struct drm_i915_private *dev_priv =
6339                 to_i915(crtc_state->base.crtc->dev);
6340         struct intel_atomic_state *intel_state =
6341                 to_intel_atomic_state(crtc_state->base.state);
6342
6343         if (!hsw_crtc_state_ips_capable(crtc_state))
6344                 return false;
6345
6346         if (crtc_state->ips_force_disable)
6347                 return false;
6348
6349         /* IPS should be fine as long as at least one plane is enabled. */
6350         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6351                 return false;
6352
6353         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6354         if (IS_BROADWELL(dev_priv) &&
6355             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6356                 return false;
6357
6358         return true;
6359 }
6360
6361 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6362 {
6363         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6364
6365         /* GDG double wide on either pipe, otherwise pipe A only */
6366         return INTEL_GEN(dev_priv) < 4 &&
6367                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6368 }
6369
6370 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6371 {
6372         uint32_t pixel_rate;
6373
6374         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6375
6376         /*
6377          * We only use IF-ID interlacing. If we ever use
6378          * PF-ID we'll need to adjust the pixel_rate here.
6379          */
6380
6381         if (pipe_config->pch_pfit.enabled) {
6382                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6383                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6384
6385                 pipe_w = pipe_config->pipe_src_w;
6386                 pipe_h = pipe_config->pipe_src_h;
6387
6388                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6389                 pfit_h = pfit_size & 0xFFFF;
6390                 if (pipe_w < pfit_w)
6391                         pipe_w = pfit_w;
6392                 if (pipe_h < pfit_h)
6393                         pipe_h = pfit_h;
6394
6395                 if (WARN_ON(!pfit_w || !pfit_h))
6396                         return pixel_rate;
6397
6398                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6399                                      pfit_w * pfit_h);
6400         }
6401
6402         return pixel_rate;
6403 }
6404
6405 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6406 {
6407         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6408
6409         if (HAS_GMCH_DISPLAY(dev_priv))
6410                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6411                 crtc_state->pixel_rate =
6412                         crtc_state->base.adjusted_mode.crtc_clock;
6413         else
6414                 crtc_state->pixel_rate =
6415                         ilk_pipe_pixel_rate(crtc_state);
6416 }
6417
6418 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6419                                      struct intel_crtc_state *pipe_config)
6420 {
6421         struct drm_device *dev = crtc->base.dev;
6422         struct drm_i915_private *dev_priv = to_i915(dev);
6423         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6424         int clock_limit = dev_priv->max_dotclk_freq;
6425
6426         if (INTEL_GEN(dev_priv) < 4) {
6427                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6428
6429                 /*
6430                  * Enable double wide mode when the dot clock
6431                  * is > 90% of the (display) core speed.
6432                  */
6433                 if (intel_crtc_supports_double_wide(crtc) &&
6434                     adjusted_mode->crtc_clock > clock_limit) {
6435                         clock_limit = dev_priv->max_dotclk_freq;
6436                         pipe_config->double_wide = true;
6437                 }
6438         }
6439
6440         if (adjusted_mode->crtc_clock > clock_limit) {
6441                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6442                               adjusted_mode->crtc_clock, clock_limit,
6443                               yesno(pipe_config->double_wide));
6444                 return -EINVAL;
6445         }
6446
6447         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6448                 /*
6449                  * There is only one pipe CSC unit per pipe, and we need that
6450                  * for output conversion from RGB->YCBCR. So if CTM is already
6451                  * applied we can't support YCBCR420 output.
6452                  */
6453                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6454                 return -EINVAL;
6455         }
6456
6457         /*
6458          * Pipe horizontal size must be even in:
6459          * - DVO ganged mode
6460          * - LVDS dual channel mode
6461          * - Double wide pipe
6462          */
6463         if (pipe_config->pipe_src_w & 1) {
6464                 if (pipe_config->double_wide) {
6465                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6466                         return -EINVAL;
6467                 }
6468
6469                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6470                     intel_is_dual_link_lvds(dev)) {
6471                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6472                         return -EINVAL;
6473                 }
6474         }
6475
6476         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6477          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6478          */
6479         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6480                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6481                 return -EINVAL;
6482
6483         intel_crtc_compute_pixel_rate(pipe_config);
6484
6485         if (pipe_config->has_pch_encoder)
6486                 return ironlake_fdi_compute_config(crtc, pipe_config);
6487
6488         return 0;
6489 }
6490
6491 static void
6492 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6493 {
6494         while (*num > DATA_LINK_M_N_MASK ||
6495                *den > DATA_LINK_M_N_MASK) {
6496                 *num >>= 1;
6497                 *den >>= 1;
6498         }
6499 }
6500
6501 static void compute_m_n(unsigned int m, unsigned int n,
6502                         uint32_t *ret_m, uint32_t *ret_n,
6503                         bool reduce_m_n)
6504 {
6505         /*
6506          * Reduce M/N as much as possible without loss in precision. Several DP
6507          * dongles in particular seem to be fussy about too large *link* M/N
6508          * values. The passed in values are more likely to have the least
6509          * significant bits zero than M after rounding below, so do this first.
6510          */
6511         if (reduce_m_n) {
6512                 while ((m & 1) == 0 && (n & 1) == 0) {
6513                         m >>= 1;
6514                         n >>= 1;
6515                 }
6516         }
6517
6518         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6519         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6520         intel_reduce_m_n_ratio(ret_m, ret_n);
6521 }
6522
6523 void
6524 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6525                        int pixel_clock, int link_clock,
6526                        struct intel_link_m_n *m_n,
6527                        bool reduce_m_n)
6528 {
6529         m_n->tu = 64;
6530
6531         compute_m_n(bits_per_pixel * pixel_clock,
6532                     link_clock * nlanes * 8,
6533                     &m_n->gmch_m, &m_n->gmch_n,
6534                     reduce_m_n);
6535
6536         compute_m_n(pixel_clock, link_clock,
6537                     &m_n->link_m, &m_n->link_n,
6538                     reduce_m_n);
6539 }
6540
6541 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6542 {
6543         if (i915_modparams.panel_use_ssc >= 0)
6544                 return i915_modparams.panel_use_ssc != 0;
6545         return dev_priv->vbt.lvds_use_ssc
6546                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6547 }
6548
6549 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6550 {
6551         return (1 << dpll->n) << 16 | dpll->m2;
6552 }
6553
6554 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6555 {
6556         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6557 }
6558
6559 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6560                                      struct intel_crtc_state *crtc_state,
6561                                      struct dpll *reduced_clock)
6562 {
6563         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6564         u32 fp, fp2 = 0;
6565
6566         if (IS_PINEVIEW(dev_priv)) {
6567                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6568                 if (reduced_clock)
6569                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6570         } else {
6571                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6572                 if (reduced_clock)
6573                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6574         }
6575
6576         crtc_state->dpll_hw_state.fp0 = fp;
6577
6578         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6579             reduced_clock) {
6580                 crtc_state->dpll_hw_state.fp1 = fp2;
6581         } else {
6582                 crtc_state->dpll_hw_state.fp1 = fp;
6583         }
6584 }
6585
6586 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6587                 pipe)
6588 {
6589         u32 reg_val;
6590
6591         /*
6592          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6593          * and set it to a reasonable value instead.
6594          */
6595         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6596         reg_val &= 0xffffff00;
6597         reg_val |= 0x00000030;
6598         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6599
6600         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6601         reg_val &= 0x00ffffff;
6602         reg_val |= 0x8c000000;
6603         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6604
6605         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6606         reg_val &= 0xffffff00;
6607         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6608
6609         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6610         reg_val &= 0x00ffffff;
6611         reg_val |= 0xb0000000;
6612         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6613 }
6614
6615 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6616                                          struct intel_link_m_n *m_n)
6617 {
6618         struct drm_device *dev = crtc->base.dev;
6619         struct drm_i915_private *dev_priv = to_i915(dev);
6620         int pipe = crtc->pipe;
6621
6622         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6623         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6624         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6625         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6626 }
6627
6628 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6629                                          struct intel_link_m_n *m_n,
6630                                          struct intel_link_m_n *m2_n2)
6631 {
6632         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6633         int pipe = crtc->pipe;
6634         enum transcoder transcoder = crtc->config->cpu_transcoder;
6635
6636         if (INTEL_GEN(dev_priv) >= 5) {
6637                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6638                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6639                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6640                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6641                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6642                  * for gen < 8) and if DRRS is supported (to make sure the
6643                  * registers are not unnecessarily accessed).
6644                  */
6645                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6646                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6647                         I915_WRITE(PIPE_DATA_M2(transcoder),
6648                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6649                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6650                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6651                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6652                 }
6653         } else {
6654                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6655                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6656                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6657                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6658         }
6659 }
6660
6661 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6662 {
6663         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6664
6665         if (m_n == M1_N1) {
6666                 dp_m_n = &crtc->config->dp_m_n;
6667                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6668         } else if (m_n == M2_N2) {
6669
6670                 /*
6671                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6672                  * needs to be programmed into M1_N1.
6673                  */
6674                 dp_m_n = &crtc->config->dp_m2_n2;
6675         } else {
6676                 DRM_ERROR("Unsupported divider value\n");
6677                 return;
6678         }
6679
6680         if (crtc->config->has_pch_encoder)
6681                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6682         else
6683                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6684 }
6685
6686 static void vlv_compute_dpll(struct intel_crtc *crtc,
6687                              struct intel_crtc_state *pipe_config)
6688 {
6689         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6690                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6691         if (crtc->pipe != PIPE_A)
6692                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6693
6694         /* DPLL not used with DSI, but still need the rest set up */
6695         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6696                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6697                         DPLL_EXT_BUFFER_ENABLE_VLV;
6698
6699         pipe_config->dpll_hw_state.dpll_md =
6700                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6701 }
6702
6703 static void chv_compute_dpll(struct intel_crtc *crtc,
6704                              struct intel_crtc_state *pipe_config)
6705 {
6706         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6707                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6708         if (crtc->pipe != PIPE_A)
6709                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6710
6711         /* DPLL not used with DSI, but still need the rest set up */
6712         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6713                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6714
6715         pipe_config->dpll_hw_state.dpll_md =
6716                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6717 }
6718
6719 static void vlv_prepare_pll(struct intel_crtc *crtc,
6720                             const struct intel_crtc_state *pipe_config)
6721 {
6722         struct drm_device *dev = crtc->base.dev;
6723         struct drm_i915_private *dev_priv = to_i915(dev);
6724         enum pipe pipe = crtc->pipe;
6725         u32 mdiv;
6726         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6727         u32 coreclk, reg_val;
6728
6729         /* Enable Refclk */
6730         I915_WRITE(DPLL(pipe),
6731                    pipe_config->dpll_hw_state.dpll &
6732                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6733
6734         /* No need to actually set up the DPLL with DSI */
6735         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6736                 return;
6737
6738         mutex_lock(&dev_priv->sb_lock);
6739
6740         bestn = pipe_config->dpll.n;
6741         bestm1 = pipe_config->dpll.m1;
6742         bestm2 = pipe_config->dpll.m2;
6743         bestp1 = pipe_config->dpll.p1;
6744         bestp2 = pipe_config->dpll.p2;
6745
6746         /* See eDP HDMI DPIO driver vbios notes doc */
6747
6748         /* PLL B needs special handling */
6749         if (pipe == PIPE_B)
6750                 vlv_pllb_recal_opamp(dev_priv, pipe);
6751
6752         /* Set up Tx target for periodic Rcomp update */
6753         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6754
6755         /* Disable target IRef on PLL */
6756         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6757         reg_val &= 0x00ffffff;
6758         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6759
6760         /* Disable fast lock */
6761         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6762
6763         /* Set idtafcrecal before PLL is enabled */
6764         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6765         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6766         mdiv |= ((bestn << DPIO_N_SHIFT));
6767         mdiv |= (1 << DPIO_K_SHIFT);
6768
6769         /*
6770          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6771          * but we don't support that).
6772          * Note: don't use the DAC post divider as it seems unstable.
6773          */
6774         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6775         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6776
6777         mdiv |= DPIO_ENABLE_CALIBRATION;
6778         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6779
6780         /* Set HBR and RBR LPF coefficients */
6781         if (pipe_config->port_clock == 162000 ||
6782             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6783             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6784                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6785                                  0x009f0003);
6786         else
6787                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6788                                  0x00d0000f);
6789
6790         if (intel_crtc_has_dp_encoder(pipe_config)) {
6791                 /* Use SSC source */
6792                 if (pipe == PIPE_A)
6793                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6794                                          0x0df40000);
6795                 else
6796                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6797                                          0x0df70000);
6798         } else { /* HDMI or VGA */
6799                 /* Use bend source */
6800                 if (pipe == PIPE_A)
6801                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6802                                          0x0df70000);
6803                 else
6804                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6805                                          0x0df40000);
6806         }
6807
6808         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6809         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6810         if (intel_crtc_has_dp_encoder(crtc->config))
6811                 coreclk |= 0x01000000;
6812         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6813
6814         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6815         mutex_unlock(&dev_priv->sb_lock);
6816 }
6817
6818 static void chv_prepare_pll(struct intel_crtc *crtc,
6819                             const struct intel_crtc_state *pipe_config)
6820 {
6821         struct drm_device *dev = crtc->base.dev;
6822         struct drm_i915_private *dev_priv = to_i915(dev);
6823         enum pipe pipe = crtc->pipe;
6824         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6825         u32 loopfilter, tribuf_calcntr;
6826         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6827         u32 dpio_val;
6828         int vco;
6829
6830         /* Enable Refclk and SSC */
6831         I915_WRITE(DPLL(pipe),
6832                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6833
6834         /* No need to actually set up the DPLL with DSI */
6835         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6836                 return;
6837
6838         bestn = pipe_config->dpll.n;
6839         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6840         bestm1 = pipe_config->dpll.m1;
6841         bestm2 = pipe_config->dpll.m2 >> 22;
6842         bestp1 = pipe_config->dpll.p1;
6843         bestp2 = pipe_config->dpll.p2;
6844         vco = pipe_config->dpll.vco;
6845         dpio_val = 0;
6846         loopfilter = 0;
6847
6848         mutex_lock(&dev_priv->sb_lock);
6849
6850         /* p1 and p2 divider */
6851         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6852                         5 << DPIO_CHV_S1_DIV_SHIFT |
6853                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6854                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6855                         1 << DPIO_CHV_K_DIV_SHIFT);
6856
6857         /* Feedback post-divider - m2 */
6858         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6859
6860         /* Feedback refclk divider - n and m1 */
6861         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6862                         DPIO_CHV_M1_DIV_BY_2 |
6863                         1 << DPIO_CHV_N_DIV_SHIFT);
6864
6865         /* M2 fraction division */
6866         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6867
6868         /* M2 fraction division enable */
6869         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6870         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6871         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6872         if (bestm2_frac)
6873                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6874         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6875
6876         /* Program digital lock detect threshold */
6877         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6878         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6879                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6880         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6881         if (!bestm2_frac)
6882                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6883         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6884
6885         /* Loop filter */
6886         if (vco == 5400000) {
6887                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6888                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6889                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6890                 tribuf_calcntr = 0x9;
6891         } else if (vco <= 6200000) {
6892                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6893                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6894                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6895                 tribuf_calcntr = 0x9;
6896         } else if (vco <= 6480000) {
6897                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6898                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6899                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6900                 tribuf_calcntr = 0x8;
6901         } else {
6902                 /* Not supported. Apply the same limits as in the max case */
6903                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6904                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6905                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6906                 tribuf_calcntr = 0;
6907         }
6908         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6909
6910         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6911         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6912         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6913         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
6914
6915         /* AFC Recal */
6916         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6917                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6918                         DPIO_AFC_RECAL);
6919
6920         mutex_unlock(&dev_priv->sb_lock);
6921 }
6922
6923 /**
6924  * vlv_force_pll_on - forcibly enable just the PLL
6925  * @dev_priv: i915 private structure
6926  * @pipe: pipe PLL to enable
6927  * @dpll: PLL configuration
6928  *
6929  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6930  * in cases where we need the PLL enabled even when @pipe is not going to
6931  * be enabled.
6932  */
6933 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
6934                      const struct dpll *dpll)
6935 {
6936         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
6937         struct intel_crtc_state *pipe_config;
6938
6939         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
6940         if (!pipe_config)
6941                 return -ENOMEM;
6942
6943         pipe_config->base.crtc = &crtc->base;
6944         pipe_config->pixel_multiplier = 1;
6945         pipe_config->dpll = *dpll;
6946
6947         if (IS_CHERRYVIEW(dev_priv)) {
6948                 chv_compute_dpll(crtc, pipe_config);
6949                 chv_prepare_pll(crtc, pipe_config);
6950                 chv_enable_pll(crtc, pipe_config);
6951         } else {
6952                 vlv_compute_dpll(crtc, pipe_config);
6953                 vlv_prepare_pll(crtc, pipe_config);
6954                 vlv_enable_pll(crtc, pipe_config);
6955         }
6956
6957         kfree(pipe_config);
6958
6959         return 0;
6960 }
6961
6962 /**
6963  * vlv_force_pll_off - forcibly disable just the PLL
6964  * @dev_priv: i915 private structure
6965  * @pipe: pipe PLL to disable
6966  *
6967  * Disable the PLL for @pipe. To be used in cases where we need
6968  * the PLL enabled even when @pipe is not going to be enabled.
6969  */
6970 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
6971 {
6972         if (IS_CHERRYVIEW(dev_priv))
6973                 chv_disable_pll(dev_priv, pipe);
6974         else
6975                 vlv_disable_pll(dev_priv, pipe);
6976 }
6977
6978 static void i9xx_compute_dpll(struct intel_crtc *crtc,
6979                               struct intel_crtc_state *crtc_state,
6980                               struct dpll *reduced_clock)
6981 {
6982         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6983         u32 dpll;
6984         struct dpll *clock = &crtc_state->dpll;
6985
6986         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6987
6988         dpll = DPLL_VGA_MODE_DIS;
6989
6990         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
6991                 dpll |= DPLLB_MODE_LVDS;
6992         else
6993                 dpll |= DPLLB_MODE_DAC_SERIAL;
6994
6995         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
6996             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
6997                 dpll |= (crtc_state->pixel_multiplier - 1)
6998                         << SDVO_MULTIPLIER_SHIFT_HIRES;
6999         }
7000
7001         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7002             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7003                 dpll |= DPLL_SDVO_HIGH_SPEED;
7004
7005         if (intel_crtc_has_dp_encoder(crtc_state))
7006                 dpll |= DPLL_SDVO_HIGH_SPEED;
7007
7008         /* compute bitmask from p1 value */
7009         if (IS_PINEVIEW(dev_priv))
7010                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7011         else {
7012                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7013                 if (IS_G4X(dev_priv) && reduced_clock)
7014                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7015         }
7016         switch (clock->p2) {
7017         case 5:
7018                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7019                 break;
7020         case 7:
7021                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7022                 break;
7023         case 10:
7024                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7025                 break;
7026         case 14:
7027                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7028                 break;
7029         }
7030         if (INTEL_GEN(dev_priv) >= 4)
7031                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7032
7033         if (crtc_state->sdvo_tv_clock)
7034                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7035         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7036                  intel_panel_use_ssc(dev_priv))
7037                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7038         else
7039                 dpll |= PLL_REF_INPUT_DREFCLK;
7040
7041         dpll |= DPLL_VCO_ENABLE;
7042         crtc_state->dpll_hw_state.dpll = dpll;
7043
7044         if (INTEL_GEN(dev_priv) >= 4) {
7045                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7046                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7047                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7048         }
7049 }
7050
7051 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7052                               struct intel_crtc_state *crtc_state,
7053                               struct dpll *reduced_clock)
7054 {
7055         struct drm_device *dev = crtc->base.dev;
7056         struct drm_i915_private *dev_priv = to_i915(dev);
7057         u32 dpll;
7058         struct dpll *clock = &crtc_state->dpll;
7059
7060         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7061
7062         dpll = DPLL_VGA_MODE_DIS;
7063
7064         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7065                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7066         } else {
7067                 if (clock->p1 == 2)
7068                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7069                 else
7070                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7071                 if (clock->p2 == 4)
7072                         dpll |= PLL_P2_DIVIDE_BY_4;
7073         }
7074
7075         if (!IS_I830(dev_priv) &&
7076             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7077                 dpll |= DPLL_DVO_2X_MODE;
7078
7079         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7080             intel_panel_use_ssc(dev_priv))
7081                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7082         else
7083                 dpll |= PLL_REF_INPUT_DREFCLK;
7084
7085         dpll |= DPLL_VCO_ENABLE;
7086         crtc_state->dpll_hw_state.dpll = dpll;
7087 }
7088
7089 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7090 {
7091         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7092         enum pipe pipe = intel_crtc->pipe;
7093         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7094         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7095         uint32_t crtc_vtotal, crtc_vblank_end;
7096         int vsyncshift = 0;
7097
7098         /* We need to be careful not to changed the adjusted mode, for otherwise
7099          * the hw state checker will get angry at the mismatch. */
7100         crtc_vtotal = adjusted_mode->crtc_vtotal;
7101         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7102
7103         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7104                 /* the chip adds 2 halflines automatically */
7105                 crtc_vtotal -= 1;
7106                 crtc_vblank_end -= 1;
7107
7108                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7109                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7110                 else
7111                         vsyncshift = adjusted_mode->crtc_hsync_start -
7112                                 adjusted_mode->crtc_htotal / 2;
7113                 if (vsyncshift < 0)
7114                         vsyncshift += adjusted_mode->crtc_htotal;
7115         }
7116
7117         if (INTEL_GEN(dev_priv) > 3)
7118                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7119
7120         I915_WRITE(HTOTAL(cpu_transcoder),
7121                    (adjusted_mode->crtc_hdisplay - 1) |
7122                    ((adjusted_mode->crtc_htotal - 1) << 16));
7123         I915_WRITE(HBLANK(cpu_transcoder),
7124                    (adjusted_mode->crtc_hblank_start - 1) |
7125                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7126         I915_WRITE(HSYNC(cpu_transcoder),
7127                    (adjusted_mode->crtc_hsync_start - 1) |
7128                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7129
7130         I915_WRITE(VTOTAL(cpu_transcoder),
7131                    (adjusted_mode->crtc_vdisplay - 1) |
7132                    ((crtc_vtotal - 1) << 16));
7133         I915_WRITE(VBLANK(cpu_transcoder),
7134                    (adjusted_mode->crtc_vblank_start - 1) |
7135                    ((crtc_vblank_end - 1) << 16));
7136         I915_WRITE(VSYNC(cpu_transcoder),
7137                    (adjusted_mode->crtc_vsync_start - 1) |
7138                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7139
7140         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7141          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7142          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7143          * bits. */
7144         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7145             (pipe == PIPE_B || pipe == PIPE_C))
7146                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7147
7148 }
7149
7150 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7151 {
7152         struct drm_device *dev = intel_crtc->base.dev;
7153         struct drm_i915_private *dev_priv = to_i915(dev);
7154         enum pipe pipe = intel_crtc->pipe;
7155
7156         /* pipesrc controls the size that is scaled from, which should
7157          * always be the user's requested size.
7158          */
7159         I915_WRITE(PIPESRC(pipe),
7160                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7161                    (intel_crtc->config->pipe_src_h - 1));
7162 }
7163
7164 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7165                                    struct intel_crtc_state *pipe_config)
7166 {
7167         struct drm_device *dev = crtc->base.dev;
7168         struct drm_i915_private *dev_priv = to_i915(dev);
7169         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7170         uint32_t tmp;
7171
7172         tmp = I915_READ(HTOTAL(cpu_transcoder));
7173         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7174         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7175         tmp = I915_READ(HBLANK(cpu_transcoder));
7176         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7177         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7178         tmp = I915_READ(HSYNC(cpu_transcoder));
7179         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7180         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7181
7182         tmp = I915_READ(VTOTAL(cpu_transcoder));
7183         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7184         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7185         tmp = I915_READ(VBLANK(cpu_transcoder));
7186         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7187         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7188         tmp = I915_READ(VSYNC(cpu_transcoder));
7189         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7190         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7191
7192         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7193                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7194                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7195                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7196         }
7197 }
7198
7199 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7200                                     struct intel_crtc_state *pipe_config)
7201 {
7202         struct drm_device *dev = crtc->base.dev;
7203         struct drm_i915_private *dev_priv = to_i915(dev);
7204         u32 tmp;
7205
7206         tmp = I915_READ(PIPESRC(crtc->pipe));
7207         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7208         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7209
7210         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7211         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7212 }
7213
7214 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7215                                  struct intel_crtc_state *pipe_config)
7216 {
7217         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7218         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7219         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7220         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7221
7222         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7223         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7224         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7225         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7226
7227         mode->flags = pipe_config->base.adjusted_mode.flags;
7228         mode->type = DRM_MODE_TYPE_DRIVER;
7229
7230         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7231
7232         mode->hsync = drm_mode_hsync(mode);
7233         mode->vrefresh = drm_mode_vrefresh(mode);
7234         drm_mode_set_name(mode);
7235 }
7236
7237 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7238 {
7239         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7240         uint32_t pipeconf;
7241
7242         pipeconf = 0;
7243
7244         /* we keep both pipes enabled on 830 */
7245         if (IS_I830(dev_priv))
7246                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7247
7248         if (intel_crtc->config->double_wide)
7249                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7250
7251         /* only g4x and later have fancy bpc/dither controls */
7252         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7253             IS_CHERRYVIEW(dev_priv)) {
7254                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7255                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7256                         pipeconf |= PIPECONF_DITHER_EN |
7257                                     PIPECONF_DITHER_TYPE_SP;
7258
7259                 switch (intel_crtc->config->pipe_bpp) {
7260                 case 18:
7261                         pipeconf |= PIPECONF_6BPC;
7262                         break;
7263                 case 24:
7264                         pipeconf |= PIPECONF_8BPC;
7265                         break;
7266                 case 30:
7267                         pipeconf |= PIPECONF_10BPC;
7268                         break;
7269                 default:
7270                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7271                         BUG();
7272                 }
7273         }
7274
7275         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7276                 if (INTEL_GEN(dev_priv) < 4 ||
7277                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7278                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7279                 else
7280                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7281         } else
7282                 pipeconf |= PIPECONF_PROGRESSIVE;
7283
7284         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7285              intel_crtc->config->limited_color_range)
7286                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7287
7288         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7289         POSTING_READ(PIPECONF(intel_crtc->pipe));
7290 }
7291
7292 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7293                                    struct intel_crtc_state *crtc_state)
7294 {
7295         struct drm_device *dev = crtc->base.dev;
7296         struct drm_i915_private *dev_priv = to_i915(dev);
7297         const struct intel_limit *limit;
7298         int refclk = 48000;
7299
7300         memset(&crtc_state->dpll_hw_state, 0,
7301                sizeof(crtc_state->dpll_hw_state));
7302
7303         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7304                 if (intel_panel_use_ssc(dev_priv)) {
7305                         refclk = dev_priv->vbt.lvds_ssc_freq;
7306                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7307                 }
7308
7309                 limit = &intel_limits_i8xx_lvds;
7310         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7311                 limit = &intel_limits_i8xx_dvo;
7312         } else {
7313                 limit = &intel_limits_i8xx_dac;
7314         }
7315
7316         if (!crtc_state->clock_set &&
7317             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7318                                  refclk, NULL, &crtc_state->dpll)) {
7319                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7320                 return -EINVAL;
7321         }
7322
7323         i8xx_compute_dpll(crtc, crtc_state, NULL);
7324
7325         return 0;
7326 }
7327
7328 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7329                                   struct intel_crtc_state *crtc_state)
7330 {
7331         struct drm_device *dev = crtc->base.dev;
7332         struct drm_i915_private *dev_priv = to_i915(dev);
7333         const struct intel_limit *limit;
7334         int refclk = 96000;
7335
7336         memset(&crtc_state->dpll_hw_state, 0,
7337                sizeof(crtc_state->dpll_hw_state));
7338
7339         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7340                 if (intel_panel_use_ssc(dev_priv)) {
7341                         refclk = dev_priv->vbt.lvds_ssc_freq;
7342                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7343                 }
7344
7345                 if (intel_is_dual_link_lvds(dev))
7346                         limit = &intel_limits_g4x_dual_channel_lvds;
7347                 else
7348                         limit = &intel_limits_g4x_single_channel_lvds;
7349         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7350                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7351                 limit = &intel_limits_g4x_hdmi;
7352         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7353                 limit = &intel_limits_g4x_sdvo;
7354         } else {
7355                 /* The option is for other outputs */
7356                 limit = &intel_limits_i9xx_sdvo;
7357         }
7358
7359         if (!crtc_state->clock_set &&
7360             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7361                                 refclk, NULL, &crtc_state->dpll)) {
7362                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7363                 return -EINVAL;
7364         }
7365
7366         i9xx_compute_dpll(crtc, crtc_state, NULL);
7367
7368         return 0;
7369 }
7370
7371 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7372                                   struct intel_crtc_state *crtc_state)
7373 {
7374         struct drm_device *dev = crtc->base.dev;
7375         struct drm_i915_private *dev_priv = to_i915(dev);
7376         const struct intel_limit *limit;
7377         int refclk = 96000;
7378
7379         memset(&crtc_state->dpll_hw_state, 0,
7380                sizeof(crtc_state->dpll_hw_state));
7381
7382         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7383                 if (intel_panel_use_ssc(dev_priv)) {
7384                         refclk = dev_priv->vbt.lvds_ssc_freq;
7385                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7386                 }
7387
7388                 limit = &intel_limits_pineview_lvds;
7389         } else {
7390                 limit = &intel_limits_pineview_sdvo;
7391         }
7392
7393         if (!crtc_state->clock_set &&
7394             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7395                                 refclk, NULL, &crtc_state->dpll)) {
7396                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7397                 return -EINVAL;
7398         }
7399
7400         i9xx_compute_dpll(crtc, crtc_state, NULL);
7401
7402         return 0;
7403 }
7404
7405 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7406                                    struct intel_crtc_state *crtc_state)
7407 {
7408         struct drm_device *dev = crtc->base.dev;
7409         struct drm_i915_private *dev_priv = to_i915(dev);
7410         const struct intel_limit *limit;
7411         int refclk = 96000;
7412
7413         memset(&crtc_state->dpll_hw_state, 0,
7414                sizeof(crtc_state->dpll_hw_state));
7415
7416         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7417                 if (intel_panel_use_ssc(dev_priv)) {
7418                         refclk = dev_priv->vbt.lvds_ssc_freq;
7419                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7420                 }
7421
7422                 limit = &intel_limits_i9xx_lvds;
7423         } else {
7424                 limit = &intel_limits_i9xx_sdvo;
7425         }
7426
7427         if (!crtc_state->clock_set &&
7428             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7429                                  refclk, NULL, &crtc_state->dpll)) {
7430                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7431                 return -EINVAL;
7432         }
7433
7434         i9xx_compute_dpll(crtc, crtc_state, NULL);
7435
7436         return 0;
7437 }
7438
7439 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7440                                   struct intel_crtc_state *crtc_state)
7441 {
7442         int refclk = 100000;
7443         const struct intel_limit *limit = &intel_limits_chv;
7444
7445         memset(&crtc_state->dpll_hw_state, 0,
7446                sizeof(crtc_state->dpll_hw_state));
7447
7448         if (!crtc_state->clock_set &&
7449             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7450                                 refclk, NULL, &crtc_state->dpll)) {
7451                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7452                 return -EINVAL;
7453         }
7454
7455         chv_compute_dpll(crtc, crtc_state);
7456
7457         return 0;
7458 }
7459
7460 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7461                                   struct intel_crtc_state *crtc_state)
7462 {
7463         int refclk = 100000;
7464         const struct intel_limit *limit = &intel_limits_vlv;
7465
7466         memset(&crtc_state->dpll_hw_state, 0,
7467                sizeof(crtc_state->dpll_hw_state));
7468
7469         if (!crtc_state->clock_set &&
7470             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7471                                 refclk, NULL, &crtc_state->dpll)) {
7472                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7473                 return -EINVAL;
7474         }
7475
7476         vlv_compute_dpll(crtc, crtc_state);
7477
7478         return 0;
7479 }
7480
7481 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7482                                  struct intel_crtc_state *pipe_config)
7483 {
7484         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7485         uint32_t tmp;
7486
7487         if (INTEL_GEN(dev_priv) <= 3 &&
7488             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7489                 return;
7490
7491         tmp = I915_READ(PFIT_CONTROL);
7492         if (!(tmp & PFIT_ENABLE))
7493                 return;
7494
7495         /* Check whether the pfit is attached to our pipe. */
7496         if (INTEL_GEN(dev_priv) < 4) {
7497                 if (crtc->pipe != PIPE_B)
7498                         return;
7499         } else {
7500                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7501                         return;
7502         }
7503
7504         pipe_config->gmch_pfit.control = tmp;
7505         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7506 }
7507
7508 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7509                                struct intel_crtc_state *pipe_config)
7510 {
7511         struct drm_device *dev = crtc->base.dev;
7512         struct drm_i915_private *dev_priv = to_i915(dev);
7513         int pipe = pipe_config->cpu_transcoder;
7514         struct dpll clock;
7515         u32 mdiv;
7516         int refclk = 100000;
7517
7518         /* In case of DSI, DPLL will not be used */
7519         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7520                 return;
7521
7522         mutex_lock(&dev_priv->sb_lock);
7523         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7524         mutex_unlock(&dev_priv->sb_lock);
7525
7526         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7527         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7528         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7529         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7530         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7531
7532         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7533 }
7534
7535 static void
7536 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7537                               struct intel_initial_plane_config *plane_config)
7538 {
7539         struct drm_device *dev = crtc->base.dev;
7540         struct drm_i915_private *dev_priv = to_i915(dev);
7541         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7542         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7543         enum pipe pipe = crtc->pipe;
7544         u32 val, base, offset;
7545         int fourcc, pixel_format;
7546         unsigned int aligned_height;
7547         struct drm_framebuffer *fb;
7548         struct intel_framebuffer *intel_fb;
7549
7550         if (!plane->get_hw_state(plane))
7551                 return;
7552
7553         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7554         if (!intel_fb) {
7555                 DRM_DEBUG_KMS("failed to alloc fb\n");
7556                 return;
7557         }
7558
7559         fb = &intel_fb->base;
7560
7561         fb->dev = dev;
7562
7563         val = I915_READ(DSPCNTR(i9xx_plane));
7564
7565         if (INTEL_GEN(dev_priv) >= 4) {
7566                 if (val & DISPPLANE_TILED) {
7567                         plane_config->tiling = I915_TILING_X;
7568                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7569                 }
7570         }
7571
7572         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7573         fourcc = i9xx_format_to_fourcc(pixel_format);
7574         fb->format = drm_format_info(fourcc);
7575
7576         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7577                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7578                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7579         } else if (INTEL_GEN(dev_priv) >= 4) {
7580                 if (plane_config->tiling)
7581                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7582                 else
7583                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7584                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7585         } else {
7586                 base = I915_READ(DSPADDR(i9xx_plane));
7587         }
7588         plane_config->base = base;
7589
7590         val = I915_READ(PIPESRC(pipe));
7591         fb->width = ((val >> 16) & 0xfff) + 1;
7592         fb->height = ((val >> 0) & 0xfff) + 1;
7593
7594         val = I915_READ(DSPSTRIDE(i9xx_plane));
7595         fb->pitches[0] = val & 0xffffffc0;
7596
7597         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7598
7599         plane_config->size = fb->pitches[0] * aligned_height;
7600
7601         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7602                       crtc->base.name, plane->base.name, fb->width, fb->height,
7603                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7604                       plane_config->size);
7605
7606         plane_config->fb = intel_fb;
7607 }
7608
7609 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7610                                struct intel_crtc_state *pipe_config)
7611 {
7612         struct drm_device *dev = crtc->base.dev;
7613         struct drm_i915_private *dev_priv = to_i915(dev);
7614         int pipe = pipe_config->cpu_transcoder;
7615         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7616         struct dpll clock;
7617         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7618         int refclk = 100000;
7619
7620         /* In case of DSI, DPLL will not be used */
7621         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7622                 return;
7623
7624         mutex_lock(&dev_priv->sb_lock);
7625         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7626         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7627         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7628         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7629         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7630         mutex_unlock(&dev_priv->sb_lock);
7631
7632         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7633         clock.m2 = (pll_dw0 & 0xff) << 22;
7634         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7635                 clock.m2 |= pll_dw2 & 0x3fffff;
7636         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7637         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7638         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7639
7640         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7641 }
7642
7643 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7644                                  struct intel_crtc_state *pipe_config)
7645 {
7646         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7647         enum intel_display_power_domain power_domain;
7648         uint32_t tmp;
7649         bool ret;
7650
7651         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7652         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7653                 return false;
7654
7655         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7656         pipe_config->shared_dpll = NULL;
7657
7658         ret = false;
7659
7660         tmp = I915_READ(PIPECONF(crtc->pipe));
7661         if (!(tmp & PIPECONF_ENABLE))
7662                 goto out;
7663
7664         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7665             IS_CHERRYVIEW(dev_priv)) {
7666                 switch (tmp & PIPECONF_BPC_MASK) {
7667                 case PIPECONF_6BPC:
7668                         pipe_config->pipe_bpp = 18;
7669                         break;
7670                 case PIPECONF_8BPC:
7671                         pipe_config->pipe_bpp = 24;
7672                         break;
7673                 case PIPECONF_10BPC:
7674                         pipe_config->pipe_bpp = 30;
7675                         break;
7676                 default:
7677                         break;
7678                 }
7679         }
7680
7681         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7682             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7683                 pipe_config->limited_color_range = true;
7684
7685         if (INTEL_GEN(dev_priv) < 4)
7686                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7687
7688         intel_get_pipe_timings(crtc, pipe_config);
7689         intel_get_pipe_src_size(crtc, pipe_config);
7690
7691         i9xx_get_pfit_config(crtc, pipe_config);
7692
7693         if (INTEL_GEN(dev_priv) >= 4) {
7694                 /* No way to read it out on pipes B and C */
7695                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7696                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7697                 else
7698                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7699                 pipe_config->pixel_multiplier =
7700                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7701                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7702                 pipe_config->dpll_hw_state.dpll_md = tmp;
7703         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7704                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7705                 tmp = I915_READ(DPLL(crtc->pipe));
7706                 pipe_config->pixel_multiplier =
7707                         ((tmp & SDVO_MULTIPLIER_MASK)
7708                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7709         } else {
7710                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7711                  * port and will be fixed up in the encoder->get_config
7712                  * function. */
7713                 pipe_config->pixel_multiplier = 1;
7714         }
7715         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7716         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7717                 /*
7718                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7719                  * on 830. Filter it out here so that we don't
7720                  * report errors due to that.
7721                  */
7722                 if (IS_I830(dev_priv))
7723                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7724
7725                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7726                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7727         } else {
7728                 /* Mask out read-only status bits. */
7729                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7730                                                      DPLL_PORTC_READY_MASK |
7731                                                      DPLL_PORTB_READY_MASK);
7732         }
7733
7734         if (IS_CHERRYVIEW(dev_priv))
7735                 chv_crtc_clock_get(crtc, pipe_config);
7736         else if (IS_VALLEYVIEW(dev_priv))
7737                 vlv_crtc_clock_get(crtc, pipe_config);
7738         else
7739                 i9xx_crtc_clock_get(crtc, pipe_config);
7740
7741         /*
7742          * Normally the dotclock is filled in by the encoder .get_config()
7743          * but in case the pipe is enabled w/o any ports we need a sane
7744          * default.
7745          */
7746         pipe_config->base.adjusted_mode.crtc_clock =
7747                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7748
7749         ret = true;
7750
7751 out:
7752         intel_display_power_put(dev_priv, power_domain);
7753
7754         return ret;
7755 }
7756
7757 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7758 {
7759         struct intel_encoder *encoder;
7760         int i;
7761         u32 val, final;
7762         bool has_lvds = false;
7763         bool has_cpu_edp = false;
7764         bool has_panel = false;
7765         bool has_ck505 = false;
7766         bool can_ssc = false;
7767         bool using_ssc_source = false;
7768
7769         /* We need to take the global config into account */
7770         for_each_intel_encoder(&dev_priv->drm, encoder) {
7771                 switch (encoder->type) {
7772                 case INTEL_OUTPUT_LVDS:
7773                         has_panel = true;
7774                         has_lvds = true;
7775                         break;
7776                 case INTEL_OUTPUT_EDP:
7777                         has_panel = true;
7778                         if (encoder->port == PORT_A)
7779                                 has_cpu_edp = true;
7780                         break;
7781                 default:
7782                         break;
7783                 }
7784         }
7785
7786         if (HAS_PCH_IBX(dev_priv)) {
7787                 has_ck505 = dev_priv->vbt.display_clock_mode;
7788                 can_ssc = has_ck505;
7789         } else {
7790                 has_ck505 = false;
7791                 can_ssc = true;
7792         }
7793
7794         /* Check if any DPLLs are using the SSC source */
7795         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7796                 u32 temp = I915_READ(PCH_DPLL(i));
7797
7798                 if (!(temp & DPLL_VCO_ENABLE))
7799                         continue;
7800
7801                 if ((temp & PLL_REF_INPUT_MASK) ==
7802                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7803                         using_ssc_source = true;
7804                         break;
7805                 }
7806         }
7807
7808         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7809                       has_panel, has_lvds, has_ck505, using_ssc_source);
7810
7811         /* Ironlake: try to setup display ref clock before DPLL
7812          * enabling. This is only under driver's control after
7813          * PCH B stepping, previous chipset stepping should be
7814          * ignoring this setting.
7815          */
7816         val = I915_READ(PCH_DREF_CONTROL);
7817
7818         /* As we must carefully and slowly disable/enable each source in turn,
7819          * compute the final state we want first and check if we need to
7820          * make any changes at all.
7821          */
7822         final = val;
7823         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7824         if (has_ck505)
7825                 final |= DREF_NONSPREAD_CK505_ENABLE;
7826         else
7827                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7828
7829         final &= ~DREF_SSC_SOURCE_MASK;
7830         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7831         final &= ~DREF_SSC1_ENABLE;
7832
7833         if (has_panel) {
7834                 final |= DREF_SSC_SOURCE_ENABLE;
7835
7836                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7837                         final |= DREF_SSC1_ENABLE;
7838
7839                 if (has_cpu_edp) {
7840                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7841                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7842                         else
7843                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7844                 } else
7845                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7846         } else if (using_ssc_source) {
7847                 final |= DREF_SSC_SOURCE_ENABLE;
7848                 final |= DREF_SSC1_ENABLE;
7849         }
7850
7851         if (final == val)
7852                 return;
7853
7854         /* Always enable nonspread source */
7855         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7856
7857         if (has_ck505)
7858                 val |= DREF_NONSPREAD_CK505_ENABLE;
7859         else
7860                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7861
7862         if (has_panel) {
7863                 val &= ~DREF_SSC_SOURCE_MASK;
7864                 val |= DREF_SSC_SOURCE_ENABLE;
7865
7866                 /* SSC must be turned on before enabling the CPU output  */
7867                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7868                         DRM_DEBUG_KMS("Using SSC on panel\n");
7869                         val |= DREF_SSC1_ENABLE;
7870                 } else
7871                         val &= ~DREF_SSC1_ENABLE;
7872
7873                 /* Get SSC going before enabling the outputs */
7874                 I915_WRITE(PCH_DREF_CONTROL, val);
7875                 POSTING_READ(PCH_DREF_CONTROL);
7876                 udelay(200);
7877
7878                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7879
7880                 /* Enable CPU source on CPU attached eDP */
7881                 if (has_cpu_edp) {
7882                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7883                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7884                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7885                         } else
7886                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7887                 } else
7888                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7889
7890                 I915_WRITE(PCH_DREF_CONTROL, val);
7891                 POSTING_READ(PCH_DREF_CONTROL);
7892                 udelay(200);
7893         } else {
7894                 DRM_DEBUG_KMS("Disabling CPU source output\n");
7895
7896                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7897
7898                 /* Turn off CPU output */
7899                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7900
7901                 I915_WRITE(PCH_DREF_CONTROL, val);
7902                 POSTING_READ(PCH_DREF_CONTROL);
7903                 udelay(200);
7904
7905                 if (!using_ssc_source) {
7906                         DRM_DEBUG_KMS("Disabling SSC source\n");
7907
7908                         /* Turn off the SSC source */
7909                         val &= ~DREF_SSC_SOURCE_MASK;
7910                         val |= DREF_SSC_SOURCE_DISABLE;
7911
7912                         /* Turn off SSC1 */
7913                         val &= ~DREF_SSC1_ENABLE;
7914
7915                         I915_WRITE(PCH_DREF_CONTROL, val);
7916                         POSTING_READ(PCH_DREF_CONTROL);
7917                         udelay(200);
7918                 }
7919         }
7920
7921         BUG_ON(val != final);
7922 }
7923
7924 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7925 {
7926         uint32_t tmp;
7927
7928         tmp = I915_READ(SOUTH_CHICKEN2);
7929         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7930         I915_WRITE(SOUTH_CHICKEN2, tmp);
7931
7932         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
7933                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7934                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7935
7936         tmp = I915_READ(SOUTH_CHICKEN2);
7937         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7938         I915_WRITE(SOUTH_CHICKEN2, tmp);
7939
7940         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
7941                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7942                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7943 }
7944
7945 /* WaMPhyProgramming:hsw */
7946 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7947 {
7948         uint32_t tmp;
7949
7950         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7951         tmp &= ~(0xFF << 24);
7952         tmp |= (0x12 << 24);
7953         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
7954
7955         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
7956         tmp |= (1 << 11);
7957         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
7958
7959         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
7960         tmp |= (1 << 11);
7961         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
7962
7963         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
7964         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7965         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
7966
7967         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
7968         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7969         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
7970
7971         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
7972         tmp &= ~(7 << 13);
7973         tmp |= (5 << 13);
7974         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
7975
7976         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
7977         tmp &= ~(7 << 13);
7978         tmp |= (5 << 13);
7979         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
7980
7981         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
7982         tmp &= ~0xFF;
7983         tmp |= 0x1C;
7984         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
7985
7986         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
7987         tmp &= ~0xFF;
7988         tmp |= 0x1C;
7989         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
7990
7991         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
7992         tmp &= ~(0xFF << 16);
7993         tmp |= (0x1C << 16);
7994         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
7995
7996         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
7997         tmp &= ~(0xFF << 16);
7998         tmp |= (0x1C << 16);
7999         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8000
8001         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8002         tmp |= (1 << 27);
8003         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8004
8005         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8006         tmp |= (1 << 27);
8007         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8008
8009         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8010         tmp &= ~(0xF << 28);
8011         tmp |= (4 << 28);
8012         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8013
8014         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8015         tmp &= ~(0xF << 28);
8016         tmp |= (4 << 28);
8017         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8018 }
8019
8020 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8021  * Programming" based on the parameters passed:
8022  * - Sequence to enable CLKOUT_DP
8023  * - Sequence to enable CLKOUT_DP without spread
8024  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8025  */
8026 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8027                                  bool with_spread, bool with_fdi)
8028 {
8029         uint32_t reg, tmp;
8030
8031         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8032                 with_spread = true;
8033         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8034             with_fdi, "LP PCH doesn't have FDI\n"))
8035                 with_fdi = false;
8036
8037         mutex_lock(&dev_priv->sb_lock);
8038
8039         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8040         tmp &= ~SBI_SSCCTL_DISABLE;
8041         tmp |= SBI_SSCCTL_PATHALT;
8042         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8043
8044         udelay(24);
8045
8046         if (with_spread) {
8047                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8048                 tmp &= ~SBI_SSCCTL_PATHALT;
8049                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8050
8051                 if (with_fdi) {
8052                         lpt_reset_fdi_mphy(dev_priv);
8053                         lpt_program_fdi_mphy(dev_priv);
8054                 }
8055         }
8056
8057         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8058         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8059         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8060         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8061
8062         mutex_unlock(&dev_priv->sb_lock);
8063 }
8064
8065 /* Sequence to disable CLKOUT_DP */
8066 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8067 {
8068         uint32_t reg, tmp;
8069
8070         mutex_lock(&dev_priv->sb_lock);
8071
8072         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8073         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8074         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8075         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8076
8077         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8078         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8079                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8080                         tmp |= SBI_SSCCTL_PATHALT;
8081                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8082                         udelay(32);
8083                 }
8084                 tmp |= SBI_SSCCTL_DISABLE;
8085                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8086         }
8087
8088         mutex_unlock(&dev_priv->sb_lock);
8089 }
8090
8091 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8092
8093 static const uint16_t sscdivintphase[] = {
8094         [BEND_IDX( 50)] = 0x3B23,
8095         [BEND_IDX( 45)] = 0x3B23,
8096         [BEND_IDX( 40)] = 0x3C23,
8097         [BEND_IDX( 35)] = 0x3C23,
8098         [BEND_IDX( 30)] = 0x3D23,
8099         [BEND_IDX( 25)] = 0x3D23,
8100         [BEND_IDX( 20)] = 0x3E23,
8101         [BEND_IDX( 15)] = 0x3E23,
8102         [BEND_IDX( 10)] = 0x3F23,
8103         [BEND_IDX(  5)] = 0x3F23,
8104         [BEND_IDX(  0)] = 0x0025,
8105         [BEND_IDX( -5)] = 0x0025,
8106         [BEND_IDX(-10)] = 0x0125,
8107         [BEND_IDX(-15)] = 0x0125,
8108         [BEND_IDX(-20)] = 0x0225,
8109         [BEND_IDX(-25)] = 0x0225,
8110         [BEND_IDX(-30)] = 0x0325,
8111         [BEND_IDX(-35)] = 0x0325,
8112         [BEND_IDX(-40)] = 0x0425,
8113         [BEND_IDX(-45)] = 0x0425,
8114         [BEND_IDX(-50)] = 0x0525,
8115 };
8116
8117 /*
8118  * Bend CLKOUT_DP
8119  * steps -50 to 50 inclusive, in steps of 5
8120  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8121  * change in clock period = -(steps / 10) * 5.787 ps
8122  */
8123 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8124 {
8125         uint32_t tmp;
8126         int idx = BEND_IDX(steps);
8127
8128         if (WARN_ON(steps % 5 != 0))
8129                 return;
8130
8131         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8132                 return;
8133
8134         mutex_lock(&dev_priv->sb_lock);
8135
8136         if (steps % 10 != 0)
8137                 tmp = 0xAAAAAAAB;
8138         else
8139                 tmp = 0x00000000;
8140         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8141
8142         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8143         tmp &= 0xffff0000;
8144         tmp |= sscdivintphase[idx];
8145         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8146
8147         mutex_unlock(&dev_priv->sb_lock);
8148 }
8149
8150 #undef BEND_IDX
8151
8152 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8153 {
8154         struct intel_encoder *encoder;
8155         bool has_vga = false;
8156
8157         for_each_intel_encoder(&dev_priv->drm, encoder) {
8158                 switch (encoder->type) {
8159                 case INTEL_OUTPUT_ANALOG:
8160                         has_vga = true;
8161                         break;
8162                 default:
8163                         break;
8164                 }
8165         }
8166
8167         if (has_vga) {
8168                 lpt_bend_clkout_dp(dev_priv, 0);
8169                 lpt_enable_clkout_dp(dev_priv, true, true);
8170         } else {
8171                 lpt_disable_clkout_dp(dev_priv);
8172         }
8173 }
8174
8175 /*
8176  * Initialize reference clocks when the driver loads
8177  */
8178 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8179 {
8180         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8181                 ironlake_init_pch_refclk(dev_priv);
8182         else if (HAS_PCH_LPT(dev_priv))
8183                 lpt_init_pch_refclk(dev_priv);
8184 }
8185
8186 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8187 {
8188         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8189         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8190         int pipe = intel_crtc->pipe;
8191         uint32_t val;
8192
8193         val = 0;
8194
8195         switch (intel_crtc->config->pipe_bpp) {
8196         case 18:
8197                 val |= PIPECONF_6BPC;
8198                 break;
8199         case 24:
8200                 val |= PIPECONF_8BPC;
8201                 break;
8202         case 30:
8203                 val |= PIPECONF_10BPC;
8204                 break;
8205         case 36:
8206                 val |= PIPECONF_12BPC;
8207                 break;
8208         default:
8209                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8210                 BUG();
8211         }
8212
8213         if (intel_crtc->config->dither)
8214                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8215
8216         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8217                 val |= PIPECONF_INTERLACED_ILK;
8218         else
8219                 val |= PIPECONF_PROGRESSIVE;
8220
8221         if (intel_crtc->config->limited_color_range)
8222                 val |= PIPECONF_COLOR_RANGE_SELECT;
8223
8224         I915_WRITE(PIPECONF(pipe), val);
8225         POSTING_READ(PIPECONF(pipe));
8226 }
8227
8228 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8229 {
8230         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8231         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8232         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8233         u32 val = 0;
8234
8235         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8236                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8237
8238         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8239                 val |= PIPECONF_INTERLACED_ILK;
8240         else
8241                 val |= PIPECONF_PROGRESSIVE;
8242
8243         I915_WRITE(PIPECONF(cpu_transcoder), val);
8244         POSTING_READ(PIPECONF(cpu_transcoder));
8245 }
8246
8247 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8248 {
8249         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8250         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8251         struct intel_crtc_state *config = intel_crtc->config;
8252
8253         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8254                 u32 val = 0;
8255
8256                 switch (intel_crtc->config->pipe_bpp) {
8257                 case 18:
8258                         val |= PIPEMISC_DITHER_6_BPC;
8259                         break;
8260                 case 24:
8261                         val |= PIPEMISC_DITHER_8_BPC;
8262                         break;
8263                 case 30:
8264                         val |= PIPEMISC_DITHER_10_BPC;
8265                         break;
8266                 case 36:
8267                         val |= PIPEMISC_DITHER_12_BPC;
8268                         break;
8269                 default:
8270                         /* Case prevented by pipe_config_set_bpp. */
8271                         BUG();
8272                 }
8273
8274                 if (intel_crtc->config->dither)
8275                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8276
8277                 if (config->ycbcr420) {
8278                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8279                                 PIPEMISC_YUV420_ENABLE |
8280                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8281                 }
8282
8283                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8284         }
8285 }
8286
8287 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8288 {
8289         /*
8290          * Account for spread spectrum to avoid
8291          * oversubscribing the link. Max center spread
8292          * is 2.5%; use 5% for safety's sake.
8293          */
8294         u32 bps = target_clock * bpp * 21 / 20;
8295         return DIV_ROUND_UP(bps, link_bw * 8);
8296 }
8297
8298 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8299 {
8300         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8301 }
8302
8303 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8304                                   struct intel_crtc_state *crtc_state,
8305                                   struct dpll *reduced_clock)
8306 {
8307         struct drm_crtc *crtc = &intel_crtc->base;
8308         struct drm_device *dev = crtc->dev;
8309         struct drm_i915_private *dev_priv = to_i915(dev);
8310         u32 dpll, fp, fp2;
8311         int factor;
8312
8313         /* Enable autotuning of the PLL clock (if permissible) */
8314         factor = 21;
8315         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8316                 if ((intel_panel_use_ssc(dev_priv) &&
8317                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8318                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8319                         factor = 25;
8320         } else if (crtc_state->sdvo_tv_clock)
8321                 factor = 20;
8322
8323         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8324
8325         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8326                 fp |= FP_CB_TUNE;
8327
8328         if (reduced_clock) {
8329                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8330
8331                 if (reduced_clock->m < factor * reduced_clock->n)
8332                         fp2 |= FP_CB_TUNE;
8333         } else {
8334                 fp2 = fp;
8335         }
8336
8337         dpll = 0;
8338
8339         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8340                 dpll |= DPLLB_MODE_LVDS;
8341         else
8342                 dpll |= DPLLB_MODE_DAC_SERIAL;
8343
8344         dpll |= (crtc_state->pixel_multiplier - 1)
8345                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8346
8347         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8348             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8349                 dpll |= DPLL_SDVO_HIGH_SPEED;
8350
8351         if (intel_crtc_has_dp_encoder(crtc_state))
8352                 dpll |= DPLL_SDVO_HIGH_SPEED;
8353
8354         /*
8355          * The high speed IO clock is only really required for
8356          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8357          * possible to share the DPLL between CRT and HDMI. Enabling
8358          * the clock needlessly does no real harm, except use up a
8359          * bit of power potentially.
8360          *
8361          * We'll limit this to IVB with 3 pipes, since it has only two
8362          * DPLLs and so DPLL sharing is the only way to get three pipes
8363          * driving PCH ports at the same time. On SNB we could do this,
8364          * and potentially avoid enabling the second DPLL, but it's not
8365          * clear if it''s a win or loss power wise. No point in doing
8366          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8367          */
8368         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8369             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8370                 dpll |= DPLL_SDVO_HIGH_SPEED;
8371
8372         /* compute bitmask from p1 value */
8373         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8374         /* also FPA1 */
8375         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8376
8377         switch (crtc_state->dpll.p2) {
8378         case 5:
8379                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8380                 break;
8381         case 7:
8382                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8383                 break;
8384         case 10:
8385                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8386                 break;
8387         case 14:
8388                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8389                 break;
8390         }
8391
8392         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8393             intel_panel_use_ssc(dev_priv))
8394                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8395         else
8396                 dpll |= PLL_REF_INPUT_DREFCLK;
8397
8398         dpll |= DPLL_VCO_ENABLE;
8399
8400         crtc_state->dpll_hw_state.dpll = dpll;
8401         crtc_state->dpll_hw_state.fp0 = fp;
8402         crtc_state->dpll_hw_state.fp1 = fp2;
8403 }
8404
8405 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8406                                        struct intel_crtc_state *crtc_state)
8407 {
8408         struct drm_device *dev = crtc->base.dev;
8409         struct drm_i915_private *dev_priv = to_i915(dev);
8410         const struct intel_limit *limit;
8411         int refclk = 120000;
8412
8413         memset(&crtc_state->dpll_hw_state, 0,
8414                sizeof(crtc_state->dpll_hw_state));
8415
8416         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8417         if (!crtc_state->has_pch_encoder)
8418                 return 0;
8419
8420         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8421                 if (intel_panel_use_ssc(dev_priv)) {
8422                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8423                                       dev_priv->vbt.lvds_ssc_freq);
8424                         refclk = dev_priv->vbt.lvds_ssc_freq;
8425                 }
8426
8427                 if (intel_is_dual_link_lvds(dev)) {
8428                         if (refclk == 100000)
8429                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8430                         else
8431                                 limit = &intel_limits_ironlake_dual_lvds;
8432                 } else {
8433                         if (refclk == 100000)
8434                                 limit = &intel_limits_ironlake_single_lvds_100m;
8435                         else
8436                                 limit = &intel_limits_ironlake_single_lvds;
8437                 }
8438         } else {
8439                 limit = &intel_limits_ironlake_dac;
8440         }
8441
8442         if (!crtc_state->clock_set &&
8443             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8444                                 refclk, NULL, &crtc_state->dpll)) {
8445                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8446                 return -EINVAL;
8447         }
8448
8449         ironlake_compute_dpll(crtc, crtc_state, NULL);
8450
8451         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8452                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8453                                  pipe_name(crtc->pipe));
8454                 return -EINVAL;
8455         }
8456
8457         return 0;
8458 }
8459
8460 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8461                                          struct intel_link_m_n *m_n)
8462 {
8463         struct drm_device *dev = crtc->base.dev;
8464         struct drm_i915_private *dev_priv = to_i915(dev);
8465         enum pipe pipe = crtc->pipe;
8466
8467         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8468         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8469         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8470                 & ~TU_SIZE_MASK;
8471         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8472         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8473                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8474 }
8475
8476 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8477                                          enum transcoder transcoder,
8478                                          struct intel_link_m_n *m_n,
8479                                          struct intel_link_m_n *m2_n2)
8480 {
8481         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8482         enum pipe pipe = crtc->pipe;
8483
8484         if (INTEL_GEN(dev_priv) >= 5) {
8485                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8486                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8487                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8488                         & ~TU_SIZE_MASK;
8489                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8490                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8491                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8492                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8493                  * gen < 8) and if DRRS is supported (to make sure the
8494                  * registers are not unnecessarily read).
8495                  */
8496                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8497                         crtc->config->has_drrs) {
8498                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8499                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8500                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8501                                         & ~TU_SIZE_MASK;
8502                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8503                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8504                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8505                 }
8506         } else {
8507                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8508                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8509                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8510                         & ~TU_SIZE_MASK;
8511                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8512                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8513                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8514         }
8515 }
8516
8517 void intel_dp_get_m_n(struct intel_crtc *crtc,
8518                       struct intel_crtc_state *pipe_config)
8519 {
8520         if (pipe_config->has_pch_encoder)
8521                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8522         else
8523                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8524                                              &pipe_config->dp_m_n,
8525                                              &pipe_config->dp_m2_n2);
8526 }
8527
8528 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8529                                         struct intel_crtc_state *pipe_config)
8530 {
8531         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8532                                      &pipe_config->fdi_m_n, NULL);
8533 }
8534
8535 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8536                                     struct intel_crtc_state *pipe_config)
8537 {
8538         struct drm_device *dev = crtc->base.dev;
8539         struct drm_i915_private *dev_priv = to_i915(dev);
8540         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8541         uint32_t ps_ctrl = 0;
8542         int id = -1;
8543         int i;
8544
8545         /* find scaler attached to this pipe */
8546         for (i = 0; i < crtc->num_scalers; i++) {
8547                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8548                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8549                         id = i;
8550                         pipe_config->pch_pfit.enabled = true;
8551                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8552                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8553                         break;
8554                 }
8555         }
8556
8557         scaler_state->scaler_id = id;
8558         if (id >= 0) {
8559                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8560         } else {
8561                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8562         }
8563 }
8564
8565 static void
8566 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8567                                  struct intel_initial_plane_config *plane_config)
8568 {
8569         struct drm_device *dev = crtc->base.dev;
8570         struct drm_i915_private *dev_priv = to_i915(dev);
8571         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8572         enum plane_id plane_id = plane->id;
8573         enum pipe pipe = crtc->pipe;
8574         u32 val, base, offset, stride_mult, tiling, alpha;
8575         int fourcc, pixel_format;
8576         unsigned int aligned_height;
8577         struct drm_framebuffer *fb;
8578         struct intel_framebuffer *intel_fb;
8579
8580         if (!plane->get_hw_state(plane))
8581                 return;
8582
8583         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8584         if (!intel_fb) {
8585                 DRM_DEBUG_KMS("failed to alloc fb\n");
8586                 return;
8587         }
8588
8589         fb = &intel_fb->base;
8590
8591         fb->dev = dev;
8592
8593         val = I915_READ(PLANE_CTL(pipe, plane_id));
8594
8595         if (INTEL_GEN(dev_priv) >= 11)
8596                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8597         else
8598                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8599
8600         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8601                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8602                 alpha &= PLANE_COLOR_ALPHA_MASK;
8603         } else {
8604                 alpha = val & PLANE_CTL_ALPHA_MASK;
8605         }
8606
8607         fourcc = skl_format_to_fourcc(pixel_format,
8608                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8609         fb->format = drm_format_info(fourcc);
8610
8611         tiling = val & PLANE_CTL_TILED_MASK;
8612         switch (tiling) {
8613         case PLANE_CTL_TILED_LINEAR:
8614                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8615                 break;
8616         case PLANE_CTL_TILED_X:
8617                 plane_config->tiling = I915_TILING_X;
8618                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8619                 break;
8620         case PLANE_CTL_TILED_Y:
8621                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8622                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8623                 else
8624                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8625                 break;
8626         case PLANE_CTL_TILED_YF:
8627                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8628                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8629                 else
8630                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8631                 break;
8632         default:
8633                 MISSING_CASE(tiling);
8634                 goto error;
8635         }
8636
8637         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8638         plane_config->base = base;
8639
8640         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8641
8642         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8643         fb->height = ((val >> 16) & 0xfff) + 1;
8644         fb->width = ((val >> 0) & 0x1fff) + 1;
8645
8646         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8647         stride_mult = intel_fb_stride_alignment(fb, 0);
8648         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8649
8650         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8651
8652         plane_config->size = fb->pitches[0] * aligned_height;
8653
8654         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8655                       crtc->base.name, plane->base.name, fb->width, fb->height,
8656                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8657                       plane_config->size);
8658
8659         plane_config->fb = intel_fb;
8660         return;
8661
8662 error:
8663         kfree(intel_fb);
8664 }
8665
8666 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8667                                      struct intel_crtc_state *pipe_config)
8668 {
8669         struct drm_device *dev = crtc->base.dev;
8670         struct drm_i915_private *dev_priv = to_i915(dev);
8671         uint32_t tmp;
8672
8673         tmp = I915_READ(PF_CTL(crtc->pipe));
8674
8675         if (tmp & PF_ENABLE) {
8676                 pipe_config->pch_pfit.enabled = true;
8677                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8678                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8679
8680                 /* We currently do not free assignements of panel fitters on
8681                  * ivb/hsw (since we don't use the higher upscaling modes which
8682                  * differentiates them) so just WARN about this case for now. */
8683                 if (IS_GEN7(dev_priv)) {
8684                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8685                                 PF_PIPE_SEL_IVB(crtc->pipe));
8686                 }
8687         }
8688 }
8689
8690 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8691                                      struct intel_crtc_state *pipe_config)
8692 {
8693         struct drm_device *dev = crtc->base.dev;
8694         struct drm_i915_private *dev_priv = to_i915(dev);
8695         enum intel_display_power_domain power_domain;
8696         uint32_t tmp;
8697         bool ret;
8698
8699         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8700         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8701                 return false;
8702
8703         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8704         pipe_config->shared_dpll = NULL;
8705
8706         ret = false;
8707         tmp = I915_READ(PIPECONF(crtc->pipe));
8708         if (!(tmp & PIPECONF_ENABLE))
8709                 goto out;
8710
8711         switch (tmp & PIPECONF_BPC_MASK) {
8712         case PIPECONF_6BPC:
8713                 pipe_config->pipe_bpp = 18;
8714                 break;
8715         case PIPECONF_8BPC:
8716                 pipe_config->pipe_bpp = 24;
8717                 break;
8718         case PIPECONF_10BPC:
8719                 pipe_config->pipe_bpp = 30;
8720                 break;
8721         case PIPECONF_12BPC:
8722                 pipe_config->pipe_bpp = 36;
8723                 break;
8724         default:
8725                 break;
8726         }
8727
8728         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8729                 pipe_config->limited_color_range = true;
8730
8731         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8732                 struct intel_shared_dpll *pll;
8733                 enum intel_dpll_id pll_id;
8734
8735                 pipe_config->has_pch_encoder = true;
8736
8737                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8738                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8739                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8740
8741                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8742
8743                 if (HAS_PCH_IBX(dev_priv)) {
8744                         /*
8745                          * The pipe->pch transcoder and pch transcoder->pll
8746                          * mapping is fixed.
8747                          */
8748                         pll_id = (enum intel_dpll_id) crtc->pipe;
8749                 } else {
8750                         tmp = I915_READ(PCH_DPLL_SEL);
8751                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8752                                 pll_id = DPLL_ID_PCH_PLL_B;
8753                         else
8754                                 pll_id= DPLL_ID_PCH_PLL_A;
8755                 }
8756
8757                 pipe_config->shared_dpll =
8758                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8759                 pll = pipe_config->shared_dpll;
8760
8761                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
8762                                                  &pipe_config->dpll_hw_state));
8763
8764                 tmp = pipe_config->dpll_hw_state.dpll;
8765                 pipe_config->pixel_multiplier =
8766                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8767                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8768
8769                 ironlake_pch_clock_get(crtc, pipe_config);
8770         } else {
8771                 pipe_config->pixel_multiplier = 1;
8772         }
8773
8774         intel_get_pipe_timings(crtc, pipe_config);
8775         intel_get_pipe_src_size(crtc, pipe_config);
8776
8777         ironlake_get_pfit_config(crtc, pipe_config);
8778
8779         ret = true;
8780
8781 out:
8782         intel_display_power_put(dev_priv, power_domain);
8783
8784         return ret;
8785 }
8786
8787 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8788 {
8789         struct drm_device *dev = &dev_priv->drm;
8790         struct intel_crtc *crtc;
8791
8792         for_each_intel_crtc(dev, crtc)
8793                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8794                      pipe_name(crtc->pipe));
8795
8796         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL)),
8797                         "Display power well on\n");
8798         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8799         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8800         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8801         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8802         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8803              "CPU PWM1 enabled\n");
8804         if (IS_HASWELL(dev_priv))
8805                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8806                      "CPU PWM2 enabled\n");
8807         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8808              "PCH PWM1 enabled\n");
8809         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8810              "Utility pin enabled\n");
8811         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8812
8813         /*
8814          * In theory we can still leave IRQs enabled, as long as only the HPD
8815          * interrupts remain enabled. We used to check for that, but since it's
8816          * gen-specific and since we only disable LCPLL after we fully disable
8817          * the interrupts, the check below should be enough.
8818          */
8819         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8820 }
8821
8822 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8823 {
8824         if (IS_HASWELL(dev_priv))
8825                 return I915_READ(D_COMP_HSW);
8826         else
8827                 return I915_READ(D_COMP_BDW);
8828 }
8829
8830 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8831 {
8832         if (IS_HASWELL(dev_priv)) {
8833                 mutex_lock(&dev_priv->pcu_lock);
8834                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8835                                             val))
8836                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
8837                 mutex_unlock(&dev_priv->pcu_lock);
8838         } else {
8839                 I915_WRITE(D_COMP_BDW, val);
8840                 POSTING_READ(D_COMP_BDW);
8841         }
8842 }
8843
8844 /*
8845  * This function implements pieces of two sequences from BSpec:
8846  * - Sequence for display software to disable LCPLL
8847  * - Sequence for display software to allow package C8+
8848  * The steps implemented here are just the steps that actually touch the LCPLL
8849  * register. Callers should take care of disabling all the display engine
8850  * functions, doing the mode unset, fixing interrupts, etc.
8851  */
8852 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8853                               bool switch_to_fclk, bool allow_power_down)
8854 {
8855         uint32_t val;
8856
8857         assert_can_disable_lcpll(dev_priv);
8858
8859         val = I915_READ(LCPLL_CTL);
8860
8861         if (switch_to_fclk) {
8862                 val |= LCPLL_CD_SOURCE_FCLK;
8863                 I915_WRITE(LCPLL_CTL, val);
8864
8865                 if (wait_for_us(I915_READ(LCPLL_CTL) &
8866                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
8867                         DRM_ERROR("Switching to FCLK failed\n");
8868
8869                 val = I915_READ(LCPLL_CTL);
8870         }
8871
8872         val |= LCPLL_PLL_DISABLE;
8873         I915_WRITE(LCPLL_CTL, val);
8874         POSTING_READ(LCPLL_CTL);
8875
8876         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
8877                 DRM_ERROR("LCPLL still locked\n");
8878
8879         val = hsw_read_dcomp(dev_priv);
8880         val |= D_COMP_COMP_DISABLE;
8881         hsw_write_dcomp(dev_priv, val);
8882         ndelay(100);
8883
8884         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8885                      1))
8886                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8887
8888         if (allow_power_down) {
8889                 val = I915_READ(LCPLL_CTL);
8890                 val |= LCPLL_POWER_DOWN_ALLOW;
8891                 I915_WRITE(LCPLL_CTL, val);
8892                 POSTING_READ(LCPLL_CTL);
8893         }
8894 }
8895
8896 /*
8897  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8898  * source.
8899  */
8900 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8901 {
8902         uint32_t val;
8903
8904         val = I915_READ(LCPLL_CTL);
8905
8906         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8907                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8908                 return;
8909
8910         /*
8911          * Make sure we're not on PC8 state before disabling PC8, otherwise
8912          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8913          */
8914         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8915
8916         if (val & LCPLL_POWER_DOWN_ALLOW) {
8917                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8918                 I915_WRITE(LCPLL_CTL, val);
8919                 POSTING_READ(LCPLL_CTL);
8920         }
8921
8922         val = hsw_read_dcomp(dev_priv);
8923         val |= D_COMP_COMP_FORCE;
8924         val &= ~D_COMP_COMP_DISABLE;
8925         hsw_write_dcomp(dev_priv, val);
8926
8927         val = I915_READ(LCPLL_CTL);
8928         val &= ~LCPLL_PLL_DISABLE;
8929         I915_WRITE(LCPLL_CTL, val);
8930
8931         if (intel_wait_for_register(dev_priv,
8932                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
8933                                     5))
8934                 DRM_ERROR("LCPLL not locked yet\n");
8935
8936         if (val & LCPLL_CD_SOURCE_FCLK) {
8937                 val = I915_READ(LCPLL_CTL);
8938                 val &= ~LCPLL_CD_SOURCE_FCLK;
8939                 I915_WRITE(LCPLL_CTL, val);
8940
8941                 if (wait_for_us((I915_READ(LCPLL_CTL) &
8942                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8943                         DRM_ERROR("Switching back to LCPLL failed\n");
8944         }
8945
8946         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8947
8948         intel_update_cdclk(dev_priv);
8949         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
8950 }
8951
8952 /*
8953  * Package states C8 and deeper are really deep PC states that can only be
8954  * reached when all the devices on the system allow it, so even if the graphics
8955  * device allows PC8+, it doesn't mean the system will actually get to these
8956  * states. Our driver only allows PC8+ when going into runtime PM.
8957  *
8958  * The requirements for PC8+ are that all the outputs are disabled, the power
8959  * well is disabled and most interrupts are disabled, and these are also
8960  * requirements for runtime PM. When these conditions are met, we manually do
8961  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
8962  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
8963  * hang the machine.
8964  *
8965  * When we really reach PC8 or deeper states (not just when we allow it) we lose
8966  * the state of some registers, so when we come back from PC8+ we need to
8967  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
8968  * need to take care of the registers kept by RC6. Notice that this happens even
8969  * if we don't put the device in PCI D3 state (which is what currently happens
8970  * because of the runtime PM support).
8971  *
8972  * For more, read "Display Sequences for Package C8" on the hardware
8973  * documentation.
8974  */
8975 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
8976 {
8977         uint32_t val;
8978
8979         DRM_DEBUG_KMS("Enabling package C8+\n");
8980
8981         if (HAS_PCH_LPT_LP(dev_priv)) {
8982                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8983                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
8984                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8985         }
8986
8987         lpt_disable_clkout_dp(dev_priv);
8988         hsw_disable_lcpll(dev_priv, true, true);
8989 }
8990
8991 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
8992 {
8993         uint32_t val;
8994
8995         DRM_DEBUG_KMS("Disabling package C8+\n");
8996
8997         hsw_restore_lcpll(dev_priv);
8998         lpt_init_pch_refclk(dev_priv);
8999
9000         if (HAS_PCH_LPT_LP(dev_priv)) {
9001                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9002                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9003                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9004         }
9005 }
9006
9007 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9008                                       struct intel_crtc_state *crtc_state)
9009 {
9010         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9011                 struct intel_encoder *encoder =
9012                         intel_ddi_get_crtc_new_encoder(crtc_state);
9013
9014                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9015                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9016                                          pipe_name(crtc->pipe));
9017                         return -EINVAL;
9018                 }
9019         }
9020
9021         return 0;
9022 }
9023
9024 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9025                                    enum port port,
9026                                    struct intel_crtc_state *pipe_config)
9027 {
9028         enum intel_dpll_id id;
9029         u32 temp;
9030
9031         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9032         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9033
9034         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9035                 return;
9036
9037         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9038 }
9039
9040 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9041                                 enum port port,
9042                                 struct intel_crtc_state *pipe_config)
9043 {
9044         enum intel_dpll_id id;
9045
9046         switch (port) {
9047         case PORT_A:
9048                 id = DPLL_ID_SKL_DPLL0;
9049                 break;
9050         case PORT_B:
9051                 id = DPLL_ID_SKL_DPLL1;
9052                 break;
9053         case PORT_C:
9054                 id = DPLL_ID_SKL_DPLL2;
9055                 break;
9056         default:
9057                 DRM_ERROR("Incorrect port type\n");
9058                 return;
9059         }
9060
9061         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9062 }
9063
9064 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9065                                 enum port port,
9066                                 struct intel_crtc_state *pipe_config)
9067 {
9068         enum intel_dpll_id id;
9069         u32 temp;
9070
9071         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9072         id = temp >> (port * 3 + 1);
9073
9074         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9075                 return;
9076
9077         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9078 }
9079
9080 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9081                                 enum port port,
9082                                 struct intel_crtc_state *pipe_config)
9083 {
9084         enum intel_dpll_id id;
9085         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9086
9087         switch (ddi_pll_sel) {
9088         case PORT_CLK_SEL_WRPLL1:
9089                 id = DPLL_ID_WRPLL1;
9090                 break;
9091         case PORT_CLK_SEL_WRPLL2:
9092                 id = DPLL_ID_WRPLL2;
9093                 break;
9094         case PORT_CLK_SEL_SPLL:
9095                 id = DPLL_ID_SPLL;
9096                 break;
9097         case PORT_CLK_SEL_LCPLL_810:
9098                 id = DPLL_ID_LCPLL_810;
9099                 break;
9100         case PORT_CLK_SEL_LCPLL_1350:
9101                 id = DPLL_ID_LCPLL_1350;
9102                 break;
9103         case PORT_CLK_SEL_LCPLL_2700:
9104                 id = DPLL_ID_LCPLL_2700;
9105                 break;
9106         default:
9107                 MISSING_CASE(ddi_pll_sel);
9108                 /* fall through */
9109         case PORT_CLK_SEL_NONE:
9110                 return;
9111         }
9112
9113         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9114 }
9115
9116 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9117                                      struct intel_crtc_state *pipe_config,
9118                                      u64 *power_domain_mask)
9119 {
9120         struct drm_device *dev = crtc->base.dev;
9121         struct drm_i915_private *dev_priv = to_i915(dev);
9122         enum intel_display_power_domain power_domain;
9123         u32 tmp;
9124
9125         /*
9126          * The pipe->transcoder mapping is fixed with the exception of the eDP
9127          * transcoder handled below.
9128          */
9129         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9130
9131         /*
9132          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9133          * consistency and less surprising code; it's in always on power).
9134          */
9135         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9136         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9137                 enum pipe trans_edp_pipe;
9138                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9139                 default:
9140                         WARN(1, "unknown pipe linked to edp transcoder\n");
9141                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9142                 case TRANS_DDI_EDP_INPUT_A_ON:
9143                         trans_edp_pipe = PIPE_A;
9144                         break;
9145                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9146                         trans_edp_pipe = PIPE_B;
9147                         break;
9148                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9149                         trans_edp_pipe = PIPE_C;
9150                         break;
9151                 }
9152
9153                 if (trans_edp_pipe == crtc->pipe)
9154                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9155         }
9156
9157         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9158         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9159                 return false;
9160         *power_domain_mask |= BIT_ULL(power_domain);
9161
9162         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9163
9164         return tmp & PIPECONF_ENABLE;
9165 }
9166
9167 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9168                                          struct intel_crtc_state *pipe_config,
9169                                          u64 *power_domain_mask)
9170 {
9171         struct drm_device *dev = crtc->base.dev;
9172         struct drm_i915_private *dev_priv = to_i915(dev);
9173         enum intel_display_power_domain power_domain;
9174         enum port port;
9175         enum transcoder cpu_transcoder;
9176         u32 tmp;
9177
9178         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9179                 if (port == PORT_A)
9180                         cpu_transcoder = TRANSCODER_DSI_A;
9181                 else
9182                         cpu_transcoder = TRANSCODER_DSI_C;
9183
9184                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9185                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9186                         continue;
9187                 *power_domain_mask |= BIT_ULL(power_domain);
9188
9189                 /*
9190                  * The PLL needs to be enabled with a valid divider
9191                  * configuration, otherwise accessing DSI registers will hang
9192                  * the machine. See BSpec North Display Engine
9193                  * registers/MIPI[BXT]. We can break out here early, since we
9194                  * need the same DSI PLL to be enabled for both DSI ports.
9195                  */
9196                 if (!intel_dsi_pll_is_enabled(dev_priv))
9197                         break;
9198
9199                 /* XXX: this works for video mode only */
9200                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9201                 if (!(tmp & DPI_ENABLE))
9202                         continue;
9203
9204                 tmp = I915_READ(MIPI_CTRL(port));
9205                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9206                         continue;
9207
9208                 pipe_config->cpu_transcoder = cpu_transcoder;
9209                 break;
9210         }
9211
9212         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9213 }
9214
9215 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9216                                        struct intel_crtc_state *pipe_config)
9217 {
9218         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9219         struct intel_shared_dpll *pll;
9220         enum port port;
9221         uint32_t tmp;
9222
9223         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9224
9225         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9226
9227         if (IS_CANNONLAKE(dev_priv))
9228                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9229         else if (IS_GEN9_BC(dev_priv))
9230                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9231         else if (IS_GEN9_LP(dev_priv))
9232                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9233         else
9234                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9235
9236         pll = pipe_config->shared_dpll;
9237         if (pll) {
9238                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9239                                                  &pipe_config->dpll_hw_state));
9240         }
9241
9242         /*
9243          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9244          * DDI E. So just check whether this pipe is wired to DDI E and whether
9245          * the PCH transcoder is on.
9246          */
9247         if (INTEL_GEN(dev_priv) < 9 &&
9248             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9249                 pipe_config->has_pch_encoder = true;
9250
9251                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9252                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9253                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9254
9255                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9256         }
9257 }
9258
9259 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9260                                     struct intel_crtc_state *pipe_config)
9261 {
9262         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9263         enum intel_display_power_domain power_domain;
9264         u64 power_domain_mask;
9265         bool active;
9266
9267         intel_crtc_init_scalers(crtc, pipe_config);
9268
9269         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9270         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9271                 return false;
9272         power_domain_mask = BIT_ULL(power_domain);
9273
9274         pipe_config->shared_dpll = NULL;
9275
9276         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9277
9278         if (IS_GEN9_LP(dev_priv) &&
9279             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9280                 WARN_ON(active);
9281                 active = true;
9282         }
9283
9284         if (!active)
9285                 goto out;
9286
9287         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9288                 haswell_get_ddi_port_state(crtc, pipe_config);
9289                 intel_get_pipe_timings(crtc, pipe_config);
9290         }
9291
9292         intel_get_pipe_src_size(crtc, pipe_config);
9293
9294         pipe_config->gamma_mode =
9295                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9296
9297         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
9298                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9299                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9300
9301                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10) {
9302                         bool blend_mode_420 = tmp &
9303                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9304
9305                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9306                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9307                             pipe_config->ycbcr420 != blend_mode_420)
9308                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9309                 } else if (clrspace_yuv) {
9310                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9311                 }
9312         }
9313
9314         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9315         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9316                 power_domain_mask |= BIT_ULL(power_domain);
9317                 if (INTEL_GEN(dev_priv) >= 9)
9318                         skylake_get_pfit_config(crtc, pipe_config);
9319                 else
9320                         ironlake_get_pfit_config(crtc, pipe_config);
9321         }
9322
9323         if (hsw_crtc_supports_ips(crtc)) {
9324                 if (IS_HASWELL(dev_priv))
9325                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9326                 else {
9327                         /*
9328                          * We cannot readout IPS state on broadwell, set to
9329                          * true so we can set it to a defined state on first
9330                          * commit.
9331                          */
9332                         pipe_config->ips_enabled = true;
9333                 }
9334         }
9335
9336         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9337             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9338                 pipe_config->pixel_multiplier =
9339                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9340         } else {
9341                 pipe_config->pixel_multiplier = 1;
9342         }
9343
9344 out:
9345         for_each_power_domain(power_domain, power_domain_mask)
9346                 intel_display_power_put(dev_priv, power_domain);
9347
9348         return active;
9349 }
9350
9351 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9352 {
9353         struct drm_i915_private *dev_priv =
9354                 to_i915(plane_state->base.plane->dev);
9355         const struct drm_framebuffer *fb = plane_state->base.fb;
9356         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9357         u32 base;
9358
9359         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9360                 base = obj->phys_handle->busaddr;
9361         else
9362                 base = intel_plane_ggtt_offset(plane_state);
9363
9364         base += plane_state->main.offset;
9365
9366         /* ILK+ do this automagically */
9367         if (HAS_GMCH_DISPLAY(dev_priv) &&
9368             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9369                 base += (plane_state->base.crtc_h *
9370                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9371
9372         return base;
9373 }
9374
9375 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9376 {
9377         int x = plane_state->base.crtc_x;
9378         int y = plane_state->base.crtc_y;
9379         u32 pos = 0;
9380
9381         if (x < 0) {
9382                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9383                 x = -x;
9384         }
9385         pos |= x << CURSOR_X_SHIFT;
9386
9387         if (y < 0) {
9388                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9389                 y = -y;
9390         }
9391         pos |= y << CURSOR_Y_SHIFT;
9392
9393         return pos;
9394 }
9395
9396 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9397 {
9398         const struct drm_mode_config *config =
9399                 &plane_state->base.plane->dev->mode_config;
9400         int width = plane_state->base.crtc_w;
9401         int height = plane_state->base.crtc_h;
9402
9403         return width > 0 && width <= config->cursor_width &&
9404                 height > 0 && height <= config->cursor_height;
9405 }
9406
9407 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9408                               struct intel_plane_state *plane_state)
9409 {
9410         const struct drm_framebuffer *fb = plane_state->base.fb;
9411         struct drm_rect clip = {};
9412         int src_x, src_y;
9413         u32 offset;
9414         int ret;
9415
9416         if (crtc_state->base.enable)
9417                 drm_mode_get_hv_timing(&crtc_state->base.mode,
9418                                        &clip.x2, &clip.y2);
9419
9420         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9421                                                   &crtc_state->base,
9422                                                   &clip,
9423                                                   DRM_PLANE_HELPER_NO_SCALING,
9424                                                   DRM_PLANE_HELPER_NO_SCALING,
9425                                                   true, true);
9426         if (ret)
9427                 return ret;
9428
9429         if (!fb)
9430                 return 0;
9431
9432         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9433                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9434                 return -EINVAL;
9435         }
9436
9437         src_x = plane_state->base.src_x >> 16;
9438         src_y = plane_state->base.src_y >> 16;
9439
9440         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9441         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9442
9443         if (src_x != 0 || src_y != 0) {
9444                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9445                 return -EINVAL;
9446         }
9447
9448         plane_state->main.offset = offset;
9449
9450         return 0;
9451 }
9452
9453 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9454                            const struct intel_plane_state *plane_state)
9455 {
9456         const struct drm_framebuffer *fb = plane_state->base.fb;
9457
9458         return CURSOR_ENABLE |
9459                 CURSOR_GAMMA_ENABLE |
9460                 CURSOR_FORMAT_ARGB |
9461                 CURSOR_STRIDE(fb->pitches[0]);
9462 }
9463
9464 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9465 {
9466         int width = plane_state->base.crtc_w;
9467
9468         /*
9469          * 845g/865g are only limited by the width of their cursors,
9470          * the height is arbitrary up to the precision of the register.
9471          */
9472         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9473 }
9474
9475 static int i845_check_cursor(struct intel_plane *plane,
9476                              struct intel_crtc_state *crtc_state,
9477                              struct intel_plane_state *plane_state)
9478 {
9479         const struct drm_framebuffer *fb = plane_state->base.fb;
9480         int ret;
9481
9482         ret = intel_check_cursor(crtc_state, plane_state);
9483         if (ret)
9484                 return ret;
9485
9486         /* if we want to turn off the cursor ignore width and height */
9487         if (!fb)
9488                 return 0;
9489
9490         /* Check for which cursor types we support */
9491         if (!i845_cursor_size_ok(plane_state)) {
9492                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9493                           plane_state->base.crtc_w,
9494                           plane_state->base.crtc_h);
9495                 return -EINVAL;
9496         }
9497
9498         switch (fb->pitches[0]) {
9499         case 256:
9500         case 512:
9501         case 1024:
9502         case 2048:
9503                 break;
9504         default:
9505                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9506                               fb->pitches[0]);
9507                 return -EINVAL;
9508         }
9509
9510         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9511
9512         return 0;
9513 }
9514
9515 static void i845_update_cursor(struct intel_plane *plane,
9516                                const struct intel_crtc_state *crtc_state,
9517                                const struct intel_plane_state *plane_state)
9518 {
9519         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9520         u32 cntl = 0, base = 0, pos = 0, size = 0;
9521         unsigned long irqflags;
9522
9523         if (plane_state && plane_state->base.visible) {
9524                 unsigned int width = plane_state->base.crtc_w;
9525                 unsigned int height = plane_state->base.crtc_h;
9526
9527                 cntl = plane_state->ctl;
9528                 size = (height << 12) | width;
9529
9530                 base = intel_cursor_base(plane_state);
9531                 pos = intel_cursor_position(plane_state);
9532         }
9533
9534         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9535
9536         /* On these chipsets we can only modify the base/size/stride
9537          * whilst the cursor is disabled.
9538          */
9539         if (plane->cursor.base != base ||
9540             plane->cursor.size != size ||
9541             plane->cursor.cntl != cntl) {
9542                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9543                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9544                 I915_WRITE_FW(CURSIZE, size);
9545                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9546                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9547
9548                 plane->cursor.base = base;
9549                 plane->cursor.size = size;
9550                 plane->cursor.cntl = cntl;
9551         } else {
9552                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9553         }
9554
9555         POSTING_READ_FW(CURCNTR(PIPE_A));
9556
9557         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9558 }
9559
9560 static void i845_disable_cursor(struct intel_plane *plane,
9561                                 struct intel_crtc *crtc)
9562 {
9563         i845_update_cursor(plane, NULL, NULL);
9564 }
9565
9566 static bool i845_cursor_get_hw_state(struct intel_plane *plane)
9567 {
9568         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9569         enum intel_display_power_domain power_domain;
9570         bool ret;
9571
9572         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9573         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9574                 return false;
9575
9576         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9577
9578         intel_display_power_put(dev_priv, power_domain);
9579
9580         return ret;
9581 }
9582
9583 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9584                            const struct intel_plane_state *plane_state)
9585 {
9586         struct drm_i915_private *dev_priv =
9587                 to_i915(plane_state->base.plane->dev);
9588         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9589         u32 cntl;
9590
9591         cntl = MCURSOR_GAMMA_ENABLE;
9592
9593         if (HAS_DDI(dev_priv))
9594                 cntl |= CURSOR_PIPE_CSC_ENABLE;
9595
9596         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
9597                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9598
9599         switch (plane_state->base.crtc_w) {
9600         case 64:
9601                 cntl |= CURSOR_MODE_64_ARGB_AX;
9602                 break;
9603         case 128:
9604                 cntl |= CURSOR_MODE_128_ARGB_AX;
9605                 break;
9606         case 256:
9607                 cntl |= CURSOR_MODE_256_ARGB_AX;
9608                 break;
9609         default:
9610                 MISSING_CASE(plane_state->base.crtc_w);
9611                 return 0;
9612         }
9613
9614         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9615                 cntl |= CURSOR_ROTATE_180;
9616
9617         return cntl;
9618 }
9619
9620 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9621 {
9622         struct drm_i915_private *dev_priv =
9623                 to_i915(plane_state->base.plane->dev);
9624         int width = plane_state->base.crtc_w;
9625         int height = plane_state->base.crtc_h;
9626
9627         if (!intel_cursor_size_ok(plane_state))
9628                 return false;
9629
9630         /* Cursor width is limited to a few power-of-two sizes */
9631         switch (width) {
9632         case 256:
9633         case 128:
9634         case 64:
9635                 break;
9636         default:
9637                 return false;
9638         }
9639
9640         /*
9641          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9642          * height from 8 lines up to the cursor width, when the
9643          * cursor is not rotated. Everything else requires square
9644          * cursors.
9645          */
9646         if (HAS_CUR_FBC(dev_priv) &&
9647             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9648                 if (height < 8 || height > width)
9649                         return false;
9650         } else {
9651                 if (height != width)
9652                         return false;
9653         }
9654
9655         return true;
9656 }
9657
9658 static int i9xx_check_cursor(struct intel_plane *plane,
9659                              struct intel_crtc_state *crtc_state,
9660                              struct intel_plane_state *plane_state)
9661 {
9662         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9663         const struct drm_framebuffer *fb = plane_state->base.fb;
9664         enum pipe pipe = plane->pipe;
9665         int ret;
9666
9667         ret = intel_check_cursor(crtc_state, plane_state);
9668         if (ret)
9669                 return ret;
9670
9671         /* if we want to turn off the cursor ignore width and height */
9672         if (!fb)
9673                 return 0;
9674
9675         /* Check for which cursor types we support */
9676         if (!i9xx_cursor_size_ok(plane_state)) {
9677                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9678                           plane_state->base.crtc_w,
9679                           plane_state->base.crtc_h);
9680                 return -EINVAL;
9681         }
9682
9683         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9684                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9685                               fb->pitches[0], plane_state->base.crtc_w);
9686                 return -EINVAL;
9687         }
9688
9689         /*
9690          * There's something wrong with the cursor on CHV pipe C.
9691          * If it straddles the left edge of the screen then
9692          * moving it away from the edge or disabling it often
9693          * results in a pipe underrun, and often that can lead to
9694          * dead pipe (constant underrun reported, and it scans
9695          * out just a solid color). To recover from that, the
9696          * display power well must be turned off and on again.
9697          * Refuse the put the cursor into that compromised position.
9698          */
9699         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9700             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9701                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9702                 return -EINVAL;
9703         }
9704
9705         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9706
9707         return 0;
9708 }
9709
9710 static void i9xx_update_cursor(struct intel_plane *plane,
9711                                const struct intel_crtc_state *crtc_state,
9712                                const struct intel_plane_state *plane_state)
9713 {
9714         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9715         enum pipe pipe = plane->pipe;
9716         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9717         unsigned long irqflags;
9718
9719         if (plane_state && plane_state->base.visible) {
9720                 cntl = plane_state->ctl;
9721
9722                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9723                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9724
9725                 base = intel_cursor_base(plane_state);
9726                 pos = intel_cursor_position(plane_state);
9727         }
9728
9729         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9730
9731         /*
9732          * On some platforms writing CURCNTR first will also
9733          * cause CURPOS to be armed by the CURBASE write.
9734          * Without the CURCNTR write the CURPOS write would
9735          * arm itself. Thus we always start the full update
9736          * with a CURCNTR write.
9737          *
9738          * On other platforms CURPOS always requires the
9739          * CURBASE write to arm the update. Additonally
9740          * a write to any of the cursor register will cancel
9741          * an already armed cursor update. Thus leaving out
9742          * the CURBASE write after CURPOS could lead to a
9743          * cursor that doesn't appear to move, or even change
9744          * shape. Thus we always write CURBASE.
9745          *
9746          * CURCNTR and CUR_FBC_CTL are always
9747          * armed by the CURBASE write only.
9748          */
9749         if (plane->cursor.base != base ||
9750             plane->cursor.size != fbc_ctl ||
9751             plane->cursor.cntl != cntl) {
9752                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9753                 if (HAS_CUR_FBC(dev_priv))
9754                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9755                 I915_WRITE_FW(CURPOS(pipe), pos);
9756                 I915_WRITE_FW(CURBASE(pipe), base);
9757
9758                 plane->cursor.base = base;
9759                 plane->cursor.size = fbc_ctl;
9760                 plane->cursor.cntl = cntl;
9761         } else {
9762                 I915_WRITE_FW(CURPOS(pipe), pos);
9763                 I915_WRITE_FW(CURBASE(pipe), base);
9764         }
9765
9766         POSTING_READ_FW(CURBASE(pipe));
9767
9768         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9769 }
9770
9771 static void i9xx_disable_cursor(struct intel_plane *plane,
9772                                 struct intel_crtc *crtc)
9773 {
9774         i9xx_update_cursor(plane, NULL, NULL);
9775 }
9776
9777 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane)
9778 {
9779         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9780         enum intel_display_power_domain power_domain;
9781         enum pipe pipe = plane->pipe;
9782         bool ret;
9783
9784         /*
9785          * Not 100% correct for planes that can move between pipes,
9786          * but that's only the case for gen2-3 which don't have any
9787          * display power wells.
9788          */
9789         power_domain = POWER_DOMAIN_PIPE(pipe);
9790         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9791                 return false;
9792
9793         ret = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
9794
9795         intel_display_power_put(dev_priv, power_domain);
9796
9797         return ret;
9798 }
9799
9800 /* VESA 640x480x72Hz mode to set on the pipe */
9801 static const struct drm_display_mode load_detect_mode = {
9802         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9803                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9804 };
9805
9806 struct drm_framebuffer *
9807 intel_framebuffer_create(struct drm_i915_gem_object *obj,
9808                          struct drm_mode_fb_cmd2 *mode_cmd)
9809 {
9810         struct intel_framebuffer *intel_fb;
9811         int ret;
9812
9813         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9814         if (!intel_fb)
9815                 return ERR_PTR(-ENOMEM);
9816
9817         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
9818         if (ret)
9819                 goto err;
9820
9821         return &intel_fb->base;
9822
9823 err:
9824         kfree(intel_fb);
9825         return ERR_PTR(ret);
9826 }
9827
9828 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
9829                                         struct drm_crtc *crtc)
9830 {
9831         struct drm_plane *plane;
9832         struct drm_plane_state *plane_state;
9833         int ret, i;
9834
9835         ret = drm_atomic_add_affected_planes(state, crtc);
9836         if (ret)
9837                 return ret;
9838
9839         for_each_new_plane_in_state(state, plane, plane_state, i) {
9840                 if (plane_state->crtc != crtc)
9841                         continue;
9842
9843                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
9844                 if (ret)
9845                         return ret;
9846
9847                 drm_atomic_set_fb_for_plane(plane_state, NULL);
9848         }
9849
9850         return 0;
9851 }
9852
9853 int intel_get_load_detect_pipe(struct drm_connector *connector,
9854                                const struct drm_display_mode *mode,
9855                                struct intel_load_detect_pipe *old,
9856                                struct drm_modeset_acquire_ctx *ctx)
9857 {
9858         struct intel_crtc *intel_crtc;
9859         struct intel_encoder *intel_encoder =
9860                 intel_attached_encoder(connector);
9861         struct drm_crtc *possible_crtc;
9862         struct drm_encoder *encoder = &intel_encoder->base;
9863         struct drm_crtc *crtc = NULL;
9864         struct drm_device *dev = encoder->dev;
9865         struct drm_i915_private *dev_priv = to_i915(dev);
9866         struct drm_mode_config *config = &dev->mode_config;
9867         struct drm_atomic_state *state = NULL, *restore_state = NULL;
9868         struct drm_connector_state *connector_state;
9869         struct intel_crtc_state *crtc_state;
9870         int ret, i = -1;
9871
9872         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9873                       connector->base.id, connector->name,
9874                       encoder->base.id, encoder->name);
9875
9876         old->restore_state = NULL;
9877
9878         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
9879
9880         /*
9881          * Algorithm gets a little messy:
9882          *
9883          *   - if the connector already has an assigned crtc, use it (but make
9884          *     sure it's on first)
9885          *
9886          *   - try to find the first unused crtc that can drive this connector,
9887          *     and use that if we find one
9888          */
9889
9890         /* See if we already have a CRTC for this connector */
9891         if (connector->state->crtc) {
9892                 crtc = connector->state->crtc;
9893
9894                 ret = drm_modeset_lock(&crtc->mutex, ctx);
9895                 if (ret)
9896                         goto fail;
9897
9898                 /* Make sure the crtc and connector are running */
9899                 goto found;
9900         }
9901
9902         /* Find an unused one (if possible) */
9903         for_each_crtc(dev, possible_crtc) {
9904                 i++;
9905                 if (!(encoder->possible_crtcs & (1 << i)))
9906                         continue;
9907
9908                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
9909                 if (ret)
9910                         goto fail;
9911
9912                 if (possible_crtc->state->enable) {
9913                         drm_modeset_unlock(&possible_crtc->mutex);
9914                         continue;
9915                 }
9916
9917                 crtc = possible_crtc;
9918                 break;
9919         }
9920
9921         /*
9922          * If we didn't find an unused CRTC, don't use any.
9923          */
9924         if (!crtc) {
9925                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
9926                 ret = -ENODEV;
9927                 goto fail;
9928         }
9929
9930 found:
9931         intel_crtc = to_intel_crtc(crtc);
9932
9933         state = drm_atomic_state_alloc(dev);
9934         restore_state = drm_atomic_state_alloc(dev);
9935         if (!state || !restore_state) {
9936                 ret = -ENOMEM;
9937                 goto fail;
9938         }
9939
9940         state->acquire_ctx = ctx;
9941         restore_state->acquire_ctx = ctx;
9942
9943         connector_state = drm_atomic_get_connector_state(state, connector);
9944         if (IS_ERR(connector_state)) {
9945                 ret = PTR_ERR(connector_state);
9946                 goto fail;
9947         }
9948
9949         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
9950         if (ret)
9951                 goto fail;
9952
9953         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9954         if (IS_ERR(crtc_state)) {
9955                 ret = PTR_ERR(crtc_state);
9956                 goto fail;
9957         }
9958
9959         crtc_state->base.active = crtc_state->base.enable = true;
9960
9961         if (!mode)
9962                 mode = &load_detect_mode;
9963
9964         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
9965         if (ret)
9966                 goto fail;
9967
9968         ret = intel_modeset_disable_planes(state, crtc);
9969         if (ret)
9970                 goto fail;
9971
9972         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
9973         if (!ret)
9974                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
9975         if (ret) {
9976                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
9977                 goto fail;
9978         }
9979
9980         ret = drm_atomic_commit(state);
9981         if (ret) {
9982                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
9983                 goto fail;
9984         }
9985
9986         old->restore_state = restore_state;
9987         drm_atomic_state_put(state);
9988
9989         /* let the connector get through one full cycle before testing */
9990         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
9991         return true;
9992
9993 fail:
9994         if (state) {
9995                 drm_atomic_state_put(state);
9996                 state = NULL;
9997         }
9998         if (restore_state) {
9999                 drm_atomic_state_put(restore_state);
10000                 restore_state = NULL;
10001         }
10002
10003         if (ret == -EDEADLK)
10004                 return ret;
10005
10006         return false;
10007 }
10008
10009 void intel_release_load_detect_pipe(struct drm_connector *connector,
10010                                     struct intel_load_detect_pipe *old,
10011                                     struct drm_modeset_acquire_ctx *ctx)
10012 {
10013         struct intel_encoder *intel_encoder =
10014                 intel_attached_encoder(connector);
10015         struct drm_encoder *encoder = &intel_encoder->base;
10016         struct drm_atomic_state *state = old->restore_state;
10017         int ret;
10018
10019         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10020                       connector->base.id, connector->name,
10021                       encoder->base.id, encoder->name);
10022
10023         if (!state)
10024                 return;
10025
10026         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10027         if (ret)
10028                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10029         drm_atomic_state_put(state);
10030 }
10031
10032 static int i9xx_pll_refclk(struct drm_device *dev,
10033                            const struct intel_crtc_state *pipe_config)
10034 {
10035         struct drm_i915_private *dev_priv = to_i915(dev);
10036         u32 dpll = pipe_config->dpll_hw_state.dpll;
10037
10038         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10039                 return dev_priv->vbt.lvds_ssc_freq;
10040         else if (HAS_PCH_SPLIT(dev_priv))
10041                 return 120000;
10042         else if (!IS_GEN2(dev_priv))
10043                 return 96000;
10044         else
10045                 return 48000;
10046 }
10047
10048 /* Returns the clock of the currently programmed mode of the given pipe. */
10049 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10050                                 struct intel_crtc_state *pipe_config)
10051 {
10052         struct drm_device *dev = crtc->base.dev;
10053         struct drm_i915_private *dev_priv = to_i915(dev);
10054         int pipe = pipe_config->cpu_transcoder;
10055         u32 dpll = pipe_config->dpll_hw_state.dpll;
10056         u32 fp;
10057         struct dpll clock;
10058         int port_clock;
10059         int refclk = i9xx_pll_refclk(dev, pipe_config);
10060
10061         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10062                 fp = pipe_config->dpll_hw_state.fp0;
10063         else
10064                 fp = pipe_config->dpll_hw_state.fp1;
10065
10066         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10067         if (IS_PINEVIEW(dev_priv)) {
10068                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10069                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10070         } else {
10071                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10072                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10073         }
10074
10075         if (!IS_GEN2(dev_priv)) {
10076                 if (IS_PINEVIEW(dev_priv))
10077                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10078                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10079                 else
10080                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10081                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10082
10083                 switch (dpll & DPLL_MODE_MASK) {
10084                 case DPLLB_MODE_DAC_SERIAL:
10085                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10086                                 5 : 10;
10087                         break;
10088                 case DPLLB_MODE_LVDS:
10089                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10090                                 7 : 14;
10091                         break;
10092                 default:
10093                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10094                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10095                         return;
10096                 }
10097
10098                 if (IS_PINEVIEW(dev_priv))
10099                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10100                 else
10101                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10102         } else {
10103                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10104                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10105
10106                 if (is_lvds) {
10107                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10108                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10109
10110                         if (lvds & LVDS_CLKB_POWER_UP)
10111                                 clock.p2 = 7;
10112                         else
10113                                 clock.p2 = 14;
10114                 } else {
10115                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10116                                 clock.p1 = 2;
10117                         else {
10118                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10119                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10120                         }
10121                         if (dpll & PLL_P2_DIVIDE_BY_4)
10122                                 clock.p2 = 4;
10123                         else
10124                                 clock.p2 = 2;
10125                 }
10126
10127                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10128         }
10129
10130         /*
10131          * This value includes pixel_multiplier. We will use
10132          * port_clock to compute adjusted_mode.crtc_clock in the
10133          * encoder's get_config() function.
10134          */
10135         pipe_config->port_clock = port_clock;
10136 }
10137
10138 int intel_dotclock_calculate(int link_freq,
10139                              const struct intel_link_m_n *m_n)
10140 {
10141         /*
10142          * The calculation for the data clock is:
10143          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10144          * But we want to avoid losing precison if possible, so:
10145          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10146          *
10147          * and the link clock is simpler:
10148          * link_clock = (m * link_clock) / n
10149          */
10150
10151         if (!m_n->link_n)
10152                 return 0;
10153
10154         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10155 }
10156
10157 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10158                                    struct intel_crtc_state *pipe_config)
10159 {
10160         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10161
10162         /* read out port_clock from the DPLL */
10163         i9xx_crtc_clock_get(crtc, pipe_config);
10164
10165         /*
10166          * In case there is an active pipe without active ports,
10167          * we may need some idea for the dotclock anyway.
10168          * Calculate one based on the FDI configuration.
10169          */
10170         pipe_config->base.adjusted_mode.crtc_clock =
10171                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10172                                          &pipe_config->fdi_m_n);
10173 }
10174
10175 /* Returns the currently programmed mode of the given encoder. */
10176 struct drm_display_mode *
10177 intel_encoder_current_mode(struct intel_encoder *encoder)
10178 {
10179         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10180         struct intel_crtc_state *crtc_state;
10181         struct drm_display_mode *mode;
10182         struct intel_crtc *crtc;
10183         enum pipe pipe;
10184
10185         if (!encoder->get_hw_state(encoder, &pipe))
10186                 return NULL;
10187
10188         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10189
10190         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10191         if (!mode)
10192                 return NULL;
10193
10194         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10195         if (!crtc_state) {
10196                 kfree(mode);
10197                 return NULL;
10198         }
10199
10200         crtc_state->base.crtc = &crtc->base;
10201
10202         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10203                 kfree(crtc_state);
10204                 kfree(mode);
10205                 return NULL;
10206         }
10207
10208         encoder->get_config(encoder, crtc_state);
10209
10210         intel_mode_from_pipe_config(mode, crtc_state);
10211
10212         kfree(crtc_state);
10213
10214         return mode;
10215 }
10216
10217 static void intel_crtc_destroy(struct drm_crtc *crtc)
10218 {
10219         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10220
10221         drm_crtc_cleanup(crtc);
10222         kfree(intel_crtc);
10223 }
10224
10225 /**
10226  * intel_wm_need_update - Check whether watermarks need updating
10227  * @plane: drm plane
10228  * @state: new plane state
10229  *
10230  * Check current plane state versus the new one to determine whether
10231  * watermarks need to be recalculated.
10232  *
10233  * Returns true or false.
10234  */
10235 static bool intel_wm_need_update(struct drm_plane *plane,
10236                                  struct drm_plane_state *state)
10237 {
10238         struct intel_plane_state *new = to_intel_plane_state(state);
10239         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10240
10241         /* Update watermarks on tiling or size changes. */
10242         if (new->base.visible != cur->base.visible)
10243                 return true;
10244
10245         if (!cur->base.fb || !new->base.fb)
10246                 return false;
10247
10248         if (cur->base.fb->modifier != new->base.fb->modifier ||
10249             cur->base.rotation != new->base.rotation ||
10250             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10251             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10252             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10253             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10254                 return true;
10255
10256         return false;
10257 }
10258
10259 static bool needs_scaling(const struct intel_plane_state *state)
10260 {
10261         int src_w = drm_rect_width(&state->base.src) >> 16;
10262         int src_h = drm_rect_height(&state->base.src) >> 16;
10263         int dst_w = drm_rect_width(&state->base.dst);
10264         int dst_h = drm_rect_height(&state->base.dst);
10265
10266         return (src_w != dst_w || src_h != dst_h);
10267 }
10268
10269 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10270                                     struct drm_crtc_state *crtc_state,
10271                                     const struct intel_plane_state *old_plane_state,
10272                                     struct drm_plane_state *plane_state)
10273 {
10274         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10275         struct drm_crtc *crtc = crtc_state->crtc;
10276         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10277         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10278         struct drm_device *dev = crtc->dev;
10279         struct drm_i915_private *dev_priv = to_i915(dev);
10280         bool mode_changed = needs_modeset(crtc_state);
10281         bool was_crtc_enabled = old_crtc_state->base.active;
10282         bool is_crtc_enabled = crtc_state->active;
10283         bool turn_off, turn_on, visible, was_visible;
10284         struct drm_framebuffer *fb = plane_state->fb;
10285         int ret;
10286
10287         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10288                 ret = skl_update_scaler_plane(
10289                         to_intel_crtc_state(crtc_state),
10290                         to_intel_plane_state(plane_state));
10291                 if (ret)
10292                         return ret;
10293         }
10294
10295         was_visible = old_plane_state->base.visible;
10296         visible = plane_state->visible;
10297
10298         if (!was_crtc_enabled && WARN_ON(was_visible))
10299                 was_visible = false;
10300
10301         /*
10302          * Visibility is calculated as if the crtc was on, but
10303          * after scaler setup everything depends on it being off
10304          * when the crtc isn't active.
10305          *
10306          * FIXME this is wrong for watermarks. Watermarks should also
10307          * be computed as if the pipe would be active. Perhaps move
10308          * per-plane wm computation to the .check_plane() hook, and
10309          * only combine the results from all planes in the current place?
10310          */
10311         if (!is_crtc_enabled) {
10312                 plane_state->visible = visible = false;
10313                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10314         }
10315
10316         if (!was_visible && !visible)
10317                 return 0;
10318
10319         if (fb != old_plane_state->base.fb)
10320                 pipe_config->fb_changed = true;
10321
10322         turn_off = was_visible && (!visible || mode_changed);
10323         turn_on = visible && (!was_visible || mode_changed);
10324
10325         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10326                          intel_crtc->base.base.id, intel_crtc->base.name,
10327                          plane->base.base.id, plane->base.name,
10328                          fb ? fb->base.id : -1);
10329
10330         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10331                          plane->base.base.id, plane->base.name,
10332                          was_visible, visible,
10333                          turn_off, turn_on, mode_changed);
10334
10335         if (turn_on) {
10336                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10337                         pipe_config->update_wm_pre = true;
10338
10339                 /* must disable cxsr around plane enable/disable */
10340                 if (plane->id != PLANE_CURSOR)
10341                         pipe_config->disable_cxsr = true;
10342         } else if (turn_off) {
10343                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10344                         pipe_config->update_wm_post = true;
10345
10346                 /* must disable cxsr around plane enable/disable */
10347                 if (plane->id != PLANE_CURSOR)
10348                         pipe_config->disable_cxsr = true;
10349         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10350                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10351                         /* FIXME bollocks */
10352                         pipe_config->update_wm_pre = true;
10353                         pipe_config->update_wm_post = true;
10354                 }
10355         }
10356
10357         if (visible || was_visible)
10358                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10359
10360         /*
10361          * WaCxSRDisabledForSpriteScaling:ivb
10362          *
10363          * cstate->update_wm was already set above, so this flag will
10364          * take effect when we commit and program watermarks.
10365          */
10366         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
10367             needs_scaling(to_intel_plane_state(plane_state)) &&
10368             !needs_scaling(old_plane_state))
10369                 pipe_config->disable_lp_wm = true;
10370
10371         return 0;
10372 }
10373
10374 static bool encoders_cloneable(const struct intel_encoder *a,
10375                                const struct intel_encoder *b)
10376 {
10377         /* masks could be asymmetric, so check both ways */
10378         return a == b || (a->cloneable & (1 << b->type) &&
10379                           b->cloneable & (1 << a->type));
10380 }
10381
10382 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10383                                          struct intel_crtc *crtc,
10384                                          struct intel_encoder *encoder)
10385 {
10386         struct intel_encoder *source_encoder;
10387         struct drm_connector *connector;
10388         struct drm_connector_state *connector_state;
10389         int i;
10390
10391         for_each_new_connector_in_state(state, connector, connector_state, i) {
10392                 if (connector_state->crtc != &crtc->base)
10393                         continue;
10394
10395                 source_encoder =
10396                         to_intel_encoder(connector_state->best_encoder);
10397                 if (!encoders_cloneable(encoder, source_encoder))
10398                         return false;
10399         }
10400
10401         return true;
10402 }
10403
10404 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10405                                    struct drm_crtc_state *crtc_state)
10406 {
10407         struct drm_device *dev = crtc->dev;
10408         struct drm_i915_private *dev_priv = to_i915(dev);
10409         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10410         struct intel_crtc_state *pipe_config =
10411                 to_intel_crtc_state(crtc_state);
10412         struct drm_atomic_state *state = crtc_state->state;
10413         int ret;
10414         bool mode_changed = needs_modeset(crtc_state);
10415
10416         if (mode_changed && !crtc_state->active)
10417                 pipe_config->update_wm_post = true;
10418
10419         if (mode_changed && crtc_state->enable &&
10420             dev_priv->display.crtc_compute_clock &&
10421             !WARN_ON(pipe_config->shared_dpll)) {
10422                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10423                                                            pipe_config);
10424                 if (ret)
10425                         return ret;
10426         }
10427
10428         if (crtc_state->color_mgmt_changed) {
10429                 ret = intel_color_check(crtc, crtc_state);
10430                 if (ret)
10431                         return ret;
10432
10433                 /*
10434                  * Changing color management on Intel hardware is
10435                  * handled as part of planes update.
10436                  */
10437                 crtc_state->planes_changed = true;
10438         }
10439
10440         ret = 0;
10441         if (dev_priv->display.compute_pipe_wm) {
10442                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10443                 if (ret) {
10444                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10445                         return ret;
10446                 }
10447         }
10448
10449         if (dev_priv->display.compute_intermediate_wm &&
10450             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10451                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10452                         return 0;
10453
10454                 /*
10455                  * Calculate 'intermediate' watermarks that satisfy both the
10456                  * old state and the new state.  We can program these
10457                  * immediately.
10458                  */
10459                 ret = dev_priv->display.compute_intermediate_wm(dev,
10460                                                                 intel_crtc,
10461                                                                 pipe_config);
10462                 if (ret) {
10463                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10464                         return ret;
10465                 }
10466         } else if (dev_priv->display.compute_intermediate_wm) {
10467                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10468                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10469         }
10470
10471         if (INTEL_GEN(dev_priv) >= 9) {
10472                 if (mode_changed)
10473                         ret = skl_update_scaler_crtc(pipe_config);
10474
10475                 if (!ret)
10476                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10477                                                             pipe_config);
10478                 if (!ret)
10479                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10480                                                          pipe_config);
10481         }
10482
10483         if (HAS_IPS(dev_priv))
10484                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10485
10486         return ret;
10487 }
10488
10489 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10490         .atomic_begin = intel_begin_crtc_commit,
10491         .atomic_flush = intel_finish_crtc_commit,
10492         .atomic_check = intel_crtc_atomic_check,
10493 };
10494
10495 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10496 {
10497         struct intel_connector *connector;
10498         struct drm_connector_list_iter conn_iter;
10499
10500         drm_connector_list_iter_begin(dev, &conn_iter);
10501         for_each_intel_connector_iter(connector, &conn_iter) {
10502                 if (connector->base.state->crtc)
10503                         drm_connector_unreference(&connector->base);
10504
10505                 if (connector->base.encoder) {
10506                         connector->base.state->best_encoder =
10507                                 connector->base.encoder;
10508                         connector->base.state->crtc =
10509                                 connector->base.encoder->crtc;
10510
10511                         drm_connector_reference(&connector->base);
10512                 } else {
10513                         connector->base.state->best_encoder = NULL;
10514                         connector->base.state->crtc = NULL;
10515                 }
10516         }
10517         drm_connector_list_iter_end(&conn_iter);
10518 }
10519
10520 static void
10521 connected_sink_compute_bpp(struct intel_connector *connector,
10522                            struct intel_crtc_state *pipe_config)
10523 {
10524         const struct drm_display_info *info = &connector->base.display_info;
10525         int bpp = pipe_config->pipe_bpp;
10526
10527         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10528                       connector->base.base.id,
10529                       connector->base.name);
10530
10531         /* Don't use an invalid EDID bpc value */
10532         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10533                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10534                               bpp, info->bpc * 3);
10535                 pipe_config->pipe_bpp = info->bpc * 3;
10536         }
10537
10538         /* Clamp bpp to 8 on screens without EDID 1.4 */
10539         if (info->bpc == 0 && bpp > 24) {
10540                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10541                               bpp);
10542                 pipe_config->pipe_bpp = 24;
10543         }
10544 }
10545
10546 static int
10547 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10548                           struct intel_crtc_state *pipe_config)
10549 {
10550         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10551         struct drm_atomic_state *state;
10552         struct drm_connector *connector;
10553         struct drm_connector_state *connector_state;
10554         int bpp, i;
10555
10556         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10557             IS_CHERRYVIEW(dev_priv)))
10558                 bpp = 10*3;
10559         else if (INTEL_GEN(dev_priv) >= 5)
10560                 bpp = 12*3;
10561         else
10562                 bpp = 8*3;
10563
10564
10565         pipe_config->pipe_bpp = bpp;
10566
10567         state = pipe_config->base.state;
10568
10569         /* Clamp display bpp to EDID value */
10570         for_each_new_connector_in_state(state, connector, connector_state, i) {
10571                 if (connector_state->crtc != &crtc->base)
10572                         continue;
10573
10574                 connected_sink_compute_bpp(to_intel_connector(connector),
10575                                            pipe_config);
10576         }
10577
10578         return bpp;
10579 }
10580
10581 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10582 {
10583         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10584                         "type: 0x%x flags: 0x%x\n",
10585                 mode->crtc_clock,
10586                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10587                 mode->crtc_hsync_end, mode->crtc_htotal,
10588                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10589                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10590 }
10591
10592 static inline void
10593 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10594                       unsigned int lane_count, struct intel_link_m_n *m_n)
10595 {
10596         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10597                       id, lane_count,
10598                       m_n->gmch_m, m_n->gmch_n,
10599                       m_n->link_m, m_n->link_n, m_n->tu);
10600 }
10601
10602 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10603
10604 static const char * const output_type_str[] = {
10605         OUTPUT_TYPE(UNUSED),
10606         OUTPUT_TYPE(ANALOG),
10607         OUTPUT_TYPE(DVO),
10608         OUTPUT_TYPE(SDVO),
10609         OUTPUT_TYPE(LVDS),
10610         OUTPUT_TYPE(TVOUT),
10611         OUTPUT_TYPE(HDMI),
10612         OUTPUT_TYPE(DP),
10613         OUTPUT_TYPE(EDP),
10614         OUTPUT_TYPE(DSI),
10615         OUTPUT_TYPE(DDI),
10616         OUTPUT_TYPE(DP_MST),
10617 };
10618
10619 #undef OUTPUT_TYPE
10620
10621 static void snprintf_output_types(char *buf, size_t len,
10622                                   unsigned int output_types)
10623 {
10624         char *str = buf;
10625         int i;
10626
10627         str[0] = '\0';
10628
10629         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
10630                 int r;
10631
10632                 if ((output_types & BIT(i)) == 0)
10633                         continue;
10634
10635                 r = snprintf(str, len, "%s%s",
10636                              str != buf ? "," : "", output_type_str[i]);
10637                 if (r >= len)
10638                         break;
10639                 str += r;
10640                 len -= r;
10641
10642                 output_types &= ~BIT(i);
10643         }
10644
10645         WARN_ON_ONCE(output_types != 0);
10646 }
10647
10648 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10649                                    struct intel_crtc_state *pipe_config,
10650                                    const char *context)
10651 {
10652         struct drm_device *dev = crtc->base.dev;
10653         struct drm_i915_private *dev_priv = to_i915(dev);
10654         struct drm_plane *plane;
10655         struct intel_plane *intel_plane;
10656         struct intel_plane_state *state;
10657         struct drm_framebuffer *fb;
10658         char buf[64];
10659
10660         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10661                       crtc->base.base.id, crtc->base.name, context);
10662
10663         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
10664         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
10665                       buf, pipe_config->output_types);
10666
10667         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
10668                       transcoder_name(pipe_config->cpu_transcoder),
10669                       pipe_config->pipe_bpp, pipe_config->dither);
10670
10671         if (pipe_config->has_pch_encoder)
10672                 intel_dump_m_n_config(pipe_config, "fdi",
10673                                       pipe_config->fdi_lanes,
10674                                       &pipe_config->fdi_m_n);
10675
10676         if (pipe_config->ycbcr420)
10677                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
10678
10679         if (intel_crtc_has_dp_encoder(pipe_config)) {
10680                 intel_dump_m_n_config(pipe_config, "dp m_n",
10681                                 pipe_config->lane_count, &pipe_config->dp_m_n);
10682                 if (pipe_config->has_drrs)
10683                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
10684                                               pipe_config->lane_count,
10685                                               &pipe_config->dp_m2_n2);
10686         }
10687
10688         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10689                       pipe_config->has_audio, pipe_config->has_infoframe);
10690
10691         DRM_DEBUG_KMS("requested mode:\n");
10692         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10693         DRM_DEBUG_KMS("adjusted mode:\n");
10694         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10695         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10696         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
10697                       pipe_config->port_clock,
10698                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
10699                       pipe_config->pixel_rate);
10700
10701         if (INTEL_GEN(dev_priv) >= 9)
10702                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
10703                               crtc->num_scalers,
10704                               pipe_config->scaler_state.scaler_users,
10705                               pipe_config->scaler_state.scaler_id);
10706
10707         if (HAS_GMCH_DISPLAY(dev_priv))
10708                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10709                               pipe_config->gmch_pfit.control,
10710                               pipe_config->gmch_pfit.pgm_ratios,
10711                               pipe_config->gmch_pfit.lvds_border_bits);
10712         else
10713                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10714                               pipe_config->pch_pfit.pos,
10715                               pipe_config->pch_pfit.size,
10716                               enableddisabled(pipe_config->pch_pfit.enabled));
10717
10718         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
10719                       pipe_config->ips_enabled, pipe_config->double_wide);
10720
10721         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
10722
10723         DRM_DEBUG_KMS("planes on this crtc\n");
10724         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
10725                 struct drm_format_name_buf format_name;
10726                 intel_plane = to_intel_plane(plane);
10727                 if (intel_plane->pipe != crtc->pipe)
10728                         continue;
10729
10730                 state = to_intel_plane_state(plane->state);
10731                 fb = state->base.fb;
10732                 if (!fb) {
10733                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
10734                                       plane->base.id, plane->name, state->scaler_id);
10735                         continue;
10736                 }
10737
10738                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
10739                               plane->base.id, plane->name,
10740                               fb->base.id, fb->width, fb->height,
10741                               drm_get_format_name(fb->format->format, &format_name));
10742                 if (INTEL_GEN(dev_priv) >= 9)
10743                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
10744                                       state->scaler_id,
10745                                       state->base.src.x1 >> 16,
10746                                       state->base.src.y1 >> 16,
10747                                       drm_rect_width(&state->base.src) >> 16,
10748                                       drm_rect_height(&state->base.src) >> 16,
10749                                       state->base.dst.x1, state->base.dst.y1,
10750                                       drm_rect_width(&state->base.dst),
10751                                       drm_rect_height(&state->base.dst));
10752         }
10753 }
10754
10755 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
10756 {
10757         struct drm_device *dev = state->dev;
10758         struct drm_connector *connector;
10759         struct drm_connector_list_iter conn_iter;
10760         unsigned int used_ports = 0;
10761         unsigned int used_mst_ports = 0;
10762         bool ret = true;
10763
10764         /*
10765          * Walk the connector list instead of the encoder
10766          * list to detect the problem on ddi platforms
10767          * where there's just one encoder per digital port.
10768          */
10769         drm_connector_list_iter_begin(dev, &conn_iter);
10770         drm_for_each_connector_iter(connector, &conn_iter) {
10771                 struct drm_connector_state *connector_state;
10772                 struct intel_encoder *encoder;
10773
10774                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
10775                 if (!connector_state)
10776                         connector_state = connector->state;
10777
10778                 if (!connector_state->best_encoder)
10779                         continue;
10780
10781                 encoder = to_intel_encoder(connector_state->best_encoder);
10782
10783                 WARN_ON(!connector_state->crtc);
10784
10785                 switch (encoder->type) {
10786                         unsigned int port_mask;
10787                 case INTEL_OUTPUT_DDI:
10788                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
10789                                 break;
10790                 case INTEL_OUTPUT_DP:
10791                 case INTEL_OUTPUT_HDMI:
10792                 case INTEL_OUTPUT_EDP:
10793                         port_mask = 1 << encoder->port;
10794
10795                         /* the same port mustn't appear more than once */
10796                         if (used_ports & port_mask)
10797                                 ret = false;
10798
10799                         used_ports |= port_mask;
10800                         break;
10801                 case INTEL_OUTPUT_DP_MST:
10802                         used_mst_ports |=
10803                                 1 << encoder->port;
10804                         break;
10805                 default:
10806                         break;
10807                 }
10808         }
10809         drm_connector_list_iter_end(&conn_iter);
10810
10811         /* can't mix MST and SST/HDMI on the same port */
10812         if (used_ports & used_mst_ports)
10813                 return false;
10814
10815         return ret;
10816 }
10817
10818 static void
10819 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
10820 {
10821         struct drm_i915_private *dev_priv =
10822                 to_i915(crtc_state->base.crtc->dev);
10823         struct intel_crtc_scaler_state scaler_state;
10824         struct intel_dpll_hw_state dpll_hw_state;
10825         struct intel_shared_dpll *shared_dpll;
10826         struct intel_crtc_wm_state wm_state;
10827         bool force_thru, ips_force_disable;
10828
10829         /* FIXME: before the switch to atomic started, a new pipe_config was
10830          * kzalloc'd. Code that depends on any field being zero should be
10831          * fixed, so that the crtc_state can be safely duplicated. For now,
10832          * only fields that are know to not cause problems are preserved. */
10833
10834         scaler_state = crtc_state->scaler_state;
10835         shared_dpll = crtc_state->shared_dpll;
10836         dpll_hw_state = crtc_state->dpll_hw_state;
10837         force_thru = crtc_state->pch_pfit.force_thru;
10838         ips_force_disable = crtc_state->ips_force_disable;
10839         if (IS_G4X(dev_priv) ||
10840             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10841                 wm_state = crtc_state->wm;
10842
10843         /* Keep base drm_crtc_state intact, only clear our extended struct */
10844         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
10845         memset(&crtc_state->base + 1, 0,
10846                sizeof(*crtc_state) - sizeof(crtc_state->base));
10847
10848         crtc_state->scaler_state = scaler_state;
10849         crtc_state->shared_dpll = shared_dpll;
10850         crtc_state->dpll_hw_state = dpll_hw_state;
10851         crtc_state->pch_pfit.force_thru = force_thru;
10852         crtc_state->ips_force_disable = ips_force_disable;
10853         if (IS_G4X(dev_priv) ||
10854             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10855                 crtc_state->wm = wm_state;
10856 }
10857
10858 static int
10859 intel_modeset_pipe_config(struct drm_crtc *crtc,
10860                           struct intel_crtc_state *pipe_config)
10861 {
10862         struct drm_atomic_state *state = pipe_config->base.state;
10863         struct intel_encoder *encoder;
10864         struct drm_connector *connector;
10865         struct drm_connector_state *connector_state;
10866         int base_bpp, ret = -EINVAL;
10867         int i;
10868         bool retry = true;
10869
10870         clear_intel_crtc_state(pipe_config);
10871
10872         pipe_config->cpu_transcoder =
10873                 (enum transcoder) to_intel_crtc(crtc)->pipe;
10874
10875         /*
10876          * Sanitize sync polarity flags based on requested ones. If neither
10877          * positive or negative polarity is requested, treat this as meaning
10878          * negative polarity.
10879          */
10880         if (!(pipe_config->base.adjusted_mode.flags &
10881               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
10882                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
10883
10884         if (!(pipe_config->base.adjusted_mode.flags &
10885               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
10886                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
10887
10888         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
10889                                              pipe_config);
10890         if (base_bpp < 0)
10891                 goto fail;
10892
10893         /*
10894          * Determine the real pipe dimensions. Note that stereo modes can
10895          * increase the actual pipe size due to the frame doubling and
10896          * insertion of additional space for blanks between the frame. This
10897          * is stored in the crtc timings. We use the requested mode to do this
10898          * computation to clearly distinguish it from the adjusted mode, which
10899          * can be changed by the connectors in the below retry loop.
10900          */
10901         drm_mode_get_hv_timing(&pipe_config->base.mode,
10902                                &pipe_config->pipe_src_w,
10903                                &pipe_config->pipe_src_h);
10904
10905         for_each_new_connector_in_state(state, connector, connector_state, i) {
10906                 if (connector_state->crtc != crtc)
10907                         continue;
10908
10909                 encoder = to_intel_encoder(connector_state->best_encoder);
10910
10911                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
10912                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
10913                         goto fail;
10914                 }
10915
10916                 /*
10917                  * Determine output_types before calling the .compute_config()
10918                  * hooks so that the hooks can use this information safely.
10919                  */
10920                 if (encoder->compute_output_type)
10921                         pipe_config->output_types |=
10922                                 BIT(encoder->compute_output_type(encoder, pipe_config,
10923                                                                  connector_state));
10924                 else
10925                         pipe_config->output_types |= BIT(encoder->type);
10926         }
10927
10928 encoder_retry:
10929         /* Ensure the port clock defaults are reset when retrying. */
10930         pipe_config->port_clock = 0;
10931         pipe_config->pixel_multiplier = 1;
10932
10933         /* Fill in default crtc timings, allow encoders to overwrite them. */
10934         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
10935                               CRTC_STEREO_DOUBLE);
10936
10937         /* Pass our mode to the connectors and the CRTC to give them a chance to
10938          * adjust it according to limitations or connector properties, and also
10939          * a chance to reject the mode entirely.
10940          */
10941         for_each_new_connector_in_state(state, connector, connector_state, i) {
10942                 if (connector_state->crtc != crtc)
10943                         continue;
10944
10945                 encoder = to_intel_encoder(connector_state->best_encoder);
10946
10947                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
10948                         DRM_DEBUG_KMS("Encoder config failure\n");
10949                         goto fail;
10950                 }
10951         }
10952
10953         /* Set default port clock if not overwritten by the encoder. Needs to be
10954          * done afterwards in case the encoder adjusts the mode. */
10955         if (!pipe_config->port_clock)
10956                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
10957                         * pipe_config->pixel_multiplier;
10958
10959         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
10960         if (ret < 0) {
10961                 DRM_DEBUG_KMS("CRTC fixup failed\n");
10962                 goto fail;
10963         }
10964
10965         if (ret == RETRY) {
10966                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
10967                         ret = -EINVAL;
10968                         goto fail;
10969                 }
10970
10971                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
10972                 retry = false;
10973                 goto encoder_retry;
10974         }
10975
10976         /* Dithering seems to not pass-through bits correctly when it should, so
10977          * only enable it on 6bpc panels and when its not a compliance
10978          * test requesting 6bpc video pattern.
10979          */
10980         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
10981                 !pipe_config->dither_force_disable;
10982         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
10983                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
10984
10985 fail:
10986         return ret;
10987 }
10988
10989 static bool intel_fuzzy_clock_check(int clock1, int clock2)
10990 {
10991         int diff;
10992
10993         if (clock1 == clock2)
10994                 return true;
10995
10996         if (!clock1 || !clock2)
10997                 return false;
10998
10999         diff = abs(clock1 - clock2);
11000
11001         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11002                 return true;
11003
11004         return false;
11005 }
11006
11007 static bool
11008 intel_compare_m_n(unsigned int m, unsigned int n,
11009                   unsigned int m2, unsigned int n2,
11010                   bool exact)
11011 {
11012         if (m == m2 && n == n2)
11013                 return true;
11014
11015         if (exact || !m || !n || !m2 || !n2)
11016                 return false;
11017
11018         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11019
11020         if (n > n2) {
11021                 while (n > n2) {
11022                         m2 <<= 1;
11023                         n2 <<= 1;
11024                 }
11025         } else if (n < n2) {
11026                 while (n < n2) {
11027                         m <<= 1;
11028                         n <<= 1;
11029                 }
11030         }
11031
11032         if (n != n2)
11033                 return false;
11034
11035         return intel_fuzzy_clock_check(m, m2);
11036 }
11037
11038 static bool
11039 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11040                        struct intel_link_m_n *m2_n2,
11041                        bool adjust)
11042 {
11043         if (m_n->tu == m2_n2->tu &&
11044             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11045                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11046             intel_compare_m_n(m_n->link_m, m_n->link_n,
11047                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11048                 if (adjust)
11049                         *m2_n2 = *m_n;
11050
11051                 return true;
11052         }
11053
11054         return false;
11055 }
11056
11057 static void __printf(3, 4)
11058 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11059 {
11060         char *level;
11061         unsigned int category;
11062         struct va_format vaf;
11063         va_list args;
11064
11065         if (adjust) {
11066                 level = KERN_DEBUG;
11067                 category = DRM_UT_KMS;
11068         } else {
11069                 level = KERN_ERR;
11070                 category = DRM_UT_NONE;
11071         }
11072
11073         va_start(args, format);
11074         vaf.fmt = format;
11075         vaf.va = &args;
11076
11077         drm_printk(level, category, "mismatch in %s %pV", name, &vaf);
11078
11079         va_end(args);
11080 }
11081
11082 static bool
11083 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11084                           struct intel_crtc_state *current_config,
11085                           struct intel_crtc_state *pipe_config,
11086                           bool adjust)
11087 {
11088         bool ret = true;
11089         bool fixup_inherited = adjust &&
11090                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11091                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11092
11093 #define PIPE_CONF_CHECK_X(name) \
11094         if (current_config->name != pipe_config->name) { \
11095                 pipe_config_err(adjust, __stringify(name), \
11096                           "(expected 0x%08x, found 0x%08x)\n", \
11097                           current_config->name, \
11098                           pipe_config->name); \
11099                 ret = false; \
11100         }
11101
11102 #define PIPE_CONF_CHECK_I(name) \
11103         if (current_config->name != pipe_config->name) { \
11104                 pipe_config_err(adjust, __stringify(name), \
11105                           "(expected %i, found %i)\n", \
11106                           current_config->name, \
11107                           pipe_config->name); \
11108                 ret = false; \
11109         }
11110
11111 #define PIPE_CONF_CHECK_BOOL(name)      \
11112         if (current_config->name != pipe_config->name) { \
11113                 pipe_config_err(adjust, __stringify(name), \
11114                           "(expected %s, found %s)\n", \
11115                           yesno(current_config->name), \
11116                           yesno(pipe_config->name)); \
11117                 ret = false; \
11118         }
11119
11120 /*
11121  * Checks state where we only read out the enabling, but not the entire
11122  * state itself (like full infoframes or ELD for audio). These states
11123  * require a full modeset on bootup to fix up.
11124  */
11125 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) \
11126         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11127                 PIPE_CONF_CHECK_BOOL(name); \
11128         } else { \
11129                 pipe_config_err(adjust, __stringify(name), \
11130                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11131                           yesno(current_config->name), \
11132                           yesno(pipe_config->name)); \
11133                 ret = false; \
11134         }
11135
11136 #define PIPE_CONF_CHECK_P(name) \
11137         if (current_config->name != pipe_config->name) { \
11138                 pipe_config_err(adjust, __stringify(name), \
11139                           "(expected %p, found %p)\n", \
11140                           current_config->name, \
11141                           pipe_config->name); \
11142                 ret = false; \
11143         }
11144
11145 #define PIPE_CONF_CHECK_M_N(name) \
11146         if (!intel_compare_link_m_n(&current_config->name, \
11147                                     &pipe_config->name,\
11148                                     adjust)) { \
11149                 pipe_config_err(adjust, __stringify(name), \
11150                           "(expected tu %i gmch %i/%i link %i/%i, " \
11151                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11152                           current_config->name.tu, \
11153                           current_config->name.gmch_m, \
11154                           current_config->name.gmch_n, \
11155                           current_config->name.link_m, \
11156                           current_config->name.link_n, \
11157                           pipe_config->name.tu, \
11158                           pipe_config->name.gmch_m, \
11159                           pipe_config->name.gmch_n, \
11160                           pipe_config->name.link_m, \
11161                           pipe_config->name.link_n); \
11162                 ret = false; \
11163         }
11164
11165 /* This is required for BDW+ where there is only one set of registers for
11166  * switching between high and low RR.
11167  * This macro can be used whenever a comparison has to be made between one
11168  * hw state and multiple sw state variables.
11169  */
11170 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
11171         if (!intel_compare_link_m_n(&current_config->name, \
11172                                     &pipe_config->name, adjust) && \
11173             !intel_compare_link_m_n(&current_config->alt_name, \
11174                                     &pipe_config->name, adjust)) { \
11175                 pipe_config_err(adjust, __stringify(name), \
11176                           "(expected tu %i gmch %i/%i link %i/%i, " \
11177                           "or tu %i gmch %i/%i link %i/%i, " \
11178                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11179                           current_config->name.tu, \
11180                           current_config->name.gmch_m, \
11181                           current_config->name.gmch_n, \
11182                           current_config->name.link_m, \
11183                           current_config->name.link_n, \
11184                           current_config->alt_name.tu, \
11185                           current_config->alt_name.gmch_m, \
11186                           current_config->alt_name.gmch_n, \
11187                           current_config->alt_name.link_m, \
11188                           current_config->alt_name.link_n, \
11189                           pipe_config->name.tu, \
11190                           pipe_config->name.gmch_m, \
11191                           pipe_config->name.gmch_n, \
11192                           pipe_config->name.link_m, \
11193                           pipe_config->name.link_n); \
11194                 ret = false; \
11195         }
11196
11197 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
11198         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11199                 pipe_config_err(adjust, __stringify(name), \
11200                           "(%x) (expected %i, found %i)\n", \
11201                           (mask), \
11202                           current_config->name & (mask), \
11203                           pipe_config->name & (mask)); \
11204                 ret = false; \
11205         }
11206
11207 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
11208         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11209                 pipe_config_err(adjust, __stringify(name), \
11210                           "(expected %i, found %i)\n", \
11211                           current_config->name, \
11212                           pipe_config->name); \
11213                 ret = false; \
11214         }
11215
11216 #define PIPE_CONF_QUIRK(quirk)  \
11217         ((current_config->quirks | pipe_config->quirks) & (quirk))
11218
11219         PIPE_CONF_CHECK_I(cpu_transcoder);
11220
11221         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11222         PIPE_CONF_CHECK_I(fdi_lanes);
11223         PIPE_CONF_CHECK_M_N(fdi_m_n);
11224
11225         PIPE_CONF_CHECK_I(lane_count);
11226         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11227
11228         if (INTEL_GEN(dev_priv) < 8) {
11229                 PIPE_CONF_CHECK_M_N(dp_m_n);
11230
11231                 if (current_config->has_drrs)
11232                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11233         } else
11234                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11235
11236         PIPE_CONF_CHECK_X(output_types);
11237
11238         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11239         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11240         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11241         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11242         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11243         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11244
11245         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11246         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11247         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11248         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11249         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11250         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11251
11252         PIPE_CONF_CHECK_I(pixel_multiplier);
11253         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11254         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11255             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11256                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11257
11258         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11259         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11260         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11261         PIPE_CONF_CHECK_BOOL(ycbcr420);
11262
11263         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11264
11265         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11266                               DRM_MODE_FLAG_INTERLACE);
11267
11268         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11269                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11270                                       DRM_MODE_FLAG_PHSYNC);
11271                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11272                                       DRM_MODE_FLAG_NHSYNC);
11273                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11274                                       DRM_MODE_FLAG_PVSYNC);
11275                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11276                                       DRM_MODE_FLAG_NVSYNC);
11277         }
11278
11279         PIPE_CONF_CHECK_X(gmch_pfit.control);
11280         /* pfit ratios are autocomputed by the hw on gen4+ */
11281         if (INTEL_GEN(dev_priv) < 4)
11282                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11283         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11284
11285         if (!adjust) {
11286                 PIPE_CONF_CHECK_I(pipe_src_w);
11287                 PIPE_CONF_CHECK_I(pipe_src_h);
11288
11289                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11290                 if (current_config->pch_pfit.enabled) {
11291                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11292                         PIPE_CONF_CHECK_X(pch_pfit.size);
11293                 }
11294
11295                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11296                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11297         }
11298
11299         PIPE_CONF_CHECK_BOOL(double_wide);
11300
11301         PIPE_CONF_CHECK_P(shared_dpll);
11302         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11303         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11304         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11305         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11306         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11307         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11308         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11309         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11310         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11311         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11312         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11313         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11314         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11315         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11316         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11317         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11318         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11319         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11320         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11321         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11322         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11323
11324         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11325         PIPE_CONF_CHECK_X(dsi_pll.div);
11326
11327         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11328                 PIPE_CONF_CHECK_I(pipe_bpp);
11329
11330         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11331         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11332
11333         PIPE_CONF_CHECK_I(min_voltage_level);
11334
11335 #undef PIPE_CONF_CHECK_X
11336 #undef PIPE_CONF_CHECK_I
11337 #undef PIPE_CONF_CHECK_BOOL
11338 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11339 #undef PIPE_CONF_CHECK_P
11340 #undef PIPE_CONF_CHECK_FLAGS
11341 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11342 #undef PIPE_CONF_QUIRK
11343
11344         return ret;
11345 }
11346
11347 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11348                                            const struct intel_crtc_state *pipe_config)
11349 {
11350         if (pipe_config->has_pch_encoder) {
11351                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11352                                                             &pipe_config->fdi_m_n);
11353                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11354
11355                 /*
11356                  * FDI already provided one idea for the dotclock.
11357                  * Yell if the encoder disagrees.
11358                  */
11359                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11360                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11361                      fdi_dotclock, dotclock);
11362         }
11363 }
11364
11365 static void verify_wm_state(struct drm_crtc *crtc,
11366                             struct drm_crtc_state *new_state)
11367 {
11368         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11369         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11370         struct skl_pipe_wm hw_wm, *sw_wm;
11371         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11372         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11373         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11374         const enum pipe pipe = intel_crtc->pipe;
11375         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11376
11377         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11378                 return;
11379
11380         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11381         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11382
11383         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11384         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11385
11386         /* planes */
11387         for_each_universal_plane(dev_priv, pipe, plane) {
11388                 hw_plane_wm = &hw_wm.planes[plane];
11389                 sw_plane_wm = &sw_wm->planes[plane];
11390
11391                 /* Watermarks */
11392                 for (level = 0; level <= max_level; level++) {
11393                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11394                                                 &sw_plane_wm->wm[level]))
11395                                 continue;
11396
11397                         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",
11398                                   pipe_name(pipe), plane + 1, level,
11399                                   sw_plane_wm->wm[level].plane_en,
11400                                   sw_plane_wm->wm[level].plane_res_b,
11401                                   sw_plane_wm->wm[level].plane_res_l,
11402                                   hw_plane_wm->wm[level].plane_en,
11403                                   hw_plane_wm->wm[level].plane_res_b,
11404                                   hw_plane_wm->wm[level].plane_res_l);
11405                 }
11406
11407                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11408                                          &sw_plane_wm->trans_wm)) {
11409                         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",
11410                                   pipe_name(pipe), plane + 1,
11411                                   sw_plane_wm->trans_wm.plane_en,
11412                                   sw_plane_wm->trans_wm.plane_res_b,
11413                                   sw_plane_wm->trans_wm.plane_res_l,
11414                                   hw_plane_wm->trans_wm.plane_en,
11415                                   hw_plane_wm->trans_wm.plane_res_b,
11416                                   hw_plane_wm->trans_wm.plane_res_l);
11417                 }
11418
11419                 /* DDB */
11420                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11421                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11422
11423                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11424                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11425                                   pipe_name(pipe), plane + 1,
11426                                   sw_ddb_entry->start, sw_ddb_entry->end,
11427                                   hw_ddb_entry->start, hw_ddb_entry->end);
11428                 }
11429         }
11430
11431         /*
11432          * cursor
11433          * If the cursor plane isn't active, we may not have updated it's ddb
11434          * allocation. In that case since the ddb allocation will be updated
11435          * once the plane becomes visible, we can skip this check
11436          */
11437         if (1) {
11438                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11439                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11440
11441                 /* Watermarks */
11442                 for (level = 0; level <= max_level; level++) {
11443                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11444                                                 &sw_plane_wm->wm[level]))
11445                                 continue;
11446
11447                         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",
11448                                   pipe_name(pipe), level,
11449                                   sw_plane_wm->wm[level].plane_en,
11450                                   sw_plane_wm->wm[level].plane_res_b,
11451                                   sw_plane_wm->wm[level].plane_res_l,
11452                                   hw_plane_wm->wm[level].plane_en,
11453                                   hw_plane_wm->wm[level].plane_res_b,
11454                                   hw_plane_wm->wm[level].plane_res_l);
11455                 }
11456
11457                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11458                                          &sw_plane_wm->trans_wm)) {
11459                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11460                                   pipe_name(pipe),
11461                                   sw_plane_wm->trans_wm.plane_en,
11462                                   sw_plane_wm->trans_wm.plane_res_b,
11463                                   sw_plane_wm->trans_wm.plane_res_l,
11464                                   hw_plane_wm->trans_wm.plane_en,
11465                                   hw_plane_wm->trans_wm.plane_res_b,
11466                                   hw_plane_wm->trans_wm.plane_res_l);
11467                 }
11468
11469                 /* DDB */
11470                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11471                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11472
11473                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11474                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11475                                   pipe_name(pipe),
11476                                   sw_ddb_entry->start, sw_ddb_entry->end,
11477                                   hw_ddb_entry->start, hw_ddb_entry->end);
11478                 }
11479         }
11480 }
11481
11482 static void
11483 verify_connector_state(struct drm_device *dev,
11484                        struct drm_atomic_state *state,
11485                        struct drm_crtc *crtc)
11486 {
11487         struct drm_connector *connector;
11488         struct drm_connector_state *new_conn_state;
11489         int i;
11490
11491         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11492                 struct drm_encoder *encoder = connector->encoder;
11493                 struct drm_crtc_state *crtc_state = NULL;
11494
11495                 if (new_conn_state->crtc != crtc)
11496                         continue;
11497
11498                 if (crtc)
11499                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11500
11501                 intel_connector_verify_state(crtc_state, new_conn_state);
11502
11503                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11504                      "connector's atomic encoder doesn't match legacy encoder\n");
11505         }
11506 }
11507
11508 static void
11509 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11510 {
11511         struct intel_encoder *encoder;
11512         struct drm_connector *connector;
11513         struct drm_connector_state *old_conn_state, *new_conn_state;
11514         int i;
11515
11516         for_each_intel_encoder(dev, encoder) {
11517                 bool enabled = false, found = false;
11518                 enum pipe pipe;
11519
11520                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11521                               encoder->base.base.id,
11522                               encoder->base.name);
11523
11524                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11525                                                    new_conn_state, i) {
11526                         if (old_conn_state->best_encoder == &encoder->base)
11527                                 found = true;
11528
11529                         if (new_conn_state->best_encoder != &encoder->base)
11530                                 continue;
11531                         found = enabled = true;
11532
11533                         I915_STATE_WARN(new_conn_state->crtc !=
11534                                         encoder->base.crtc,
11535                              "connector's crtc doesn't match encoder crtc\n");
11536                 }
11537
11538                 if (!found)
11539                         continue;
11540
11541                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11542                      "encoder's enabled state mismatch "
11543                      "(expected %i, found %i)\n",
11544                      !!encoder->base.crtc, enabled);
11545
11546                 if (!encoder->base.crtc) {
11547                         bool active;
11548
11549                         active = encoder->get_hw_state(encoder, &pipe);
11550                         I915_STATE_WARN(active,
11551                              "encoder detached but still enabled on pipe %c.\n",
11552                              pipe_name(pipe));
11553                 }
11554         }
11555 }
11556
11557 static void
11558 verify_crtc_state(struct drm_crtc *crtc,
11559                   struct drm_crtc_state *old_crtc_state,
11560                   struct drm_crtc_state *new_crtc_state)
11561 {
11562         struct drm_device *dev = crtc->dev;
11563         struct drm_i915_private *dev_priv = to_i915(dev);
11564         struct intel_encoder *encoder;
11565         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11566         struct intel_crtc_state *pipe_config, *sw_config;
11567         struct drm_atomic_state *old_state;
11568         bool active;
11569
11570         old_state = old_crtc_state->state;
11571         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11572         pipe_config = to_intel_crtc_state(old_crtc_state);
11573         memset(pipe_config, 0, sizeof(*pipe_config));
11574         pipe_config->base.crtc = crtc;
11575         pipe_config->base.state = old_state;
11576
11577         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11578
11579         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11580
11581         /* we keep both pipes enabled on 830 */
11582         if (IS_I830(dev_priv))
11583                 active = new_crtc_state->active;
11584
11585         I915_STATE_WARN(new_crtc_state->active != active,
11586              "crtc active state doesn't match with hw state "
11587              "(expected %i, found %i)\n", new_crtc_state->active, active);
11588
11589         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11590              "transitional active state does not match atomic hw state "
11591              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11592
11593         for_each_encoder_on_crtc(dev, crtc, encoder) {
11594                 enum pipe pipe;
11595
11596                 active = encoder->get_hw_state(encoder, &pipe);
11597                 I915_STATE_WARN(active != new_crtc_state->active,
11598                         "[ENCODER:%i] active %i with crtc active %i\n",
11599                         encoder->base.base.id, active, new_crtc_state->active);
11600
11601                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11602                                 "Encoder connected to wrong pipe %c\n",
11603                                 pipe_name(pipe));
11604
11605                 if (active)
11606                         encoder->get_config(encoder, pipe_config);
11607         }
11608
11609         intel_crtc_compute_pixel_rate(pipe_config);
11610
11611         if (!new_crtc_state->active)
11612                 return;
11613
11614         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11615
11616         sw_config = to_intel_crtc_state(new_crtc_state);
11617         if (!intel_pipe_config_compare(dev_priv, sw_config,
11618                                        pipe_config, false)) {
11619                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11620                 intel_dump_pipe_config(intel_crtc, pipe_config,
11621                                        "[hw state]");
11622                 intel_dump_pipe_config(intel_crtc, sw_config,
11623                                        "[sw state]");
11624         }
11625 }
11626
11627 static void
11628 intel_verify_planes(struct intel_atomic_state *state)
11629 {
11630         struct intel_plane *plane;
11631         const struct intel_plane_state *plane_state;
11632         int i;
11633
11634         for_each_new_intel_plane_in_state(state, plane,
11635                                           plane_state, i)
11636                 assert_plane(plane, plane_state->base.visible);
11637 }
11638
11639 static void
11640 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11641                          struct intel_shared_dpll *pll,
11642                          struct drm_crtc *crtc,
11643                          struct drm_crtc_state *new_state)
11644 {
11645         struct intel_dpll_hw_state dpll_hw_state;
11646         unsigned crtc_mask;
11647         bool active;
11648
11649         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11650
11651         DRM_DEBUG_KMS("%s\n", pll->name);
11652
11653         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
11654
11655         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
11656                 I915_STATE_WARN(!pll->on && pll->active_mask,
11657                      "pll in active use but not on in sw tracking\n");
11658                 I915_STATE_WARN(pll->on && !pll->active_mask,
11659                      "pll is on but not used by any active crtc\n");
11660                 I915_STATE_WARN(pll->on != active,
11661                      "pll on state mismatch (expected %i, found %i)\n",
11662                      pll->on, active);
11663         }
11664
11665         if (!crtc) {
11666                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
11667                                 "more active pll users than references: %x vs %x\n",
11668                                 pll->active_mask, pll->state.crtc_mask);
11669
11670                 return;
11671         }
11672
11673         crtc_mask = 1 << drm_crtc_index(crtc);
11674
11675         if (new_state->active)
11676                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
11677                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
11678                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11679         else
11680                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11681                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
11682                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11683
11684         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
11685                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
11686                         crtc_mask, pll->state.crtc_mask);
11687
11688         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
11689                                           &dpll_hw_state,
11690                                           sizeof(dpll_hw_state)),
11691                         "pll hw state mismatch\n");
11692 }
11693
11694 static void
11695 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
11696                          struct drm_crtc_state *old_crtc_state,
11697                          struct drm_crtc_state *new_crtc_state)
11698 {
11699         struct drm_i915_private *dev_priv = to_i915(dev);
11700         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
11701         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
11702
11703         if (new_state->shared_dpll)
11704                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
11705
11706         if (old_state->shared_dpll &&
11707             old_state->shared_dpll != new_state->shared_dpll) {
11708                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
11709                 struct intel_shared_dpll *pll = old_state->shared_dpll;
11710
11711                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11712                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
11713                                 pipe_name(drm_crtc_index(crtc)));
11714                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
11715                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
11716                                 pipe_name(drm_crtc_index(crtc)));
11717         }
11718 }
11719
11720 static void
11721 intel_modeset_verify_crtc(struct drm_crtc *crtc,
11722                           struct drm_atomic_state *state,
11723                           struct drm_crtc_state *old_state,
11724                           struct drm_crtc_state *new_state)
11725 {
11726         if (!needs_modeset(new_state) &&
11727             !to_intel_crtc_state(new_state)->update_pipe)
11728                 return;
11729
11730         verify_wm_state(crtc, new_state);
11731         verify_connector_state(crtc->dev, state, crtc);
11732         verify_crtc_state(crtc, old_state, new_state);
11733         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
11734 }
11735
11736 static void
11737 verify_disabled_dpll_state(struct drm_device *dev)
11738 {
11739         struct drm_i915_private *dev_priv = to_i915(dev);
11740         int i;
11741
11742         for (i = 0; i < dev_priv->num_shared_dpll; i++)
11743                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
11744 }
11745
11746 static void
11747 intel_modeset_verify_disabled(struct drm_device *dev,
11748                               struct drm_atomic_state *state)
11749 {
11750         verify_encoder_state(dev, state);
11751         verify_connector_state(dev, state, NULL);
11752         verify_disabled_dpll_state(dev);
11753 }
11754
11755 static void update_scanline_offset(struct intel_crtc *crtc)
11756 {
11757         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11758
11759         /*
11760          * The scanline counter increments at the leading edge of hsync.
11761          *
11762          * On most platforms it starts counting from vtotal-1 on the
11763          * first active line. That means the scanline counter value is
11764          * always one less than what we would expect. Ie. just after
11765          * start of vblank, which also occurs at start of hsync (on the
11766          * last active line), the scanline counter will read vblank_start-1.
11767          *
11768          * On gen2 the scanline counter starts counting from 1 instead
11769          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
11770          * to keep the value positive), instead of adding one.
11771          *
11772          * On HSW+ the behaviour of the scanline counter depends on the output
11773          * type. For DP ports it behaves like most other platforms, but on HDMI
11774          * there's an extra 1 line difference. So we need to add two instead of
11775          * one to the value.
11776          *
11777          * On VLV/CHV DSI the scanline counter would appear to increment
11778          * approx. 1/3 of a scanline before start of vblank. Unfortunately
11779          * that means we can't tell whether we're in vblank or not while
11780          * we're on that particular line. We must still set scanline_offset
11781          * to 1 so that the vblank timestamps come out correct when we query
11782          * the scanline counter from within the vblank interrupt handler.
11783          * However if queried just before the start of vblank we'll get an
11784          * answer that's slightly in the future.
11785          */
11786         if (IS_GEN2(dev_priv)) {
11787                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
11788                 int vtotal;
11789
11790                 vtotal = adjusted_mode->crtc_vtotal;
11791                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
11792                         vtotal /= 2;
11793
11794                 crtc->scanline_offset = vtotal - 1;
11795         } else if (HAS_DDI(dev_priv) &&
11796                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
11797                 crtc->scanline_offset = 2;
11798         } else
11799                 crtc->scanline_offset = 1;
11800 }
11801
11802 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
11803 {
11804         struct drm_device *dev = state->dev;
11805         struct drm_i915_private *dev_priv = to_i915(dev);
11806         struct drm_crtc *crtc;
11807         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11808         int i;
11809
11810         if (!dev_priv->display.crtc_compute_clock)
11811                 return;
11812
11813         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11814                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11815                 struct intel_shared_dpll *old_dpll =
11816                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
11817
11818                 if (!needs_modeset(new_crtc_state))
11819                         continue;
11820
11821                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
11822
11823                 if (!old_dpll)
11824                         continue;
11825
11826                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
11827         }
11828 }
11829
11830 /*
11831  * This implements the workaround described in the "notes" section of the mode
11832  * set sequence documentation. When going from no pipes or single pipe to
11833  * multiple pipes, and planes are enabled after the pipe, we need to wait at
11834  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
11835  */
11836 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
11837 {
11838         struct drm_crtc_state *crtc_state;
11839         struct intel_crtc *intel_crtc;
11840         struct drm_crtc *crtc;
11841         struct intel_crtc_state *first_crtc_state = NULL;
11842         struct intel_crtc_state *other_crtc_state = NULL;
11843         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
11844         int i;
11845
11846         /* look at all crtc's that are going to be enabled in during modeset */
11847         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
11848                 intel_crtc = to_intel_crtc(crtc);
11849
11850                 if (!crtc_state->active || !needs_modeset(crtc_state))
11851                         continue;
11852
11853                 if (first_crtc_state) {
11854                         other_crtc_state = to_intel_crtc_state(crtc_state);
11855                         break;
11856                 } else {
11857                         first_crtc_state = to_intel_crtc_state(crtc_state);
11858                         first_pipe = intel_crtc->pipe;
11859                 }
11860         }
11861
11862         /* No workaround needed? */
11863         if (!first_crtc_state)
11864                 return 0;
11865
11866         /* w/a possibly needed, check how many crtc's are already enabled. */
11867         for_each_intel_crtc(state->dev, intel_crtc) {
11868                 struct intel_crtc_state *pipe_config;
11869
11870                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
11871                 if (IS_ERR(pipe_config))
11872                         return PTR_ERR(pipe_config);
11873
11874                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
11875
11876                 if (!pipe_config->base.active ||
11877                     needs_modeset(&pipe_config->base))
11878                         continue;
11879
11880                 /* 2 or more enabled crtcs means no need for w/a */
11881                 if (enabled_pipe != INVALID_PIPE)
11882                         return 0;
11883
11884                 enabled_pipe = intel_crtc->pipe;
11885         }
11886
11887         if (enabled_pipe != INVALID_PIPE)
11888                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
11889         else if (other_crtc_state)
11890                 other_crtc_state->hsw_workaround_pipe = first_pipe;
11891
11892         return 0;
11893 }
11894
11895 static int intel_lock_all_pipes(struct drm_atomic_state *state)
11896 {
11897         struct drm_crtc *crtc;
11898
11899         /* Add all pipes to the state */
11900         for_each_crtc(state->dev, crtc) {
11901                 struct drm_crtc_state *crtc_state;
11902
11903                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11904                 if (IS_ERR(crtc_state))
11905                         return PTR_ERR(crtc_state);
11906         }
11907
11908         return 0;
11909 }
11910
11911 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
11912 {
11913         struct drm_crtc *crtc;
11914
11915         /*
11916          * Add all pipes to the state, and force
11917          * a modeset on all the active ones.
11918          */
11919         for_each_crtc(state->dev, crtc) {
11920                 struct drm_crtc_state *crtc_state;
11921                 int ret;
11922
11923                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11924                 if (IS_ERR(crtc_state))
11925                         return PTR_ERR(crtc_state);
11926
11927                 if (!crtc_state->active || needs_modeset(crtc_state))
11928                         continue;
11929
11930                 crtc_state->mode_changed = true;
11931
11932                 ret = drm_atomic_add_affected_connectors(state, crtc);
11933                 if (ret)
11934                         return ret;
11935
11936                 ret = drm_atomic_add_affected_planes(state, crtc);
11937                 if (ret)
11938                         return ret;
11939         }
11940
11941         return 0;
11942 }
11943
11944 static int intel_modeset_checks(struct drm_atomic_state *state)
11945 {
11946         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
11947         struct drm_i915_private *dev_priv = to_i915(state->dev);
11948         struct drm_crtc *crtc;
11949         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11950         int ret = 0, i;
11951
11952         if (!check_digital_port_conflicts(state)) {
11953                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
11954                 return -EINVAL;
11955         }
11956
11957         intel_state->modeset = true;
11958         intel_state->active_crtcs = dev_priv->active_crtcs;
11959         intel_state->cdclk.logical = dev_priv->cdclk.logical;
11960         intel_state->cdclk.actual = dev_priv->cdclk.actual;
11961
11962         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11963                 if (new_crtc_state->active)
11964                         intel_state->active_crtcs |= 1 << i;
11965                 else
11966                         intel_state->active_crtcs &= ~(1 << i);
11967
11968                 if (old_crtc_state->active != new_crtc_state->active)
11969                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
11970         }
11971
11972         /*
11973          * See if the config requires any additional preparation, e.g.
11974          * to adjust global state with pipes off.  We need to do this
11975          * here so we can get the modeset_pipe updated config for the new
11976          * mode set on this crtc.  For other crtcs we need to use the
11977          * adjusted_mode bits in the crtc directly.
11978          */
11979         if (dev_priv->display.modeset_calc_cdclk) {
11980                 ret = dev_priv->display.modeset_calc_cdclk(state);
11981                 if (ret < 0)
11982                         return ret;
11983
11984                 /*
11985                  * Writes to dev_priv->cdclk.logical must protected by
11986                  * holding all the crtc locks, even if we don't end up
11987                  * touching the hardware
11988                  */
11989                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
11990                                         &intel_state->cdclk.logical)) {
11991                         ret = intel_lock_all_pipes(state);
11992                         if (ret < 0)
11993                                 return ret;
11994                 }
11995
11996                 /* All pipes must be switched off while we change the cdclk. */
11997                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
11998                                               &intel_state->cdclk.actual)) {
11999                         ret = intel_modeset_all_pipes(state);
12000                         if (ret < 0)
12001                                 return ret;
12002                 }
12003
12004                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12005                               intel_state->cdclk.logical.cdclk,
12006                               intel_state->cdclk.actual.cdclk);
12007                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12008                               intel_state->cdclk.logical.voltage_level,
12009                               intel_state->cdclk.actual.voltage_level);
12010         } else {
12011                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12012         }
12013
12014         intel_modeset_clear_plls(state);
12015
12016         if (IS_HASWELL(dev_priv))
12017                 return haswell_mode_set_planes_workaround(state);
12018
12019         return 0;
12020 }
12021
12022 /*
12023  * Handle calculation of various watermark data at the end of the atomic check
12024  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12025  * handlers to ensure that all derived state has been updated.
12026  */
12027 static int calc_watermark_data(struct drm_atomic_state *state)
12028 {
12029         struct drm_device *dev = state->dev;
12030         struct drm_i915_private *dev_priv = to_i915(dev);
12031
12032         /* Is there platform-specific watermark information to calculate? */
12033         if (dev_priv->display.compute_global_watermarks)
12034                 return dev_priv->display.compute_global_watermarks(state);
12035
12036         return 0;
12037 }
12038
12039 /**
12040  * intel_atomic_check - validate state object
12041  * @dev: drm device
12042  * @state: state to validate
12043  */
12044 static int intel_atomic_check(struct drm_device *dev,
12045                               struct drm_atomic_state *state)
12046 {
12047         struct drm_i915_private *dev_priv = to_i915(dev);
12048         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12049         struct drm_crtc *crtc;
12050         struct drm_crtc_state *old_crtc_state, *crtc_state;
12051         int ret, i;
12052         bool any_ms = false;
12053
12054         /* Catch I915_MODE_FLAG_INHERITED */
12055         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12056                                       crtc_state, i) {
12057                 if (crtc_state->mode.private_flags !=
12058                     old_crtc_state->mode.private_flags)
12059                         crtc_state->mode_changed = true;
12060         }
12061
12062         ret = drm_atomic_helper_check_modeset(dev, state);
12063         if (ret)
12064                 return ret;
12065
12066         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12067                 struct intel_crtc_state *pipe_config =
12068                         to_intel_crtc_state(crtc_state);
12069
12070                 if (!needs_modeset(crtc_state))
12071                         continue;
12072
12073                 if (!crtc_state->enable) {
12074                         any_ms = true;
12075                         continue;
12076                 }
12077
12078                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12079                 if (ret) {
12080                         intel_dump_pipe_config(to_intel_crtc(crtc),
12081                                                pipe_config, "[failed]");
12082                         return ret;
12083                 }
12084
12085                 if (i915_modparams.fastboot &&
12086                     intel_pipe_config_compare(dev_priv,
12087                                         to_intel_crtc_state(old_crtc_state),
12088                                         pipe_config, true)) {
12089                         crtc_state->mode_changed = false;
12090                         pipe_config->update_pipe = true;
12091                 }
12092
12093                 if (needs_modeset(crtc_state))
12094                         any_ms = true;
12095
12096                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12097                                        needs_modeset(crtc_state) ?
12098                                        "[modeset]" : "[fastset]");
12099         }
12100
12101         if (any_ms) {
12102                 ret = intel_modeset_checks(state);
12103
12104                 if (ret)
12105                         return ret;
12106         } else {
12107                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12108         }
12109
12110         ret = drm_atomic_helper_check_planes(dev, state);
12111         if (ret)
12112                 return ret;
12113
12114         intel_fbc_choose_crtc(dev_priv, intel_state);
12115         return calc_watermark_data(state);
12116 }
12117
12118 static int intel_atomic_prepare_commit(struct drm_device *dev,
12119                                        struct drm_atomic_state *state)
12120 {
12121         return drm_atomic_helper_prepare_planes(dev, state);
12122 }
12123
12124 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12125 {
12126         struct drm_device *dev = crtc->base.dev;
12127
12128         if (!dev->max_vblank_count)
12129                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12130
12131         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12132 }
12133
12134 static void intel_update_crtc(struct drm_crtc *crtc,
12135                               struct drm_atomic_state *state,
12136                               struct drm_crtc_state *old_crtc_state,
12137                               struct drm_crtc_state *new_crtc_state)
12138 {
12139         struct drm_device *dev = crtc->dev;
12140         struct drm_i915_private *dev_priv = to_i915(dev);
12141         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12142         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12143         bool modeset = needs_modeset(new_crtc_state);
12144
12145         if (modeset) {
12146                 update_scanline_offset(intel_crtc);
12147                 dev_priv->display.crtc_enable(pipe_config, state);
12148         } else {
12149                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12150                                        pipe_config);
12151         }
12152
12153         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12154                 intel_fbc_enable(
12155                     intel_crtc, pipe_config,
12156                     to_intel_plane_state(crtc->primary->state));
12157         }
12158
12159         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12160 }
12161
12162 static void intel_update_crtcs(struct drm_atomic_state *state)
12163 {
12164         struct drm_crtc *crtc;
12165         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12166         int i;
12167
12168         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12169                 if (!new_crtc_state->active)
12170                         continue;
12171
12172                 intel_update_crtc(crtc, state, old_crtc_state,
12173                                   new_crtc_state);
12174         }
12175 }
12176
12177 static void skl_update_crtcs(struct drm_atomic_state *state)
12178 {
12179         struct drm_i915_private *dev_priv = to_i915(state->dev);
12180         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12181         struct drm_crtc *crtc;
12182         struct intel_crtc *intel_crtc;
12183         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12184         struct intel_crtc_state *cstate;
12185         unsigned int updated = 0;
12186         bool progress;
12187         enum pipe pipe;
12188         int i;
12189
12190         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12191
12192         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12193                 /* ignore allocations for crtc's that have been turned off. */
12194                 if (new_crtc_state->active)
12195                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12196
12197         /*
12198          * Whenever the number of active pipes changes, we need to make sure we
12199          * update the pipes in the right order so that their ddb allocations
12200          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12201          * cause pipe underruns and other bad stuff.
12202          */
12203         do {
12204                 progress = false;
12205
12206                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12207                         bool vbl_wait = false;
12208                         unsigned int cmask = drm_crtc_mask(crtc);
12209
12210                         intel_crtc = to_intel_crtc(crtc);
12211                         cstate = to_intel_crtc_state(new_crtc_state);
12212                         pipe = intel_crtc->pipe;
12213
12214                         if (updated & cmask || !cstate->base.active)
12215                                 continue;
12216
12217                         if (skl_ddb_allocation_overlaps(dev_priv,
12218                                                         entries,
12219                                                         &cstate->wm.skl.ddb,
12220                                                         i))
12221                                 continue;
12222
12223                         updated |= cmask;
12224                         entries[i] = &cstate->wm.skl.ddb;
12225
12226                         /*
12227                          * If this is an already active pipe, it's DDB changed,
12228                          * and this isn't the last pipe that needs updating
12229                          * then we need to wait for a vblank to pass for the
12230                          * new ddb allocation to take effect.
12231                          */
12232                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12233                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12234                             !new_crtc_state->active_changed &&
12235                             intel_state->wm_results.dirty_pipes != updated)
12236                                 vbl_wait = true;
12237
12238                         intel_update_crtc(crtc, state, old_crtc_state,
12239                                           new_crtc_state);
12240
12241                         if (vbl_wait)
12242                                 intel_wait_for_vblank(dev_priv, pipe);
12243
12244                         progress = true;
12245                 }
12246         } while (progress);
12247 }
12248
12249 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12250 {
12251         struct intel_atomic_state *state, *next;
12252         struct llist_node *freed;
12253
12254         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12255         llist_for_each_entry_safe(state, next, freed, freed)
12256                 drm_atomic_state_put(&state->base);
12257 }
12258
12259 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12260 {
12261         struct drm_i915_private *dev_priv =
12262                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12263
12264         intel_atomic_helper_free_state(dev_priv);
12265 }
12266
12267 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12268 {
12269         struct wait_queue_entry wait_fence, wait_reset;
12270         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12271
12272         init_wait_entry(&wait_fence, 0);
12273         init_wait_entry(&wait_reset, 0);
12274         for (;;) {
12275                 prepare_to_wait(&intel_state->commit_ready.wait,
12276                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12277                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12278                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12279
12280
12281                 if (i915_sw_fence_done(&intel_state->commit_ready)
12282                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12283                         break;
12284
12285                 schedule();
12286         }
12287         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12288         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12289 }
12290
12291 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12292 {
12293         struct drm_device *dev = state->dev;
12294         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12295         struct drm_i915_private *dev_priv = to_i915(dev);
12296         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12297         struct drm_crtc *crtc;
12298         struct intel_crtc_state *intel_cstate;
12299         u64 put_domains[I915_MAX_PIPES] = {};
12300         int i;
12301
12302         intel_atomic_commit_fence_wait(intel_state);
12303
12304         drm_atomic_helper_wait_for_dependencies(state);
12305
12306         if (intel_state->modeset)
12307                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12308
12309         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12310                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12311
12312                 if (needs_modeset(new_crtc_state) ||
12313                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12314
12315                         put_domains[to_intel_crtc(crtc)->pipe] =
12316                                 modeset_get_crtc_power_domains(crtc,
12317                                         to_intel_crtc_state(new_crtc_state));
12318                 }
12319
12320                 if (!needs_modeset(new_crtc_state))
12321                         continue;
12322
12323                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12324                                        to_intel_crtc_state(new_crtc_state));
12325
12326                 if (old_crtc_state->active) {
12327                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
12328                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
12329                         intel_crtc->active = false;
12330                         intel_fbc_disable(intel_crtc);
12331                         intel_disable_shared_dpll(intel_crtc);
12332
12333                         /*
12334                          * Underruns don't always raise
12335                          * interrupts, so check manually.
12336                          */
12337                         intel_check_cpu_fifo_underruns(dev_priv);
12338                         intel_check_pch_fifo_underruns(dev_priv);
12339
12340                         if (!new_crtc_state->active) {
12341                                 /*
12342                                  * Make sure we don't call initial_watermarks
12343                                  * for ILK-style watermark updates.
12344                                  *
12345                                  * No clue what this is supposed to achieve.
12346                                  */
12347                                 if (INTEL_GEN(dev_priv) >= 9)
12348                                         dev_priv->display.initial_watermarks(intel_state,
12349                                                                              to_intel_crtc_state(new_crtc_state));
12350                         }
12351                 }
12352         }
12353
12354         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12355         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12356                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12357
12358         if (intel_state->modeset) {
12359                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12360
12361                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12362
12363                 /*
12364                  * SKL workaround: bspec recommends we disable the SAGV when we
12365                  * have more then one pipe enabled
12366                  */
12367                 if (!intel_can_enable_sagv(state))
12368                         intel_disable_sagv(dev_priv);
12369
12370                 intel_modeset_verify_disabled(dev, state);
12371         }
12372
12373         /* Complete the events for pipes that have now been disabled */
12374         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12375                 bool modeset = needs_modeset(new_crtc_state);
12376
12377                 /* Complete events for now disable pipes here. */
12378                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12379                         spin_lock_irq(&dev->event_lock);
12380                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12381                         spin_unlock_irq(&dev->event_lock);
12382
12383                         new_crtc_state->event = NULL;
12384                 }
12385         }
12386
12387         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12388         dev_priv->display.update_crtcs(state);
12389
12390         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12391          * already, but still need the state for the delayed optimization. To
12392          * fix this:
12393          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12394          * - schedule that vblank worker _before_ calling hw_done
12395          * - at the start of commit_tail, cancel it _synchrously
12396          * - switch over to the vblank wait helper in the core after that since
12397          *   we don't need out special handling any more.
12398          */
12399         drm_atomic_helper_wait_for_flip_done(dev, state);
12400
12401         /*
12402          * Now that the vblank has passed, we can go ahead and program the
12403          * optimal watermarks on platforms that need two-step watermark
12404          * programming.
12405          *
12406          * TODO: Move this (and other cleanup) to an async worker eventually.
12407          */
12408         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12409                 intel_cstate = to_intel_crtc_state(new_crtc_state);
12410
12411                 if (dev_priv->display.optimize_watermarks)
12412                         dev_priv->display.optimize_watermarks(intel_state,
12413                                                               intel_cstate);
12414         }
12415
12416         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12417                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12418
12419                 if (put_domains[i])
12420                         modeset_put_power_domains(dev_priv, put_domains[i]);
12421
12422                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12423         }
12424
12425         if (intel_state->modeset)
12426                 intel_verify_planes(intel_state);
12427
12428         if (intel_state->modeset && intel_can_enable_sagv(state))
12429                 intel_enable_sagv(dev_priv);
12430
12431         drm_atomic_helper_commit_hw_done(state);
12432
12433         if (intel_state->modeset) {
12434                 /* As one of the primary mmio accessors, KMS has a high
12435                  * likelihood of triggering bugs in unclaimed access. After we
12436                  * finish modesetting, see if an error has been flagged, and if
12437                  * so enable debugging for the next modeset - and hope we catch
12438                  * the culprit.
12439                  */
12440                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12441                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12442         }
12443
12444         drm_atomic_helper_cleanup_planes(dev, state);
12445
12446         drm_atomic_helper_commit_cleanup_done(state);
12447
12448         drm_atomic_state_put(state);
12449
12450         intel_atomic_helper_free_state(dev_priv);
12451 }
12452
12453 static void intel_atomic_commit_work(struct work_struct *work)
12454 {
12455         struct drm_atomic_state *state =
12456                 container_of(work, struct drm_atomic_state, commit_work);
12457
12458         intel_atomic_commit_tail(state);
12459 }
12460
12461 static int __i915_sw_fence_call
12462 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12463                           enum i915_sw_fence_notify notify)
12464 {
12465         struct intel_atomic_state *state =
12466                 container_of(fence, struct intel_atomic_state, commit_ready);
12467
12468         switch (notify) {
12469         case FENCE_COMPLETE:
12470                 /* we do blocking waits in the worker, nothing to do here */
12471                 break;
12472         case FENCE_FREE:
12473                 {
12474                         struct intel_atomic_helper *helper =
12475                                 &to_i915(state->base.dev)->atomic_helper;
12476
12477                         if (llist_add(&state->freed, &helper->free_list))
12478                                 schedule_work(&helper->free_work);
12479                         break;
12480                 }
12481         }
12482
12483         return NOTIFY_DONE;
12484 }
12485
12486 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12487 {
12488         struct drm_plane_state *old_plane_state, *new_plane_state;
12489         struct drm_plane *plane;
12490         int i;
12491
12492         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12493                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12494                                   intel_fb_obj(new_plane_state->fb),
12495                                   to_intel_plane(plane)->frontbuffer_bit);
12496 }
12497
12498 /**
12499  * intel_atomic_commit - commit validated state object
12500  * @dev: DRM device
12501  * @state: the top-level driver state object
12502  * @nonblock: nonblocking commit
12503  *
12504  * This function commits a top-level state object that has been validated
12505  * with drm_atomic_helper_check().
12506  *
12507  * RETURNS
12508  * Zero for success or -errno.
12509  */
12510 static int intel_atomic_commit(struct drm_device *dev,
12511                                struct drm_atomic_state *state,
12512                                bool nonblock)
12513 {
12514         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12515         struct drm_i915_private *dev_priv = to_i915(dev);
12516         int ret = 0;
12517
12518         drm_atomic_state_get(state);
12519         i915_sw_fence_init(&intel_state->commit_ready,
12520                            intel_atomic_commit_ready);
12521
12522         /*
12523          * The intel_legacy_cursor_update() fast path takes care
12524          * of avoiding the vblank waits for simple cursor
12525          * movement and flips. For cursor on/off and size changes,
12526          * we want to perform the vblank waits so that watermark
12527          * updates happen during the correct frames. Gen9+ have
12528          * double buffered watermarks and so shouldn't need this.
12529          *
12530          * Unset state->legacy_cursor_update before the call to
12531          * drm_atomic_helper_setup_commit() because otherwise
12532          * drm_atomic_helper_wait_for_flip_done() is a noop and
12533          * we get FIFO underruns because we didn't wait
12534          * for vblank.
12535          *
12536          * FIXME doing watermarks and fb cleanup from a vblank worker
12537          * (assuming we had any) would solve these problems.
12538          */
12539         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12540                 struct intel_crtc_state *new_crtc_state;
12541                 struct intel_crtc *crtc;
12542                 int i;
12543
12544                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12545                         if (new_crtc_state->wm.need_postvbl_update ||
12546                             new_crtc_state->update_wm_post)
12547                                 state->legacy_cursor_update = false;
12548         }
12549
12550         ret = intel_atomic_prepare_commit(dev, state);
12551         if (ret) {
12552                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12553                 i915_sw_fence_commit(&intel_state->commit_ready);
12554                 return ret;
12555         }
12556
12557         ret = drm_atomic_helper_setup_commit(state, nonblock);
12558         if (!ret)
12559                 ret = drm_atomic_helper_swap_state(state, true);
12560
12561         if (ret) {
12562                 i915_sw_fence_commit(&intel_state->commit_ready);
12563
12564                 drm_atomic_helper_cleanup_planes(dev, state);
12565                 return ret;
12566         }
12567         dev_priv->wm.distrust_bios_wm = false;
12568         intel_shared_dpll_swap_state(state);
12569         intel_atomic_track_fbs(state);
12570
12571         if (intel_state->modeset) {
12572                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12573                        sizeof(intel_state->min_cdclk));
12574                 memcpy(dev_priv->min_voltage_level,
12575                        intel_state->min_voltage_level,
12576                        sizeof(intel_state->min_voltage_level));
12577                 dev_priv->active_crtcs = intel_state->active_crtcs;
12578                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12579                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12580         }
12581
12582         drm_atomic_state_get(state);
12583         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12584
12585         i915_sw_fence_commit(&intel_state->commit_ready);
12586         if (nonblock && intel_state->modeset) {
12587                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12588         } else if (nonblock) {
12589                 queue_work(system_unbound_wq, &state->commit_work);
12590         } else {
12591                 if (intel_state->modeset)
12592                         flush_workqueue(dev_priv->modeset_wq);
12593                 intel_atomic_commit_tail(state);
12594         }
12595
12596         return 0;
12597 }
12598
12599 static const struct drm_crtc_funcs intel_crtc_funcs = {
12600         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12601         .set_config = drm_atomic_helper_set_config,
12602         .destroy = intel_crtc_destroy,
12603         .page_flip = drm_atomic_helper_page_flip,
12604         .atomic_duplicate_state = intel_crtc_duplicate_state,
12605         .atomic_destroy_state = intel_crtc_destroy_state,
12606         .set_crc_source = intel_crtc_set_crc_source,
12607 };
12608
12609 struct wait_rps_boost {
12610         struct wait_queue_entry wait;
12611
12612         struct drm_crtc *crtc;
12613         struct i915_request *request;
12614 };
12615
12616 static int do_rps_boost(struct wait_queue_entry *_wait,
12617                         unsigned mode, int sync, void *key)
12618 {
12619         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
12620         struct i915_request *rq = wait->request;
12621
12622         /*
12623          * If we missed the vblank, but the request is already running it
12624          * is reasonable to assume that it will complete before the next
12625          * vblank without our intervention, so leave RPS alone.
12626          */
12627         if (!i915_request_started(rq))
12628                 gen6_rps_boost(rq, NULL);
12629         i915_request_put(rq);
12630
12631         drm_crtc_vblank_put(wait->crtc);
12632
12633         list_del(&wait->wait.entry);
12634         kfree(wait);
12635         return 1;
12636 }
12637
12638 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
12639                                        struct dma_fence *fence)
12640 {
12641         struct wait_rps_boost *wait;
12642
12643         if (!dma_fence_is_i915(fence))
12644                 return;
12645
12646         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
12647                 return;
12648
12649         if (drm_crtc_vblank_get(crtc))
12650                 return;
12651
12652         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
12653         if (!wait) {
12654                 drm_crtc_vblank_put(crtc);
12655                 return;
12656         }
12657
12658         wait->request = to_request(dma_fence_get(fence));
12659         wait->crtc = crtc;
12660
12661         wait->wait.func = do_rps_boost;
12662         wait->wait.flags = 0;
12663
12664         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
12665 }
12666
12667 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
12668 {
12669         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
12670         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12671         struct drm_framebuffer *fb = plane_state->base.fb;
12672         struct i915_vma *vma;
12673
12674         if (plane->id == PLANE_CURSOR &&
12675             INTEL_INFO(dev_priv)->cursor_needs_physical) {
12676                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12677                 const int align = intel_cursor_alignment(dev_priv);
12678
12679                 return i915_gem_object_attach_phys(obj, align);
12680         }
12681
12682         vma = intel_pin_and_fence_fb_obj(fb,
12683                                          plane_state->base.rotation,
12684                                          intel_plane_uses_fence(plane_state),
12685                                          &plane_state->flags);
12686         if (IS_ERR(vma))
12687                 return PTR_ERR(vma);
12688
12689         plane_state->vma = vma;
12690
12691         return 0;
12692 }
12693
12694 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
12695 {
12696         struct i915_vma *vma;
12697
12698         vma = fetch_and_zero(&old_plane_state->vma);
12699         if (vma)
12700                 intel_unpin_fb_vma(vma, old_plane_state->flags);
12701 }
12702
12703 /**
12704  * intel_prepare_plane_fb - Prepare fb for usage on plane
12705  * @plane: drm plane to prepare for
12706  * @new_state: the plane state being prepared
12707  *
12708  * Prepares a framebuffer for usage on a display plane.  Generally this
12709  * involves pinning the underlying object and updating the frontbuffer tracking
12710  * bits.  Some older platforms need special physical address handling for
12711  * cursor planes.
12712  *
12713  * Must be called with struct_mutex held.
12714  *
12715  * Returns 0 on success, negative error code on failure.
12716  */
12717 int
12718 intel_prepare_plane_fb(struct drm_plane *plane,
12719                        struct drm_plane_state *new_state)
12720 {
12721         struct intel_atomic_state *intel_state =
12722                 to_intel_atomic_state(new_state->state);
12723         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12724         struct drm_framebuffer *fb = new_state->fb;
12725         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12726         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
12727         int ret;
12728
12729         if (old_obj) {
12730                 struct drm_crtc_state *crtc_state =
12731                         drm_atomic_get_existing_crtc_state(new_state->state,
12732                                                            plane->state->crtc);
12733
12734                 /* Big Hammer, we also need to ensure that any pending
12735                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
12736                  * current scanout is retired before unpinning the old
12737                  * framebuffer. Note that we rely on userspace rendering
12738                  * into the buffer attached to the pipe they are waiting
12739                  * on. If not, userspace generates a GPU hang with IPEHR
12740                  * point to the MI_WAIT_FOR_EVENT.
12741                  *
12742                  * This should only fail upon a hung GPU, in which case we
12743                  * can safely continue.
12744                  */
12745                 if (needs_modeset(crtc_state)) {
12746                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12747                                                               old_obj->resv, NULL,
12748                                                               false, 0,
12749                                                               GFP_KERNEL);
12750                         if (ret < 0)
12751                                 return ret;
12752                 }
12753         }
12754
12755         if (new_state->fence) { /* explicit fencing */
12756                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
12757                                                     new_state->fence,
12758                                                     I915_FENCE_TIMEOUT,
12759                                                     GFP_KERNEL);
12760                 if (ret < 0)
12761                         return ret;
12762         }
12763
12764         if (!obj)
12765                 return 0;
12766
12767         ret = i915_gem_object_pin_pages(obj);
12768         if (ret)
12769                 return ret;
12770
12771         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
12772         if (ret) {
12773                 i915_gem_object_unpin_pages(obj);
12774                 return ret;
12775         }
12776
12777         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
12778
12779         i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
12780
12781         mutex_unlock(&dev_priv->drm.struct_mutex);
12782         i915_gem_object_unpin_pages(obj);
12783         if (ret)
12784                 return ret;
12785
12786         if (!new_state->fence) { /* implicit fencing */
12787                 struct dma_fence *fence;
12788
12789                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12790                                                       obj->resv, NULL,
12791                                                       false, I915_FENCE_TIMEOUT,
12792                                                       GFP_KERNEL);
12793                 if (ret < 0)
12794                         return ret;
12795
12796                 fence = reservation_object_get_excl_rcu(obj->resv);
12797                 if (fence) {
12798                         add_rps_boost_after_vblank(new_state->crtc, fence);
12799                         dma_fence_put(fence);
12800                 }
12801         } else {
12802                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
12803         }
12804
12805         return 0;
12806 }
12807
12808 /**
12809  * intel_cleanup_plane_fb - Cleans up an fb after plane use
12810  * @plane: drm plane to clean up for
12811  * @old_state: the state from the previous modeset
12812  *
12813  * Cleans up a framebuffer that has just been removed from a plane.
12814  *
12815  * Must be called with struct_mutex held.
12816  */
12817 void
12818 intel_cleanup_plane_fb(struct drm_plane *plane,
12819                        struct drm_plane_state *old_state)
12820 {
12821         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12822
12823         /* Should only be called after a successful intel_prepare_plane_fb()! */
12824         mutex_lock(&dev_priv->drm.struct_mutex);
12825         intel_plane_unpin_fb(to_intel_plane_state(old_state));
12826         mutex_unlock(&dev_priv->drm.struct_mutex);
12827 }
12828
12829 int
12830 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
12831 {
12832         struct drm_i915_private *dev_priv;
12833         int max_scale;
12834         int crtc_clock, max_dotclk;
12835
12836         if (!intel_crtc || !crtc_state->base.enable)
12837                 return DRM_PLANE_HELPER_NO_SCALING;
12838
12839         dev_priv = to_i915(intel_crtc->base.dev);
12840
12841         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
12842         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
12843
12844         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
12845                 max_dotclk *= 2;
12846
12847         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
12848                 return DRM_PLANE_HELPER_NO_SCALING;
12849
12850         /*
12851          * skl max scale is lower of:
12852          *    close to 3 but not 3, -1 is for that purpose
12853          *            or
12854          *    cdclk/crtc_clock
12855          */
12856         max_scale = min((1 << 16) * 3 - 1,
12857                         (1 << 8) * ((max_dotclk << 8) / crtc_clock));
12858
12859         return max_scale;
12860 }
12861
12862 static int
12863 intel_check_primary_plane(struct intel_plane *plane,
12864                           struct intel_crtc_state *crtc_state,
12865                           struct intel_plane_state *state)
12866 {
12867         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12868         struct drm_crtc *crtc = state->base.crtc;
12869         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
12870         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
12871         bool can_position = false;
12872         struct drm_rect clip = {};
12873         int ret;
12874
12875         if (INTEL_GEN(dev_priv) >= 9) {
12876                 /* use scaler when colorkey is not required */
12877                 if (!state->ckey.flags) {
12878                         min_scale = 1;
12879                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
12880                 }
12881                 can_position = true;
12882         }
12883
12884         if (crtc_state->base.enable)
12885                 drm_mode_get_hv_timing(&crtc_state->base.mode,
12886                                        &clip.x2, &clip.y2);
12887
12888         ret = drm_atomic_helper_check_plane_state(&state->base,
12889                                                   &crtc_state->base,
12890                                                   &clip,
12891                                                   min_scale, max_scale,
12892                                                   can_position, true);
12893         if (ret)
12894                 return ret;
12895
12896         if (!state->base.fb)
12897                 return 0;
12898
12899         if (INTEL_GEN(dev_priv) >= 9) {
12900                 ret = skl_check_plane_surface(crtc_state, state);
12901                 if (ret)
12902                         return ret;
12903
12904                 state->ctl = skl_plane_ctl(crtc_state, state);
12905         } else {
12906                 ret = i9xx_check_plane_surface(state);
12907                 if (ret)
12908                         return ret;
12909
12910                 state->ctl = i9xx_plane_ctl(crtc_state, state);
12911         }
12912
12913         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
12914                 state->color_ctl = glk_plane_color_ctl(crtc_state, state);
12915
12916         return 0;
12917 }
12918
12919 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
12920                                     struct drm_crtc_state *old_crtc_state)
12921 {
12922         struct drm_device *dev = crtc->dev;
12923         struct drm_i915_private *dev_priv = to_i915(dev);
12924         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12925         struct intel_crtc_state *old_intel_cstate =
12926                 to_intel_crtc_state(old_crtc_state);
12927         struct intel_atomic_state *old_intel_state =
12928                 to_intel_atomic_state(old_crtc_state->state);
12929         struct intel_crtc_state *intel_cstate =
12930                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
12931         bool modeset = needs_modeset(&intel_cstate->base);
12932
12933         if (!modeset &&
12934             (intel_cstate->base.color_mgmt_changed ||
12935              intel_cstate->update_pipe)) {
12936                 intel_color_set_csc(&intel_cstate->base);
12937                 intel_color_load_luts(&intel_cstate->base);
12938         }
12939
12940         /* Perform vblank evasion around commit operation */
12941         intel_pipe_update_start(intel_cstate);
12942
12943         if (modeset)
12944                 goto out;
12945
12946         if (intel_cstate->update_pipe)
12947                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
12948         else if (INTEL_GEN(dev_priv) >= 9)
12949                 skl_detach_scalers(intel_crtc);
12950
12951 out:
12952         if (dev_priv->display.atomic_update_watermarks)
12953                 dev_priv->display.atomic_update_watermarks(old_intel_state,
12954                                                            intel_cstate);
12955 }
12956
12957 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
12958                                      struct drm_crtc_state *old_crtc_state)
12959 {
12960         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12961         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12962         struct intel_atomic_state *old_intel_state =
12963                 to_intel_atomic_state(old_crtc_state->state);
12964         struct intel_crtc_state *new_crtc_state =
12965                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
12966
12967         intel_pipe_update_end(new_crtc_state);
12968
12969         if (new_crtc_state->update_pipe &&
12970             !needs_modeset(&new_crtc_state->base) &&
12971             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED) {
12972                 if (!IS_GEN2(dev_priv))
12973                         intel_set_cpu_fifo_underrun_reporting(dev_priv, intel_crtc->pipe, true);
12974
12975                 if (new_crtc_state->has_pch_encoder) {
12976                         enum pipe pch_transcoder =
12977                                 intel_crtc_pch_transcoder(intel_crtc);
12978
12979                         intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
12980                 }
12981         }
12982 }
12983
12984 /**
12985  * intel_plane_destroy - destroy a plane
12986  * @plane: plane to destroy
12987  *
12988  * Common destruction function for all types of planes (primary, cursor,
12989  * sprite).
12990  */
12991 void intel_plane_destroy(struct drm_plane *plane)
12992 {
12993         drm_plane_cleanup(plane);
12994         kfree(to_intel_plane(plane));
12995 }
12996
12997 static bool i8xx_mod_supported(uint32_t format, uint64_t modifier)
12998 {
12999         switch (format) {
13000         case DRM_FORMAT_C8:
13001         case DRM_FORMAT_RGB565:
13002         case DRM_FORMAT_XRGB1555:
13003         case DRM_FORMAT_XRGB8888:
13004                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13005                         modifier == I915_FORMAT_MOD_X_TILED;
13006         default:
13007                 return false;
13008         }
13009 }
13010
13011 static bool i965_mod_supported(uint32_t format, uint64_t modifier)
13012 {
13013         switch (format) {
13014         case DRM_FORMAT_C8:
13015         case DRM_FORMAT_RGB565:
13016         case DRM_FORMAT_XRGB8888:
13017         case DRM_FORMAT_XBGR8888:
13018         case DRM_FORMAT_XRGB2101010:
13019         case DRM_FORMAT_XBGR2101010:
13020                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13021                         modifier == I915_FORMAT_MOD_X_TILED;
13022         default:
13023                 return false;
13024         }
13025 }
13026
13027 static bool skl_mod_supported(uint32_t format, uint64_t modifier)
13028 {
13029         switch (format) {
13030         case DRM_FORMAT_XRGB8888:
13031         case DRM_FORMAT_XBGR8888:
13032         case DRM_FORMAT_ARGB8888:
13033         case DRM_FORMAT_ABGR8888:
13034                 if (modifier == I915_FORMAT_MOD_Yf_TILED_CCS ||
13035                     modifier == I915_FORMAT_MOD_Y_TILED_CCS)
13036                         return true;
13037                 /* fall through */
13038         case DRM_FORMAT_RGB565:
13039         case DRM_FORMAT_XRGB2101010:
13040         case DRM_FORMAT_XBGR2101010:
13041         case DRM_FORMAT_YUYV:
13042         case DRM_FORMAT_YVYU:
13043         case DRM_FORMAT_UYVY:
13044         case DRM_FORMAT_VYUY:
13045                 if (modifier == I915_FORMAT_MOD_Yf_TILED)
13046                         return true;
13047                 /* fall through */
13048         case DRM_FORMAT_C8:
13049                 if (modifier == DRM_FORMAT_MOD_LINEAR ||
13050                     modifier == I915_FORMAT_MOD_X_TILED ||
13051                     modifier == I915_FORMAT_MOD_Y_TILED)
13052                         return true;
13053                 /* fall through */
13054         default:
13055                 return false;
13056         }
13057 }
13058
13059 static bool intel_primary_plane_format_mod_supported(struct drm_plane *plane,
13060                                                      uint32_t format,
13061                                                      uint64_t modifier)
13062 {
13063         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13064
13065         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13066                 return false;
13067
13068         if ((modifier >> 56) != DRM_FORMAT_MOD_VENDOR_INTEL &&
13069             modifier != DRM_FORMAT_MOD_LINEAR)
13070                 return false;
13071
13072         if (INTEL_GEN(dev_priv) >= 9)
13073                 return skl_mod_supported(format, modifier);
13074         else if (INTEL_GEN(dev_priv) >= 4)
13075                 return i965_mod_supported(format, modifier);
13076         else
13077                 return i8xx_mod_supported(format, modifier);
13078 }
13079
13080 static bool intel_cursor_plane_format_mod_supported(struct drm_plane *plane,
13081                                                     uint32_t format,
13082                                                     uint64_t modifier)
13083 {
13084         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13085                 return false;
13086
13087         return modifier == DRM_FORMAT_MOD_LINEAR && format == DRM_FORMAT_ARGB8888;
13088 }
13089
13090 static struct drm_plane_funcs intel_plane_funcs = {
13091         .update_plane = drm_atomic_helper_update_plane,
13092         .disable_plane = drm_atomic_helper_disable_plane,
13093         .destroy = intel_plane_destroy,
13094         .atomic_get_property = intel_plane_atomic_get_property,
13095         .atomic_set_property = intel_plane_atomic_set_property,
13096         .atomic_duplicate_state = intel_plane_duplicate_state,
13097         .atomic_destroy_state = intel_plane_destroy_state,
13098         .format_mod_supported = intel_primary_plane_format_mod_supported,
13099 };
13100
13101 static int
13102 intel_legacy_cursor_update(struct drm_plane *plane,
13103                            struct drm_crtc *crtc,
13104                            struct drm_framebuffer *fb,
13105                            int crtc_x, int crtc_y,
13106                            unsigned int crtc_w, unsigned int crtc_h,
13107                            uint32_t src_x, uint32_t src_y,
13108                            uint32_t src_w, uint32_t src_h,
13109                            struct drm_modeset_acquire_ctx *ctx)
13110 {
13111         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13112         int ret;
13113         struct drm_plane_state *old_plane_state, *new_plane_state;
13114         struct intel_plane *intel_plane = to_intel_plane(plane);
13115         struct drm_framebuffer *old_fb;
13116         struct drm_crtc_state *crtc_state = crtc->state;
13117
13118         /*
13119          * When crtc is inactive or there is a modeset pending,
13120          * wait for it to complete in the slowpath
13121          */
13122         if (!crtc_state->active || needs_modeset(crtc_state) ||
13123             to_intel_crtc_state(crtc_state)->update_pipe)
13124                 goto slow;
13125
13126         old_plane_state = plane->state;
13127         /*
13128          * Don't do an async update if there is an outstanding commit modifying
13129          * the plane.  This prevents our async update's changes from getting
13130          * overridden by a previous synchronous update's state.
13131          */
13132         if (old_plane_state->commit &&
13133             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13134                 goto slow;
13135
13136         /*
13137          * If any parameters change that may affect watermarks,
13138          * take the slowpath. Only changing fb or position should be
13139          * in the fastpath.
13140          */
13141         if (old_plane_state->crtc != crtc ||
13142             old_plane_state->src_w != src_w ||
13143             old_plane_state->src_h != src_h ||
13144             old_plane_state->crtc_w != crtc_w ||
13145             old_plane_state->crtc_h != crtc_h ||
13146             !old_plane_state->fb != !fb)
13147                 goto slow;
13148
13149         new_plane_state = intel_plane_duplicate_state(plane);
13150         if (!new_plane_state)
13151                 return -ENOMEM;
13152
13153         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13154
13155         new_plane_state->src_x = src_x;
13156         new_plane_state->src_y = src_y;
13157         new_plane_state->src_w = src_w;
13158         new_plane_state->src_h = src_h;
13159         new_plane_state->crtc_x = crtc_x;
13160         new_plane_state->crtc_y = crtc_y;
13161         new_plane_state->crtc_w = crtc_w;
13162         new_plane_state->crtc_h = crtc_h;
13163
13164         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13165                                                   to_intel_crtc_state(crtc->state), /* FIXME need a new crtc state? */
13166                                                   to_intel_plane_state(plane->state),
13167                                                   to_intel_plane_state(new_plane_state));
13168         if (ret)
13169                 goto out_free;
13170
13171         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13172         if (ret)
13173                 goto out_free;
13174
13175         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13176         if (ret)
13177                 goto out_unlock;
13178
13179         old_fb = old_plane_state->fb;
13180
13181         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13182                           intel_plane->frontbuffer_bit);
13183
13184         /* Swap plane state */
13185         plane->state = new_plane_state;
13186
13187         if (plane->state->visible) {
13188                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13189                 intel_plane->update_plane(intel_plane,
13190                                           to_intel_crtc_state(crtc->state),
13191                                           to_intel_plane_state(plane->state));
13192         } else {
13193                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13194                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13195         }
13196
13197         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13198
13199 out_unlock:
13200         mutex_unlock(&dev_priv->drm.struct_mutex);
13201 out_free:
13202         if (ret)
13203                 intel_plane_destroy_state(plane, new_plane_state);
13204         else
13205                 intel_plane_destroy_state(plane, old_plane_state);
13206         return ret;
13207
13208 slow:
13209         return drm_atomic_helper_update_plane(plane, crtc, fb,
13210                                               crtc_x, crtc_y, crtc_w, crtc_h,
13211                                               src_x, src_y, src_w, src_h, ctx);
13212 }
13213
13214 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13215         .update_plane = intel_legacy_cursor_update,
13216         .disable_plane = drm_atomic_helper_disable_plane,
13217         .destroy = intel_plane_destroy,
13218         .atomic_get_property = intel_plane_atomic_get_property,
13219         .atomic_set_property = intel_plane_atomic_set_property,
13220         .atomic_duplicate_state = intel_plane_duplicate_state,
13221         .atomic_destroy_state = intel_plane_destroy_state,
13222         .format_mod_supported = intel_cursor_plane_format_mod_supported,
13223 };
13224
13225 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13226                                enum i9xx_plane_id i9xx_plane)
13227 {
13228         if (!HAS_FBC(dev_priv))
13229                 return false;
13230
13231         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13232                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13233         else if (IS_IVYBRIDGE(dev_priv))
13234                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13235                         i9xx_plane == PLANE_C;
13236         else if (INTEL_GEN(dev_priv) >= 4)
13237                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13238         else
13239                 return i9xx_plane == PLANE_A;
13240 }
13241
13242 static bool skl_plane_has_fbc(struct drm_i915_private *dev_priv,
13243                               enum pipe pipe, enum plane_id plane_id)
13244 {
13245         if (!HAS_FBC(dev_priv))
13246                 return false;
13247
13248         return pipe == PIPE_A && plane_id == PLANE_PRIMARY;
13249 }
13250
13251 static struct intel_plane *
13252 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13253 {
13254         struct intel_plane *primary = NULL;
13255         struct intel_plane_state *state = NULL;
13256         const uint32_t *intel_primary_formats;
13257         unsigned int supported_rotations;
13258         unsigned int num_formats;
13259         const uint64_t *modifiers;
13260         int ret;
13261
13262         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13263         if (!primary) {
13264                 ret = -ENOMEM;
13265                 goto fail;
13266         }
13267
13268         state = intel_create_plane_state(&primary->base);
13269         if (!state) {
13270                 ret = -ENOMEM;
13271                 goto fail;
13272         }
13273
13274         primary->base.state = &state->base;
13275
13276         primary->can_scale = false;
13277         primary->max_downscale = 1;
13278         if (INTEL_GEN(dev_priv) >= 9) {
13279                 primary->can_scale = true;
13280                 state->scaler_id = -1;
13281         }
13282         primary->pipe = pipe;
13283         /*
13284          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13285          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13286          */
13287         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13288                 primary->i9xx_plane = (enum i9xx_plane_id) !pipe;
13289         else
13290                 primary->i9xx_plane = (enum i9xx_plane_id) pipe;
13291         primary->id = PLANE_PRIMARY;
13292         primary->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, primary->id);
13293
13294         if (INTEL_GEN(dev_priv) >= 9)
13295                 primary->has_fbc = skl_plane_has_fbc(dev_priv,
13296                                                      primary->pipe,
13297                                                      primary->id);
13298         else
13299                 primary->has_fbc = i9xx_plane_has_fbc(dev_priv,
13300                                                       primary->i9xx_plane);
13301
13302         if (primary->has_fbc) {
13303                 struct intel_fbc *fbc = &dev_priv->fbc;
13304
13305                 fbc->possible_framebuffer_bits |= primary->frontbuffer_bit;
13306         }
13307
13308         primary->check_plane = intel_check_primary_plane;
13309
13310         if (INTEL_GEN(dev_priv) >= 9) {
13311                 intel_primary_formats = skl_primary_formats;
13312                 num_formats = ARRAY_SIZE(skl_primary_formats);
13313
13314                 if (skl_plane_has_ccs(dev_priv, pipe, PLANE_PRIMARY))
13315                         modifiers = skl_format_modifiers_ccs;
13316                 else
13317                         modifiers = skl_format_modifiers_noccs;
13318
13319                 primary->update_plane = skl_update_plane;
13320                 primary->disable_plane = skl_disable_plane;
13321                 primary->get_hw_state = skl_plane_get_hw_state;
13322         } else if (INTEL_GEN(dev_priv) >= 4) {
13323                 intel_primary_formats = i965_primary_formats;
13324                 num_formats = ARRAY_SIZE(i965_primary_formats);
13325                 modifiers = i9xx_format_modifiers;
13326
13327                 primary->update_plane = i9xx_update_plane;
13328                 primary->disable_plane = i9xx_disable_plane;
13329                 primary->get_hw_state = i9xx_plane_get_hw_state;
13330         } else {
13331                 intel_primary_formats = i8xx_primary_formats;
13332                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13333                 modifiers = i9xx_format_modifiers;
13334
13335                 primary->update_plane = i9xx_update_plane;
13336                 primary->disable_plane = i9xx_disable_plane;
13337                 primary->get_hw_state = i9xx_plane_get_hw_state;
13338         }
13339
13340         if (INTEL_GEN(dev_priv) >= 9)
13341                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13342                                                0, &intel_plane_funcs,
13343                                                intel_primary_formats, num_formats,
13344                                                modifiers,
13345                                                DRM_PLANE_TYPE_PRIMARY,
13346                                                "plane 1%c", pipe_name(pipe));
13347         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13348                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13349                                                0, &intel_plane_funcs,
13350                                                intel_primary_formats, num_formats,
13351                                                modifiers,
13352                                                DRM_PLANE_TYPE_PRIMARY,
13353                                                "primary %c", pipe_name(pipe));
13354         else
13355                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13356                                                0, &intel_plane_funcs,
13357                                                intel_primary_formats, num_formats,
13358                                                modifiers,
13359                                                DRM_PLANE_TYPE_PRIMARY,
13360                                                "plane %c",
13361                                                plane_name(primary->i9xx_plane));
13362         if (ret)
13363                 goto fail;
13364
13365         if (INTEL_GEN(dev_priv) >= 10) {
13366                 supported_rotations =
13367                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13368                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270 |
13369                         DRM_MODE_REFLECT_X;
13370         } else if (INTEL_GEN(dev_priv) >= 9) {
13371                 supported_rotations =
13372                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13373                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13374         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13375                 supported_rotations =
13376                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13377                         DRM_MODE_REFLECT_X;
13378         } else if (INTEL_GEN(dev_priv) >= 4) {
13379                 supported_rotations =
13380                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13381         } else {
13382                 supported_rotations = DRM_MODE_ROTATE_0;
13383         }
13384
13385         if (INTEL_GEN(dev_priv) >= 4)
13386                 drm_plane_create_rotation_property(&primary->base,
13387                                                    DRM_MODE_ROTATE_0,
13388                                                    supported_rotations);
13389
13390         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13391
13392         return primary;
13393
13394 fail:
13395         kfree(state);
13396         kfree(primary);
13397
13398         return ERR_PTR(ret);
13399 }
13400
13401 static struct intel_plane *
13402 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13403                           enum pipe pipe)
13404 {
13405         struct intel_plane *cursor = NULL;
13406         struct intel_plane_state *state = NULL;
13407         int ret;
13408
13409         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13410         if (!cursor) {
13411                 ret = -ENOMEM;
13412                 goto fail;
13413         }
13414
13415         state = intel_create_plane_state(&cursor->base);
13416         if (!state) {
13417                 ret = -ENOMEM;
13418                 goto fail;
13419         }
13420
13421         cursor->base.state = &state->base;
13422
13423         cursor->can_scale = false;
13424         cursor->max_downscale = 1;
13425         cursor->pipe = pipe;
13426         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13427         cursor->id = PLANE_CURSOR;
13428         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13429
13430         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13431                 cursor->update_plane = i845_update_cursor;
13432                 cursor->disable_plane = i845_disable_cursor;
13433                 cursor->get_hw_state = i845_cursor_get_hw_state;
13434                 cursor->check_plane = i845_check_cursor;
13435         } else {
13436                 cursor->update_plane = i9xx_update_cursor;
13437                 cursor->disable_plane = i9xx_disable_cursor;
13438                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13439                 cursor->check_plane = i9xx_check_cursor;
13440         }
13441
13442         cursor->cursor.base = ~0;
13443         cursor->cursor.cntl = ~0;
13444
13445         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13446                 cursor->cursor.size = ~0;
13447
13448         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13449                                        0, &intel_cursor_plane_funcs,
13450                                        intel_cursor_formats,
13451                                        ARRAY_SIZE(intel_cursor_formats),
13452                                        cursor_format_modifiers,
13453                                        DRM_PLANE_TYPE_CURSOR,
13454                                        "cursor %c", pipe_name(pipe));
13455         if (ret)
13456                 goto fail;
13457
13458         if (INTEL_GEN(dev_priv) >= 4)
13459                 drm_plane_create_rotation_property(&cursor->base,
13460                                                    DRM_MODE_ROTATE_0,
13461                                                    DRM_MODE_ROTATE_0 |
13462                                                    DRM_MODE_ROTATE_180);
13463
13464         if (INTEL_GEN(dev_priv) >= 9)
13465                 state->scaler_id = -1;
13466
13467         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13468
13469         return cursor;
13470
13471 fail:
13472         kfree(state);
13473         kfree(cursor);
13474
13475         return ERR_PTR(ret);
13476 }
13477
13478 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13479                                     struct intel_crtc_state *crtc_state)
13480 {
13481         struct intel_crtc_scaler_state *scaler_state =
13482                 &crtc_state->scaler_state;
13483         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13484         int i;
13485
13486         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13487         if (!crtc->num_scalers)
13488                 return;
13489
13490         for (i = 0; i < crtc->num_scalers; i++) {
13491                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13492
13493                 scaler->in_use = 0;
13494                 scaler->mode = PS_SCALER_MODE_DYN;
13495         }
13496
13497         scaler_state->scaler_id = -1;
13498 }
13499
13500 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13501 {
13502         struct intel_crtc *intel_crtc;
13503         struct intel_crtc_state *crtc_state = NULL;
13504         struct intel_plane *primary = NULL;
13505         struct intel_plane *cursor = NULL;
13506         int sprite, ret;
13507
13508         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13509         if (!intel_crtc)
13510                 return -ENOMEM;
13511
13512         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13513         if (!crtc_state) {
13514                 ret = -ENOMEM;
13515                 goto fail;
13516         }
13517         intel_crtc->config = crtc_state;
13518         intel_crtc->base.state = &crtc_state->base;
13519         crtc_state->base.crtc = &intel_crtc->base;
13520
13521         primary = intel_primary_plane_create(dev_priv, pipe);
13522         if (IS_ERR(primary)) {
13523                 ret = PTR_ERR(primary);
13524                 goto fail;
13525         }
13526         intel_crtc->plane_ids_mask |= BIT(primary->id);
13527
13528         for_each_sprite(dev_priv, pipe, sprite) {
13529                 struct intel_plane *plane;
13530
13531                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13532                 if (IS_ERR(plane)) {
13533                         ret = PTR_ERR(plane);
13534                         goto fail;
13535                 }
13536                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13537         }
13538
13539         cursor = intel_cursor_plane_create(dev_priv, pipe);
13540         if (IS_ERR(cursor)) {
13541                 ret = PTR_ERR(cursor);
13542                 goto fail;
13543         }
13544         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13545
13546         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13547                                         &primary->base, &cursor->base,
13548                                         &intel_crtc_funcs,
13549                                         "pipe %c", pipe_name(pipe));
13550         if (ret)
13551                 goto fail;
13552
13553         intel_crtc->pipe = pipe;
13554
13555         /* initialize shared scalers */
13556         intel_crtc_init_scalers(intel_crtc, crtc_state);
13557
13558         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13559                dev_priv->plane_to_crtc_mapping[primary->i9xx_plane] != NULL);
13560         dev_priv->plane_to_crtc_mapping[primary->i9xx_plane] = intel_crtc;
13561         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = intel_crtc;
13562
13563         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13564
13565         intel_color_init(&intel_crtc->base);
13566
13567         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13568
13569         return 0;
13570
13571 fail:
13572         /*
13573          * drm_mode_config_cleanup() will free up any
13574          * crtcs/planes already initialized.
13575          */
13576         kfree(crtc_state);
13577         kfree(intel_crtc);
13578
13579         return ret;
13580 }
13581
13582 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13583 {
13584         struct drm_device *dev = connector->base.dev;
13585
13586         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13587
13588         if (!connector->base.state->crtc)
13589                 return INVALID_PIPE;
13590
13591         return to_intel_crtc(connector->base.state->crtc)->pipe;
13592 }
13593
13594 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
13595                                       struct drm_file *file)
13596 {
13597         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13598         struct drm_crtc *drmmode_crtc;
13599         struct intel_crtc *crtc;
13600
13601         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
13602         if (!drmmode_crtc)
13603                 return -ENOENT;
13604
13605         crtc = to_intel_crtc(drmmode_crtc);
13606         pipe_from_crtc_id->pipe = crtc->pipe;
13607
13608         return 0;
13609 }
13610
13611 static int intel_encoder_clones(struct intel_encoder *encoder)
13612 {
13613         struct drm_device *dev = encoder->base.dev;
13614         struct intel_encoder *source_encoder;
13615         int index_mask = 0;
13616         int entry = 0;
13617
13618         for_each_intel_encoder(dev, source_encoder) {
13619                 if (encoders_cloneable(encoder, source_encoder))
13620                         index_mask |= (1 << entry);
13621
13622                 entry++;
13623         }
13624
13625         return index_mask;
13626 }
13627
13628 static bool has_edp_a(struct drm_i915_private *dev_priv)
13629 {
13630         if (!IS_MOBILE(dev_priv))
13631                 return false;
13632
13633         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13634                 return false;
13635
13636         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13637                 return false;
13638
13639         return true;
13640 }
13641
13642 static bool intel_crt_present(struct drm_i915_private *dev_priv)
13643 {
13644         if (INTEL_GEN(dev_priv) >= 9)
13645                 return false;
13646
13647         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
13648                 return false;
13649
13650         if (IS_CHERRYVIEW(dev_priv))
13651                 return false;
13652
13653         if (HAS_PCH_LPT_H(dev_priv) &&
13654             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
13655                 return false;
13656
13657         /* DDI E can't be used if DDI A requires 4 lanes */
13658         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
13659                 return false;
13660
13661         if (!dev_priv->vbt.int_crt_support)
13662                 return false;
13663
13664         return true;
13665 }
13666
13667 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
13668 {
13669         int pps_num;
13670         int pps_idx;
13671
13672         if (HAS_DDI(dev_priv))
13673                 return;
13674         /*
13675          * This w/a is needed at least on CPT/PPT, but to be sure apply it
13676          * everywhere where registers can be write protected.
13677          */
13678         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13679                 pps_num = 2;
13680         else
13681                 pps_num = 1;
13682
13683         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
13684                 u32 val = I915_READ(PP_CONTROL(pps_idx));
13685
13686                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
13687                 I915_WRITE(PP_CONTROL(pps_idx), val);
13688         }
13689 }
13690
13691 static void intel_pps_init(struct drm_i915_private *dev_priv)
13692 {
13693         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
13694                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
13695         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13696                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
13697         else
13698                 dev_priv->pps_mmio_base = PPS_BASE;
13699
13700         intel_pps_unlock_regs_wa(dev_priv);
13701 }
13702
13703 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
13704 {
13705         struct intel_encoder *encoder;
13706         bool dpd_is_edp = false;
13707
13708         intel_pps_init(dev_priv);
13709
13710         /*
13711          * intel_edp_init_connector() depends on this completing first, to
13712          * prevent the registeration of both eDP and LVDS and the incorrect
13713          * sharing of the PPS.
13714          */
13715         intel_lvds_init(dev_priv);
13716
13717         if (intel_crt_present(dev_priv))
13718                 intel_crt_init(dev_priv);
13719
13720         if (IS_GEN9_LP(dev_priv)) {
13721                 /*
13722                  * FIXME: Broxton doesn't support port detection via the
13723                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13724                  * detect the ports.
13725                  */
13726                 intel_ddi_init(dev_priv, PORT_A);
13727                 intel_ddi_init(dev_priv, PORT_B);
13728                 intel_ddi_init(dev_priv, PORT_C);
13729
13730                 intel_dsi_init(dev_priv);
13731         } else if (HAS_DDI(dev_priv)) {
13732                 int found;
13733
13734                 /*
13735                  * Haswell uses DDI functions to detect digital outputs.
13736                  * On SKL pre-D0 the strap isn't connected, so we assume
13737                  * it's there.
13738                  */
13739                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
13740                 /* WaIgnoreDDIAStrap: skl */
13741                 if (found || IS_GEN9_BC(dev_priv))
13742                         intel_ddi_init(dev_priv, PORT_A);
13743
13744                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
13745                  * register */
13746                 found = I915_READ(SFUSE_STRAP);
13747
13748                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13749                         intel_ddi_init(dev_priv, PORT_B);
13750                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13751                         intel_ddi_init(dev_priv, PORT_C);
13752                 if (found & SFUSE_STRAP_DDID_DETECTED)
13753                         intel_ddi_init(dev_priv, PORT_D);
13754                 if (found & SFUSE_STRAP_DDIF_DETECTED)
13755                         intel_ddi_init(dev_priv, PORT_F);
13756                 /*
13757                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
13758                  */
13759                 if (IS_GEN9_BC(dev_priv) &&
13760                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
13761                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
13762                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
13763                         intel_ddi_init(dev_priv, PORT_E);
13764
13765         } else if (HAS_PCH_SPLIT(dev_priv)) {
13766                 int found;
13767                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
13768
13769                 if (has_edp_a(dev_priv))
13770                         intel_dp_init(dev_priv, DP_A, PORT_A);
13771
13772                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13773                         /* PCH SDVOB multiplex with HDMIB */
13774                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
13775                         if (!found)
13776                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
13777                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13778                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
13779                 }
13780
13781                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13782                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
13783
13784                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13785                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
13786
13787                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13788                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
13789
13790                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13791                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
13792         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
13793                 bool has_edp, has_port;
13794
13795                 /*
13796                  * The DP_DETECTED bit is the latched state of the DDC
13797                  * SDA pin at boot. However since eDP doesn't require DDC
13798                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13799                  * eDP ports may have been muxed to an alternate function.
13800                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13801                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13802                  * detect eDP ports.
13803                  *
13804                  * Sadly the straps seem to be missing sometimes even for HDMI
13805                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
13806                  * and VBT for the presence of the port. Additionally we can't
13807                  * trust the port type the VBT declares as we've seen at least
13808                  * HDMI ports that the VBT claim are DP or eDP.
13809                  */
13810                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
13811                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
13812                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
13813                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
13814                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
13815                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
13816
13817                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
13818                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
13819                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
13820                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
13821                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
13822                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
13823
13824                 if (IS_CHERRYVIEW(dev_priv)) {
13825                         /*
13826                          * eDP not supported on port D,
13827                          * so no need to worry about it
13828                          */
13829                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
13830                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
13831                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
13832                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
13833                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
13834                 }
13835
13836                 intel_dsi_init(dev_priv);
13837         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
13838                 bool found = false;
13839
13840                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13841                         DRM_DEBUG_KMS("probing SDVOB\n");
13842                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
13843                         if (!found && IS_G4X(dev_priv)) {
13844                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
13845                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
13846                         }
13847
13848                         if (!found && IS_G4X(dev_priv))
13849                                 intel_dp_init(dev_priv, DP_B, PORT_B);
13850                 }
13851
13852                 /* Before G4X SDVOC doesn't have its own detect register */
13853
13854                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13855                         DRM_DEBUG_KMS("probing SDVOC\n");
13856                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
13857                 }
13858
13859                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
13860
13861                         if (IS_G4X(dev_priv)) {
13862                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
13863                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
13864                         }
13865                         if (IS_G4X(dev_priv))
13866                                 intel_dp_init(dev_priv, DP_C, PORT_C);
13867                 }
13868
13869                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
13870                         intel_dp_init(dev_priv, DP_D, PORT_D);
13871         } else if (IS_GEN2(dev_priv))
13872                 intel_dvo_init(dev_priv);
13873
13874         if (SUPPORTS_TV(dev_priv))
13875                 intel_tv_init(dev_priv);
13876
13877         intel_psr_init(dev_priv);
13878
13879         for_each_intel_encoder(&dev_priv->drm, encoder) {
13880                 encoder->base.possible_crtcs = encoder->crtc_mask;
13881                 encoder->base.possible_clones =
13882                         intel_encoder_clones(encoder);
13883         }
13884
13885         intel_init_pch_refclk(dev_priv);
13886
13887         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
13888 }
13889
13890 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
13891 {
13892         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13893
13894         drm_framebuffer_cleanup(fb);
13895
13896         i915_gem_object_lock(intel_fb->obj);
13897         WARN_ON(!intel_fb->obj->framebuffer_references--);
13898         i915_gem_object_unlock(intel_fb->obj);
13899
13900         i915_gem_object_put(intel_fb->obj);
13901
13902         kfree(intel_fb);
13903 }
13904
13905 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
13906                                                 struct drm_file *file,
13907                                                 unsigned int *handle)
13908 {
13909         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13910         struct drm_i915_gem_object *obj = intel_fb->obj;
13911
13912         if (obj->userptr.mm) {
13913                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
13914                 return -EINVAL;
13915         }
13916
13917         return drm_gem_handle_create(file, &obj->base, handle);
13918 }
13919
13920 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
13921                                         struct drm_file *file,
13922                                         unsigned flags, unsigned color,
13923                                         struct drm_clip_rect *clips,
13924                                         unsigned num_clips)
13925 {
13926         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13927
13928         i915_gem_object_flush_if_display(obj);
13929         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13930
13931         return 0;
13932 }
13933
13934 static const struct drm_framebuffer_funcs intel_fb_funcs = {
13935         .destroy = intel_user_framebuffer_destroy,
13936         .create_handle = intel_user_framebuffer_create_handle,
13937         .dirty = intel_user_framebuffer_dirty,
13938 };
13939
13940 static
13941 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
13942                          uint64_t fb_modifier, uint32_t pixel_format)
13943 {
13944         u32 gen = INTEL_GEN(dev_priv);
13945
13946         if (gen >= 9) {
13947                 int cpp = drm_format_plane_cpp(pixel_format, 0);
13948
13949                 /* "The stride in bytes must not exceed the of the size of 8K
13950                  *  pixels and 32K bytes."
13951                  */
13952                 return min(8192 * cpp, 32768);
13953         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
13954                 return 32*1024;
13955         } else if (gen >= 4) {
13956                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13957                         return 16*1024;
13958                 else
13959                         return 32*1024;
13960         } else if (gen >= 3) {
13961                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13962                         return 8*1024;
13963                 else
13964                         return 16*1024;
13965         } else {
13966                 /* XXX DSPC is limited to 4k tiled */
13967                 return 8*1024;
13968         }
13969 }
13970
13971 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
13972                                   struct drm_i915_gem_object *obj,
13973                                   struct drm_mode_fb_cmd2 *mode_cmd)
13974 {
13975         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
13976         struct drm_framebuffer *fb = &intel_fb->base;
13977         struct drm_format_name_buf format_name;
13978         u32 pitch_limit;
13979         unsigned int tiling, stride;
13980         int ret = -EINVAL;
13981         int i;
13982
13983         i915_gem_object_lock(obj);
13984         obj->framebuffer_references++;
13985         tiling = i915_gem_object_get_tiling(obj);
13986         stride = i915_gem_object_get_stride(obj);
13987         i915_gem_object_unlock(obj);
13988
13989         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
13990                 /*
13991                  * If there's a fence, enforce that
13992                  * the fb modifier and tiling mode match.
13993                  */
13994                 if (tiling != I915_TILING_NONE &&
13995                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
13996                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
13997                         goto err;
13998                 }
13999         } else {
14000                 if (tiling == I915_TILING_X) {
14001                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14002                 } else if (tiling == I915_TILING_Y) {
14003                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14004                         goto err;
14005                 }
14006         }
14007
14008         /* Passed in modifier sanity checking. */
14009         switch (mode_cmd->modifier[0]) {
14010         case I915_FORMAT_MOD_Y_TILED_CCS:
14011         case I915_FORMAT_MOD_Yf_TILED_CCS:
14012                 switch (mode_cmd->pixel_format) {
14013                 case DRM_FORMAT_XBGR8888:
14014                 case DRM_FORMAT_ABGR8888:
14015                 case DRM_FORMAT_XRGB8888:
14016                 case DRM_FORMAT_ARGB8888:
14017                         break;
14018                 default:
14019                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
14020                         goto err;
14021                 }
14022                 /* fall through */
14023         case I915_FORMAT_MOD_Y_TILED:
14024         case I915_FORMAT_MOD_Yf_TILED:
14025                 if (INTEL_GEN(dev_priv) < 9) {
14026                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14027                                       mode_cmd->modifier[0]);
14028                         goto err;
14029                 }
14030         case DRM_FORMAT_MOD_LINEAR:
14031         case I915_FORMAT_MOD_X_TILED:
14032                 break;
14033         default:
14034                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14035                               mode_cmd->modifier[0]);
14036                 goto err;
14037         }
14038
14039         /*
14040          * gen2/3 display engine uses the fence if present,
14041          * so the tiling mode must match the fb modifier exactly.
14042          */
14043         if (INTEL_GEN(dev_priv) < 4 &&
14044             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14045                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14046                 goto err;
14047         }
14048
14049         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14050                                            mode_cmd->pixel_format);
14051         if (mode_cmd->pitches[0] > pitch_limit) {
14052                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14053                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14054                               "tiled" : "linear",
14055                               mode_cmd->pitches[0], pitch_limit);
14056                 goto err;
14057         }
14058
14059         /*
14060          * If there's a fence, enforce that
14061          * the fb pitch and fence stride match.
14062          */
14063         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14064                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14065                               mode_cmd->pitches[0], stride);
14066                 goto err;
14067         }
14068
14069         /* Reject formats not supported by any plane early. */
14070         switch (mode_cmd->pixel_format) {
14071         case DRM_FORMAT_C8:
14072         case DRM_FORMAT_RGB565:
14073         case DRM_FORMAT_XRGB8888:
14074         case DRM_FORMAT_ARGB8888:
14075                 break;
14076         case DRM_FORMAT_XRGB1555:
14077                 if (INTEL_GEN(dev_priv) > 3) {
14078                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14079                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14080                         goto err;
14081                 }
14082                 break;
14083         case DRM_FORMAT_ABGR8888:
14084                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14085                     INTEL_GEN(dev_priv) < 9) {
14086                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14087                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14088                         goto err;
14089                 }
14090                 break;
14091         case DRM_FORMAT_XBGR8888:
14092         case DRM_FORMAT_XRGB2101010:
14093         case DRM_FORMAT_XBGR2101010:
14094                 if (INTEL_GEN(dev_priv) < 4) {
14095                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14096                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14097                         goto err;
14098                 }
14099                 break;
14100         case DRM_FORMAT_ABGR2101010:
14101                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14102                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14103                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14104                         goto err;
14105                 }
14106                 break;
14107         case DRM_FORMAT_YUYV:
14108         case DRM_FORMAT_UYVY:
14109         case DRM_FORMAT_YVYU:
14110         case DRM_FORMAT_VYUY:
14111                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14112                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14113                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14114                         goto err;
14115                 }
14116                 break;
14117         default:
14118                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14119                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14120                 goto err;
14121         }
14122
14123         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14124         if (mode_cmd->offsets[0] != 0)
14125                 goto err;
14126
14127         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14128
14129         for (i = 0; i < fb->format->num_planes; i++) {
14130                 u32 stride_alignment;
14131
14132                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14133                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14134                         goto err;
14135                 }
14136
14137                 stride_alignment = intel_fb_stride_alignment(fb, i);
14138
14139                 /*
14140                  * Display WA #0531: skl,bxt,kbl,glk
14141                  *
14142                  * Render decompression and plane width > 3840
14143                  * combined with horizontal panning requires the
14144                  * plane stride to be a multiple of 4. We'll just
14145                  * require the entire fb to accommodate that to avoid
14146                  * potential runtime errors at plane configuration time.
14147                  */
14148                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14149                     (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
14150                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS))
14151                         stride_alignment *= 4;
14152
14153                 if (fb->pitches[i] & (stride_alignment - 1)) {
14154                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14155                                       i, fb->pitches[i], stride_alignment);
14156                         goto err;
14157                 }
14158         }
14159
14160         intel_fb->obj = obj;
14161
14162         ret = intel_fill_fb_info(dev_priv, fb);
14163         if (ret)
14164                 goto err;
14165
14166         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14167         if (ret) {
14168                 DRM_ERROR("framebuffer init failed %d\n", ret);
14169                 goto err;
14170         }
14171
14172         return 0;
14173
14174 err:
14175         i915_gem_object_lock(obj);
14176         obj->framebuffer_references--;
14177         i915_gem_object_unlock(obj);
14178         return ret;
14179 }
14180
14181 static struct drm_framebuffer *
14182 intel_user_framebuffer_create(struct drm_device *dev,
14183                               struct drm_file *filp,
14184                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14185 {
14186         struct drm_framebuffer *fb;
14187         struct drm_i915_gem_object *obj;
14188         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14189
14190         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14191         if (!obj)
14192                 return ERR_PTR(-ENOENT);
14193
14194         fb = intel_framebuffer_create(obj, &mode_cmd);
14195         if (IS_ERR(fb))
14196                 i915_gem_object_put(obj);
14197
14198         return fb;
14199 }
14200
14201 static void intel_atomic_state_free(struct drm_atomic_state *state)
14202 {
14203         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14204
14205         drm_atomic_state_default_release(state);
14206
14207         i915_sw_fence_fini(&intel_state->commit_ready);
14208
14209         kfree(state);
14210 }
14211
14212 static enum drm_mode_status
14213 intel_mode_valid(struct drm_device *dev,
14214                  const struct drm_display_mode *mode)
14215 {
14216         if (mode->vscan > 1)
14217                 return MODE_NO_VSCAN;
14218
14219         if (mode->flags & DRM_MODE_FLAG_DBLSCAN)
14220                 return MODE_NO_DBLESCAN;
14221
14222         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14223                 return MODE_H_ILLEGAL;
14224
14225         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14226                            DRM_MODE_FLAG_NCSYNC |
14227                            DRM_MODE_FLAG_PCSYNC))
14228                 return MODE_HSYNC;
14229
14230         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14231                            DRM_MODE_FLAG_PIXMUX |
14232                            DRM_MODE_FLAG_CLKDIV2))
14233                 return MODE_BAD;
14234
14235         return MODE_OK;
14236 }
14237
14238 static const struct drm_mode_config_funcs intel_mode_funcs = {
14239         .fb_create = intel_user_framebuffer_create,
14240         .get_format_info = intel_get_format_info,
14241         .output_poll_changed = intel_fbdev_output_poll_changed,
14242         .mode_valid = intel_mode_valid,
14243         .atomic_check = intel_atomic_check,
14244         .atomic_commit = intel_atomic_commit,
14245         .atomic_state_alloc = intel_atomic_state_alloc,
14246         .atomic_state_clear = intel_atomic_state_clear,
14247         .atomic_state_free = intel_atomic_state_free,
14248 };
14249
14250 /**
14251  * intel_init_display_hooks - initialize the display modesetting hooks
14252  * @dev_priv: device private
14253  */
14254 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14255 {
14256         intel_init_cdclk_hooks(dev_priv);
14257
14258         if (INTEL_GEN(dev_priv) >= 9) {
14259                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14260                 dev_priv->display.get_initial_plane_config =
14261                         skylake_get_initial_plane_config;
14262                 dev_priv->display.crtc_compute_clock =
14263                         haswell_crtc_compute_clock;
14264                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14265                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14266         } else if (HAS_DDI(dev_priv)) {
14267                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14268                 dev_priv->display.get_initial_plane_config =
14269                         i9xx_get_initial_plane_config;
14270                 dev_priv->display.crtc_compute_clock =
14271                         haswell_crtc_compute_clock;
14272                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14273                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14274         } else if (HAS_PCH_SPLIT(dev_priv)) {
14275                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14276                 dev_priv->display.get_initial_plane_config =
14277                         i9xx_get_initial_plane_config;
14278                 dev_priv->display.crtc_compute_clock =
14279                         ironlake_crtc_compute_clock;
14280                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14281                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14282         } else if (IS_CHERRYVIEW(dev_priv)) {
14283                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14284                 dev_priv->display.get_initial_plane_config =
14285                         i9xx_get_initial_plane_config;
14286                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14287                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14288                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14289         } else if (IS_VALLEYVIEW(dev_priv)) {
14290                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14291                 dev_priv->display.get_initial_plane_config =
14292                         i9xx_get_initial_plane_config;
14293                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14294                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14295                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14296         } else if (IS_G4X(dev_priv)) {
14297                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14298                 dev_priv->display.get_initial_plane_config =
14299                         i9xx_get_initial_plane_config;
14300                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14301                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14302                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14303         } else if (IS_PINEVIEW(dev_priv)) {
14304                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14305                 dev_priv->display.get_initial_plane_config =
14306                         i9xx_get_initial_plane_config;
14307                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14308                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14309                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14310         } else if (!IS_GEN2(dev_priv)) {
14311                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14312                 dev_priv->display.get_initial_plane_config =
14313                         i9xx_get_initial_plane_config;
14314                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14315                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14316                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14317         } else {
14318                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14319                 dev_priv->display.get_initial_plane_config =
14320                         i9xx_get_initial_plane_config;
14321                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14322                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14323                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14324         }
14325
14326         if (IS_GEN5(dev_priv)) {
14327                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14328         } else if (IS_GEN6(dev_priv)) {
14329                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14330         } else if (IS_IVYBRIDGE(dev_priv)) {
14331                 /* FIXME: detect B0+ stepping and use auto training */
14332                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14333         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14334                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14335         }
14336
14337         if (INTEL_GEN(dev_priv) >= 9)
14338                 dev_priv->display.update_crtcs = skl_update_crtcs;
14339         else
14340                 dev_priv->display.update_crtcs = intel_update_crtcs;
14341 }
14342
14343 /*
14344  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14345  */
14346 static void quirk_ssc_force_disable(struct drm_device *dev)
14347 {
14348         struct drm_i915_private *dev_priv = to_i915(dev);
14349         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14350         DRM_INFO("applying lvds SSC disable quirk\n");
14351 }
14352
14353 /*
14354  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14355  * brightness value
14356  */
14357 static void quirk_invert_brightness(struct drm_device *dev)
14358 {
14359         struct drm_i915_private *dev_priv = to_i915(dev);
14360         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14361         DRM_INFO("applying inverted panel brightness quirk\n");
14362 }
14363
14364 /* Some VBT's incorrectly indicate no backlight is present */
14365 static void quirk_backlight_present(struct drm_device *dev)
14366 {
14367         struct drm_i915_private *dev_priv = to_i915(dev);
14368         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14369         DRM_INFO("applying backlight present quirk\n");
14370 }
14371
14372 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14373  * which is 300 ms greater than eDP spec T12 min.
14374  */
14375 static void quirk_increase_t12_delay(struct drm_device *dev)
14376 {
14377         struct drm_i915_private *dev_priv = to_i915(dev);
14378
14379         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14380         DRM_INFO("Applying T12 delay quirk\n");
14381 }
14382
14383 struct intel_quirk {
14384         int device;
14385         int subsystem_vendor;
14386         int subsystem_device;
14387         void (*hook)(struct drm_device *dev);
14388 };
14389
14390 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14391 struct intel_dmi_quirk {
14392         void (*hook)(struct drm_device *dev);
14393         const struct dmi_system_id (*dmi_id_list)[];
14394 };
14395
14396 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14397 {
14398         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14399         return 1;
14400 }
14401
14402 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14403         {
14404                 .dmi_id_list = &(const struct dmi_system_id[]) {
14405                         {
14406                                 .callback = intel_dmi_reverse_brightness,
14407                                 .ident = "NCR Corporation",
14408                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14409                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14410                                 },
14411                         },
14412                         { }  /* terminating entry */
14413                 },
14414                 .hook = quirk_invert_brightness,
14415         },
14416 };
14417
14418 static struct intel_quirk intel_quirks[] = {
14419         /* Lenovo U160 cannot use SSC on LVDS */
14420         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14421
14422         /* Sony Vaio Y cannot use SSC on LVDS */
14423         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14424
14425         /* Acer Aspire 5734Z must invert backlight brightness */
14426         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14427
14428         /* Acer/eMachines G725 */
14429         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14430
14431         /* Acer/eMachines e725 */
14432         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14433
14434         /* Acer/Packard Bell NCL20 */
14435         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14436
14437         /* Acer Aspire 4736Z */
14438         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14439
14440         /* Acer Aspire 5336 */
14441         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14442
14443         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14444         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14445
14446         /* Acer C720 Chromebook (Core i3 4005U) */
14447         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14448
14449         /* Apple Macbook 2,1 (Core 2 T7400) */
14450         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14451
14452         /* Apple Macbook 4,1 */
14453         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14454
14455         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14456         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14457
14458         /* HP Chromebook 14 (Celeron 2955U) */
14459         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14460
14461         /* Dell Chromebook 11 */
14462         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14463
14464         /* Dell Chromebook 11 (2015 version) */
14465         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14466
14467         /* Toshiba Satellite P50-C-18C */
14468         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14469 };
14470
14471 static void intel_init_quirks(struct drm_device *dev)
14472 {
14473         struct pci_dev *d = dev->pdev;
14474         int i;
14475
14476         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14477                 struct intel_quirk *q = &intel_quirks[i];
14478
14479                 if (d->device == q->device &&
14480                     (d->subsystem_vendor == q->subsystem_vendor ||
14481                      q->subsystem_vendor == PCI_ANY_ID) &&
14482                     (d->subsystem_device == q->subsystem_device ||
14483                      q->subsystem_device == PCI_ANY_ID))
14484                         q->hook(dev);
14485         }
14486         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14487                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14488                         intel_dmi_quirks[i].hook(dev);
14489         }
14490 }
14491
14492 /* Disable the VGA plane that we never use */
14493 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14494 {
14495         struct pci_dev *pdev = dev_priv->drm.pdev;
14496         u8 sr1;
14497         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14498
14499         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14500         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14501         outb(SR01, VGA_SR_INDEX);
14502         sr1 = inb(VGA_SR_DATA);
14503         outb(sr1 | 1<<5, VGA_SR_DATA);
14504         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14505         udelay(300);
14506
14507         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14508         POSTING_READ(vga_reg);
14509 }
14510
14511 void intel_modeset_init_hw(struct drm_device *dev)
14512 {
14513         struct drm_i915_private *dev_priv = to_i915(dev);
14514
14515         intel_update_cdclk(dev_priv);
14516         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
14517         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14518 }
14519
14520 /*
14521  * Calculate what we think the watermarks should be for the state we've read
14522  * out of the hardware and then immediately program those watermarks so that
14523  * we ensure the hardware settings match our internal state.
14524  *
14525  * We can calculate what we think WM's should be by creating a duplicate of the
14526  * current state (which was constructed during hardware readout) and running it
14527  * through the atomic check code to calculate new watermark values in the
14528  * state object.
14529  */
14530 static void sanitize_watermarks(struct drm_device *dev)
14531 {
14532         struct drm_i915_private *dev_priv = to_i915(dev);
14533         struct drm_atomic_state *state;
14534         struct intel_atomic_state *intel_state;
14535         struct drm_crtc *crtc;
14536         struct drm_crtc_state *cstate;
14537         struct drm_modeset_acquire_ctx ctx;
14538         int ret;
14539         int i;
14540
14541         /* Only supported on platforms that use atomic watermark design */
14542         if (!dev_priv->display.optimize_watermarks)
14543                 return;
14544
14545         /*
14546          * We need to hold connection_mutex before calling duplicate_state so
14547          * that the connector loop is protected.
14548          */
14549         drm_modeset_acquire_init(&ctx, 0);
14550 retry:
14551         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14552         if (ret == -EDEADLK) {
14553                 drm_modeset_backoff(&ctx);
14554                 goto retry;
14555         } else if (WARN_ON(ret)) {
14556                 goto fail;
14557         }
14558
14559         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14560         if (WARN_ON(IS_ERR(state)))
14561                 goto fail;
14562
14563         intel_state = to_intel_atomic_state(state);
14564
14565         /*
14566          * Hardware readout is the only time we don't want to calculate
14567          * intermediate watermarks (since we don't trust the current
14568          * watermarks).
14569          */
14570         if (!HAS_GMCH_DISPLAY(dev_priv))
14571                 intel_state->skip_intermediate_wm = true;
14572
14573         ret = intel_atomic_check(dev, state);
14574         if (ret) {
14575                 /*
14576                  * If we fail here, it means that the hardware appears to be
14577                  * programmed in a way that shouldn't be possible, given our
14578                  * understanding of watermark requirements.  This might mean a
14579                  * mistake in the hardware readout code or a mistake in the
14580                  * watermark calculations for a given platform.  Raise a WARN
14581                  * so that this is noticeable.
14582                  *
14583                  * If this actually happens, we'll have to just leave the
14584                  * BIOS-programmed watermarks untouched and hope for the best.
14585                  */
14586                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14587                 goto put_state;
14588         }
14589
14590         /* Write calculated watermark values back */
14591         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14592                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14593
14594                 cs->wm.need_postvbl_update = true;
14595                 dev_priv->display.optimize_watermarks(intel_state, cs);
14596
14597                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
14598         }
14599
14600 put_state:
14601         drm_atomic_state_put(state);
14602 fail:
14603         drm_modeset_drop_locks(&ctx);
14604         drm_modeset_acquire_fini(&ctx);
14605 }
14606
14607 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
14608 {
14609         if (IS_GEN5(dev_priv)) {
14610                 u32 fdi_pll_clk =
14611                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
14612
14613                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
14614         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
14615                 dev_priv->fdi_pll_freq = 270000;
14616         } else {
14617                 return;
14618         }
14619
14620         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
14621 }
14622
14623 int intel_modeset_init(struct drm_device *dev)
14624 {
14625         struct drm_i915_private *dev_priv = to_i915(dev);
14626         struct i915_ggtt *ggtt = &dev_priv->ggtt;
14627         enum pipe pipe;
14628         struct intel_crtc *crtc;
14629
14630         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
14631
14632         drm_mode_config_init(dev);
14633
14634         dev->mode_config.min_width = 0;
14635         dev->mode_config.min_height = 0;
14636
14637         dev->mode_config.preferred_depth = 24;
14638         dev->mode_config.prefer_shadow = 1;
14639
14640         dev->mode_config.allow_fb_modifiers = true;
14641
14642         dev->mode_config.funcs = &intel_mode_funcs;
14643
14644         init_llist_head(&dev_priv->atomic_helper.free_list);
14645         INIT_WORK(&dev_priv->atomic_helper.free_work,
14646                   intel_atomic_helper_free_state_worker);
14647
14648         intel_init_quirks(dev);
14649
14650         intel_init_pm(dev_priv);
14651
14652         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14653                 return 0;
14654
14655         /*
14656          * There may be no VBT; and if the BIOS enabled SSC we can
14657          * just keep using it to avoid unnecessary flicker.  Whereas if the
14658          * BIOS isn't using it, don't assume it will work even if the VBT
14659          * indicates as much.
14660          */
14661         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
14662                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14663                                             DREF_SSC1_ENABLE);
14664
14665                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
14666                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
14667                                      bios_lvds_use_ssc ? "en" : "dis",
14668                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
14669                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
14670                 }
14671         }
14672
14673         if (IS_GEN2(dev_priv)) {
14674                 dev->mode_config.max_width = 2048;
14675                 dev->mode_config.max_height = 2048;
14676         } else if (IS_GEN3(dev_priv)) {
14677                 dev->mode_config.max_width = 4096;
14678                 dev->mode_config.max_height = 4096;
14679         } else {
14680                 dev->mode_config.max_width = 8192;
14681                 dev->mode_config.max_height = 8192;
14682         }
14683
14684         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14685                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
14686                 dev->mode_config.cursor_height = 1023;
14687         } else if (IS_GEN2(dev_priv)) {
14688                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14689                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14690         } else {
14691                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14692                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14693         }
14694
14695         dev->mode_config.fb_base = ggtt->gmadr.start;
14696
14697         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14698                       INTEL_INFO(dev_priv)->num_pipes,
14699                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
14700
14701         for_each_pipe(dev_priv, pipe) {
14702                 int ret;
14703
14704                 ret = intel_crtc_init(dev_priv, pipe);
14705                 if (ret) {
14706                         drm_mode_config_cleanup(dev);
14707                         return ret;
14708                 }
14709         }
14710
14711         intel_shared_dpll_init(dev);
14712         intel_update_fdi_pll_freq(dev_priv);
14713
14714         intel_update_czclk(dev_priv);
14715         intel_modeset_init_hw(dev);
14716
14717         if (dev_priv->max_cdclk_freq == 0)
14718                 intel_update_max_cdclk(dev_priv);
14719
14720         /* Just disable it once at startup */
14721         i915_disable_vga(dev_priv);
14722         intel_setup_outputs(dev_priv);
14723
14724         drm_modeset_lock_all(dev);
14725         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
14726         drm_modeset_unlock_all(dev);
14727
14728         for_each_intel_crtc(dev, crtc) {
14729                 struct intel_initial_plane_config plane_config = {};
14730
14731                 if (!crtc->active)
14732                         continue;
14733
14734                 /*
14735                  * Note that reserving the BIOS fb up front prevents us
14736                  * from stuffing other stolen allocations like the ring
14737                  * on top.  This prevents some ugliness at boot time, and
14738                  * can even allow for smooth boot transitions if the BIOS
14739                  * fb is large enough for the active pipe configuration.
14740                  */
14741                 dev_priv->display.get_initial_plane_config(crtc,
14742                                                            &plane_config);
14743
14744                 /*
14745                  * If the fb is shared between multiple heads, we'll
14746                  * just get the first one.
14747                  */
14748                 intel_find_initial_plane_obj(crtc, &plane_config);
14749         }
14750
14751         /*
14752          * Make sure hardware watermarks really match the state we read out.
14753          * Note that we need to do this after reconstructing the BIOS fb's
14754          * since the watermark calculation done here will use pstate->fb.
14755          */
14756         if (!HAS_GMCH_DISPLAY(dev_priv))
14757                 sanitize_watermarks(dev);
14758
14759         return 0;
14760 }
14761
14762 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14763 {
14764         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14765         /* 640x480@60Hz, ~25175 kHz */
14766         struct dpll clock = {
14767                 .m1 = 18,
14768                 .m2 = 7,
14769                 .p1 = 13,
14770                 .p2 = 4,
14771                 .n = 2,
14772         };
14773         u32 dpll, fp;
14774         int i;
14775
14776         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
14777
14778         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
14779                       pipe_name(pipe), clock.vco, clock.dot);
14780
14781         fp = i9xx_dpll_compute_fp(&clock);
14782         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
14783                 DPLL_VGA_MODE_DIS |
14784                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
14785                 PLL_P2_DIVIDE_BY_4 |
14786                 PLL_REF_INPUT_DREFCLK |
14787                 DPLL_VCO_ENABLE;
14788
14789         I915_WRITE(FP0(pipe), fp);
14790         I915_WRITE(FP1(pipe), fp);
14791
14792         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
14793         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
14794         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
14795         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
14796         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
14797         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
14798         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
14799
14800         /*
14801          * Apparently we need to have VGA mode enabled prior to changing
14802          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
14803          * dividers, even though the register value does change.
14804          */
14805         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
14806         I915_WRITE(DPLL(pipe), dpll);
14807
14808         /* Wait for the clocks to stabilize. */
14809         POSTING_READ(DPLL(pipe));
14810         udelay(150);
14811
14812         /* The pixel multiplier can only be updated once the
14813          * DPLL is enabled and the clocks are stable.
14814          *
14815          * So write it again.
14816          */
14817         I915_WRITE(DPLL(pipe), dpll);
14818
14819         /* We do this three times for luck */
14820         for (i = 0; i < 3 ; i++) {
14821                 I915_WRITE(DPLL(pipe), dpll);
14822                 POSTING_READ(DPLL(pipe));
14823                 udelay(150); /* wait for warmup */
14824         }
14825
14826         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
14827         POSTING_READ(PIPECONF(pipe));
14828
14829         intel_wait_for_pipe_scanline_moving(crtc);
14830 }
14831
14832 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14833 {
14834         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14835
14836         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
14837                       pipe_name(pipe));
14838
14839         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
14840         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
14841         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
14842         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & CURSOR_MODE);
14843         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & CURSOR_MODE);
14844
14845         I915_WRITE(PIPECONF(pipe), 0);
14846         POSTING_READ(PIPECONF(pipe));
14847
14848         intel_wait_for_pipe_scanline_stopped(crtc);
14849
14850         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
14851         POSTING_READ(DPLL(pipe));
14852 }
14853
14854 static bool intel_plane_mapping_ok(struct intel_crtc *crtc,
14855                                    struct intel_plane *plane)
14856 {
14857         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14858         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
14859         u32 val = I915_READ(DSPCNTR(i9xx_plane));
14860
14861         return (val & DISPLAY_PLANE_ENABLE) == 0 ||
14862                 (val & DISPPLANE_SEL_PIPE_MASK) == DISPPLANE_SEL_PIPE(crtc->pipe);
14863 }
14864
14865 static void
14866 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
14867 {
14868         struct intel_crtc *crtc;
14869
14870         if (INTEL_GEN(dev_priv) >= 4)
14871                 return;
14872
14873         for_each_intel_crtc(&dev_priv->drm, crtc) {
14874                 struct intel_plane *plane =
14875                         to_intel_plane(crtc->base.primary);
14876
14877                 if (intel_plane_mapping_ok(crtc, plane))
14878                         continue;
14879
14880                 DRM_DEBUG_KMS("%s attached to the wrong pipe, disabling plane\n",
14881                               plane->base.name);
14882                 intel_plane_disable_noatomic(crtc, plane);
14883         }
14884 }
14885
14886 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
14887 {
14888         struct drm_device *dev = crtc->base.dev;
14889         struct intel_encoder *encoder;
14890
14891         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14892                 return true;
14893
14894         return false;
14895 }
14896
14897 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
14898 {
14899         struct drm_device *dev = encoder->base.dev;
14900         struct intel_connector *connector;
14901
14902         for_each_connector_on_encoder(dev, &encoder->base, connector)
14903                 return connector;
14904
14905         return NULL;
14906 }
14907
14908 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
14909                               enum pipe pch_transcoder)
14910 {
14911         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
14912                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
14913 }
14914
14915 static void intel_sanitize_crtc(struct intel_crtc *crtc,
14916                                 struct drm_modeset_acquire_ctx *ctx)
14917 {
14918         struct drm_device *dev = crtc->base.dev;
14919         struct drm_i915_private *dev_priv = to_i915(dev);
14920         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
14921
14922         /* Clear any frame start delays used for debugging left by the BIOS */
14923         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
14924                 i915_reg_t reg = PIPECONF(cpu_transcoder);
14925
14926                 I915_WRITE(reg,
14927                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14928         }
14929
14930         /* restore vblank interrupts to correct state */
14931         drm_crtc_vblank_reset(&crtc->base);
14932         if (crtc->active) {
14933                 struct intel_plane *plane;
14934
14935                 drm_crtc_vblank_on(&crtc->base);
14936
14937                 /* Disable everything but the primary plane */
14938                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
14939                         const struct intel_plane_state *plane_state =
14940                                 to_intel_plane_state(plane->base.state);
14941
14942                         if (plane_state->base.visible &&
14943                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
14944                                 intel_plane_disable_noatomic(crtc, plane);
14945                 }
14946         }
14947
14948         /* Adjust the state of the output pipe according to whether we
14949          * have active connectors/encoders. */
14950         if (crtc->active && !intel_crtc_has_encoders(crtc))
14951                 intel_crtc_disable_noatomic(&crtc->base, ctx);
14952
14953         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
14954                 /*
14955                  * We start out with underrun reporting disabled to avoid races.
14956                  * For correct bookkeeping mark this on active crtcs.
14957                  *
14958                  * Also on gmch platforms we dont have any hardware bits to
14959                  * disable the underrun reporting. Which means we need to start
14960                  * out with underrun reporting disabled also on inactive pipes,
14961                  * since otherwise we'll complain about the garbage we read when
14962                  * e.g. coming up after runtime pm.
14963                  *
14964                  * No protection against concurrent access is required - at
14965                  * worst a fifo underrun happens which also sets this to false.
14966                  */
14967                 crtc->cpu_fifo_underrun_disabled = true;
14968                 /*
14969                  * We track the PCH trancoder underrun reporting state
14970                  * within the crtc. With crtc for pipe A housing the underrun
14971                  * reporting state for PCH transcoder A, crtc for pipe B housing
14972                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
14973                  * and marking underrun reporting as disabled for the non-existing
14974                  * PCH transcoders B and C would prevent enabling the south
14975                  * error interrupt (see cpt_can_enable_serr_int()).
14976                  */
14977                 if (has_pch_trancoder(dev_priv, crtc->pipe))
14978                         crtc->pch_fifo_underrun_disabled = true;
14979         }
14980 }
14981
14982 static void intel_sanitize_encoder(struct intel_encoder *encoder)
14983 {
14984         struct intel_connector *connector;
14985
14986         /* We need to check both for a crtc link (meaning that the
14987          * encoder is active and trying to read from a pipe) and the
14988          * pipe itself being active. */
14989         bool has_active_crtc = encoder->base.crtc &&
14990                 to_intel_crtc(encoder->base.crtc)->active;
14991
14992         connector = intel_encoder_find_connector(encoder);
14993         if (connector && !has_active_crtc) {
14994                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
14995                               encoder->base.base.id,
14996                               encoder->base.name);
14997
14998                 /* Connector is active, but has no active pipe. This is
14999                  * fallout from our resume register restoring. Disable
15000                  * the encoder manually again. */
15001                 if (encoder->base.crtc) {
15002                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15003
15004                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15005                                       encoder->base.base.id,
15006                                       encoder->base.name);
15007                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15008                         if (encoder->post_disable)
15009                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15010                 }
15011                 encoder->base.crtc = NULL;
15012
15013                 /* Inconsistent output/port/pipe state happens presumably due to
15014                  * a bug in one of the get_hw_state functions. Or someplace else
15015                  * in our code, like the register restore mess on resume. Clamp
15016                  * things to off as a safer default. */
15017
15018                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15019                 connector->base.encoder = NULL;
15020         }
15021 }
15022
15023 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15024 {
15025         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15026
15027         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15028                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15029                 i915_disable_vga(dev_priv);
15030         }
15031 }
15032
15033 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15034 {
15035         /* This function can be called both from intel_modeset_setup_hw_state or
15036          * at a very early point in our resume sequence, where the power well
15037          * structures are not yet restored. Since this function is at a very
15038          * paranoid "someone might have enabled VGA while we were not looking"
15039          * level, just check if the power well is enabled instead of trying to
15040          * follow the "don't touch the power well if we don't need it" policy
15041          * the rest of the driver uses. */
15042         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15043                 return;
15044
15045         i915_redisable_vga_power_on(dev_priv);
15046
15047         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15048 }
15049
15050 /* FIXME read out full plane state for all planes */
15051 static void readout_plane_state(struct intel_crtc *crtc)
15052 {
15053         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15054         struct intel_crtc_state *crtc_state =
15055                 to_intel_crtc_state(crtc->base.state);
15056         struct intel_plane *plane;
15057
15058         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
15059                 struct intel_plane_state *plane_state =
15060                         to_intel_plane_state(plane->base.state);
15061                 bool visible = plane->get_hw_state(plane);
15062
15063                 intel_set_plane_visible(crtc_state, plane_state, visible);
15064         }
15065 }
15066
15067 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15068 {
15069         struct drm_i915_private *dev_priv = to_i915(dev);
15070         enum pipe pipe;
15071         struct intel_crtc *crtc;
15072         struct intel_encoder *encoder;
15073         struct intel_connector *connector;
15074         struct drm_connector_list_iter conn_iter;
15075         int i;
15076
15077         dev_priv->active_crtcs = 0;
15078
15079         for_each_intel_crtc(dev, crtc) {
15080                 struct intel_crtc_state *crtc_state =
15081                         to_intel_crtc_state(crtc->base.state);
15082
15083                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15084                 memset(crtc_state, 0, sizeof(*crtc_state));
15085                 crtc_state->base.crtc = &crtc->base;
15086
15087                 crtc_state->base.active = crtc_state->base.enable =
15088                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15089
15090                 crtc->base.enabled = crtc_state->base.enable;
15091                 crtc->active = crtc_state->base.active;
15092
15093                 if (crtc_state->base.active)
15094                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15095
15096                 readout_plane_state(crtc);
15097
15098                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15099                               crtc->base.base.id, crtc->base.name,
15100                               enableddisabled(crtc_state->base.active));
15101         }
15102
15103         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15104                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15105
15106                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15107                                                   &pll->state.hw_state);
15108                 pll->state.crtc_mask = 0;
15109                 for_each_intel_crtc(dev, crtc) {
15110                         struct intel_crtc_state *crtc_state =
15111                                 to_intel_crtc_state(crtc->base.state);
15112
15113                         if (crtc_state->base.active &&
15114                             crtc_state->shared_dpll == pll)
15115                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15116                 }
15117                 pll->active_mask = pll->state.crtc_mask;
15118
15119                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15120                               pll->name, pll->state.crtc_mask, pll->on);
15121         }
15122
15123         for_each_intel_encoder(dev, encoder) {
15124                 pipe = 0;
15125
15126                 if (encoder->get_hw_state(encoder, &pipe)) {
15127                         struct intel_crtc_state *crtc_state;
15128
15129                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15130                         crtc_state = to_intel_crtc_state(crtc->base.state);
15131
15132                         encoder->base.crtc = &crtc->base;
15133                         encoder->get_config(encoder, crtc_state);
15134                 } else {
15135                         encoder->base.crtc = NULL;
15136                 }
15137
15138                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15139                               encoder->base.base.id, encoder->base.name,
15140                               enableddisabled(encoder->base.crtc),
15141                               pipe_name(pipe));
15142         }
15143
15144         drm_connector_list_iter_begin(dev, &conn_iter);
15145         for_each_intel_connector_iter(connector, &conn_iter) {
15146                 if (connector->get_hw_state(connector)) {
15147                         connector->base.dpms = DRM_MODE_DPMS_ON;
15148
15149                         encoder = connector->encoder;
15150                         connector->base.encoder = &encoder->base;
15151
15152                         if (encoder->base.crtc &&
15153                             encoder->base.crtc->state->active) {
15154                                 /*
15155                                  * This has to be done during hardware readout
15156                                  * because anything calling .crtc_disable may
15157                                  * rely on the connector_mask being accurate.
15158                                  */
15159                                 encoder->base.crtc->state->connector_mask |=
15160                                         1 << drm_connector_index(&connector->base);
15161                                 encoder->base.crtc->state->encoder_mask |=
15162                                         1 << drm_encoder_index(&encoder->base);
15163                         }
15164
15165                 } else {
15166                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15167                         connector->base.encoder = NULL;
15168                 }
15169                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15170                               connector->base.base.id, connector->base.name,
15171                               enableddisabled(connector->base.encoder));
15172         }
15173         drm_connector_list_iter_end(&conn_iter);
15174
15175         for_each_intel_crtc(dev, crtc) {
15176                 struct intel_crtc_state *crtc_state =
15177                         to_intel_crtc_state(crtc->base.state);
15178                 int min_cdclk = 0;
15179
15180                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15181                 if (crtc_state->base.active) {
15182                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15183                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15184                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15185
15186                         /*
15187                          * The initial mode needs to be set in order to keep
15188                          * the atomic core happy. It wants a valid mode if the
15189                          * crtc's enabled, so we do the above call.
15190                          *
15191                          * But we don't set all the derived state fully, hence
15192                          * set a flag to indicate that a full recalculation is
15193                          * needed on the next commit.
15194                          */
15195                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15196
15197                         intel_crtc_compute_pixel_rate(crtc_state);
15198
15199                         if (dev_priv->display.modeset_calc_cdclk) {
15200                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15201                                 if (WARN_ON(min_cdclk < 0))
15202                                         min_cdclk = 0;
15203                         }
15204
15205                         drm_calc_timestamping_constants(&crtc->base,
15206                                                         &crtc_state->base.adjusted_mode);
15207                         update_scanline_offset(crtc);
15208                 }
15209
15210                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15211                 dev_priv->min_voltage_level[crtc->pipe] =
15212                         crtc_state->min_voltage_level;
15213
15214                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15215         }
15216 }
15217
15218 static void
15219 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15220 {
15221         struct intel_encoder *encoder;
15222
15223         for_each_intel_encoder(&dev_priv->drm, encoder) {
15224                 u64 get_domains;
15225                 enum intel_display_power_domain domain;
15226
15227                 if (!encoder->get_power_domains)
15228                         continue;
15229
15230                 get_domains = encoder->get_power_domains(encoder);
15231                 for_each_power_domain(domain, get_domains)
15232                         intel_display_power_get(dev_priv, domain);
15233         }
15234 }
15235
15236 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15237 {
15238         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15239         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15240                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15241                            DARBF_GATING_DIS);
15242
15243         if (IS_HASWELL(dev_priv)) {
15244                 /*
15245                  * WaRsPkgCStateDisplayPMReq:hsw
15246                  * System hang if this isn't done before disabling all planes!
15247                  */
15248                 I915_WRITE(CHICKEN_PAR1_1,
15249                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15250         }
15251 }
15252
15253 /* Scan out the current hw modeset state,
15254  * and sanitizes it to the current state
15255  */
15256 static void
15257 intel_modeset_setup_hw_state(struct drm_device *dev,
15258                              struct drm_modeset_acquire_ctx *ctx)
15259 {
15260         struct drm_i915_private *dev_priv = to_i915(dev);
15261         enum pipe pipe;
15262         struct intel_crtc *crtc;
15263         struct intel_encoder *encoder;
15264         int i;
15265
15266         intel_early_display_was(dev_priv);
15267         intel_modeset_readout_hw_state(dev);
15268
15269         /* HW state is read out, now we need to sanitize this mess. */
15270         get_encoder_power_domains(dev_priv);
15271
15272         intel_sanitize_plane_mapping(dev_priv);
15273
15274         for_each_intel_encoder(dev, encoder) {
15275                 intel_sanitize_encoder(encoder);
15276         }
15277
15278         for_each_pipe(dev_priv, pipe) {
15279                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15280
15281                 intel_sanitize_crtc(crtc, ctx);
15282                 intel_dump_pipe_config(crtc, crtc->config,
15283                                        "[setup_hw_state]");
15284         }
15285
15286         intel_modeset_update_connector_atomic_state(dev);
15287
15288         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15289                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15290
15291                 if (!pll->on || pll->active_mask)
15292                         continue;
15293
15294                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15295
15296                 pll->funcs.disable(dev_priv, pll);
15297                 pll->on = false;
15298         }
15299
15300         if (IS_G4X(dev_priv)) {
15301                 g4x_wm_get_hw_state(dev);
15302                 g4x_wm_sanitize(dev_priv);
15303         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15304                 vlv_wm_get_hw_state(dev);
15305                 vlv_wm_sanitize(dev_priv);
15306         } else if (INTEL_GEN(dev_priv) >= 9) {
15307                 skl_wm_get_hw_state(dev);
15308         } else if (HAS_PCH_SPLIT(dev_priv)) {
15309                 ilk_wm_get_hw_state(dev);
15310         }
15311
15312         for_each_intel_crtc(dev, crtc) {
15313                 u64 put_domains;
15314
15315                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15316                 if (WARN_ON(put_domains))
15317                         modeset_put_power_domains(dev_priv, put_domains);
15318         }
15319         intel_display_set_init_power(dev_priv, false);
15320
15321         intel_power_domains_verify_state(dev_priv);
15322
15323         intel_fbc_init_pipe_state(dev_priv);
15324 }
15325
15326 void intel_display_resume(struct drm_device *dev)
15327 {
15328         struct drm_i915_private *dev_priv = to_i915(dev);
15329         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15330         struct drm_modeset_acquire_ctx ctx;
15331         int ret;
15332
15333         dev_priv->modeset_restore_state = NULL;
15334         if (state)
15335                 state->acquire_ctx = &ctx;
15336
15337         drm_modeset_acquire_init(&ctx, 0);
15338
15339         while (1) {
15340                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15341                 if (ret != -EDEADLK)
15342                         break;
15343
15344                 drm_modeset_backoff(&ctx);
15345         }
15346
15347         if (!ret)
15348                 ret = __intel_display_resume(dev, state, &ctx);
15349
15350         intel_enable_ipc(dev_priv);
15351         drm_modeset_drop_locks(&ctx);
15352         drm_modeset_acquire_fini(&ctx);
15353
15354         if (ret)
15355                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15356         if (state)
15357                 drm_atomic_state_put(state);
15358 }
15359
15360 int intel_connector_register(struct drm_connector *connector)
15361 {
15362         struct intel_connector *intel_connector = to_intel_connector(connector);
15363         int ret;
15364
15365         ret = intel_backlight_device_register(intel_connector);
15366         if (ret)
15367                 goto err;
15368
15369         return 0;
15370
15371 err:
15372         return ret;
15373 }
15374
15375 void intel_connector_unregister(struct drm_connector *connector)
15376 {
15377         struct intel_connector *intel_connector = to_intel_connector(connector);
15378
15379         intel_backlight_device_unregister(intel_connector);
15380         intel_panel_destroy_backlight(connector);
15381 }
15382
15383 static void intel_hpd_poll_fini(struct drm_device *dev)
15384 {
15385         struct intel_connector *connector;
15386         struct drm_connector_list_iter conn_iter;
15387
15388         /* Kill all the work that may have been queued by hpd. */
15389         drm_connector_list_iter_begin(dev, &conn_iter);
15390         for_each_intel_connector_iter(connector, &conn_iter) {
15391                 if (connector->modeset_retry_work.func)
15392                         cancel_work_sync(&connector->modeset_retry_work);
15393                 if (connector->hdcp_shim) {
15394                         cancel_delayed_work_sync(&connector->hdcp_check_work);
15395                         cancel_work_sync(&connector->hdcp_prop_work);
15396                 }
15397         }
15398         drm_connector_list_iter_end(&conn_iter);
15399 }
15400
15401 void intel_modeset_cleanup(struct drm_device *dev)
15402 {
15403         struct drm_i915_private *dev_priv = to_i915(dev);
15404
15405         flush_work(&dev_priv->atomic_helper.free_work);
15406         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15407
15408         intel_disable_gt_powersave(dev_priv);
15409
15410         /*
15411          * Interrupts and polling as the first thing to avoid creating havoc.
15412          * Too much stuff here (turning of connectors, ...) would
15413          * experience fancy races otherwise.
15414          */
15415         intel_irq_uninstall(dev_priv);
15416
15417         /*
15418          * Due to the hpd irq storm handling the hotplug work can re-arm the
15419          * poll handlers. Hence disable polling after hpd handling is shut down.
15420          */
15421         intel_hpd_poll_fini(dev);
15422
15423         /* poll work can call into fbdev, hence clean that up afterwards */
15424         intel_fbdev_fini(dev_priv);
15425
15426         intel_unregister_dsm_handler();
15427
15428         intel_fbc_global_disable(dev_priv);
15429
15430         /* flush any delayed tasks or pending work */
15431         flush_scheduled_work();
15432
15433         drm_mode_config_cleanup(dev);
15434
15435         intel_cleanup_overlay(dev_priv);
15436
15437         intel_cleanup_gt_powersave(dev_priv);
15438
15439         intel_teardown_gmbus(dev_priv);
15440
15441         destroy_workqueue(dev_priv->modeset_wq);
15442 }
15443
15444 void intel_connector_attach_encoder(struct intel_connector *connector,
15445                                     struct intel_encoder *encoder)
15446 {
15447         connector->encoder = encoder;
15448         drm_mode_connector_attach_encoder(&connector->base,
15449                                           &encoder->base);
15450 }
15451
15452 /*
15453  * set vga decode state - true == enable VGA decode
15454  */
15455 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15456 {
15457         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15458         u16 gmch_ctrl;
15459
15460         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15461                 DRM_ERROR("failed to read control word\n");
15462                 return -EIO;
15463         }
15464
15465         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15466                 return 0;
15467
15468         if (state)
15469                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15470         else
15471                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15472
15473         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15474                 DRM_ERROR("failed to write control word\n");
15475                 return -EIO;
15476         }
15477
15478         return 0;
15479 }
15480
15481 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15482
15483 struct intel_display_error_state {
15484
15485         u32 power_well_driver;
15486
15487         int num_transcoders;
15488
15489         struct intel_cursor_error_state {
15490                 u32 control;
15491                 u32 position;
15492                 u32 base;
15493                 u32 size;
15494         } cursor[I915_MAX_PIPES];
15495
15496         struct intel_pipe_error_state {
15497                 bool power_domain_on;
15498                 u32 source;
15499                 u32 stat;
15500         } pipe[I915_MAX_PIPES];
15501
15502         struct intel_plane_error_state {
15503                 u32 control;
15504                 u32 stride;
15505                 u32 size;
15506                 u32 pos;
15507                 u32 addr;
15508                 u32 surface;
15509                 u32 tile_offset;
15510         } plane[I915_MAX_PIPES];
15511
15512         struct intel_transcoder_error_state {
15513                 bool power_domain_on;
15514                 enum transcoder cpu_transcoder;
15515
15516                 u32 conf;
15517
15518                 u32 htotal;
15519                 u32 hblank;
15520                 u32 hsync;
15521                 u32 vtotal;
15522                 u32 vblank;
15523                 u32 vsync;
15524         } transcoder[4];
15525 };
15526
15527 struct intel_display_error_state *
15528 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15529 {
15530         struct intel_display_error_state *error;
15531         int transcoders[] = {
15532                 TRANSCODER_A,
15533                 TRANSCODER_B,
15534                 TRANSCODER_C,
15535                 TRANSCODER_EDP,
15536         };
15537         int i;
15538
15539         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15540                 return NULL;
15541
15542         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15543         if (error == NULL)
15544                 return NULL;
15545
15546         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15547                 error->power_well_driver =
15548                         I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL));
15549
15550         for_each_pipe(dev_priv, i) {
15551                 error->pipe[i].power_domain_on =
15552                         __intel_display_power_is_enabled(dev_priv,
15553                                                          POWER_DOMAIN_PIPE(i));
15554                 if (!error->pipe[i].power_domain_on)
15555                         continue;
15556
15557                 error->cursor[i].control = I915_READ(CURCNTR(i));
15558                 error->cursor[i].position = I915_READ(CURPOS(i));
15559                 error->cursor[i].base = I915_READ(CURBASE(i));
15560
15561                 error->plane[i].control = I915_READ(DSPCNTR(i));
15562                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15563                 if (INTEL_GEN(dev_priv) <= 3) {
15564                         error->plane[i].size = I915_READ(DSPSIZE(i));
15565                         error->plane[i].pos = I915_READ(DSPPOS(i));
15566                 }
15567                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15568                         error->plane[i].addr = I915_READ(DSPADDR(i));
15569                 if (INTEL_GEN(dev_priv) >= 4) {
15570                         error->plane[i].surface = I915_READ(DSPSURF(i));
15571                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15572                 }
15573
15574                 error->pipe[i].source = I915_READ(PIPESRC(i));
15575
15576                 if (HAS_GMCH_DISPLAY(dev_priv))
15577                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15578         }
15579
15580         /* Note: this does not include DSI transcoders. */
15581         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15582         if (HAS_DDI(dev_priv))
15583                 error->num_transcoders++; /* Account for eDP. */
15584
15585         for (i = 0; i < error->num_transcoders; i++) {
15586                 enum transcoder cpu_transcoder = transcoders[i];
15587
15588                 error->transcoder[i].power_domain_on =
15589                         __intel_display_power_is_enabled(dev_priv,
15590                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15591                 if (!error->transcoder[i].power_domain_on)
15592                         continue;
15593
15594                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15595
15596                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15597                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15598                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15599                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15600                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15601                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15602                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15603         }
15604
15605         return error;
15606 }
15607
15608 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15609
15610 void
15611 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15612                                 struct intel_display_error_state *error)
15613 {
15614         struct drm_i915_private *dev_priv = m->i915;
15615         int i;
15616
15617         if (!error)
15618                 return;
15619
15620         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
15621         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15622                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15623                            error->power_well_driver);
15624         for_each_pipe(dev_priv, i) {
15625                 err_printf(m, "Pipe [%d]:\n", i);
15626                 err_printf(m, "  Power: %s\n",
15627                            onoff(error->pipe[i].power_domain_on));
15628                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15629                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15630
15631                 err_printf(m, "Plane [%d]:\n", i);
15632                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15633                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15634                 if (INTEL_GEN(dev_priv) <= 3) {
15635                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15636                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15637                 }
15638                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15639                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15640                 if (INTEL_GEN(dev_priv) >= 4) {
15641                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15642                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15643                 }
15644
15645                 err_printf(m, "Cursor [%d]:\n", i);
15646                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15647                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15648                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15649         }
15650
15651         for (i = 0; i < error->num_transcoders; i++) {
15652                 err_printf(m, "CPU transcoder: %s\n",
15653                            transcoder_name(error->transcoder[i].cpu_transcoder));
15654                 err_printf(m, "  Power: %s\n",
15655                            onoff(error->transcoder[i].power_domain_on));
15656                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15657                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15658                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15659                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15660                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15661                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15662                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15663         }
15664 }
15665
15666 #endif