]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/gpu/drm/i915/intel_display.c
drm: Don't pass clip to drm_atomic_helper_check_plane_state()
[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  * Returns whether the given set of divisors are valid for a given refclk with
563  * the given connectors.
564  */
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_INFO(dev_priv)->gen >= 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_INFO(dev_priv)->gen >= 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 struct i915_vma *
2071 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2072 {
2073         struct drm_device *dev = fb->dev;
2074         struct drm_i915_private *dev_priv = to_i915(dev);
2075         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2076         struct i915_ggtt_view view;
2077         struct i915_vma *vma;
2078         u32 alignment;
2079
2080         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2081
2082         alignment = intel_surf_alignment(fb, 0);
2083
2084         intel_fill_fb_ggtt_view(&view, fb, rotation);
2085
2086         /* Note that the w/a also requires 64 PTE of padding following the
2087          * bo. We currently fill all unused PTE with the shadow page and so
2088          * we should always have valid PTE following the scanout preventing
2089          * the VT-d warning.
2090          */
2091         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2092                 alignment = 256 * 1024;
2093
2094         /*
2095          * Global gtt pte registers are special registers which actually forward
2096          * writes to a chunk of system memory. Which means that there is no risk
2097          * that the register values disappear as soon as we call
2098          * intel_runtime_pm_put(), so it is correct to wrap only the
2099          * pin/unpin/fence and not more.
2100          */
2101         intel_runtime_pm_get(dev_priv);
2102
2103         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2104
2105         vma = i915_gem_object_pin_to_display_plane(obj, alignment, &view);
2106         if (IS_ERR(vma))
2107                 goto err;
2108
2109         if (i915_vma_is_map_and_fenceable(vma)) {
2110                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2111                  * fence, whereas 965+ only requires a fence if using
2112                  * framebuffer compression.  For simplicity, we always, when
2113                  * possible, install a fence as the cost is not that onerous.
2114                  *
2115                  * If we fail to fence the tiled scanout, then either the
2116                  * modeset will reject the change (which is highly unlikely as
2117                  * the affected systems, all but one, do not have unmappable
2118                  * space) or we will not be able to enable full powersaving
2119                  * techniques (also likely not to apply due to various limits
2120                  * FBC and the like impose on the size of the buffer, which
2121                  * presumably we violated anyway with this unmappable buffer).
2122                  * Anyway, it is presumably better to stumble onwards with
2123                  * something and try to run the system in a "less than optimal"
2124                  * mode that matches the user configuration.
2125                  */
2126                 i915_vma_pin_fence(vma);
2127         }
2128
2129         i915_vma_get(vma);
2130 err:
2131         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2132
2133         intel_runtime_pm_put(dev_priv);
2134         return vma;
2135 }
2136
2137 void intel_unpin_fb_vma(struct i915_vma *vma)
2138 {
2139         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2140
2141         i915_vma_unpin_fence(vma);
2142         i915_gem_object_unpin_from_display_plane(vma);
2143         i915_vma_put(vma);
2144 }
2145
2146 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2147                           unsigned int rotation)
2148 {
2149         if (drm_rotation_90_or_270(rotation))
2150                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2151         else
2152                 return fb->pitches[plane];
2153 }
2154
2155 /*
2156  * Convert the x/y offsets into a linear offset.
2157  * Only valid with 0/180 degree rotation, which is fine since linear
2158  * offset is only used with linear buffers on pre-hsw and tiled buffers
2159  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2160  */
2161 u32 intel_fb_xy_to_linear(int x, int y,
2162                           const struct intel_plane_state *state,
2163                           int plane)
2164 {
2165         const struct drm_framebuffer *fb = state->base.fb;
2166         unsigned int cpp = fb->format->cpp[plane];
2167         unsigned int pitch = fb->pitches[plane];
2168
2169         return y * pitch + x * cpp;
2170 }
2171
2172 /*
2173  * Add the x/y offsets derived from fb->offsets[] to the user
2174  * specified plane src x/y offsets. The resulting x/y offsets
2175  * specify the start of scanout from the beginning of the gtt mapping.
2176  */
2177 void intel_add_fb_offsets(int *x, int *y,
2178                           const struct intel_plane_state *state,
2179                           int plane)
2180
2181 {
2182         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2183         unsigned int rotation = state->base.rotation;
2184
2185         if (drm_rotation_90_or_270(rotation)) {
2186                 *x += intel_fb->rotated[plane].x;
2187                 *y += intel_fb->rotated[plane].y;
2188         } else {
2189                 *x += intel_fb->normal[plane].x;
2190                 *y += intel_fb->normal[plane].y;
2191         }
2192 }
2193
2194 static u32 __intel_adjust_tile_offset(int *x, int *y,
2195                                       unsigned int tile_width,
2196                                       unsigned int tile_height,
2197                                       unsigned int tile_size,
2198                                       unsigned int pitch_tiles,
2199                                       u32 old_offset,
2200                                       u32 new_offset)
2201 {
2202         unsigned int pitch_pixels = pitch_tiles * tile_width;
2203         unsigned int tiles;
2204
2205         WARN_ON(old_offset & (tile_size - 1));
2206         WARN_ON(new_offset & (tile_size - 1));
2207         WARN_ON(new_offset > old_offset);
2208
2209         tiles = (old_offset - new_offset) / tile_size;
2210
2211         *y += tiles / pitch_tiles * tile_height;
2212         *x += tiles % pitch_tiles * tile_width;
2213
2214         /* minimize x in case it got needlessly big */
2215         *y += *x / pitch_pixels * tile_height;
2216         *x %= pitch_pixels;
2217
2218         return new_offset;
2219 }
2220
2221 static u32 _intel_adjust_tile_offset(int *x, int *y,
2222                                      const struct drm_framebuffer *fb, int plane,
2223                                      unsigned int rotation,
2224                                      u32 old_offset, u32 new_offset)
2225 {
2226         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2227         unsigned int cpp = fb->format->cpp[plane];
2228         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2229
2230         WARN_ON(new_offset > old_offset);
2231
2232         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2233                 unsigned int tile_size, tile_width, tile_height;
2234                 unsigned int pitch_tiles;
2235
2236                 tile_size = intel_tile_size(dev_priv);
2237                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2238
2239                 if (drm_rotation_90_or_270(rotation)) {
2240                         pitch_tiles = pitch / tile_height;
2241                         swap(tile_width, tile_height);
2242                 } else {
2243                         pitch_tiles = pitch / (tile_width * cpp);
2244                 }
2245
2246                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2247                                            tile_size, pitch_tiles,
2248                                            old_offset, new_offset);
2249         } else {
2250                 old_offset += *y * pitch + *x * cpp;
2251
2252                 *y = (old_offset - new_offset) / pitch;
2253                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2254         }
2255
2256         return new_offset;
2257 }
2258
2259 /*
2260  * Adjust the tile offset by moving the difference into
2261  * the x/y offsets.
2262  */
2263 static u32 intel_adjust_tile_offset(int *x, int *y,
2264                                     const struct intel_plane_state *state, int plane,
2265                                     u32 old_offset, u32 new_offset)
2266 {
2267         return _intel_adjust_tile_offset(x, y, state->base.fb, plane,
2268                                          state->base.rotation,
2269                                          old_offset, new_offset);
2270 }
2271
2272 /*
2273  * Computes the linear offset to the base tile and adjusts
2274  * x, y. bytes per pixel is assumed to be a power-of-two.
2275  *
2276  * In the 90/270 rotated case, x and y are assumed
2277  * to be already rotated to match the rotated GTT view, and
2278  * pitch is the tile_height aligned framebuffer height.
2279  *
2280  * This function is used when computing the derived information
2281  * under intel_framebuffer, so using any of that information
2282  * here is not allowed. Anything under drm_framebuffer can be
2283  * used. This is why the user has to pass in the pitch since it
2284  * is specified in the rotated orientation.
2285  */
2286 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2287                                       int *x, int *y,
2288                                       const struct drm_framebuffer *fb, int plane,
2289                                       unsigned int pitch,
2290                                       unsigned int rotation,
2291                                       u32 alignment)
2292 {
2293         uint64_t fb_modifier = fb->modifier;
2294         unsigned int cpp = fb->format->cpp[plane];
2295         u32 offset, offset_aligned;
2296
2297         if (alignment)
2298                 alignment--;
2299
2300         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2301                 unsigned int tile_size, tile_width, tile_height;
2302                 unsigned int tile_rows, tiles, pitch_tiles;
2303
2304                 tile_size = intel_tile_size(dev_priv);
2305                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2306
2307                 if (drm_rotation_90_or_270(rotation)) {
2308                         pitch_tiles = pitch / tile_height;
2309                         swap(tile_width, tile_height);
2310                 } else {
2311                         pitch_tiles = pitch / (tile_width * cpp);
2312                 }
2313
2314                 tile_rows = *y / tile_height;
2315                 *y %= tile_height;
2316
2317                 tiles = *x / tile_width;
2318                 *x %= tile_width;
2319
2320                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2321                 offset_aligned = offset & ~alignment;
2322
2323                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2324                                            tile_size, pitch_tiles,
2325                                            offset, offset_aligned);
2326         } else {
2327                 offset = *y * pitch + *x * cpp;
2328                 offset_aligned = offset & ~alignment;
2329
2330                 *y = (offset & alignment) / pitch;
2331                 *x = ((offset & alignment) - *y * pitch) / cpp;
2332         }
2333
2334         return offset_aligned;
2335 }
2336
2337 u32 intel_compute_tile_offset(int *x, int *y,
2338                               const struct intel_plane_state *state,
2339                               int plane)
2340 {
2341         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2342         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2343         const struct drm_framebuffer *fb = state->base.fb;
2344         unsigned int rotation = state->base.rotation;
2345         int pitch = intel_fb_pitch(fb, plane, rotation);
2346         u32 alignment;
2347
2348         if (intel_plane->id == PLANE_CURSOR)
2349                 alignment = intel_cursor_alignment(dev_priv);
2350         else
2351                 alignment = intel_surf_alignment(fb, plane);
2352
2353         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2354                                           rotation, alignment);
2355 }
2356
2357 /* Convert the fb->offset[] into x/y offsets */
2358 static int intel_fb_offset_to_xy(int *x, int *y,
2359                                  const struct drm_framebuffer *fb, int plane)
2360 {
2361         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2362
2363         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2364             fb->offsets[plane] % intel_tile_size(dev_priv))
2365                 return -EINVAL;
2366
2367         *x = 0;
2368         *y = 0;
2369
2370         _intel_adjust_tile_offset(x, y,
2371                                   fb, plane, DRM_MODE_ROTATE_0,
2372                                   fb->offsets[plane], 0);
2373
2374         return 0;
2375 }
2376
2377 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2378 {
2379         switch (fb_modifier) {
2380         case I915_FORMAT_MOD_X_TILED:
2381                 return I915_TILING_X;
2382         case I915_FORMAT_MOD_Y_TILED:
2383         case I915_FORMAT_MOD_Y_TILED_CCS:
2384                 return I915_TILING_Y;
2385         default:
2386                 return I915_TILING_NONE;
2387         }
2388 }
2389
2390 /*
2391  * From the Sky Lake PRM:
2392  * "The Color Control Surface (CCS) contains the compression status of
2393  *  the cache-line pairs. The compression state of the cache-line pair
2394  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2395  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2396  *  cache-line-pairs. CCS is always Y tiled."
2397  *
2398  * Since cache line pairs refers to horizontally adjacent cache lines,
2399  * each cache line in the CCS corresponds to an area of 32x16 cache
2400  * lines on the main surface. Since each pixel is 4 bytes, this gives
2401  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2402  * main surface.
2403  */
2404 static const struct drm_format_info ccs_formats[] = {
2405         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2406         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2407         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2408         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2409 };
2410
2411 static const struct drm_format_info *
2412 lookup_format_info(const struct drm_format_info formats[],
2413                    int num_formats, u32 format)
2414 {
2415         int i;
2416
2417         for (i = 0; i < num_formats; i++) {
2418                 if (formats[i].format == format)
2419                         return &formats[i];
2420         }
2421
2422         return NULL;
2423 }
2424
2425 static const struct drm_format_info *
2426 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2427 {
2428         switch (cmd->modifier[0]) {
2429         case I915_FORMAT_MOD_Y_TILED_CCS:
2430         case I915_FORMAT_MOD_Yf_TILED_CCS:
2431                 return lookup_format_info(ccs_formats,
2432                                           ARRAY_SIZE(ccs_formats),
2433                                           cmd->pixel_format);
2434         default:
2435                 return NULL;
2436         }
2437 }
2438
2439 static int
2440 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2441                    struct drm_framebuffer *fb)
2442 {
2443         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2444         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2445         u32 gtt_offset_rotated = 0;
2446         unsigned int max_size = 0;
2447         int i, num_planes = fb->format->num_planes;
2448         unsigned int tile_size = intel_tile_size(dev_priv);
2449
2450         for (i = 0; i < num_planes; i++) {
2451                 unsigned int width, height;
2452                 unsigned int cpp, size;
2453                 u32 offset;
2454                 int x, y;
2455                 int ret;
2456
2457                 cpp = fb->format->cpp[i];
2458                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2459                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2460
2461                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2462                 if (ret) {
2463                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2464                                       i, fb->offsets[i]);
2465                         return ret;
2466                 }
2467
2468                 if ((fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2469                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) && i == 1) {
2470                         int hsub = fb->format->hsub;
2471                         int vsub = fb->format->vsub;
2472                         int tile_width, tile_height;
2473                         int main_x, main_y;
2474                         int ccs_x, ccs_y;
2475
2476                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2477                         tile_width *= hsub;
2478                         tile_height *= vsub;
2479
2480                         ccs_x = (x * hsub) % tile_width;
2481                         ccs_y = (y * vsub) % tile_height;
2482                         main_x = intel_fb->normal[0].x % tile_width;
2483                         main_y = intel_fb->normal[0].y % tile_height;
2484
2485                         /*
2486                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2487                          * x/y offsets must match between CCS and the main surface.
2488                          */
2489                         if (main_x != ccs_x || main_y != ccs_y) {
2490                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2491                                               main_x, main_y,
2492                                               ccs_x, ccs_y,
2493                                               intel_fb->normal[0].x,
2494                                               intel_fb->normal[0].y,
2495                                               x, y);
2496                                 return -EINVAL;
2497                         }
2498                 }
2499
2500                 /*
2501                  * The fence (if used) is aligned to the start of the object
2502                  * so having the framebuffer wrap around across the edge of the
2503                  * fenced region doesn't really work. We have no API to configure
2504                  * the fence start offset within the object (nor could we probably
2505                  * on gen2/3). So it's just easier if we just require that the
2506                  * fb layout agrees with the fence layout. We already check that the
2507                  * fb stride matches the fence stride elsewhere.
2508                  */
2509                 if (i == 0 && i915_gem_object_is_tiled(intel_fb->obj) &&
2510                     (x + width) * cpp > fb->pitches[i]) {
2511                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2512                                       i, fb->offsets[i]);
2513                         return -EINVAL;
2514                 }
2515
2516                 /*
2517                  * First pixel of the framebuffer from
2518                  * the start of the normal gtt mapping.
2519                  */
2520                 intel_fb->normal[i].x = x;
2521                 intel_fb->normal[i].y = y;
2522
2523                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2524                                                     fb, i, fb->pitches[i],
2525                                                     DRM_MODE_ROTATE_0, tile_size);
2526                 offset /= tile_size;
2527
2528                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2529                         unsigned int tile_width, tile_height;
2530                         unsigned int pitch_tiles;
2531                         struct drm_rect r;
2532
2533                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2534
2535                         rot_info->plane[i].offset = offset;
2536                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2537                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2538                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2539
2540                         intel_fb->rotated[i].pitch =
2541                                 rot_info->plane[i].height * tile_height;
2542
2543                         /* how many tiles does this plane need */
2544                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2545                         /*
2546                          * If the plane isn't horizontally tile aligned,
2547                          * we need one more tile.
2548                          */
2549                         if (x != 0)
2550                                 size++;
2551
2552                         /* rotate the x/y offsets to match the GTT view */
2553                         r.x1 = x;
2554                         r.y1 = y;
2555                         r.x2 = x + width;
2556                         r.y2 = y + height;
2557                         drm_rect_rotate(&r,
2558                                         rot_info->plane[i].width * tile_width,
2559                                         rot_info->plane[i].height * tile_height,
2560                                         DRM_MODE_ROTATE_270);
2561                         x = r.x1;
2562                         y = r.y1;
2563
2564                         /* rotate the tile dimensions to match the GTT view */
2565                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2566                         swap(tile_width, tile_height);
2567
2568                         /*
2569                          * We only keep the x/y offsets, so push all of the
2570                          * gtt offset into the x/y offsets.
2571                          */
2572                         __intel_adjust_tile_offset(&x, &y,
2573                                                    tile_width, tile_height,
2574                                                    tile_size, pitch_tiles,
2575                                                    gtt_offset_rotated * tile_size, 0);
2576
2577                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2578
2579                         /*
2580                          * First pixel of the framebuffer from
2581                          * the start of the rotated gtt mapping.
2582                          */
2583                         intel_fb->rotated[i].x = x;
2584                         intel_fb->rotated[i].y = y;
2585                 } else {
2586                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2587                                             x * cpp, tile_size);
2588                 }
2589
2590                 /* how many tiles in total needed in the bo */
2591                 max_size = max(max_size, offset + size);
2592         }
2593
2594         if (max_size * tile_size > intel_fb->obj->base.size) {
2595                 DRM_DEBUG_KMS("fb too big for bo (need %u bytes, have %zu bytes)\n",
2596                               max_size * tile_size, intel_fb->obj->base.size);
2597                 return -EINVAL;
2598         }
2599
2600         return 0;
2601 }
2602
2603 static int i9xx_format_to_fourcc(int format)
2604 {
2605         switch (format) {
2606         case DISPPLANE_8BPP:
2607                 return DRM_FORMAT_C8;
2608         case DISPPLANE_BGRX555:
2609                 return DRM_FORMAT_XRGB1555;
2610         case DISPPLANE_BGRX565:
2611                 return DRM_FORMAT_RGB565;
2612         default:
2613         case DISPPLANE_BGRX888:
2614                 return DRM_FORMAT_XRGB8888;
2615         case DISPPLANE_RGBX888:
2616                 return DRM_FORMAT_XBGR8888;
2617         case DISPPLANE_BGRX101010:
2618                 return DRM_FORMAT_XRGB2101010;
2619         case DISPPLANE_RGBX101010:
2620                 return DRM_FORMAT_XBGR2101010;
2621         }
2622 }
2623
2624 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2625 {
2626         switch (format) {
2627         case PLANE_CTL_FORMAT_RGB_565:
2628                 return DRM_FORMAT_RGB565;
2629         default:
2630         case PLANE_CTL_FORMAT_XRGB_8888:
2631                 if (rgb_order) {
2632                         if (alpha)
2633                                 return DRM_FORMAT_ABGR8888;
2634                         else
2635                                 return DRM_FORMAT_XBGR8888;
2636                 } else {
2637                         if (alpha)
2638                                 return DRM_FORMAT_ARGB8888;
2639                         else
2640                                 return DRM_FORMAT_XRGB8888;
2641                 }
2642         case PLANE_CTL_FORMAT_XRGB_2101010:
2643                 if (rgb_order)
2644                         return DRM_FORMAT_XBGR2101010;
2645                 else
2646                         return DRM_FORMAT_XRGB2101010;
2647         }
2648 }
2649
2650 static bool
2651 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2652                               struct intel_initial_plane_config *plane_config)
2653 {
2654         struct drm_device *dev = crtc->base.dev;
2655         struct drm_i915_private *dev_priv = to_i915(dev);
2656         struct drm_i915_gem_object *obj = NULL;
2657         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2658         struct drm_framebuffer *fb = &plane_config->fb->base;
2659         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2660         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2661                                     PAGE_SIZE);
2662
2663         size_aligned -= base_aligned;
2664
2665         if (plane_config->size == 0)
2666                 return false;
2667
2668         /* If the FB is too big, just don't use it since fbdev is not very
2669          * important and we should probably use that space with FBC or other
2670          * features. */
2671         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2672                 return false;
2673
2674         mutex_lock(&dev->struct_mutex);
2675         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2676                                                              base_aligned,
2677                                                              base_aligned,
2678                                                              size_aligned);
2679         mutex_unlock(&dev->struct_mutex);
2680         if (!obj)
2681                 return false;
2682
2683         if (plane_config->tiling == I915_TILING_X)
2684                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2685
2686         mode_cmd.pixel_format = fb->format->format;
2687         mode_cmd.width = fb->width;
2688         mode_cmd.height = fb->height;
2689         mode_cmd.pitches[0] = fb->pitches[0];
2690         mode_cmd.modifier[0] = fb->modifier;
2691         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2692
2693         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2694                 DRM_DEBUG_KMS("intel fb init failed\n");
2695                 goto out_unref_obj;
2696         }
2697
2698
2699         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2700         return true;
2701
2702 out_unref_obj:
2703         i915_gem_object_put(obj);
2704         return false;
2705 }
2706
2707 static void
2708 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2709                         struct intel_plane_state *plane_state,
2710                         bool visible)
2711 {
2712         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2713
2714         plane_state->base.visible = visible;
2715
2716         /* FIXME pre-g4x don't work like this */
2717         if (visible) {
2718                 crtc_state->base.plane_mask |= BIT(drm_plane_index(&plane->base));
2719                 crtc_state->active_planes |= BIT(plane->id);
2720         } else {
2721                 crtc_state->base.plane_mask &= ~BIT(drm_plane_index(&plane->base));
2722                 crtc_state->active_planes &= ~BIT(plane->id);
2723         }
2724
2725         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2726                       crtc_state->base.crtc->name,
2727                       crtc_state->active_planes);
2728 }
2729
2730 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2731                                          struct intel_plane *plane)
2732 {
2733         struct intel_crtc_state *crtc_state =
2734                 to_intel_crtc_state(crtc->base.state);
2735         struct intel_plane_state *plane_state =
2736                 to_intel_plane_state(plane->base.state);
2737
2738         intel_set_plane_visible(crtc_state, plane_state, false);
2739
2740         if (plane->id == PLANE_PRIMARY)
2741                 intel_pre_disable_primary_noatomic(&crtc->base);
2742
2743         trace_intel_disable_plane(&plane->base, crtc);
2744         plane->disable_plane(plane, crtc);
2745 }
2746
2747 static void
2748 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2749                              struct intel_initial_plane_config *plane_config)
2750 {
2751         struct drm_device *dev = intel_crtc->base.dev;
2752         struct drm_i915_private *dev_priv = to_i915(dev);
2753         struct drm_crtc *c;
2754         struct drm_i915_gem_object *obj;
2755         struct drm_plane *primary = intel_crtc->base.primary;
2756         struct drm_plane_state *plane_state = primary->state;
2757         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2758         struct intel_plane *intel_plane = to_intel_plane(primary);
2759         struct intel_plane_state *intel_state =
2760                 to_intel_plane_state(plane_state);
2761         struct drm_framebuffer *fb;
2762
2763         if (!plane_config->fb)
2764                 return;
2765
2766         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2767                 fb = &plane_config->fb->base;
2768                 goto valid_fb;
2769         }
2770
2771         kfree(plane_config->fb);
2772
2773         /*
2774          * Failed to alloc the obj, check to see if we should share
2775          * an fb with another CRTC instead
2776          */
2777         for_each_crtc(dev, c) {
2778                 struct intel_plane_state *state;
2779
2780                 if (c == &intel_crtc->base)
2781                         continue;
2782
2783                 if (!to_intel_crtc(c)->active)
2784                         continue;
2785
2786                 state = to_intel_plane_state(c->primary->state);
2787                 if (!state->vma)
2788                         continue;
2789
2790                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2791                         fb = c->primary->fb;
2792                         drm_framebuffer_get(fb);
2793                         goto valid_fb;
2794                 }
2795         }
2796
2797         /*
2798          * We've failed to reconstruct the BIOS FB.  Current display state
2799          * indicates that the primary plane is visible, but has a NULL FB,
2800          * which will lead to problems later if we don't fix it up.  The
2801          * simplest solution is to just disable the primary plane now and
2802          * pretend the BIOS never had it enabled.
2803          */
2804         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2805
2806         return;
2807
2808 valid_fb:
2809         mutex_lock(&dev->struct_mutex);
2810         intel_state->vma =
2811                 intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
2812         mutex_unlock(&dev->struct_mutex);
2813         if (IS_ERR(intel_state->vma)) {
2814                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2815                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2816
2817                 intel_state->vma = NULL;
2818                 drm_framebuffer_put(fb);
2819                 return;
2820         }
2821
2822         plane_state->src_x = 0;
2823         plane_state->src_y = 0;
2824         plane_state->src_w = fb->width << 16;
2825         plane_state->src_h = fb->height << 16;
2826
2827         plane_state->crtc_x = 0;
2828         plane_state->crtc_y = 0;
2829         plane_state->crtc_w = fb->width;
2830         plane_state->crtc_h = fb->height;
2831
2832         intel_state->base.src = drm_plane_state_src(plane_state);
2833         intel_state->base.dst = drm_plane_state_dest(plane_state);
2834
2835         obj = intel_fb_obj(fb);
2836         if (i915_gem_object_is_tiled(obj))
2837                 dev_priv->preserve_bios_swizzle = true;
2838
2839         drm_framebuffer_get(fb);
2840         primary->fb = primary->state->fb = fb;
2841         primary->crtc = primary->state->crtc = &intel_crtc->base;
2842
2843         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2844                                 to_intel_plane_state(plane_state),
2845                                 true);
2846
2847         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2848                   &obj->frontbuffer_bits);
2849 }
2850
2851 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2852                                unsigned int rotation)
2853 {
2854         int cpp = fb->format->cpp[plane];
2855
2856         switch (fb->modifier) {
2857         case DRM_FORMAT_MOD_LINEAR:
2858         case I915_FORMAT_MOD_X_TILED:
2859                 switch (cpp) {
2860                 case 8:
2861                         return 4096;
2862                 case 4:
2863                 case 2:
2864                 case 1:
2865                         return 8192;
2866                 default:
2867                         MISSING_CASE(cpp);
2868                         break;
2869                 }
2870                 break;
2871         case I915_FORMAT_MOD_Y_TILED_CCS:
2872         case I915_FORMAT_MOD_Yf_TILED_CCS:
2873                 /* FIXME AUX plane? */
2874         case I915_FORMAT_MOD_Y_TILED:
2875         case I915_FORMAT_MOD_Yf_TILED:
2876                 switch (cpp) {
2877                 case 8:
2878                         return 2048;
2879                 case 4:
2880                         return 4096;
2881                 case 2:
2882                 case 1:
2883                         return 8192;
2884                 default:
2885                         MISSING_CASE(cpp);
2886                         break;
2887                 }
2888                 break;
2889         default:
2890                 MISSING_CASE(fb->modifier);
2891         }
2892
2893         return 2048;
2894 }
2895
2896 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2897                                            int main_x, int main_y, u32 main_offset)
2898 {
2899         const struct drm_framebuffer *fb = plane_state->base.fb;
2900         int hsub = fb->format->hsub;
2901         int vsub = fb->format->vsub;
2902         int aux_x = plane_state->aux.x;
2903         int aux_y = plane_state->aux.y;
2904         u32 aux_offset = plane_state->aux.offset;
2905         u32 alignment = intel_surf_alignment(fb, 1);
2906
2907         while (aux_offset >= main_offset && aux_y <= main_y) {
2908                 int x, y;
2909
2910                 if (aux_x == main_x && aux_y == main_y)
2911                         break;
2912
2913                 if (aux_offset == 0)
2914                         break;
2915
2916                 x = aux_x / hsub;
2917                 y = aux_y / vsub;
2918                 aux_offset = intel_adjust_tile_offset(&x, &y, plane_state, 1,
2919                                                       aux_offset, aux_offset - alignment);
2920                 aux_x = x * hsub + aux_x % hsub;
2921                 aux_y = y * vsub + aux_y % vsub;
2922         }
2923
2924         if (aux_x != main_x || aux_y != main_y)
2925                 return false;
2926
2927         plane_state->aux.offset = aux_offset;
2928         plane_state->aux.x = aux_x;
2929         plane_state->aux.y = aux_y;
2930
2931         return true;
2932 }
2933
2934 static int skl_check_main_surface(const struct intel_crtc_state *crtc_state,
2935                                   struct intel_plane_state *plane_state)
2936 {
2937         struct drm_i915_private *dev_priv =
2938                 to_i915(plane_state->base.plane->dev);
2939         const struct drm_framebuffer *fb = plane_state->base.fb;
2940         unsigned int rotation = plane_state->base.rotation;
2941         int x = plane_state->base.src.x1 >> 16;
2942         int y = plane_state->base.src.y1 >> 16;
2943         int w = drm_rect_width(&plane_state->base.src) >> 16;
2944         int h = drm_rect_height(&plane_state->base.src) >> 16;
2945         int dst_x = plane_state->base.dst.x1;
2946         int pipe_src_w = crtc_state->pipe_src_w;
2947         int max_width = skl_max_plane_width(fb, 0, rotation);
2948         int max_height = 4096;
2949         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2950
2951         if (w > max_width || h > max_height) {
2952                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2953                               w, h, max_width, max_height);
2954                 return -EINVAL;
2955         }
2956
2957         /*
2958          * Display WA #1175: cnl,glk
2959          * Planes other than the cursor may cause FIFO underflow and display
2960          * corruption if starting less than 4 pixels from the right edge of
2961          * the screen.
2962          * Besides the above WA fix the similar problem, where planes other
2963          * than the cursor ending less than 4 pixels from the left edge of the
2964          * screen may cause FIFO underflow and display corruption.
2965          */
2966         if ((IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
2967             (dst_x + w < 4 || dst_x > pipe_src_w - 4)) {
2968                 DRM_DEBUG_KMS("requested plane X %s position %d invalid (valid range %d-%d)\n",
2969                               dst_x + w < 4 ? "end" : "start",
2970                               dst_x + w < 4 ? dst_x + w : dst_x,
2971                               4, pipe_src_w - 4);
2972                 return -ERANGE;
2973         }
2974
2975         intel_add_fb_offsets(&x, &y, plane_state, 0);
2976         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
2977         alignment = intel_surf_alignment(fb, 0);
2978
2979         /*
2980          * AUX surface offset is specified as the distance from the
2981          * main surface offset, and it must be non-negative. Make
2982          * sure that is what we will get.
2983          */
2984         if (offset > aux_offset)
2985                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2986                                                   offset, aux_offset & ~(alignment - 1));
2987
2988         /*
2989          * When using an X-tiled surface, the plane blows up
2990          * if the x offset + width exceed the stride.
2991          *
2992          * TODO: linear and Y-tiled seem fine, Yf untested,
2993          */
2994         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
2995                 int cpp = fb->format->cpp[0];
2996
2997                 while ((x + w) * cpp > fb->pitches[0]) {
2998                         if (offset == 0) {
2999                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3000                                 return -EINVAL;
3001                         }
3002
3003                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3004                                                           offset, offset - alignment);
3005                 }
3006         }
3007
3008         /*
3009          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3010          * they match with the main surface x/y offsets.
3011          */
3012         if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3013             fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3014                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3015                         if (offset == 0)
3016                                 break;
3017
3018                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3019                                                           offset, offset - alignment);
3020                 }
3021
3022                 if (x != plane_state->aux.x || y != plane_state->aux.y) {
3023                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3024                         return -EINVAL;
3025                 }
3026         }
3027
3028         plane_state->main.offset = offset;
3029         plane_state->main.x = x;
3030         plane_state->main.y = y;
3031
3032         return 0;
3033 }
3034
3035 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3036 {
3037         const struct drm_framebuffer *fb = plane_state->base.fb;
3038         unsigned int rotation = plane_state->base.rotation;
3039         int max_width = skl_max_plane_width(fb, 1, rotation);
3040         int max_height = 4096;
3041         int x = plane_state->base.src.x1 >> 17;
3042         int y = plane_state->base.src.y1 >> 17;
3043         int w = drm_rect_width(&plane_state->base.src) >> 17;
3044         int h = drm_rect_height(&plane_state->base.src) >> 17;
3045         u32 offset;
3046
3047         intel_add_fb_offsets(&x, &y, plane_state, 1);
3048         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3049
3050         /* FIXME not quite sure how/if these apply to the chroma plane */
3051         if (w > max_width || h > max_height) {
3052                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3053                               w, h, max_width, max_height);
3054                 return -EINVAL;
3055         }
3056
3057         plane_state->aux.offset = offset;
3058         plane_state->aux.x = x;
3059         plane_state->aux.y = y;
3060
3061         return 0;
3062 }
3063
3064 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3065 {
3066         const struct drm_framebuffer *fb = plane_state->base.fb;
3067         int src_x = plane_state->base.src.x1 >> 16;
3068         int src_y = plane_state->base.src.y1 >> 16;
3069         int hsub = fb->format->hsub;
3070         int vsub = fb->format->vsub;
3071         int x = src_x / hsub;
3072         int y = src_y / vsub;
3073         u32 offset;
3074
3075         if (plane_state->base.rotation & ~(DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180)) {
3076                 DRM_DEBUG_KMS("RC support only with 0/180 degree rotation %x\n",
3077                               plane_state->base.rotation);
3078                 return -EINVAL;
3079         }
3080
3081         intel_add_fb_offsets(&x, &y, plane_state, 1);
3082         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3083
3084         plane_state->aux.offset = offset;
3085         plane_state->aux.x = x * hsub + src_x % hsub;
3086         plane_state->aux.y = y * vsub + src_y % vsub;
3087
3088         return 0;
3089 }
3090
3091 int skl_check_plane_surface(const struct intel_crtc_state *crtc_state,
3092                             struct intel_plane_state *plane_state)
3093 {
3094         const struct drm_framebuffer *fb = plane_state->base.fb;
3095         unsigned int rotation = plane_state->base.rotation;
3096         int ret;
3097
3098         if (rotation & DRM_MODE_REFLECT_X &&
3099             fb->modifier == DRM_FORMAT_MOD_LINEAR) {
3100                 DRM_DEBUG_KMS("horizontal flip is not supported with linear surface formats\n");
3101                 return -EINVAL;
3102         }
3103
3104         if (!plane_state->base.visible)
3105                 return 0;
3106
3107         /* Rotate src coordinates to match rotated GTT view */
3108         if (drm_rotation_90_or_270(rotation))
3109                 drm_rect_rotate(&plane_state->base.src,
3110                                 fb->width << 16, fb->height << 16,
3111                                 DRM_MODE_ROTATE_270);
3112
3113         /*
3114          * Handle the AUX surface first since
3115          * the main surface setup depends on it.
3116          */
3117         if (fb->format->format == DRM_FORMAT_NV12) {
3118                 ret = skl_check_nv12_aux_surface(plane_state);
3119                 if (ret)
3120                         return ret;
3121         } else if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3122                    fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3123                 ret = skl_check_ccs_aux_surface(plane_state);
3124                 if (ret)
3125                         return ret;
3126         } else {
3127                 plane_state->aux.offset = ~0xfff;
3128                 plane_state->aux.x = 0;
3129                 plane_state->aux.y = 0;
3130         }
3131
3132         ret = skl_check_main_surface(crtc_state, plane_state);
3133         if (ret)
3134                 return ret;
3135
3136         return 0;
3137 }
3138
3139 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3140                           const struct intel_plane_state *plane_state)
3141 {
3142         struct drm_i915_private *dev_priv =
3143                 to_i915(plane_state->base.plane->dev);
3144         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3145         const struct drm_framebuffer *fb = plane_state->base.fb;
3146         unsigned int rotation = plane_state->base.rotation;
3147         u32 dspcntr;
3148
3149         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3150
3151         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3152             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3153                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3154
3155         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3156                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3157
3158         if (INTEL_GEN(dev_priv) < 4)
3159                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3160
3161         switch (fb->format->format) {
3162         case DRM_FORMAT_C8:
3163                 dspcntr |= DISPPLANE_8BPP;
3164                 break;
3165         case DRM_FORMAT_XRGB1555:
3166                 dspcntr |= DISPPLANE_BGRX555;
3167                 break;
3168         case DRM_FORMAT_RGB565:
3169                 dspcntr |= DISPPLANE_BGRX565;
3170                 break;
3171         case DRM_FORMAT_XRGB8888:
3172                 dspcntr |= DISPPLANE_BGRX888;
3173                 break;
3174         case DRM_FORMAT_XBGR8888:
3175                 dspcntr |= DISPPLANE_RGBX888;
3176                 break;
3177         case DRM_FORMAT_XRGB2101010:
3178                 dspcntr |= DISPPLANE_BGRX101010;
3179                 break;
3180         case DRM_FORMAT_XBGR2101010:
3181                 dspcntr |= DISPPLANE_RGBX101010;
3182                 break;
3183         default:
3184                 MISSING_CASE(fb->format->format);
3185                 return 0;
3186         }
3187
3188         if (INTEL_GEN(dev_priv) >= 4 &&
3189             fb->modifier == I915_FORMAT_MOD_X_TILED)
3190                 dspcntr |= DISPPLANE_TILED;
3191
3192         if (rotation & DRM_MODE_ROTATE_180)
3193                 dspcntr |= DISPPLANE_ROTATE_180;
3194
3195         if (rotation & DRM_MODE_REFLECT_X)
3196                 dspcntr |= DISPPLANE_MIRROR;
3197
3198         return dspcntr;
3199 }
3200
3201 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3202 {
3203         struct drm_i915_private *dev_priv =
3204                 to_i915(plane_state->base.plane->dev);
3205         int src_x = plane_state->base.src.x1 >> 16;
3206         int src_y = plane_state->base.src.y1 >> 16;
3207         u32 offset;
3208
3209         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3210
3211         if (INTEL_GEN(dev_priv) >= 4)
3212                 offset = intel_compute_tile_offset(&src_x, &src_y,
3213                                                    plane_state, 0);
3214         else
3215                 offset = 0;
3216
3217         /* HSW/BDW do this automagically in hardware */
3218         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3219                 unsigned int rotation = plane_state->base.rotation;
3220                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3221                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3222
3223                 if (rotation & DRM_MODE_ROTATE_180) {
3224                         src_x += src_w - 1;
3225                         src_y += src_h - 1;
3226                 } else if (rotation & DRM_MODE_REFLECT_X) {
3227                         src_x += src_w - 1;
3228                 }
3229         }
3230
3231         plane_state->main.offset = offset;
3232         plane_state->main.x = src_x;
3233         plane_state->main.y = src_y;
3234
3235         return 0;
3236 }
3237
3238 static void i9xx_update_plane(struct intel_plane *plane,
3239                               const struct intel_crtc_state *crtc_state,
3240                               const struct intel_plane_state *plane_state)
3241 {
3242         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3243         const struct drm_framebuffer *fb = plane_state->base.fb;
3244         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3245         u32 linear_offset;
3246         u32 dspcntr = plane_state->ctl;
3247         i915_reg_t reg = DSPCNTR(i9xx_plane);
3248         int x = plane_state->main.x;
3249         int y = plane_state->main.y;
3250         unsigned long irqflags;
3251         u32 dspaddr_offset;
3252
3253         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3254
3255         if (INTEL_GEN(dev_priv) >= 4)
3256                 dspaddr_offset = plane_state->main.offset;
3257         else
3258                 dspaddr_offset = linear_offset;
3259
3260         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3261
3262         if (INTEL_GEN(dev_priv) < 4) {
3263                 /* pipesrc and dspsize control the size that is scaled from,
3264                  * which should always be the user's requested size.
3265                  */
3266                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3267                               ((crtc_state->pipe_src_h - 1) << 16) |
3268                               (crtc_state->pipe_src_w - 1));
3269                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3270         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3271                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3272                               ((crtc_state->pipe_src_h - 1) << 16) |
3273                               (crtc_state->pipe_src_w - 1));
3274                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3275                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3276         }
3277
3278         I915_WRITE_FW(reg, dspcntr);
3279
3280         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), fb->pitches[0]);
3281         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3282                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3283                               intel_plane_ggtt_offset(plane_state) +
3284                               dspaddr_offset);
3285                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3286         } else if (INTEL_GEN(dev_priv) >= 4) {
3287                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3288                               intel_plane_ggtt_offset(plane_state) +
3289                               dspaddr_offset);
3290                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3291                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3292         } else {
3293                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3294                               intel_plane_ggtt_offset(plane_state) +
3295                               dspaddr_offset);
3296         }
3297         POSTING_READ_FW(reg);
3298
3299         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3300 }
3301
3302 static void i9xx_disable_plane(struct intel_plane *plane,
3303                                struct intel_crtc *crtc)
3304 {
3305         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3306         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3307         unsigned long irqflags;
3308
3309         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3310
3311         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3312         if (INTEL_GEN(dev_priv) >= 4)
3313                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3314         else
3315                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3316         POSTING_READ_FW(DSPCNTR(i9xx_plane));
3317
3318         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3319 }
3320
3321 static bool i9xx_plane_get_hw_state(struct intel_plane *plane)
3322 {
3323         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3324         enum intel_display_power_domain power_domain;
3325         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3326         enum pipe pipe = plane->pipe;
3327         bool ret;
3328
3329         /*
3330          * Not 100% correct for planes that can move between pipes,
3331          * but that's only the case for gen2-4 which don't have any
3332          * display power wells.
3333          */
3334         power_domain = POWER_DOMAIN_PIPE(pipe);
3335         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3336                 return false;
3337
3338         ret = I915_READ(DSPCNTR(i9xx_plane)) & DISPLAY_PLANE_ENABLE;
3339
3340         intel_display_power_put(dev_priv, power_domain);
3341
3342         return ret;
3343 }
3344
3345 static u32
3346 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int plane)
3347 {
3348         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3349                 return 64;
3350         else
3351                 return intel_tile_width_bytes(fb, plane);
3352 }
3353
3354 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3355 {
3356         struct drm_device *dev = intel_crtc->base.dev;
3357         struct drm_i915_private *dev_priv = to_i915(dev);
3358
3359         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3360         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3361         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3362 }
3363
3364 /*
3365  * This function detaches (aka. unbinds) unused scalers in hardware
3366  */
3367 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3368 {
3369         struct intel_crtc_scaler_state *scaler_state;
3370         int i;
3371
3372         scaler_state = &intel_crtc->config->scaler_state;
3373
3374         /* loop through and disable scalers that aren't in use */
3375         for (i = 0; i < intel_crtc->num_scalers; i++) {
3376                 if (!scaler_state->scalers[i].in_use)
3377                         skl_detach_scaler(intel_crtc, i);
3378         }
3379 }
3380
3381 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3382                      unsigned int rotation)
3383 {
3384         u32 stride;
3385
3386         if (plane >= fb->format->num_planes)
3387                 return 0;
3388
3389         stride = intel_fb_pitch(fb, plane, rotation);
3390
3391         /*
3392          * The stride is either expressed as a multiple of 64 bytes chunks for
3393          * linear buffers or in number of tiles for tiled buffers.
3394          */
3395         if (drm_rotation_90_or_270(rotation))
3396                 stride /= intel_tile_height(fb, plane);
3397         else
3398                 stride /= intel_fb_stride_alignment(fb, plane);
3399
3400         return stride;
3401 }
3402
3403 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3404 {
3405         switch (pixel_format) {
3406         case DRM_FORMAT_C8:
3407                 return PLANE_CTL_FORMAT_INDEXED;
3408         case DRM_FORMAT_RGB565:
3409                 return PLANE_CTL_FORMAT_RGB_565;
3410         case DRM_FORMAT_XBGR8888:
3411         case DRM_FORMAT_ABGR8888:
3412                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3413         case DRM_FORMAT_XRGB8888:
3414         case DRM_FORMAT_ARGB8888:
3415                 return PLANE_CTL_FORMAT_XRGB_8888;
3416         case DRM_FORMAT_XRGB2101010:
3417                 return PLANE_CTL_FORMAT_XRGB_2101010;
3418         case DRM_FORMAT_XBGR2101010:
3419                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3420         case DRM_FORMAT_YUYV:
3421                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3422         case DRM_FORMAT_YVYU:
3423                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3424         case DRM_FORMAT_UYVY:
3425                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3426         case DRM_FORMAT_VYUY:
3427                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3428         default:
3429                 MISSING_CASE(pixel_format);
3430         }
3431
3432         return 0;
3433 }
3434
3435 /*
3436  * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3437  * to be already pre-multiplied. We need to add a knob (or a different
3438  * DRM_FORMAT) for user-space to configure that.
3439  */
3440 static u32 skl_plane_ctl_alpha(uint32_t pixel_format)
3441 {
3442         switch (pixel_format) {
3443         case DRM_FORMAT_ABGR8888:
3444         case DRM_FORMAT_ARGB8888:
3445                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3446         default:
3447                 return PLANE_CTL_ALPHA_DISABLE;
3448         }
3449 }
3450
3451 static u32 glk_plane_color_ctl_alpha(uint32_t pixel_format)
3452 {
3453         switch (pixel_format) {
3454         case DRM_FORMAT_ABGR8888:
3455         case DRM_FORMAT_ARGB8888:
3456                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3457         default:
3458                 return PLANE_COLOR_ALPHA_DISABLE;
3459         }
3460 }
3461
3462 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3463 {
3464         switch (fb_modifier) {
3465         case DRM_FORMAT_MOD_LINEAR:
3466                 break;
3467         case I915_FORMAT_MOD_X_TILED:
3468                 return PLANE_CTL_TILED_X;
3469         case I915_FORMAT_MOD_Y_TILED:
3470                 return PLANE_CTL_TILED_Y;
3471         case I915_FORMAT_MOD_Y_TILED_CCS:
3472                 return PLANE_CTL_TILED_Y | PLANE_CTL_DECOMPRESSION_ENABLE;
3473         case I915_FORMAT_MOD_Yf_TILED:
3474                 return PLANE_CTL_TILED_YF;
3475         case I915_FORMAT_MOD_Yf_TILED_CCS:
3476                 return PLANE_CTL_TILED_YF | PLANE_CTL_DECOMPRESSION_ENABLE;
3477         default:
3478                 MISSING_CASE(fb_modifier);
3479         }
3480
3481         return 0;
3482 }
3483
3484 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3485 {
3486         switch (rotate) {
3487         case DRM_MODE_ROTATE_0:
3488                 break;
3489         /*
3490          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3491          * while i915 HW rotation is clockwise, thats why this swapping.
3492          */
3493         case DRM_MODE_ROTATE_90:
3494                 return PLANE_CTL_ROTATE_270;
3495         case DRM_MODE_ROTATE_180:
3496                 return PLANE_CTL_ROTATE_180;
3497         case DRM_MODE_ROTATE_270:
3498                 return PLANE_CTL_ROTATE_90;
3499         default:
3500                 MISSING_CASE(rotate);
3501         }
3502
3503         return 0;
3504 }
3505
3506 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3507 {
3508         switch (reflect) {
3509         case 0:
3510                 break;
3511         case DRM_MODE_REFLECT_X:
3512                 return PLANE_CTL_FLIP_HORIZONTAL;
3513         case DRM_MODE_REFLECT_Y:
3514         default:
3515                 MISSING_CASE(reflect);
3516         }
3517
3518         return 0;
3519 }
3520
3521 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3522                   const struct intel_plane_state *plane_state)
3523 {
3524         struct drm_i915_private *dev_priv =
3525                 to_i915(plane_state->base.plane->dev);
3526         const struct drm_framebuffer *fb = plane_state->base.fb;
3527         unsigned int rotation = plane_state->base.rotation;
3528         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3529         u32 plane_ctl;
3530
3531         plane_ctl = PLANE_CTL_ENABLE;
3532
3533         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3534                 plane_ctl |= skl_plane_ctl_alpha(fb->format->format);
3535                 plane_ctl |=
3536                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3537                         PLANE_CTL_PIPE_CSC_ENABLE |
3538                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3539
3540                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3541                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3542
3543                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3544                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3545         }
3546
3547         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3548         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3549         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3550
3551         if (INTEL_GEN(dev_priv) >= 10)
3552                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3553                                                 DRM_MODE_REFLECT_MASK);
3554
3555         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3556                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3557         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3558                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3559
3560         return plane_ctl;
3561 }
3562
3563 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3564                         const struct intel_plane_state *plane_state)
3565 {
3566         const struct drm_framebuffer *fb = plane_state->base.fb;
3567         u32 plane_color_ctl = 0;
3568
3569         plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3570         plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3571         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3572         plane_color_ctl |= glk_plane_color_ctl_alpha(fb->format->format);
3573
3574         if (intel_format_is_yuv(fb->format->format)) {
3575                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3576                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3577                 else
3578                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3579
3580                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3581                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3582         }
3583
3584         return plane_color_ctl;
3585 }
3586
3587 static int
3588 __intel_display_resume(struct drm_device *dev,
3589                        struct drm_atomic_state *state,
3590                        struct drm_modeset_acquire_ctx *ctx)
3591 {
3592         struct drm_crtc_state *crtc_state;
3593         struct drm_crtc *crtc;
3594         int i, ret;
3595
3596         intel_modeset_setup_hw_state(dev, ctx);
3597         i915_redisable_vga(to_i915(dev));
3598
3599         if (!state)
3600                 return 0;
3601
3602         /*
3603          * We've duplicated the state, pointers to the old state are invalid.
3604          *
3605          * Don't attempt to use the old state until we commit the duplicated state.
3606          */
3607         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3608                 /*
3609                  * Force recalculation even if we restore
3610                  * current state. With fast modeset this may not result
3611                  * in a modeset when the state is compatible.
3612                  */
3613                 crtc_state->mode_changed = true;
3614         }
3615
3616         /* ignore any reset values/BIOS leftovers in the WM registers */
3617         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3618                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3619
3620         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3621
3622         WARN_ON(ret == -EDEADLK);
3623         return ret;
3624 }
3625
3626 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3627 {
3628         return intel_has_gpu_reset(dev_priv) &&
3629                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3630 }
3631
3632 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3633 {
3634         struct drm_device *dev = &dev_priv->drm;
3635         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3636         struct drm_atomic_state *state;
3637         int ret;
3638
3639
3640         /* reset doesn't touch the display */
3641         if (!i915_modparams.force_reset_modeset_test &&
3642             !gpu_reset_clobbers_display(dev_priv))
3643                 return;
3644
3645         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3646         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3647         wake_up_all(&dev_priv->gpu_error.wait_queue);
3648
3649         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3650                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3651                 i915_gem_set_wedged(dev_priv);
3652         }
3653
3654         /*
3655          * Need mode_config.mutex so that we don't
3656          * trample ongoing ->detect() and whatnot.
3657          */
3658         mutex_lock(&dev->mode_config.mutex);
3659         drm_modeset_acquire_init(ctx, 0);
3660         while (1) {
3661                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3662                 if (ret != -EDEADLK)
3663                         break;
3664
3665                 drm_modeset_backoff(ctx);
3666         }
3667         /*
3668          * Disabling the crtcs gracefully seems nicer. Also the
3669          * g33 docs say we should at least disable all the planes.
3670          */
3671         state = drm_atomic_helper_duplicate_state(dev, ctx);
3672         if (IS_ERR(state)) {
3673                 ret = PTR_ERR(state);
3674                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3675                 return;
3676         }
3677
3678         ret = drm_atomic_helper_disable_all(dev, ctx);
3679         if (ret) {
3680                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3681                 drm_atomic_state_put(state);
3682                 return;
3683         }
3684
3685         dev_priv->modeset_restore_state = state;
3686         state->acquire_ctx = ctx;
3687 }
3688
3689 void intel_finish_reset(struct drm_i915_private *dev_priv)
3690 {
3691         struct drm_device *dev = &dev_priv->drm;
3692         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3693         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3694         int ret;
3695
3696         /* reset doesn't touch the display */
3697         if (!i915_modparams.force_reset_modeset_test &&
3698             !gpu_reset_clobbers_display(dev_priv))
3699                 return;
3700
3701         if (!state)
3702                 goto unlock;
3703
3704         dev_priv->modeset_restore_state = NULL;
3705
3706         /* reset doesn't touch the display */
3707         if (!gpu_reset_clobbers_display(dev_priv)) {
3708                 /* for testing only restore the display */
3709                 ret = __intel_display_resume(dev, state, ctx);
3710                 if (ret)
3711                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3712         } else {
3713                 /*
3714                  * The display has been reset as well,
3715                  * so need a full re-initialization.
3716                  */
3717                 intel_runtime_pm_disable_interrupts(dev_priv);
3718                 intel_runtime_pm_enable_interrupts(dev_priv);
3719
3720                 intel_pps_unlock_regs_wa(dev_priv);
3721                 intel_modeset_init_hw(dev);
3722                 intel_init_clock_gating(dev_priv);
3723
3724                 spin_lock_irq(&dev_priv->irq_lock);
3725                 if (dev_priv->display.hpd_irq_setup)
3726                         dev_priv->display.hpd_irq_setup(dev_priv);
3727                 spin_unlock_irq(&dev_priv->irq_lock);
3728
3729                 ret = __intel_display_resume(dev, state, ctx);
3730                 if (ret)
3731                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3732
3733                 intel_hpd_init(dev_priv);
3734         }
3735
3736         drm_atomic_state_put(state);
3737 unlock:
3738         drm_modeset_drop_locks(ctx);
3739         drm_modeset_acquire_fini(ctx);
3740         mutex_unlock(&dev->mode_config.mutex);
3741
3742         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3743 }
3744
3745 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3746                                      const struct intel_crtc_state *new_crtc_state)
3747 {
3748         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3749         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3750
3751         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3752         crtc->base.mode = new_crtc_state->base.mode;
3753
3754         /*
3755          * Update pipe size and adjust fitter if needed: the reason for this is
3756          * that in compute_mode_changes we check the native mode (not the pfit
3757          * mode) to see if we can flip rather than do a full mode set. In the
3758          * fastboot case, we'll flip, but if we don't update the pipesrc and
3759          * pfit state, we'll end up with a big fb scanned out into the wrong
3760          * sized surface.
3761          */
3762
3763         I915_WRITE(PIPESRC(crtc->pipe),
3764                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3765                    (new_crtc_state->pipe_src_h - 1));
3766
3767         /* on skylake this is done by detaching scalers */
3768         if (INTEL_GEN(dev_priv) >= 9) {
3769                 skl_detach_scalers(crtc);
3770
3771                 if (new_crtc_state->pch_pfit.enabled)
3772                         skylake_pfit_enable(crtc);
3773         } else if (HAS_PCH_SPLIT(dev_priv)) {
3774                 if (new_crtc_state->pch_pfit.enabled)
3775                         ironlake_pfit_enable(crtc);
3776                 else if (old_crtc_state->pch_pfit.enabled)
3777                         ironlake_pfit_disable(crtc, true);
3778         }
3779 }
3780
3781 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3782 {
3783         struct drm_device *dev = crtc->base.dev;
3784         struct drm_i915_private *dev_priv = to_i915(dev);
3785         int pipe = crtc->pipe;
3786         i915_reg_t reg;
3787         u32 temp;
3788
3789         /* enable normal train */
3790         reg = FDI_TX_CTL(pipe);
3791         temp = I915_READ(reg);
3792         if (IS_IVYBRIDGE(dev_priv)) {
3793                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3794                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3795         } else {
3796                 temp &= ~FDI_LINK_TRAIN_NONE;
3797                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3798         }
3799         I915_WRITE(reg, temp);
3800
3801         reg = FDI_RX_CTL(pipe);
3802         temp = I915_READ(reg);
3803         if (HAS_PCH_CPT(dev_priv)) {
3804                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3805                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3806         } else {
3807                 temp &= ~FDI_LINK_TRAIN_NONE;
3808                 temp |= FDI_LINK_TRAIN_NONE;
3809         }
3810         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3811
3812         /* wait one idle pattern time */
3813         POSTING_READ(reg);
3814         udelay(1000);
3815
3816         /* IVB wants error correction enabled */
3817         if (IS_IVYBRIDGE(dev_priv))
3818                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3819                            FDI_FE_ERRC_ENABLE);
3820 }
3821
3822 /* The FDI link training functions for ILK/Ibexpeak. */
3823 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3824                                     const struct intel_crtc_state *crtc_state)
3825 {
3826         struct drm_device *dev = crtc->base.dev;
3827         struct drm_i915_private *dev_priv = to_i915(dev);
3828         int pipe = crtc->pipe;
3829         i915_reg_t reg;
3830         u32 temp, tries;
3831
3832         /* FDI needs bits from pipe first */
3833         assert_pipe_enabled(dev_priv, pipe);
3834
3835         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3836            for train result */
3837         reg = FDI_RX_IMR(pipe);
3838         temp = I915_READ(reg);
3839         temp &= ~FDI_RX_SYMBOL_LOCK;
3840         temp &= ~FDI_RX_BIT_LOCK;
3841         I915_WRITE(reg, temp);
3842         I915_READ(reg);
3843         udelay(150);
3844
3845         /* enable CPU FDI TX and PCH FDI RX */
3846         reg = FDI_TX_CTL(pipe);
3847         temp = I915_READ(reg);
3848         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3849         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3850         temp &= ~FDI_LINK_TRAIN_NONE;
3851         temp |= FDI_LINK_TRAIN_PATTERN_1;
3852         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3853
3854         reg = FDI_RX_CTL(pipe);
3855         temp = I915_READ(reg);
3856         temp &= ~FDI_LINK_TRAIN_NONE;
3857         temp |= FDI_LINK_TRAIN_PATTERN_1;
3858         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3859
3860         POSTING_READ(reg);
3861         udelay(150);
3862
3863         /* Ironlake workaround, enable clock pointer after FDI enable*/
3864         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3865         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3866                    FDI_RX_PHASE_SYNC_POINTER_EN);
3867
3868         reg = FDI_RX_IIR(pipe);
3869         for (tries = 0; tries < 5; tries++) {
3870                 temp = I915_READ(reg);
3871                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3872
3873                 if ((temp & FDI_RX_BIT_LOCK)) {
3874                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3875                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3876                         break;
3877                 }
3878         }
3879         if (tries == 5)
3880                 DRM_ERROR("FDI train 1 fail!\n");
3881
3882         /* Train 2 */
3883         reg = FDI_TX_CTL(pipe);
3884         temp = I915_READ(reg);
3885         temp &= ~FDI_LINK_TRAIN_NONE;
3886         temp |= FDI_LINK_TRAIN_PATTERN_2;
3887         I915_WRITE(reg, temp);
3888
3889         reg = FDI_RX_CTL(pipe);
3890         temp = I915_READ(reg);
3891         temp &= ~FDI_LINK_TRAIN_NONE;
3892         temp |= FDI_LINK_TRAIN_PATTERN_2;
3893         I915_WRITE(reg, temp);
3894
3895         POSTING_READ(reg);
3896         udelay(150);
3897
3898         reg = FDI_RX_IIR(pipe);
3899         for (tries = 0; tries < 5; tries++) {
3900                 temp = I915_READ(reg);
3901                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3902
3903                 if (temp & FDI_RX_SYMBOL_LOCK) {
3904                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3905                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3906                         break;
3907                 }
3908         }
3909         if (tries == 5)
3910                 DRM_ERROR("FDI train 2 fail!\n");
3911
3912         DRM_DEBUG_KMS("FDI train done\n");
3913
3914 }
3915
3916 static const int snb_b_fdi_train_param[] = {
3917         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3918         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3919         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3920         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3921 };
3922
3923 /* The FDI link training functions for SNB/Cougarpoint. */
3924 static void gen6_fdi_link_train(struct intel_crtc *crtc,
3925                                 const struct intel_crtc_state *crtc_state)
3926 {
3927         struct drm_device *dev = crtc->base.dev;
3928         struct drm_i915_private *dev_priv = to_i915(dev);
3929         int pipe = crtc->pipe;
3930         i915_reg_t reg;
3931         u32 temp, i, retry;
3932
3933         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3934            for train result */
3935         reg = FDI_RX_IMR(pipe);
3936         temp = I915_READ(reg);
3937         temp &= ~FDI_RX_SYMBOL_LOCK;
3938         temp &= ~FDI_RX_BIT_LOCK;
3939         I915_WRITE(reg, temp);
3940
3941         POSTING_READ(reg);
3942         udelay(150);
3943
3944         /* enable CPU FDI TX and PCH FDI RX */
3945         reg = FDI_TX_CTL(pipe);
3946         temp = I915_READ(reg);
3947         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3948         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3949         temp &= ~FDI_LINK_TRAIN_NONE;
3950         temp |= FDI_LINK_TRAIN_PATTERN_1;
3951         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3952         /* SNB-B */
3953         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3954         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3955
3956         I915_WRITE(FDI_RX_MISC(pipe),
3957                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3958
3959         reg = FDI_RX_CTL(pipe);
3960         temp = I915_READ(reg);
3961         if (HAS_PCH_CPT(dev_priv)) {
3962                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3963                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3964         } else {
3965                 temp &= ~FDI_LINK_TRAIN_NONE;
3966                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3967         }
3968         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3969
3970         POSTING_READ(reg);
3971         udelay(150);
3972
3973         for (i = 0; i < 4; i++) {
3974                 reg = FDI_TX_CTL(pipe);
3975                 temp = I915_READ(reg);
3976                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3977                 temp |= snb_b_fdi_train_param[i];
3978                 I915_WRITE(reg, temp);
3979
3980                 POSTING_READ(reg);
3981                 udelay(500);
3982
3983                 for (retry = 0; retry < 5; retry++) {
3984                         reg = FDI_RX_IIR(pipe);
3985                         temp = I915_READ(reg);
3986                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3987                         if (temp & FDI_RX_BIT_LOCK) {
3988                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3989                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3990                                 break;
3991                         }
3992                         udelay(50);
3993                 }
3994                 if (retry < 5)
3995                         break;
3996         }
3997         if (i == 4)
3998                 DRM_ERROR("FDI train 1 fail!\n");
3999
4000         /* Train 2 */
4001         reg = FDI_TX_CTL(pipe);
4002         temp = I915_READ(reg);
4003         temp &= ~FDI_LINK_TRAIN_NONE;
4004         temp |= FDI_LINK_TRAIN_PATTERN_2;
4005         if (IS_GEN6(dev_priv)) {
4006                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4007                 /* SNB-B */
4008                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4009         }
4010         I915_WRITE(reg, temp);
4011
4012         reg = FDI_RX_CTL(pipe);
4013         temp = I915_READ(reg);
4014         if (HAS_PCH_CPT(dev_priv)) {
4015                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4016                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4017         } else {
4018                 temp &= ~FDI_LINK_TRAIN_NONE;
4019                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4020         }
4021         I915_WRITE(reg, temp);
4022
4023         POSTING_READ(reg);
4024         udelay(150);
4025
4026         for (i = 0; i < 4; i++) {
4027                 reg = FDI_TX_CTL(pipe);
4028                 temp = I915_READ(reg);
4029                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4030                 temp |= snb_b_fdi_train_param[i];
4031                 I915_WRITE(reg, temp);
4032
4033                 POSTING_READ(reg);
4034                 udelay(500);
4035
4036                 for (retry = 0; retry < 5; retry++) {
4037                         reg = FDI_RX_IIR(pipe);
4038                         temp = I915_READ(reg);
4039                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4040                         if (temp & FDI_RX_SYMBOL_LOCK) {
4041                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4042                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4043                                 break;
4044                         }
4045                         udelay(50);
4046                 }
4047                 if (retry < 5)
4048                         break;
4049         }
4050         if (i == 4)
4051                 DRM_ERROR("FDI train 2 fail!\n");
4052
4053         DRM_DEBUG_KMS("FDI train done.\n");
4054 }
4055
4056 /* Manual link training for Ivy Bridge A0 parts */
4057 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4058                                       const struct intel_crtc_state *crtc_state)
4059 {
4060         struct drm_device *dev = crtc->base.dev;
4061         struct drm_i915_private *dev_priv = to_i915(dev);
4062         int pipe = crtc->pipe;
4063         i915_reg_t reg;
4064         u32 temp, i, j;
4065
4066         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4067            for train result */
4068         reg = FDI_RX_IMR(pipe);
4069         temp = I915_READ(reg);
4070         temp &= ~FDI_RX_SYMBOL_LOCK;
4071         temp &= ~FDI_RX_BIT_LOCK;
4072         I915_WRITE(reg, temp);
4073
4074         POSTING_READ(reg);
4075         udelay(150);
4076
4077         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4078                       I915_READ(FDI_RX_IIR(pipe)));
4079
4080         /* Try each vswing and preemphasis setting twice before moving on */
4081         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4082                 /* disable first in case we need to retry */
4083                 reg = FDI_TX_CTL(pipe);
4084                 temp = I915_READ(reg);
4085                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4086                 temp &= ~FDI_TX_ENABLE;
4087                 I915_WRITE(reg, temp);
4088
4089                 reg = FDI_RX_CTL(pipe);
4090                 temp = I915_READ(reg);
4091                 temp &= ~FDI_LINK_TRAIN_AUTO;
4092                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4093                 temp &= ~FDI_RX_ENABLE;
4094                 I915_WRITE(reg, temp);
4095
4096                 /* enable CPU FDI TX and PCH FDI RX */
4097                 reg = FDI_TX_CTL(pipe);
4098                 temp = I915_READ(reg);
4099                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4100                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4101                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4102                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4103                 temp |= snb_b_fdi_train_param[j/2];
4104                 temp |= FDI_COMPOSITE_SYNC;
4105                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4106
4107                 I915_WRITE(FDI_RX_MISC(pipe),
4108                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4109
4110                 reg = FDI_RX_CTL(pipe);
4111                 temp = I915_READ(reg);
4112                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4113                 temp |= FDI_COMPOSITE_SYNC;
4114                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4115
4116                 POSTING_READ(reg);
4117                 udelay(1); /* should be 0.5us */
4118
4119                 for (i = 0; i < 4; i++) {
4120                         reg = FDI_RX_IIR(pipe);
4121                         temp = I915_READ(reg);
4122                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4123
4124                         if (temp & FDI_RX_BIT_LOCK ||
4125                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4126                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4127                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4128                                               i);
4129                                 break;
4130                         }
4131                         udelay(1); /* should be 0.5us */
4132                 }
4133                 if (i == 4) {
4134                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4135                         continue;
4136                 }
4137
4138                 /* Train 2 */
4139                 reg = FDI_TX_CTL(pipe);
4140                 temp = I915_READ(reg);
4141                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4142                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4143                 I915_WRITE(reg, temp);
4144
4145                 reg = FDI_RX_CTL(pipe);
4146                 temp = I915_READ(reg);
4147                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4148                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4149                 I915_WRITE(reg, temp);
4150
4151                 POSTING_READ(reg);
4152                 udelay(2); /* should be 1.5us */
4153
4154                 for (i = 0; i < 4; i++) {
4155                         reg = FDI_RX_IIR(pipe);
4156                         temp = I915_READ(reg);
4157                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4158
4159                         if (temp & FDI_RX_SYMBOL_LOCK ||
4160                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4161                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4162                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4163                                               i);
4164                                 goto train_done;
4165                         }
4166                         udelay(2); /* should be 1.5us */
4167                 }
4168                 if (i == 4)
4169                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4170         }
4171
4172 train_done:
4173         DRM_DEBUG_KMS("FDI train done.\n");
4174 }
4175
4176 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4177 {
4178         struct drm_device *dev = intel_crtc->base.dev;
4179         struct drm_i915_private *dev_priv = to_i915(dev);
4180         int pipe = intel_crtc->pipe;
4181         i915_reg_t reg;
4182         u32 temp;
4183
4184         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4185         reg = FDI_RX_CTL(pipe);
4186         temp = I915_READ(reg);
4187         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4188         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4189         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4190         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4191
4192         POSTING_READ(reg);
4193         udelay(200);
4194
4195         /* Switch from Rawclk to PCDclk */
4196         temp = I915_READ(reg);
4197         I915_WRITE(reg, temp | FDI_PCDCLK);
4198
4199         POSTING_READ(reg);
4200         udelay(200);
4201
4202         /* Enable CPU FDI TX PLL, always on for Ironlake */
4203         reg = FDI_TX_CTL(pipe);
4204         temp = I915_READ(reg);
4205         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4206                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4207
4208                 POSTING_READ(reg);
4209                 udelay(100);
4210         }
4211 }
4212
4213 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4214 {
4215         struct drm_device *dev = intel_crtc->base.dev;
4216         struct drm_i915_private *dev_priv = to_i915(dev);
4217         int pipe = intel_crtc->pipe;
4218         i915_reg_t reg;
4219         u32 temp;
4220
4221         /* Switch from PCDclk to Rawclk */
4222         reg = FDI_RX_CTL(pipe);
4223         temp = I915_READ(reg);
4224         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4225
4226         /* Disable CPU FDI TX PLL */
4227         reg = FDI_TX_CTL(pipe);
4228         temp = I915_READ(reg);
4229         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4230
4231         POSTING_READ(reg);
4232         udelay(100);
4233
4234         reg = FDI_RX_CTL(pipe);
4235         temp = I915_READ(reg);
4236         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4237
4238         /* Wait for the clocks to turn off. */
4239         POSTING_READ(reg);
4240         udelay(100);
4241 }
4242
4243 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4244 {
4245         struct drm_device *dev = crtc->dev;
4246         struct drm_i915_private *dev_priv = to_i915(dev);
4247         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4248         int pipe = intel_crtc->pipe;
4249         i915_reg_t reg;
4250         u32 temp;
4251
4252         /* disable CPU FDI tx and PCH FDI rx */
4253         reg = FDI_TX_CTL(pipe);
4254         temp = I915_READ(reg);
4255         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4256         POSTING_READ(reg);
4257
4258         reg = FDI_RX_CTL(pipe);
4259         temp = I915_READ(reg);
4260         temp &= ~(0x7 << 16);
4261         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4262         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4263
4264         POSTING_READ(reg);
4265         udelay(100);
4266
4267         /* Ironlake workaround, disable clock pointer after downing FDI */
4268         if (HAS_PCH_IBX(dev_priv))
4269                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4270
4271         /* still set train pattern 1 */
4272         reg = FDI_TX_CTL(pipe);
4273         temp = I915_READ(reg);
4274         temp &= ~FDI_LINK_TRAIN_NONE;
4275         temp |= FDI_LINK_TRAIN_PATTERN_1;
4276         I915_WRITE(reg, temp);
4277
4278         reg = FDI_RX_CTL(pipe);
4279         temp = I915_READ(reg);
4280         if (HAS_PCH_CPT(dev_priv)) {
4281                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4282                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4283         } else {
4284                 temp &= ~FDI_LINK_TRAIN_NONE;
4285                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4286         }
4287         /* BPC in FDI rx is consistent with that in PIPECONF */
4288         temp &= ~(0x07 << 16);
4289         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4290         I915_WRITE(reg, temp);
4291
4292         POSTING_READ(reg);
4293         udelay(100);
4294 }
4295
4296 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4297 {
4298         struct drm_crtc *crtc;
4299         bool cleanup_done;
4300
4301         drm_for_each_crtc(crtc, &dev_priv->drm) {
4302                 struct drm_crtc_commit *commit;
4303                 spin_lock(&crtc->commit_lock);
4304                 commit = list_first_entry_or_null(&crtc->commit_list,
4305                                                   struct drm_crtc_commit, commit_entry);
4306                 cleanup_done = commit ?
4307                         try_wait_for_completion(&commit->cleanup_done) : true;
4308                 spin_unlock(&crtc->commit_lock);
4309
4310                 if (cleanup_done)
4311                         continue;
4312
4313                 drm_crtc_wait_one_vblank(crtc);
4314
4315                 return true;
4316         }
4317
4318         return false;
4319 }
4320
4321 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4322 {
4323         u32 temp;
4324
4325         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4326
4327         mutex_lock(&dev_priv->sb_lock);
4328
4329         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4330         temp |= SBI_SSCCTL_DISABLE;
4331         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4332
4333         mutex_unlock(&dev_priv->sb_lock);
4334 }
4335
4336 /* Program iCLKIP clock to the desired frequency */
4337 static void lpt_program_iclkip(struct intel_crtc *crtc)
4338 {
4339         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4340         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4341         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4342         u32 temp;
4343
4344         lpt_disable_iclkip(dev_priv);
4345
4346         /* The iCLK virtual clock root frequency is in MHz,
4347          * but the adjusted_mode->crtc_clock in in KHz. To get the
4348          * divisors, it is necessary to divide one by another, so we
4349          * convert the virtual clock precision to KHz here for higher
4350          * precision.
4351          */
4352         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4353                 u32 iclk_virtual_root_freq = 172800 * 1000;
4354                 u32 iclk_pi_range = 64;
4355                 u32 desired_divisor;
4356
4357                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4358                                                     clock << auxdiv);
4359                 divsel = (desired_divisor / iclk_pi_range) - 2;
4360                 phaseinc = desired_divisor % iclk_pi_range;
4361
4362                 /*
4363                  * Near 20MHz is a corner case which is
4364                  * out of range for the 7-bit divisor
4365                  */
4366                 if (divsel <= 0x7f)
4367                         break;
4368         }
4369
4370         /* This should not happen with any sane values */
4371         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4372                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4373         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4374                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4375
4376         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4377                         clock,
4378                         auxdiv,
4379                         divsel,
4380                         phasedir,
4381                         phaseinc);
4382
4383         mutex_lock(&dev_priv->sb_lock);
4384
4385         /* Program SSCDIVINTPHASE6 */
4386         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4387         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4388         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4389         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4390         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4391         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4392         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4393         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4394
4395         /* Program SSCAUXDIV */
4396         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4397         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4398         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4399         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4400
4401         /* Enable modulator and associated divider */
4402         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4403         temp &= ~SBI_SSCCTL_DISABLE;
4404         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4405
4406         mutex_unlock(&dev_priv->sb_lock);
4407
4408         /* Wait for initialization time */
4409         udelay(24);
4410
4411         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4412 }
4413
4414 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4415 {
4416         u32 divsel, phaseinc, auxdiv;
4417         u32 iclk_virtual_root_freq = 172800 * 1000;
4418         u32 iclk_pi_range = 64;
4419         u32 desired_divisor;
4420         u32 temp;
4421
4422         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4423                 return 0;
4424
4425         mutex_lock(&dev_priv->sb_lock);
4426
4427         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4428         if (temp & SBI_SSCCTL_DISABLE) {
4429                 mutex_unlock(&dev_priv->sb_lock);
4430                 return 0;
4431         }
4432
4433         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4434         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4435                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4436         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4437                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4438
4439         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4440         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4441                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4442
4443         mutex_unlock(&dev_priv->sb_lock);
4444
4445         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4446
4447         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4448                                  desired_divisor << auxdiv);
4449 }
4450
4451 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4452                                                 enum pipe pch_transcoder)
4453 {
4454         struct drm_device *dev = crtc->base.dev;
4455         struct drm_i915_private *dev_priv = to_i915(dev);
4456         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4457
4458         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4459                    I915_READ(HTOTAL(cpu_transcoder)));
4460         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4461                    I915_READ(HBLANK(cpu_transcoder)));
4462         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4463                    I915_READ(HSYNC(cpu_transcoder)));
4464
4465         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4466                    I915_READ(VTOTAL(cpu_transcoder)));
4467         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4468                    I915_READ(VBLANK(cpu_transcoder)));
4469         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4470                    I915_READ(VSYNC(cpu_transcoder)));
4471         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4472                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4473 }
4474
4475 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4476 {
4477         struct drm_i915_private *dev_priv = to_i915(dev);
4478         uint32_t temp;
4479
4480         temp = I915_READ(SOUTH_CHICKEN1);
4481         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4482                 return;
4483
4484         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4485         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4486
4487         temp &= ~FDI_BC_BIFURCATION_SELECT;
4488         if (enable)
4489                 temp |= FDI_BC_BIFURCATION_SELECT;
4490
4491         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4492         I915_WRITE(SOUTH_CHICKEN1, temp);
4493         POSTING_READ(SOUTH_CHICKEN1);
4494 }
4495
4496 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4497 {
4498         struct drm_device *dev = intel_crtc->base.dev;
4499
4500         switch (intel_crtc->pipe) {
4501         case PIPE_A:
4502                 break;
4503         case PIPE_B:
4504                 if (intel_crtc->config->fdi_lanes > 2)
4505                         cpt_set_fdi_bc_bifurcation(dev, false);
4506                 else
4507                         cpt_set_fdi_bc_bifurcation(dev, true);
4508
4509                 break;
4510         case PIPE_C:
4511                 cpt_set_fdi_bc_bifurcation(dev, true);
4512
4513                 break;
4514         default:
4515                 BUG();
4516         }
4517 }
4518
4519 /* Return which DP Port should be selected for Transcoder DP control */
4520 static enum port
4521 intel_trans_dp_port_sel(struct intel_crtc *crtc)
4522 {
4523         struct drm_device *dev = crtc->base.dev;
4524         struct intel_encoder *encoder;
4525
4526         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
4527                 if (encoder->type == INTEL_OUTPUT_DP ||
4528                     encoder->type == INTEL_OUTPUT_EDP)
4529                         return encoder->port;
4530         }
4531
4532         return -1;
4533 }
4534
4535 /*
4536  * Enable PCH resources required for PCH ports:
4537  *   - PCH PLLs
4538  *   - FDI training & RX/TX
4539  *   - update transcoder timings
4540  *   - DP transcoding bits
4541  *   - transcoder
4542  */
4543 static void ironlake_pch_enable(const struct intel_crtc_state *crtc_state)
4544 {
4545         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4546         struct drm_device *dev = crtc->base.dev;
4547         struct drm_i915_private *dev_priv = to_i915(dev);
4548         int pipe = crtc->pipe;
4549         u32 temp;
4550
4551         assert_pch_transcoder_disabled(dev_priv, pipe);
4552
4553         if (IS_IVYBRIDGE(dev_priv))
4554                 ivybridge_update_fdi_bc_bifurcation(crtc);
4555
4556         /* Write the TU size bits before fdi link training, so that error
4557          * detection works. */
4558         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4559                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4560
4561         /* For PCH output, training FDI link */
4562         dev_priv->display.fdi_link_train(crtc, crtc_state);
4563
4564         /* We need to program the right clock selection before writing the pixel
4565          * mutliplier into the DPLL. */
4566         if (HAS_PCH_CPT(dev_priv)) {
4567                 u32 sel;
4568
4569                 temp = I915_READ(PCH_DPLL_SEL);
4570                 temp |= TRANS_DPLL_ENABLE(pipe);
4571                 sel = TRANS_DPLLB_SEL(pipe);
4572                 if (crtc_state->shared_dpll ==
4573                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4574                         temp |= sel;
4575                 else
4576                         temp &= ~sel;
4577                 I915_WRITE(PCH_DPLL_SEL, temp);
4578         }
4579
4580         /* XXX: pch pll's can be enabled any time before we enable the PCH
4581          * transcoder, and we actually should do this to not upset any PCH
4582          * transcoder that already use the clock when we share it.
4583          *
4584          * Note that enable_shared_dpll tries to do the right thing, but
4585          * get_shared_dpll unconditionally resets the pll - we need that to have
4586          * the right LVDS enable sequence. */
4587         intel_enable_shared_dpll(crtc);
4588
4589         /* set transcoder timing, panel must allow it */
4590         assert_panel_unlocked(dev_priv, pipe);
4591         ironlake_pch_transcoder_set_timings(crtc, pipe);
4592
4593         intel_fdi_normal_train(crtc);
4594
4595         /* For PCH DP, enable TRANS_DP_CTL */
4596         if (HAS_PCH_CPT(dev_priv) &&
4597             intel_crtc_has_dp_encoder(crtc_state)) {
4598                 const struct drm_display_mode *adjusted_mode =
4599                         &crtc_state->base.adjusted_mode;
4600                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4601                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4602                 temp = I915_READ(reg);
4603                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4604                           TRANS_DP_SYNC_MASK |
4605                           TRANS_DP_BPC_MASK);
4606                 temp |= TRANS_DP_OUTPUT_ENABLE;
4607                 temp |= bpc << 9; /* same format but at 11:9 */
4608
4609                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4610                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4611                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4612                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4613
4614                 switch (intel_trans_dp_port_sel(crtc)) {
4615                 case PORT_B:
4616                         temp |= TRANS_DP_PORT_SEL_B;
4617                         break;
4618                 case PORT_C:
4619                         temp |= TRANS_DP_PORT_SEL_C;
4620                         break;
4621                 case PORT_D:
4622                         temp |= TRANS_DP_PORT_SEL_D;
4623                         break;
4624                 default:
4625                         BUG();
4626                 }
4627
4628                 I915_WRITE(reg, temp);
4629         }
4630
4631         ironlake_enable_pch_transcoder(dev_priv, pipe);
4632 }
4633
4634 static void lpt_pch_enable(const struct intel_crtc_state *crtc_state)
4635 {
4636         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4637         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4638         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4639
4640         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4641
4642         lpt_program_iclkip(crtc);
4643
4644         /* Set transcoder timing. */
4645         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4646
4647         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4648 }
4649
4650 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4651 {
4652         struct drm_i915_private *dev_priv = to_i915(dev);
4653         i915_reg_t dslreg = PIPEDSL(pipe);
4654         u32 temp;
4655
4656         temp = I915_READ(dslreg);
4657         udelay(500);
4658         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4659                 if (wait_for(I915_READ(dslreg) != temp, 5))
4660                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4661         }
4662 }
4663
4664 static int
4665 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4666                   unsigned int scaler_user, int *scaler_id,
4667                   int src_w, int src_h, int dst_w, int dst_h)
4668 {
4669         struct intel_crtc_scaler_state *scaler_state =
4670                 &crtc_state->scaler_state;
4671         struct intel_crtc *intel_crtc =
4672                 to_intel_crtc(crtc_state->base.crtc);
4673         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4674         const struct drm_display_mode *adjusted_mode =
4675                 &crtc_state->base.adjusted_mode;
4676         int need_scaling;
4677
4678         /*
4679          * Src coordinates are already rotated by 270 degrees for
4680          * the 90/270 degree plane rotation cases (to match the
4681          * GTT mapping), hence no need to account for rotation here.
4682          */
4683         need_scaling = src_w != dst_w || src_h != dst_h;
4684
4685         if (crtc_state->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4686                 need_scaling = true;
4687
4688         /*
4689          * Scaling/fitting not supported in IF-ID mode in GEN9+
4690          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4691          * Once NV12 is enabled, handle it here while allocating scaler
4692          * for NV12.
4693          */
4694         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4695             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4696                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4697                 return -EINVAL;
4698         }
4699
4700         /*
4701          * if plane is being disabled or scaler is no more required or force detach
4702          *  - free scaler binded to this plane/crtc
4703          *  - in order to do this, update crtc->scaler_usage
4704          *
4705          * Here scaler state in crtc_state is set free so that
4706          * scaler can be assigned to other user. Actual register
4707          * update to free the scaler is done in plane/panel-fit programming.
4708          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4709          */
4710         if (force_detach || !need_scaling) {
4711                 if (*scaler_id >= 0) {
4712                         scaler_state->scaler_users &= ~(1 << scaler_user);
4713                         scaler_state->scalers[*scaler_id].in_use = 0;
4714
4715                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4716                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4717                                 intel_crtc->pipe, scaler_user, *scaler_id,
4718                                 scaler_state->scaler_users);
4719                         *scaler_id = -1;
4720                 }
4721                 return 0;
4722         }
4723
4724         /* range checks */
4725         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4726                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4727
4728                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4729                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4730                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4731                         "size is out of scaler range\n",
4732                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4733                 return -EINVAL;
4734         }
4735
4736         /* mark this plane as a scaler user in crtc_state */
4737         scaler_state->scaler_users |= (1 << scaler_user);
4738         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4739                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4740                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4741                 scaler_state->scaler_users);
4742
4743         return 0;
4744 }
4745
4746 /**
4747  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4748  *
4749  * @state: crtc's scaler state
4750  *
4751  * Return
4752  *     0 - scaler_usage updated successfully
4753  *    error - requested scaling cannot be supported or other error condition
4754  */
4755 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4756 {
4757         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4758
4759         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4760                 &state->scaler_state.scaler_id,
4761                 state->pipe_src_w, state->pipe_src_h,
4762                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4763 }
4764
4765 /**
4766  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4767  *
4768  * @state: crtc's scaler state
4769  * @plane_state: atomic plane state to update
4770  *
4771  * Return
4772  *     0 - scaler_usage updated successfully
4773  *    error - requested scaling cannot be supported or other error condition
4774  */
4775 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4776                                    struct intel_plane_state *plane_state)
4777 {
4778
4779         struct intel_plane *intel_plane =
4780                 to_intel_plane(plane_state->base.plane);
4781         struct drm_framebuffer *fb = plane_state->base.fb;
4782         int ret;
4783
4784         bool force_detach = !fb || !plane_state->base.visible;
4785
4786         ret = skl_update_scaler(crtc_state, force_detach,
4787                                 drm_plane_index(&intel_plane->base),
4788                                 &plane_state->scaler_id,
4789                                 drm_rect_width(&plane_state->base.src) >> 16,
4790                                 drm_rect_height(&plane_state->base.src) >> 16,
4791                                 drm_rect_width(&plane_state->base.dst),
4792                                 drm_rect_height(&plane_state->base.dst));
4793
4794         if (ret || plane_state->scaler_id < 0)
4795                 return ret;
4796
4797         /* check colorkey */
4798         if (plane_state->ckey.flags) {
4799                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4800                               intel_plane->base.base.id,
4801                               intel_plane->base.name);
4802                 return -EINVAL;
4803         }
4804
4805         /* Check src format */
4806         switch (fb->format->format) {
4807         case DRM_FORMAT_RGB565:
4808         case DRM_FORMAT_XBGR8888:
4809         case DRM_FORMAT_XRGB8888:
4810         case DRM_FORMAT_ABGR8888:
4811         case DRM_FORMAT_ARGB8888:
4812         case DRM_FORMAT_XRGB2101010:
4813         case DRM_FORMAT_XBGR2101010:
4814         case DRM_FORMAT_YUYV:
4815         case DRM_FORMAT_YVYU:
4816         case DRM_FORMAT_UYVY:
4817         case DRM_FORMAT_VYUY:
4818                 break;
4819         default:
4820                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4821                               intel_plane->base.base.id, intel_plane->base.name,
4822                               fb->base.id, fb->format->format);
4823                 return -EINVAL;
4824         }
4825
4826         return 0;
4827 }
4828
4829 static void skylake_scaler_disable(struct intel_crtc *crtc)
4830 {
4831         int i;
4832
4833         for (i = 0; i < crtc->num_scalers; i++)
4834                 skl_detach_scaler(crtc, i);
4835 }
4836
4837 static void skylake_pfit_enable(struct intel_crtc *crtc)
4838 {
4839         struct drm_device *dev = crtc->base.dev;
4840         struct drm_i915_private *dev_priv = to_i915(dev);
4841         int pipe = crtc->pipe;
4842         struct intel_crtc_scaler_state *scaler_state =
4843                 &crtc->config->scaler_state;
4844
4845         if (crtc->config->pch_pfit.enabled) {
4846                 int id;
4847
4848                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4849                         return;
4850
4851                 id = scaler_state->scaler_id;
4852                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4853                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4854                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4855                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4856         }
4857 }
4858
4859 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4860 {
4861         struct drm_device *dev = crtc->base.dev;
4862         struct drm_i915_private *dev_priv = to_i915(dev);
4863         int pipe = crtc->pipe;
4864
4865         if (crtc->config->pch_pfit.enabled) {
4866                 /* Force use of hard-coded filter coefficients
4867                  * as some pre-programmed values are broken,
4868                  * e.g. x201.
4869                  */
4870                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4871                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4872                                                  PF_PIPE_SEL_IVB(pipe));
4873                 else
4874                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4875                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4876                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4877         }
4878 }
4879
4880 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
4881 {
4882         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4883         struct drm_device *dev = crtc->base.dev;
4884         struct drm_i915_private *dev_priv = to_i915(dev);
4885
4886         if (!crtc_state->ips_enabled)
4887                 return;
4888
4889         /*
4890          * We can only enable IPS after we enable a plane and wait for a vblank
4891          * This function is called from post_plane_update, which is run after
4892          * a vblank wait.
4893          */
4894         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
4895
4896         if (IS_BROADWELL(dev_priv)) {
4897                 mutex_lock(&dev_priv->pcu_lock);
4898                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
4899                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
4900                 mutex_unlock(&dev_priv->pcu_lock);
4901                 /* Quoting Art Runyan: "its not safe to expect any particular
4902                  * value in IPS_CTL bit 31 after enabling IPS through the
4903                  * mailbox." Moreover, the mailbox may return a bogus state,
4904                  * so we need to just enable it and continue on.
4905                  */
4906         } else {
4907                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4908                 /* The bit only becomes 1 in the next vblank, so this wait here
4909                  * is essentially intel_wait_for_vblank. If we don't have this
4910                  * and don't wait for vblanks until the end of crtc_enable, then
4911                  * the HW state readout code will complain that the expected
4912                  * IPS_CTL value is not the one we read. */
4913                 if (intel_wait_for_register(dev_priv,
4914                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4915                                             50))
4916                         DRM_ERROR("Timed out waiting for IPS enable\n");
4917         }
4918 }
4919
4920 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
4921 {
4922         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4923         struct drm_device *dev = crtc->base.dev;
4924         struct drm_i915_private *dev_priv = to_i915(dev);
4925
4926         if (!crtc_state->ips_enabled)
4927                 return;
4928
4929         if (IS_BROADWELL(dev_priv)) {
4930                 mutex_lock(&dev_priv->pcu_lock);
4931                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4932                 mutex_unlock(&dev_priv->pcu_lock);
4933                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4934                 if (intel_wait_for_register(dev_priv,
4935                                             IPS_CTL, IPS_ENABLE, 0,
4936                                             42))
4937                         DRM_ERROR("Timed out waiting for IPS disable\n");
4938         } else {
4939                 I915_WRITE(IPS_CTL, 0);
4940                 POSTING_READ(IPS_CTL);
4941         }
4942
4943         /* We need to wait for a vblank before we can disable the plane. */
4944         intel_wait_for_vblank(dev_priv, crtc->pipe);
4945 }
4946
4947 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4948 {
4949         if (intel_crtc->overlay) {
4950                 struct drm_device *dev = intel_crtc->base.dev;
4951
4952                 mutex_lock(&dev->struct_mutex);
4953                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4954                 mutex_unlock(&dev->struct_mutex);
4955         }
4956
4957         /* Let userspace switch the overlay on again. In most cases userspace
4958          * has to recompute where to put it anyway.
4959          */
4960 }
4961
4962 /**
4963  * intel_post_enable_primary - Perform operations after enabling primary plane
4964  * @crtc: the CRTC whose primary plane was just enabled
4965  *
4966  * Performs potentially sleeping operations that must be done after the primary
4967  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4968  * called due to an explicit primary plane update, or due to an implicit
4969  * re-enable that is caused when a sprite plane is updated to no longer
4970  * completely hide the primary plane.
4971  */
4972 static void
4973 intel_post_enable_primary(struct drm_crtc *crtc,
4974                           const struct intel_crtc_state *new_crtc_state)
4975 {
4976         struct drm_device *dev = crtc->dev;
4977         struct drm_i915_private *dev_priv = to_i915(dev);
4978         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4979         int pipe = intel_crtc->pipe;
4980
4981         /*
4982          * Gen2 reports pipe underruns whenever all planes are disabled.
4983          * So don't enable underrun reporting before at least some planes
4984          * are enabled.
4985          * FIXME: Need to fix the logic to work when we turn off all planes
4986          * but leave the pipe running.
4987          */
4988         if (IS_GEN2(dev_priv))
4989                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4990
4991         /* Underruns don't always raise interrupts, so check manually. */
4992         intel_check_cpu_fifo_underruns(dev_priv);
4993         intel_check_pch_fifo_underruns(dev_priv);
4994 }
4995
4996 /* FIXME get rid of this and use pre_plane_update */
4997 static void
4998 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4999 {
5000         struct drm_device *dev = crtc->dev;
5001         struct drm_i915_private *dev_priv = to_i915(dev);
5002         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5003         int pipe = intel_crtc->pipe;
5004
5005         /*
5006          * Gen2 reports pipe underruns whenever all planes are disabled.
5007          * So disable underrun reporting before all the planes get disabled.
5008          */
5009         if (IS_GEN2(dev_priv))
5010                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5011
5012         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5013
5014         /*
5015          * Vblank time updates from the shadow to live plane control register
5016          * are blocked if the memory self-refresh mode is active at that
5017          * moment. So to make sure the plane gets truly disabled, disable
5018          * first the self-refresh mode. The self-refresh enable bit in turn
5019          * will be checked/applied by the HW only at the next frame start
5020          * event which is after the vblank start event, so we need to have a
5021          * wait-for-vblank between disabling the plane and the pipe.
5022          */
5023         if (HAS_GMCH_DISPLAY(dev_priv) &&
5024             intel_set_memory_cxsr(dev_priv, false))
5025                 intel_wait_for_vblank(dev_priv, pipe);
5026 }
5027
5028 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5029                                        const struct intel_crtc_state *new_crtc_state)
5030 {
5031         if (!old_crtc_state->ips_enabled)
5032                 return false;
5033
5034         if (needs_modeset(&new_crtc_state->base))
5035                 return true;
5036
5037         return !new_crtc_state->ips_enabled;
5038 }
5039
5040 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5041                                        const struct intel_crtc_state *new_crtc_state)
5042 {
5043         if (!new_crtc_state->ips_enabled)
5044                 return false;
5045
5046         if (needs_modeset(&new_crtc_state->base))
5047                 return true;
5048
5049         /*
5050          * We can't read out IPS on broadwell, assume the worst and
5051          * forcibly enable IPS on the first fastset.
5052          */
5053         if (new_crtc_state->update_pipe &&
5054             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5055                 return true;
5056
5057         return !old_crtc_state->ips_enabled;
5058 }
5059
5060 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5061 {
5062         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5063         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5064         struct intel_crtc_state *pipe_config =
5065                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5066                                                 crtc);
5067         struct drm_plane *primary = crtc->base.primary;
5068         struct drm_plane_state *old_pri_state =
5069                 drm_atomic_get_existing_plane_state(old_state, primary);
5070
5071         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5072
5073         if (pipe_config->update_wm_post && pipe_config->base.active)
5074                 intel_update_watermarks(crtc);
5075
5076         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5077                 hsw_enable_ips(pipe_config);
5078
5079         if (old_pri_state) {
5080                 struct intel_plane_state *primary_state =
5081                         intel_atomic_get_new_plane_state(to_intel_atomic_state(old_state),
5082                                                          to_intel_plane(primary));
5083                 struct intel_plane_state *old_primary_state =
5084                         to_intel_plane_state(old_pri_state);
5085
5086                 intel_fbc_post_update(crtc);
5087
5088                 if (primary_state->base.visible &&
5089                     (needs_modeset(&pipe_config->base) ||
5090                      !old_primary_state->base.visible))
5091                         intel_post_enable_primary(&crtc->base, pipe_config);
5092         }
5093 }
5094
5095 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5096                                    struct intel_crtc_state *pipe_config)
5097 {
5098         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5099         struct drm_device *dev = crtc->base.dev;
5100         struct drm_i915_private *dev_priv = to_i915(dev);
5101         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5102         struct drm_plane *primary = crtc->base.primary;
5103         struct drm_plane_state *old_pri_state =
5104                 drm_atomic_get_existing_plane_state(old_state, primary);
5105         bool modeset = needs_modeset(&pipe_config->base);
5106         struct intel_atomic_state *old_intel_state =
5107                 to_intel_atomic_state(old_state);
5108
5109         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5110                 hsw_disable_ips(old_crtc_state);
5111
5112         if (old_pri_state) {
5113                 struct intel_plane_state *primary_state =
5114                         intel_atomic_get_new_plane_state(old_intel_state,
5115                                                          to_intel_plane(primary));
5116                 struct intel_plane_state *old_primary_state =
5117                         to_intel_plane_state(old_pri_state);
5118
5119                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5120                 /*
5121                  * Gen2 reports pipe underruns whenever all planes are disabled.
5122                  * So disable underrun reporting before all the planes get disabled.
5123                  */
5124                 if (IS_GEN2(dev_priv) && old_primary_state->base.visible &&
5125                     (modeset || !primary_state->base.visible))
5126                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5127         }
5128
5129         /*
5130          * Vblank time updates from the shadow to live plane control register
5131          * are blocked if the memory self-refresh mode is active at that
5132          * moment. So to make sure the plane gets truly disabled, disable
5133          * first the self-refresh mode. The self-refresh enable bit in turn
5134          * will be checked/applied by the HW only at the next frame start
5135          * event which is after the vblank start event, so we need to have a
5136          * wait-for-vblank between disabling the plane and the pipe.
5137          */
5138         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5139             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5140                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5141
5142         /*
5143          * IVB workaround: must disable low power watermarks for at least
5144          * one frame before enabling scaling.  LP watermarks can be re-enabled
5145          * when scaling is disabled.
5146          *
5147          * WaCxSRDisabledForSpriteScaling:ivb
5148          */
5149         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5150                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5151
5152         /*
5153          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5154          * watermark programming here.
5155          */
5156         if (needs_modeset(&pipe_config->base))
5157                 return;
5158
5159         /*
5160          * For platforms that support atomic watermarks, program the
5161          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5162          * will be the intermediate values that are safe for both pre- and
5163          * post- vblank; when vblank happens, the 'active' values will be set
5164          * to the final 'target' values and we'll do this again to get the
5165          * optimal watermarks.  For gen9+ platforms, the values we program here
5166          * will be the final target values which will get automatically latched
5167          * at vblank time; no further programming will be necessary.
5168          *
5169          * If a platform hasn't been transitioned to atomic watermarks yet,
5170          * we'll continue to update watermarks the old way, if flags tell
5171          * us to.
5172          */
5173         if (dev_priv->display.initial_watermarks != NULL)
5174                 dev_priv->display.initial_watermarks(old_intel_state,
5175                                                      pipe_config);
5176         else if (pipe_config->update_wm_pre)
5177                 intel_update_watermarks(crtc);
5178 }
5179
5180 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5181 {
5182         struct drm_device *dev = crtc->dev;
5183         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5184         struct drm_plane *p;
5185         int pipe = intel_crtc->pipe;
5186
5187         intel_crtc_dpms_overlay_disable(intel_crtc);
5188
5189         drm_for_each_plane_mask(p, dev, plane_mask)
5190                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5191
5192         /*
5193          * FIXME: Once we grow proper nuclear flip support out of this we need
5194          * to compute the mask of flip planes precisely. For the time being
5195          * consider this a flip to a NULL plane.
5196          */
5197         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5198 }
5199
5200 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5201                                           struct intel_crtc_state *crtc_state,
5202                                           struct drm_atomic_state *old_state)
5203 {
5204         struct drm_connector_state *conn_state;
5205         struct drm_connector *conn;
5206         int i;
5207
5208         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5209                 struct intel_encoder *encoder =
5210                         to_intel_encoder(conn_state->best_encoder);
5211
5212                 if (conn_state->crtc != crtc)
5213                         continue;
5214
5215                 if (encoder->pre_pll_enable)
5216                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5217         }
5218 }
5219
5220 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5221                                       struct intel_crtc_state *crtc_state,
5222                                       struct drm_atomic_state *old_state)
5223 {
5224         struct drm_connector_state *conn_state;
5225         struct drm_connector *conn;
5226         int i;
5227
5228         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5229                 struct intel_encoder *encoder =
5230                         to_intel_encoder(conn_state->best_encoder);
5231
5232                 if (conn_state->crtc != crtc)
5233                         continue;
5234
5235                 if (encoder->pre_enable)
5236                         encoder->pre_enable(encoder, crtc_state, conn_state);
5237         }
5238 }
5239
5240 static void intel_encoders_enable(struct drm_crtc *crtc,
5241                                   struct intel_crtc_state *crtc_state,
5242                                   struct drm_atomic_state *old_state)
5243 {
5244         struct drm_connector_state *conn_state;
5245         struct drm_connector *conn;
5246         int i;
5247
5248         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5249                 struct intel_encoder *encoder =
5250                         to_intel_encoder(conn_state->best_encoder);
5251
5252                 if (conn_state->crtc != crtc)
5253                         continue;
5254
5255                 encoder->enable(encoder, crtc_state, conn_state);
5256                 intel_opregion_notify_encoder(encoder, true);
5257         }
5258 }
5259
5260 static void intel_encoders_disable(struct drm_crtc *crtc,
5261                                    struct intel_crtc_state *old_crtc_state,
5262                                    struct drm_atomic_state *old_state)
5263 {
5264         struct drm_connector_state *old_conn_state;
5265         struct drm_connector *conn;
5266         int i;
5267
5268         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5269                 struct intel_encoder *encoder =
5270                         to_intel_encoder(old_conn_state->best_encoder);
5271
5272                 if (old_conn_state->crtc != crtc)
5273                         continue;
5274
5275                 intel_opregion_notify_encoder(encoder, false);
5276                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5277         }
5278 }
5279
5280 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5281                                         struct intel_crtc_state *old_crtc_state,
5282                                         struct drm_atomic_state *old_state)
5283 {
5284         struct drm_connector_state *old_conn_state;
5285         struct drm_connector *conn;
5286         int i;
5287
5288         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5289                 struct intel_encoder *encoder =
5290                         to_intel_encoder(old_conn_state->best_encoder);
5291
5292                 if (old_conn_state->crtc != crtc)
5293                         continue;
5294
5295                 if (encoder->post_disable)
5296                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5297         }
5298 }
5299
5300 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5301                                             struct intel_crtc_state *old_crtc_state,
5302                                             struct drm_atomic_state *old_state)
5303 {
5304         struct drm_connector_state *old_conn_state;
5305         struct drm_connector *conn;
5306         int i;
5307
5308         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5309                 struct intel_encoder *encoder =
5310                         to_intel_encoder(old_conn_state->best_encoder);
5311
5312                 if (old_conn_state->crtc != crtc)
5313                         continue;
5314
5315                 if (encoder->post_pll_disable)
5316                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5317         }
5318 }
5319
5320 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5321                                  struct drm_atomic_state *old_state)
5322 {
5323         struct drm_crtc *crtc = pipe_config->base.crtc;
5324         struct drm_device *dev = crtc->dev;
5325         struct drm_i915_private *dev_priv = to_i915(dev);
5326         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5327         int pipe = intel_crtc->pipe;
5328         struct intel_atomic_state *old_intel_state =
5329                 to_intel_atomic_state(old_state);
5330
5331         if (WARN_ON(intel_crtc->active))
5332                 return;
5333
5334         /*
5335          * Sometimes spurious CPU pipe underruns happen during FDI
5336          * training, at least with VGA+HDMI cloning. Suppress them.
5337          *
5338          * On ILK we get an occasional spurious CPU pipe underruns
5339          * between eDP port A enable and vdd enable. Also PCH port
5340          * enable seems to result in the occasional CPU pipe underrun.
5341          *
5342          * Spurious PCH underruns also occur during PCH enabling.
5343          */
5344         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5345                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5346         if (intel_crtc->config->has_pch_encoder)
5347                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5348
5349         if (intel_crtc->config->has_pch_encoder)
5350                 intel_prepare_shared_dpll(intel_crtc);
5351
5352         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5353                 intel_dp_set_m_n(intel_crtc, M1_N1);
5354
5355         intel_set_pipe_timings(intel_crtc);
5356         intel_set_pipe_src_size(intel_crtc);
5357
5358         if (intel_crtc->config->has_pch_encoder) {
5359                 intel_cpu_transcoder_set_m_n(intel_crtc,
5360                                      &intel_crtc->config->fdi_m_n, NULL);
5361         }
5362
5363         ironlake_set_pipeconf(crtc);
5364
5365         intel_crtc->active = true;
5366
5367         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5368
5369         if (intel_crtc->config->has_pch_encoder) {
5370                 /* Note: FDI PLL enabling _must_ be done before we enable the
5371                  * cpu pipes, hence this is separate from all the other fdi/pch
5372                  * enabling. */
5373                 ironlake_fdi_pll_enable(intel_crtc);
5374         } else {
5375                 assert_fdi_tx_disabled(dev_priv, pipe);
5376                 assert_fdi_rx_disabled(dev_priv, pipe);
5377         }
5378
5379         ironlake_pfit_enable(intel_crtc);
5380
5381         /*
5382          * On ILK+ LUT must be loaded before the pipe is running but with
5383          * clocks enabled
5384          */
5385         intel_color_load_luts(&pipe_config->base);
5386
5387         if (dev_priv->display.initial_watermarks != NULL)
5388                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5389         intel_enable_pipe(pipe_config);
5390
5391         if (intel_crtc->config->has_pch_encoder)
5392                 ironlake_pch_enable(pipe_config);
5393
5394         assert_vblank_disabled(crtc);
5395         drm_crtc_vblank_on(crtc);
5396
5397         intel_encoders_enable(crtc, pipe_config, old_state);
5398
5399         if (HAS_PCH_CPT(dev_priv))
5400                 cpt_verify_modeset(dev, intel_crtc->pipe);
5401
5402         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5403         if (intel_crtc->config->has_pch_encoder)
5404                 intel_wait_for_vblank(dev_priv, pipe);
5405         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5406         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5407 }
5408
5409 /* IPS only exists on ULT machines and is tied to pipe A. */
5410 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5411 {
5412         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5413 }
5414
5415 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5416                                             enum pipe pipe, bool apply)
5417 {
5418         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5419         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5420
5421         if (apply)
5422                 val |= mask;
5423         else
5424                 val &= ~mask;
5425
5426         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5427 }
5428
5429 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5430                                 struct drm_atomic_state *old_state)
5431 {
5432         struct drm_crtc *crtc = pipe_config->base.crtc;
5433         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5434         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5435         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5436         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5437         struct intel_atomic_state *old_intel_state =
5438                 to_intel_atomic_state(old_state);
5439         bool psl_clkgate_wa;
5440
5441         if (WARN_ON(intel_crtc->active))
5442                 return;
5443
5444         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5445
5446         if (intel_crtc->config->shared_dpll)
5447                 intel_enable_shared_dpll(intel_crtc);
5448
5449         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5450                 intel_dp_set_m_n(intel_crtc, M1_N1);
5451
5452         if (!transcoder_is_dsi(cpu_transcoder))
5453                 intel_set_pipe_timings(intel_crtc);
5454
5455         intel_set_pipe_src_size(intel_crtc);
5456
5457         if (cpu_transcoder != TRANSCODER_EDP &&
5458             !transcoder_is_dsi(cpu_transcoder)) {
5459                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5460                            intel_crtc->config->pixel_multiplier - 1);
5461         }
5462
5463         if (intel_crtc->config->has_pch_encoder) {
5464                 intel_cpu_transcoder_set_m_n(intel_crtc,
5465                                      &intel_crtc->config->fdi_m_n, NULL);
5466         }
5467
5468         if (!transcoder_is_dsi(cpu_transcoder))
5469                 haswell_set_pipeconf(crtc);
5470
5471         haswell_set_pipemisc(crtc);
5472
5473         intel_color_set_csc(&pipe_config->base);
5474
5475         intel_crtc->active = true;
5476
5477         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5478
5479         if (!transcoder_is_dsi(cpu_transcoder))
5480                 intel_ddi_enable_pipe_clock(pipe_config);
5481
5482         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5483         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5484                          intel_crtc->config->pch_pfit.enabled;
5485         if (psl_clkgate_wa)
5486                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5487
5488         if (INTEL_GEN(dev_priv) >= 9)
5489                 skylake_pfit_enable(intel_crtc);
5490         else
5491                 ironlake_pfit_enable(intel_crtc);
5492
5493         /*
5494          * On ILK+ LUT must be loaded before the pipe is running but with
5495          * clocks enabled
5496          */
5497         intel_color_load_luts(&pipe_config->base);
5498
5499         intel_ddi_set_pipe_settings(pipe_config);
5500         if (!transcoder_is_dsi(cpu_transcoder))
5501                 intel_ddi_enable_transcoder_func(pipe_config);
5502
5503         if (dev_priv->display.initial_watermarks != NULL)
5504                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5505
5506         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5507         if (!transcoder_is_dsi(cpu_transcoder))
5508                 intel_enable_pipe(pipe_config);
5509
5510         if (intel_crtc->config->has_pch_encoder)
5511                 lpt_pch_enable(pipe_config);
5512
5513         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5514                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5515
5516         assert_vblank_disabled(crtc);
5517         drm_crtc_vblank_on(crtc);
5518
5519         intel_encoders_enable(crtc, pipe_config, old_state);
5520
5521         if (psl_clkgate_wa) {
5522                 intel_wait_for_vblank(dev_priv, pipe);
5523                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5524         }
5525
5526         /* If we change the relative order between pipe/planes enabling, we need
5527          * to change the workaround. */
5528         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5529         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5530                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5531                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5532         }
5533 }
5534
5535 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5536 {
5537         struct drm_device *dev = crtc->base.dev;
5538         struct drm_i915_private *dev_priv = to_i915(dev);
5539         int pipe = crtc->pipe;
5540
5541         /* To avoid upsetting the power well on haswell only disable the pfit if
5542          * it's in use. The hw state code will make sure we get this right. */
5543         if (force || crtc->config->pch_pfit.enabled) {
5544                 I915_WRITE(PF_CTL(pipe), 0);
5545                 I915_WRITE(PF_WIN_POS(pipe), 0);
5546                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5547         }
5548 }
5549
5550 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5551                                   struct drm_atomic_state *old_state)
5552 {
5553         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5554         struct drm_device *dev = crtc->dev;
5555         struct drm_i915_private *dev_priv = to_i915(dev);
5556         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5557         int pipe = intel_crtc->pipe;
5558
5559         /*
5560          * Sometimes spurious CPU pipe underruns happen when the
5561          * pipe is already disabled, but FDI RX/TX is still enabled.
5562          * Happens at least with VGA+HDMI cloning. Suppress them.
5563          */
5564         if (intel_crtc->config->has_pch_encoder) {
5565                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5566                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5567         }
5568
5569         intel_encoders_disable(crtc, old_crtc_state, old_state);
5570
5571         drm_crtc_vblank_off(crtc);
5572         assert_vblank_disabled(crtc);
5573
5574         intel_disable_pipe(old_crtc_state);
5575
5576         ironlake_pfit_disable(intel_crtc, false);
5577
5578         if (intel_crtc->config->has_pch_encoder)
5579                 ironlake_fdi_disable(crtc);
5580
5581         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5582
5583         if (intel_crtc->config->has_pch_encoder) {
5584                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5585
5586                 if (HAS_PCH_CPT(dev_priv)) {
5587                         i915_reg_t reg;
5588                         u32 temp;
5589
5590                         /* disable TRANS_DP_CTL */
5591                         reg = TRANS_DP_CTL(pipe);
5592                         temp = I915_READ(reg);
5593                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5594                                   TRANS_DP_PORT_SEL_MASK);
5595                         temp |= TRANS_DP_PORT_SEL_NONE;
5596                         I915_WRITE(reg, temp);
5597
5598                         /* disable DPLL_SEL */
5599                         temp = I915_READ(PCH_DPLL_SEL);
5600                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5601                         I915_WRITE(PCH_DPLL_SEL, temp);
5602                 }
5603
5604                 ironlake_fdi_pll_disable(intel_crtc);
5605         }
5606
5607         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5608         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5609 }
5610
5611 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5612                                  struct drm_atomic_state *old_state)
5613 {
5614         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5615         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5616         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5617         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5618
5619         intel_encoders_disable(crtc, old_crtc_state, old_state);
5620
5621         drm_crtc_vblank_off(crtc);
5622         assert_vblank_disabled(crtc);
5623
5624         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5625         if (!transcoder_is_dsi(cpu_transcoder))
5626                 intel_disable_pipe(old_crtc_state);
5627
5628         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5629                 intel_ddi_set_vc_payload_alloc(intel_crtc->config, false);
5630
5631         if (!transcoder_is_dsi(cpu_transcoder))
5632                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5633
5634         if (INTEL_GEN(dev_priv) >= 9)
5635                 skylake_scaler_disable(intel_crtc);
5636         else
5637                 ironlake_pfit_disable(intel_crtc, false);
5638
5639         if (!transcoder_is_dsi(cpu_transcoder))
5640                 intel_ddi_disable_pipe_clock(intel_crtc->config);
5641
5642         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5643 }
5644
5645 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5646 {
5647         struct drm_device *dev = crtc->base.dev;
5648         struct drm_i915_private *dev_priv = to_i915(dev);
5649         struct intel_crtc_state *pipe_config = crtc->config;
5650
5651         if (!pipe_config->gmch_pfit.control)
5652                 return;
5653
5654         /*
5655          * The panel fitter should only be adjusted whilst the pipe is disabled,
5656          * according to register description and PRM.
5657          */
5658         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5659         assert_pipe_disabled(dev_priv, crtc->pipe);
5660
5661         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5662         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5663
5664         /* Border color in case we don't scale up to the full screen. Black by
5665          * default, change to something else for debugging. */
5666         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5667 }
5668
5669 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5670 {
5671         switch (port) {
5672         case PORT_A:
5673                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5674         case PORT_B:
5675                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5676         case PORT_C:
5677                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5678         case PORT_D:
5679                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5680         case PORT_E:
5681                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5682         case PORT_F:
5683                 return POWER_DOMAIN_PORT_DDI_F_LANES;
5684         default:
5685                 MISSING_CASE(port);
5686                 return POWER_DOMAIN_PORT_OTHER;
5687         }
5688 }
5689
5690 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5691                                   struct intel_crtc_state *crtc_state)
5692 {
5693         struct drm_device *dev = crtc->dev;
5694         struct drm_i915_private *dev_priv = to_i915(dev);
5695         struct drm_encoder *encoder;
5696         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5697         enum pipe pipe = intel_crtc->pipe;
5698         u64 mask;
5699         enum transcoder transcoder = crtc_state->cpu_transcoder;
5700
5701         if (!crtc_state->base.active)
5702                 return 0;
5703
5704         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
5705         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
5706         if (crtc_state->pch_pfit.enabled ||
5707             crtc_state->pch_pfit.force_thru)
5708                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5709
5710         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5711                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5712
5713                 mask |= BIT_ULL(intel_encoder->power_domain);
5714         }
5715
5716         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5717                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
5718
5719         if (crtc_state->shared_dpll)
5720                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5721
5722         return mask;
5723 }
5724
5725 static u64
5726 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5727                                struct intel_crtc_state *crtc_state)
5728 {
5729         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5730         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5731         enum intel_display_power_domain domain;
5732         u64 domains, new_domains, old_domains;
5733
5734         old_domains = intel_crtc->enabled_power_domains;
5735         intel_crtc->enabled_power_domains = new_domains =
5736                 get_crtc_power_domains(crtc, crtc_state);
5737
5738         domains = new_domains & ~old_domains;
5739
5740         for_each_power_domain(domain, domains)
5741                 intel_display_power_get(dev_priv, domain);
5742
5743         return old_domains & ~new_domains;
5744 }
5745
5746 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5747                                       u64 domains)
5748 {
5749         enum intel_display_power_domain domain;
5750
5751         for_each_power_domain(domain, domains)
5752                 intel_display_power_put(dev_priv, domain);
5753 }
5754
5755 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5756                                    struct drm_atomic_state *old_state)
5757 {
5758         struct intel_atomic_state *old_intel_state =
5759                 to_intel_atomic_state(old_state);
5760         struct drm_crtc *crtc = pipe_config->base.crtc;
5761         struct drm_device *dev = crtc->dev;
5762         struct drm_i915_private *dev_priv = to_i915(dev);
5763         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5764         int pipe = intel_crtc->pipe;
5765
5766         if (WARN_ON(intel_crtc->active))
5767                 return;
5768
5769         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5770                 intel_dp_set_m_n(intel_crtc, M1_N1);
5771
5772         intel_set_pipe_timings(intel_crtc);
5773         intel_set_pipe_src_size(intel_crtc);
5774
5775         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
5776                 struct drm_i915_private *dev_priv = to_i915(dev);
5777
5778                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5779                 I915_WRITE(CHV_CANVAS(pipe), 0);
5780         }
5781
5782         i9xx_set_pipeconf(intel_crtc);
5783
5784         intel_crtc->active = true;
5785
5786         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5787
5788         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5789
5790         if (IS_CHERRYVIEW(dev_priv)) {
5791                 chv_prepare_pll(intel_crtc, intel_crtc->config);
5792                 chv_enable_pll(intel_crtc, intel_crtc->config);
5793         } else {
5794                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
5795                 vlv_enable_pll(intel_crtc, intel_crtc->config);
5796         }
5797
5798         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5799
5800         i9xx_pfit_enable(intel_crtc);
5801
5802         intel_color_load_luts(&pipe_config->base);
5803
5804         dev_priv->display.initial_watermarks(old_intel_state,
5805                                              pipe_config);
5806         intel_enable_pipe(pipe_config);
5807
5808         assert_vblank_disabled(crtc);
5809         drm_crtc_vblank_on(crtc);
5810
5811         intel_encoders_enable(crtc, pipe_config, old_state);
5812 }
5813
5814 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5815 {
5816         struct drm_device *dev = crtc->base.dev;
5817         struct drm_i915_private *dev_priv = to_i915(dev);
5818
5819         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5820         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5821 }
5822
5823 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
5824                              struct drm_atomic_state *old_state)
5825 {
5826         struct intel_atomic_state *old_intel_state =
5827                 to_intel_atomic_state(old_state);
5828         struct drm_crtc *crtc = pipe_config->base.crtc;
5829         struct drm_device *dev = crtc->dev;
5830         struct drm_i915_private *dev_priv = to_i915(dev);
5831         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5832         enum pipe pipe = intel_crtc->pipe;
5833
5834         if (WARN_ON(intel_crtc->active))
5835                 return;
5836
5837         i9xx_set_pll_dividers(intel_crtc);
5838
5839         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5840                 intel_dp_set_m_n(intel_crtc, M1_N1);
5841
5842         intel_set_pipe_timings(intel_crtc);
5843         intel_set_pipe_src_size(intel_crtc);
5844
5845         i9xx_set_pipeconf(intel_crtc);
5846
5847         intel_crtc->active = true;
5848
5849         if (!IS_GEN2(dev_priv))
5850                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5851
5852         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5853
5854         i9xx_enable_pll(intel_crtc, pipe_config);
5855
5856         i9xx_pfit_enable(intel_crtc);
5857
5858         intel_color_load_luts(&pipe_config->base);
5859
5860         if (dev_priv->display.initial_watermarks != NULL)
5861                 dev_priv->display.initial_watermarks(old_intel_state,
5862                                                      intel_crtc->config);
5863         else
5864                 intel_update_watermarks(intel_crtc);
5865         intel_enable_pipe(pipe_config);
5866
5867         assert_vblank_disabled(crtc);
5868         drm_crtc_vblank_on(crtc);
5869
5870         intel_encoders_enable(crtc, pipe_config, old_state);
5871 }
5872
5873 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5874 {
5875         struct drm_device *dev = crtc->base.dev;
5876         struct drm_i915_private *dev_priv = to_i915(dev);
5877
5878         if (!crtc->config->gmch_pfit.control)
5879                 return;
5880
5881         assert_pipe_disabled(dev_priv, crtc->pipe);
5882
5883         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5884                          I915_READ(PFIT_CONTROL));
5885         I915_WRITE(PFIT_CONTROL, 0);
5886 }
5887
5888 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
5889                               struct drm_atomic_state *old_state)
5890 {
5891         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5892         struct drm_device *dev = crtc->dev;
5893         struct drm_i915_private *dev_priv = to_i915(dev);
5894         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5895         int pipe = intel_crtc->pipe;
5896
5897         /*
5898          * On gen2 planes are double buffered but the pipe isn't, so we must
5899          * wait for planes to fully turn off before disabling the pipe.
5900          */
5901         if (IS_GEN2(dev_priv))
5902                 intel_wait_for_vblank(dev_priv, pipe);
5903
5904         intel_encoders_disable(crtc, old_crtc_state, old_state);
5905
5906         drm_crtc_vblank_off(crtc);
5907         assert_vblank_disabled(crtc);
5908
5909         intel_disable_pipe(old_crtc_state);
5910
5911         i9xx_pfit_disable(intel_crtc);
5912
5913         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5914
5915         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
5916                 if (IS_CHERRYVIEW(dev_priv))
5917                         chv_disable_pll(dev_priv, pipe);
5918                 else if (IS_VALLEYVIEW(dev_priv))
5919                         vlv_disable_pll(dev_priv, pipe);
5920                 else
5921                         i9xx_disable_pll(intel_crtc);
5922         }
5923
5924         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
5925
5926         if (!IS_GEN2(dev_priv))
5927                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5928
5929         if (!dev_priv->display.initial_watermarks)
5930                 intel_update_watermarks(intel_crtc);
5931
5932         /* clock the pipe down to 640x480@60 to potentially save power */
5933         if (IS_I830(dev_priv))
5934                 i830_enable_pipe(dev_priv, pipe);
5935 }
5936
5937 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
5938                                         struct drm_modeset_acquire_ctx *ctx)
5939 {
5940         struct intel_encoder *encoder;
5941         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5942         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5943         enum intel_display_power_domain domain;
5944         struct intel_plane *plane;
5945         u64 domains;
5946         struct drm_atomic_state *state;
5947         struct intel_crtc_state *crtc_state;
5948         int ret;
5949
5950         if (!intel_crtc->active)
5951                 return;
5952
5953         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
5954                 const struct intel_plane_state *plane_state =
5955                         to_intel_plane_state(plane->base.state);
5956
5957                 if (plane_state->base.visible)
5958                         intel_plane_disable_noatomic(intel_crtc, plane);
5959         }
5960
5961         state = drm_atomic_state_alloc(crtc->dev);
5962         if (!state) {
5963                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
5964                               crtc->base.id, crtc->name);
5965                 return;
5966         }
5967
5968         state->acquire_ctx = ctx;
5969
5970         /* Everything's already locked, -EDEADLK can't happen. */
5971         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
5972         ret = drm_atomic_add_affected_connectors(state, crtc);
5973
5974         WARN_ON(IS_ERR(crtc_state) || ret);
5975
5976         dev_priv->display.crtc_disable(crtc_state, state);
5977
5978         drm_atomic_state_put(state);
5979
5980         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
5981                       crtc->base.id, crtc->name);
5982
5983         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
5984         crtc->state->active = false;
5985         intel_crtc->active = false;
5986         crtc->enabled = false;
5987         crtc->state->connector_mask = 0;
5988         crtc->state->encoder_mask = 0;
5989
5990         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
5991                 encoder->base.crtc = NULL;
5992
5993         intel_fbc_disable(intel_crtc);
5994         intel_update_watermarks(intel_crtc);
5995         intel_disable_shared_dpll(intel_crtc);
5996
5997         domains = intel_crtc->enabled_power_domains;
5998         for_each_power_domain(domain, domains)
5999                 intel_display_power_put(dev_priv, domain);
6000         intel_crtc->enabled_power_domains = 0;
6001
6002         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6003         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6004         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6005 }
6006
6007 /*
6008  * turn all crtc's off, but do not adjust state
6009  * This has to be paired with a call to intel_modeset_setup_hw_state.
6010  */
6011 int intel_display_suspend(struct drm_device *dev)
6012 {
6013         struct drm_i915_private *dev_priv = to_i915(dev);
6014         struct drm_atomic_state *state;
6015         int ret;
6016
6017         state = drm_atomic_helper_suspend(dev);
6018         ret = PTR_ERR_OR_ZERO(state);
6019         if (ret)
6020                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6021         else
6022                 dev_priv->modeset_restore_state = state;
6023         return ret;
6024 }
6025
6026 void intel_encoder_destroy(struct drm_encoder *encoder)
6027 {
6028         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6029
6030         drm_encoder_cleanup(encoder);
6031         kfree(intel_encoder);
6032 }
6033
6034 /* Cross check the actual hw state with our own modeset state tracking (and it's
6035  * internal consistency). */
6036 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6037                                          struct drm_connector_state *conn_state)
6038 {
6039         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6040
6041         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6042                       connector->base.base.id,
6043                       connector->base.name);
6044
6045         if (connector->get_hw_state(connector)) {
6046                 struct intel_encoder *encoder = connector->encoder;
6047
6048                 I915_STATE_WARN(!crtc_state,
6049                          "connector enabled without attached crtc\n");
6050
6051                 if (!crtc_state)
6052                         return;
6053
6054                 I915_STATE_WARN(!crtc_state->active,
6055                       "connector is active, but attached crtc isn't\n");
6056
6057                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6058                         return;
6059
6060                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6061                         "atomic encoder doesn't match attached encoder\n");
6062
6063                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6064                         "attached encoder crtc differs from connector crtc\n");
6065         } else {
6066                 I915_STATE_WARN(crtc_state && crtc_state->active,
6067                         "attached crtc is active, but connector isn't\n");
6068                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6069                         "best encoder set without crtc!\n");
6070         }
6071 }
6072
6073 int intel_connector_init(struct intel_connector *connector)
6074 {
6075         struct intel_digital_connector_state *conn_state;
6076
6077         /*
6078          * Allocate enough memory to hold intel_digital_connector_state,
6079          * This might be a few bytes too many, but for connectors that don't
6080          * need it we'll free the state and allocate a smaller one on the first
6081          * succesful commit anyway.
6082          */
6083         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
6084         if (!conn_state)
6085                 return -ENOMEM;
6086
6087         __drm_atomic_helper_connector_reset(&connector->base,
6088                                             &conn_state->base);
6089
6090         return 0;
6091 }
6092
6093 struct intel_connector *intel_connector_alloc(void)
6094 {
6095         struct intel_connector *connector;
6096
6097         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6098         if (!connector)
6099                 return NULL;
6100
6101         if (intel_connector_init(connector) < 0) {
6102                 kfree(connector);
6103                 return NULL;
6104         }
6105
6106         return connector;
6107 }
6108
6109 /*
6110  * Free the bits allocated by intel_connector_alloc.
6111  * This should only be used after intel_connector_alloc has returned
6112  * successfully, and before drm_connector_init returns successfully.
6113  * Otherwise the destroy callbacks for the connector and the state should
6114  * take care of proper cleanup/free
6115  */
6116 void intel_connector_free(struct intel_connector *connector)
6117 {
6118         kfree(to_intel_digital_connector_state(connector->base.state));
6119         kfree(connector);
6120 }
6121
6122 /* Simple connector->get_hw_state implementation for encoders that support only
6123  * one connector and no cloning and hence the encoder state determines the state
6124  * of the connector. */
6125 bool intel_connector_get_hw_state(struct intel_connector *connector)
6126 {
6127         enum pipe pipe = 0;
6128         struct intel_encoder *encoder = connector->encoder;
6129
6130         return encoder->get_hw_state(encoder, &pipe);
6131 }
6132
6133 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6134 {
6135         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6136                 return crtc_state->fdi_lanes;
6137
6138         return 0;
6139 }
6140
6141 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6142                                      struct intel_crtc_state *pipe_config)
6143 {
6144         struct drm_i915_private *dev_priv = to_i915(dev);
6145         struct drm_atomic_state *state = pipe_config->base.state;
6146         struct intel_crtc *other_crtc;
6147         struct intel_crtc_state *other_crtc_state;
6148
6149         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6150                       pipe_name(pipe), pipe_config->fdi_lanes);
6151         if (pipe_config->fdi_lanes > 4) {
6152                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6153                               pipe_name(pipe), pipe_config->fdi_lanes);
6154                 return -EINVAL;
6155         }
6156
6157         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6158                 if (pipe_config->fdi_lanes > 2) {
6159                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6160                                       pipe_config->fdi_lanes);
6161                         return -EINVAL;
6162                 } else {
6163                         return 0;
6164                 }
6165         }
6166
6167         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6168                 return 0;
6169
6170         /* Ivybridge 3 pipe is really complicated */
6171         switch (pipe) {
6172         case PIPE_A:
6173                 return 0;
6174         case PIPE_B:
6175                 if (pipe_config->fdi_lanes <= 2)
6176                         return 0;
6177
6178                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6179                 other_crtc_state =
6180                         intel_atomic_get_crtc_state(state, other_crtc);
6181                 if (IS_ERR(other_crtc_state))
6182                         return PTR_ERR(other_crtc_state);
6183
6184                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6185                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6186                                       pipe_name(pipe), pipe_config->fdi_lanes);
6187                         return -EINVAL;
6188                 }
6189                 return 0;
6190         case PIPE_C:
6191                 if (pipe_config->fdi_lanes > 2) {
6192                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6193                                       pipe_name(pipe), pipe_config->fdi_lanes);
6194                         return -EINVAL;
6195                 }
6196
6197                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6198                 other_crtc_state =
6199                         intel_atomic_get_crtc_state(state, other_crtc);
6200                 if (IS_ERR(other_crtc_state))
6201                         return PTR_ERR(other_crtc_state);
6202
6203                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6204                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6205                         return -EINVAL;
6206                 }
6207                 return 0;
6208         default:
6209                 BUG();
6210         }
6211 }
6212
6213 #define RETRY 1
6214 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6215                                        struct intel_crtc_state *pipe_config)
6216 {
6217         struct drm_device *dev = intel_crtc->base.dev;
6218         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6219         int lane, link_bw, fdi_dotclock, ret;
6220         bool needs_recompute = false;
6221
6222 retry:
6223         /* FDI is a binary signal running at ~2.7GHz, encoding
6224          * each output octet as 10 bits. The actual frequency
6225          * is stored as a divider into a 100MHz clock, and the
6226          * mode pixel clock is stored in units of 1KHz.
6227          * Hence the bw of each lane in terms of the mode signal
6228          * is:
6229          */
6230         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6231
6232         fdi_dotclock = adjusted_mode->crtc_clock;
6233
6234         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6235                                            pipe_config->pipe_bpp);
6236
6237         pipe_config->fdi_lanes = lane;
6238
6239         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6240                                link_bw, &pipe_config->fdi_m_n, false);
6241
6242         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6243         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6244                 pipe_config->pipe_bpp -= 2*3;
6245                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6246                               pipe_config->pipe_bpp);
6247                 needs_recompute = true;
6248                 pipe_config->bw_constrained = true;
6249
6250                 goto retry;
6251         }
6252
6253         if (needs_recompute)
6254                 return RETRY;
6255
6256         return ret;
6257 }
6258
6259 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6260 {
6261         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6262         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6263
6264         /* IPS only exists on ULT machines and is tied to pipe A. */
6265         if (!hsw_crtc_supports_ips(crtc))
6266                 return false;
6267
6268         if (!i915_modparams.enable_ips)
6269                 return false;
6270
6271         if (crtc_state->pipe_bpp > 24)
6272                 return false;
6273
6274         /*
6275          * We compare against max which means we must take
6276          * the increased cdclk requirement into account when
6277          * calculating the new cdclk.
6278          *
6279          * Should measure whether using a lower cdclk w/o IPS
6280          */
6281         if (IS_BROADWELL(dev_priv) &&
6282             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6283                 return false;
6284
6285         return true;
6286 }
6287
6288 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6289 {
6290         struct drm_i915_private *dev_priv =
6291                 to_i915(crtc_state->base.crtc->dev);
6292         struct intel_atomic_state *intel_state =
6293                 to_intel_atomic_state(crtc_state->base.state);
6294
6295         if (!hsw_crtc_state_ips_capable(crtc_state))
6296                 return false;
6297
6298         if (crtc_state->ips_force_disable)
6299                 return false;
6300
6301         /* IPS should be fine as long as at least one plane is enabled. */
6302         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6303                 return false;
6304
6305         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6306         if (IS_BROADWELL(dev_priv) &&
6307             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6308                 return false;
6309
6310         return true;
6311 }
6312
6313 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6314 {
6315         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6316
6317         /* GDG double wide on either pipe, otherwise pipe A only */
6318         return INTEL_INFO(dev_priv)->gen < 4 &&
6319                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6320 }
6321
6322 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6323 {
6324         uint32_t pixel_rate;
6325
6326         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6327
6328         /*
6329          * We only use IF-ID interlacing. If we ever use
6330          * PF-ID we'll need to adjust the pixel_rate here.
6331          */
6332
6333         if (pipe_config->pch_pfit.enabled) {
6334                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6335                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6336
6337                 pipe_w = pipe_config->pipe_src_w;
6338                 pipe_h = pipe_config->pipe_src_h;
6339
6340                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6341                 pfit_h = pfit_size & 0xFFFF;
6342                 if (pipe_w < pfit_w)
6343                         pipe_w = pfit_w;
6344                 if (pipe_h < pfit_h)
6345                         pipe_h = pfit_h;
6346
6347                 if (WARN_ON(!pfit_w || !pfit_h))
6348                         return pixel_rate;
6349
6350                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6351                                      pfit_w * pfit_h);
6352         }
6353
6354         return pixel_rate;
6355 }
6356
6357 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6358 {
6359         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6360
6361         if (HAS_GMCH_DISPLAY(dev_priv))
6362                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6363                 crtc_state->pixel_rate =
6364                         crtc_state->base.adjusted_mode.crtc_clock;
6365         else
6366                 crtc_state->pixel_rate =
6367                         ilk_pipe_pixel_rate(crtc_state);
6368 }
6369
6370 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6371                                      struct intel_crtc_state *pipe_config)
6372 {
6373         struct drm_device *dev = crtc->base.dev;
6374         struct drm_i915_private *dev_priv = to_i915(dev);
6375         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6376         int clock_limit = dev_priv->max_dotclk_freq;
6377
6378         if (INTEL_GEN(dev_priv) < 4) {
6379                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6380
6381                 /*
6382                  * Enable double wide mode when the dot clock
6383                  * is > 90% of the (display) core speed.
6384                  */
6385                 if (intel_crtc_supports_double_wide(crtc) &&
6386                     adjusted_mode->crtc_clock > clock_limit) {
6387                         clock_limit = dev_priv->max_dotclk_freq;
6388                         pipe_config->double_wide = true;
6389                 }
6390         }
6391
6392         if (adjusted_mode->crtc_clock > clock_limit) {
6393                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6394                               adjusted_mode->crtc_clock, clock_limit,
6395                               yesno(pipe_config->double_wide));
6396                 return -EINVAL;
6397         }
6398
6399         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6400                 /*
6401                  * There is only one pipe CSC unit per pipe, and we need that
6402                  * for output conversion from RGB->YCBCR. So if CTM is already
6403                  * applied we can't support YCBCR420 output.
6404                  */
6405                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6406                 return -EINVAL;
6407         }
6408
6409         /*
6410          * Pipe horizontal size must be even in:
6411          * - DVO ganged mode
6412          * - LVDS dual channel mode
6413          * - Double wide pipe
6414          */
6415         if (pipe_config->pipe_src_w & 1) {
6416                 if (pipe_config->double_wide) {
6417                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6418                         return -EINVAL;
6419                 }
6420
6421                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6422                     intel_is_dual_link_lvds(dev)) {
6423                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6424                         return -EINVAL;
6425                 }
6426         }
6427
6428         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6429          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6430          */
6431         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6432                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6433                 return -EINVAL;
6434
6435         intel_crtc_compute_pixel_rate(pipe_config);
6436
6437         if (pipe_config->has_pch_encoder)
6438                 return ironlake_fdi_compute_config(crtc, pipe_config);
6439
6440         return 0;
6441 }
6442
6443 static void
6444 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6445 {
6446         while (*num > DATA_LINK_M_N_MASK ||
6447                *den > DATA_LINK_M_N_MASK) {
6448                 *num >>= 1;
6449                 *den >>= 1;
6450         }
6451 }
6452
6453 static void compute_m_n(unsigned int m, unsigned int n,
6454                         uint32_t *ret_m, uint32_t *ret_n,
6455                         bool reduce_m_n)
6456 {
6457         /*
6458          * Reduce M/N as much as possible without loss in precision. Several DP
6459          * dongles in particular seem to be fussy about too large *link* M/N
6460          * values. The passed in values are more likely to have the least
6461          * significant bits zero than M after rounding below, so do this first.
6462          */
6463         if (reduce_m_n) {
6464                 while ((m & 1) == 0 && (n & 1) == 0) {
6465                         m >>= 1;
6466                         n >>= 1;
6467                 }
6468         }
6469
6470         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6471         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6472         intel_reduce_m_n_ratio(ret_m, ret_n);
6473 }
6474
6475 void
6476 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6477                        int pixel_clock, int link_clock,
6478                        struct intel_link_m_n *m_n,
6479                        bool reduce_m_n)
6480 {
6481         m_n->tu = 64;
6482
6483         compute_m_n(bits_per_pixel * pixel_clock,
6484                     link_clock * nlanes * 8,
6485                     &m_n->gmch_m, &m_n->gmch_n,
6486                     reduce_m_n);
6487
6488         compute_m_n(pixel_clock, link_clock,
6489                     &m_n->link_m, &m_n->link_n,
6490                     reduce_m_n);
6491 }
6492
6493 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6494 {
6495         if (i915_modparams.panel_use_ssc >= 0)
6496                 return i915_modparams.panel_use_ssc != 0;
6497         return dev_priv->vbt.lvds_use_ssc
6498                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6499 }
6500
6501 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6502 {
6503         return (1 << dpll->n) << 16 | dpll->m2;
6504 }
6505
6506 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6507 {
6508         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6509 }
6510
6511 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6512                                      struct intel_crtc_state *crtc_state,
6513                                      struct dpll *reduced_clock)
6514 {
6515         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6516         u32 fp, fp2 = 0;
6517
6518         if (IS_PINEVIEW(dev_priv)) {
6519                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6520                 if (reduced_clock)
6521                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6522         } else {
6523                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6524                 if (reduced_clock)
6525                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6526         }
6527
6528         crtc_state->dpll_hw_state.fp0 = fp;
6529
6530         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6531             reduced_clock) {
6532                 crtc_state->dpll_hw_state.fp1 = fp2;
6533         } else {
6534                 crtc_state->dpll_hw_state.fp1 = fp;
6535         }
6536 }
6537
6538 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6539                 pipe)
6540 {
6541         u32 reg_val;
6542
6543         /*
6544          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6545          * and set it to a reasonable value instead.
6546          */
6547         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6548         reg_val &= 0xffffff00;
6549         reg_val |= 0x00000030;
6550         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6551
6552         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6553         reg_val &= 0x00ffffff;
6554         reg_val |= 0x8c000000;
6555         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6556
6557         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6558         reg_val &= 0xffffff00;
6559         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6560
6561         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6562         reg_val &= 0x00ffffff;
6563         reg_val |= 0xb0000000;
6564         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6565 }
6566
6567 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6568                                          struct intel_link_m_n *m_n)
6569 {
6570         struct drm_device *dev = crtc->base.dev;
6571         struct drm_i915_private *dev_priv = to_i915(dev);
6572         int pipe = crtc->pipe;
6573
6574         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6575         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6576         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6577         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6578 }
6579
6580 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6581                                          struct intel_link_m_n *m_n,
6582                                          struct intel_link_m_n *m2_n2)
6583 {
6584         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6585         int pipe = crtc->pipe;
6586         enum transcoder transcoder = crtc->config->cpu_transcoder;
6587
6588         if (INTEL_GEN(dev_priv) >= 5) {
6589                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6590                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6591                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6592                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6593                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6594                  * for gen < 8) and if DRRS is supported (to make sure the
6595                  * registers are not unnecessarily accessed).
6596                  */
6597                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6598                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6599                         I915_WRITE(PIPE_DATA_M2(transcoder),
6600                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6601                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6602                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6603                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6604                 }
6605         } else {
6606                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6607                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6608                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6609                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6610         }
6611 }
6612
6613 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6614 {
6615         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6616
6617         if (m_n == M1_N1) {
6618                 dp_m_n = &crtc->config->dp_m_n;
6619                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6620         } else if (m_n == M2_N2) {
6621
6622                 /*
6623                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6624                  * needs to be programmed into M1_N1.
6625                  */
6626                 dp_m_n = &crtc->config->dp_m2_n2;
6627         } else {
6628                 DRM_ERROR("Unsupported divider value\n");
6629                 return;
6630         }
6631
6632         if (crtc->config->has_pch_encoder)
6633                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6634         else
6635                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6636 }
6637
6638 static void vlv_compute_dpll(struct intel_crtc *crtc,
6639                              struct intel_crtc_state *pipe_config)
6640 {
6641         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6642                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6643         if (crtc->pipe != PIPE_A)
6644                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6645
6646         /* DPLL not used with DSI, but still need the rest set up */
6647         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6648                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6649                         DPLL_EXT_BUFFER_ENABLE_VLV;
6650
6651         pipe_config->dpll_hw_state.dpll_md =
6652                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6653 }
6654
6655 static void chv_compute_dpll(struct intel_crtc *crtc,
6656                              struct intel_crtc_state *pipe_config)
6657 {
6658         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6659                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6660         if (crtc->pipe != PIPE_A)
6661                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6662
6663         /* DPLL not used with DSI, but still need the rest set up */
6664         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6665                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6666
6667         pipe_config->dpll_hw_state.dpll_md =
6668                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6669 }
6670
6671 static void vlv_prepare_pll(struct intel_crtc *crtc,
6672                             const struct intel_crtc_state *pipe_config)
6673 {
6674         struct drm_device *dev = crtc->base.dev;
6675         struct drm_i915_private *dev_priv = to_i915(dev);
6676         enum pipe pipe = crtc->pipe;
6677         u32 mdiv;
6678         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6679         u32 coreclk, reg_val;
6680
6681         /* Enable Refclk */
6682         I915_WRITE(DPLL(pipe),
6683                    pipe_config->dpll_hw_state.dpll &
6684                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6685
6686         /* No need to actually set up the DPLL with DSI */
6687         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6688                 return;
6689
6690         mutex_lock(&dev_priv->sb_lock);
6691
6692         bestn = pipe_config->dpll.n;
6693         bestm1 = pipe_config->dpll.m1;
6694         bestm2 = pipe_config->dpll.m2;
6695         bestp1 = pipe_config->dpll.p1;
6696         bestp2 = pipe_config->dpll.p2;
6697
6698         /* See eDP HDMI DPIO driver vbios notes doc */
6699
6700         /* PLL B needs special handling */
6701         if (pipe == PIPE_B)
6702                 vlv_pllb_recal_opamp(dev_priv, pipe);
6703
6704         /* Set up Tx target for periodic Rcomp update */
6705         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6706
6707         /* Disable target IRef on PLL */
6708         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6709         reg_val &= 0x00ffffff;
6710         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6711
6712         /* Disable fast lock */
6713         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6714
6715         /* Set idtafcrecal before PLL is enabled */
6716         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6717         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6718         mdiv |= ((bestn << DPIO_N_SHIFT));
6719         mdiv |= (1 << DPIO_K_SHIFT);
6720
6721         /*
6722          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6723          * but we don't support that).
6724          * Note: don't use the DAC post divider as it seems unstable.
6725          */
6726         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6727         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6728
6729         mdiv |= DPIO_ENABLE_CALIBRATION;
6730         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6731
6732         /* Set HBR and RBR LPF coefficients */
6733         if (pipe_config->port_clock == 162000 ||
6734             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6735             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6736                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6737                                  0x009f0003);
6738         else
6739                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6740                                  0x00d0000f);
6741
6742         if (intel_crtc_has_dp_encoder(pipe_config)) {
6743                 /* Use SSC source */
6744                 if (pipe == PIPE_A)
6745                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6746                                          0x0df40000);
6747                 else
6748                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6749                                          0x0df70000);
6750         } else { /* HDMI or VGA */
6751                 /* Use bend source */
6752                 if (pipe == PIPE_A)
6753                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6754                                          0x0df70000);
6755                 else
6756                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6757                                          0x0df40000);
6758         }
6759
6760         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6761         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6762         if (intel_crtc_has_dp_encoder(crtc->config))
6763                 coreclk |= 0x01000000;
6764         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6765
6766         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6767         mutex_unlock(&dev_priv->sb_lock);
6768 }
6769
6770 static void chv_prepare_pll(struct intel_crtc *crtc,
6771                             const struct intel_crtc_state *pipe_config)
6772 {
6773         struct drm_device *dev = crtc->base.dev;
6774         struct drm_i915_private *dev_priv = to_i915(dev);
6775         enum pipe pipe = crtc->pipe;
6776         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6777         u32 loopfilter, tribuf_calcntr;
6778         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6779         u32 dpio_val;
6780         int vco;
6781
6782         /* Enable Refclk and SSC */
6783         I915_WRITE(DPLL(pipe),
6784                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6785
6786         /* No need to actually set up the DPLL with DSI */
6787         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6788                 return;
6789
6790         bestn = pipe_config->dpll.n;
6791         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6792         bestm1 = pipe_config->dpll.m1;
6793         bestm2 = pipe_config->dpll.m2 >> 22;
6794         bestp1 = pipe_config->dpll.p1;
6795         bestp2 = pipe_config->dpll.p2;
6796         vco = pipe_config->dpll.vco;
6797         dpio_val = 0;
6798         loopfilter = 0;
6799
6800         mutex_lock(&dev_priv->sb_lock);
6801
6802         /* p1 and p2 divider */
6803         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6804                         5 << DPIO_CHV_S1_DIV_SHIFT |
6805                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6806                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6807                         1 << DPIO_CHV_K_DIV_SHIFT);
6808
6809         /* Feedback post-divider - m2 */
6810         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6811
6812         /* Feedback refclk divider - n and m1 */
6813         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6814                         DPIO_CHV_M1_DIV_BY_2 |
6815                         1 << DPIO_CHV_N_DIV_SHIFT);
6816
6817         /* M2 fraction division */
6818         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6819
6820         /* M2 fraction division enable */
6821         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6822         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6823         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6824         if (bestm2_frac)
6825                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6826         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6827
6828         /* Program digital lock detect threshold */
6829         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6830         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6831                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6832         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6833         if (!bestm2_frac)
6834                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6835         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6836
6837         /* Loop filter */
6838         if (vco == 5400000) {
6839                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6840                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6841                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6842                 tribuf_calcntr = 0x9;
6843         } else if (vco <= 6200000) {
6844                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6845                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6846                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6847                 tribuf_calcntr = 0x9;
6848         } else if (vco <= 6480000) {
6849                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6850                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6851                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6852                 tribuf_calcntr = 0x8;
6853         } else {
6854                 /* Not supported. Apply the same limits as in the max case */
6855                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6856                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6857                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6858                 tribuf_calcntr = 0;
6859         }
6860         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6861
6862         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6863         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6864         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6865         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
6866
6867         /* AFC Recal */
6868         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6869                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6870                         DPIO_AFC_RECAL);
6871
6872         mutex_unlock(&dev_priv->sb_lock);
6873 }
6874
6875 /**
6876  * vlv_force_pll_on - forcibly enable just the PLL
6877  * @dev_priv: i915 private structure
6878  * @pipe: pipe PLL to enable
6879  * @dpll: PLL configuration
6880  *
6881  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6882  * in cases where we need the PLL enabled even when @pipe is not going to
6883  * be enabled.
6884  */
6885 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
6886                      const struct dpll *dpll)
6887 {
6888         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
6889         struct intel_crtc_state *pipe_config;
6890
6891         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
6892         if (!pipe_config)
6893                 return -ENOMEM;
6894
6895         pipe_config->base.crtc = &crtc->base;
6896         pipe_config->pixel_multiplier = 1;
6897         pipe_config->dpll = *dpll;
6898
6899         if (IS_CHERRYVIEW(dev_priv)) {
6900                 chv_compute_dpll(crtc, pipe_config);
6901                 chv_prepare_pll(crtc, pipe_config);
6902                 chv_enable_pll(crtc, pipe_config);
6903         } else {
6904                 vlv_compute_dpll(crtc, pipe_config);
6905                 vlv_prepare_pll(crtc, pipe_config);
6906                 vlv_enable_pll(crtc, pipe_config);
6907         }
6908
6909         kfree(pipe_config);
6910
6911         return 0;
6912 }
6913
6914 /**
6915  * vlv_force_pll_off - forcibly disable just the PLL
6916  * @dev_priv: i915 private structure
6917  * @pipe: pipe PLL to disable
6918  *
6919  * Disable the PLL for @pipe. To be used in cases where we need
6920  * the PLL enabled even when @pipe is not going to be enabled.
6921  */
6922 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
6923 {
6924         if (IS_CHERRYVIEW(dev_priv))
6925                 chv_disable_pll(dev_priv, pipe);
6926         else
6927                 vlv_disable_pll(dev_priv, pipe);
6928 }
6929
6930 static void i9xx_compute_dpll(struct intel_crtc *crtc,
6931                               struct intel_crtc_state *crtc_state,
6932                               struct dpll *reduced_clock)
6933 {
6934         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6935         u32 dpll;
6936         struct dpll *clock = &crtc_state->dpll;
6937
6938         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6939
6940         dpll = DPLL_VGA_MODE_DIS;
6941
6942         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
6943                 dpll |= DPLLB_MODE_LVDS;
6944         else
6945                 dpll |= DPLLB_MODE_DAC_SERIAL;
6946
6947         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
6948             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
6949                 dpll |= (crtc_state->pixel_multiplier - 1)
6950                         << SDVO_MULTIPLIER_SHIFT_HIRES;
6951         }
6952
6953         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
6954             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
6955                 dpll |= DPLL_SDVO_HIGH_SPEED;
6956
6957         if (intel_crtc_has_dp_encoder(crtc_state))
6958                 dpll |= DPLL_SDVO_HIGH_SPEED;
6959
6960         /* compute bitmask from p1 value */
6961         if (IS_PINEVIEW(dev_priv))
6962                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
6963         else {
6964                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6965                 if (IS_G4X(dev_priv) && reduced_clock)
6966                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
6967         }
6968         switch (clock->p2) {
6969         case 5:
6970                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
6971                 break;
6972         case 7:
6973                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
6974                 break;
6975         case 10:
6976                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
6977                 break;
6978         case 14:
6979                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
6980                 break;
6981         }
6982         if (INTEL_GEN(dev_priv) >= 4)
6983                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
6984
6985         if (crtc_state->sdvo_tv_clock)
6986                 dpll |= PLL_REF_INPUT_TVCLKINBC;
6987         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6988                  intel_panel_use_ssc(dev_priv))
6989                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6990         else
6991                 dpll |= PLL_REF_INPUT_DREFCLK;
6992
6993         dpll |= DPLL_VCO_ENABLE;
6994         crtc_state->dpll_hw_state.dpll = dpll;
6995
6996         if (INTEL_GEN(dev_priv) >= 4) {
6997                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
6998                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6999                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7000         }
7001 }
7002
7003 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7004                               struct intel_crtc_state *crtc_state,
7005                               struct dpll *reduced_clock)
7006 {
7007         struct drm_device *dev = crtc->base.dev;
7008         struct drm_i915_private *dev_priv = to_i915(dev);
7009         u32 dpll;
7010         struct dpll *clock = &crtc_state->dpll;
7011
7012         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7013
7014         dpll = DPLL_VGA_MODE_DIS;
7015
7016         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7017                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7018         } else {
7019                 if (clock->p1 == 2)
7020                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7021                 else
7022                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7023                 if (clock->p2 == 4)
7024                         dpll |= PLL_P2_DIVIDE_BY_4;
7025         }
7026
7027         if (!IS_I830(dev_priv) &&
7028             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7029                 dpll |= DPLL_DVO_2X_MODE;
7030
7031         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7032             intel_panel_use_ssc(dev_priv))
7033                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7034         else
7035                 dpll |= PLL_REF_INPUT_DREFCLK;
7036
7037         dpll |= DPLL_VCO_ENABLE;
7038         crtc_state->dpll_hw_state.dpll = dpll;
7039 }
7040
7041 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7042 {
7043         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7044         enum pipe pipe = intel_crtc->pipe;
7045         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7046         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7047         uint32_t crtc_vtotal, crtc_vblank_end;
7048         int vsyncshift = 0;
7049
7050         /* We need to be careful not to changed the adjusted mode, for otherwise
7051          * the hw state checker will get angry at the mismatch. */
7052         crtc_vtotal = adjusted_mode->crtc_vtotal;
7053         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7054
7055         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7056                 /* the chip adds 2 halflines automatically */
7057                 crtc_vtotal -= 1;
7058                 crtc_vblank_end -= 1;
7059
7060                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7061                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7062                 else
7063                         vsyncshift = adjusted_mode->crtc_hsync_start -
7064                                 adjusted_mode->crtc_htotal / 2;
7065                 if (vsyncshift < 0)
7066                         vsyncshift += adjusted_mode->crtc_htotal;
7067         }
7068
7069         if (INTEL_GEN(dev_priv) > 3)
7070                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7071
7072         I915_WRITE(HTOTAL(cpu_transcoder),
7073                    (adjusted_mode->crtc_hdisplay - 1) |
7074                    ((adjusted_mode->crtc_htotal - 1) << 16));
7075         I915_WRITE(HBLANK(cpu_transcoder),
7076                    (adjusted_mode->crtc_hblank_start - 1) |
7077                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7078         I915_WRITE(HSYNC(cpu_transcoder),
7079                    (adjusted_mode->crtc_hsync_start - 1) |
7080                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7081
7082         I915_WRITE(VTOTAL(cpu_transcoder),
7083                    (adjusted_mode->crtc_vdisplay - 1) |
7084                    ((crtc_vtotal - 1) << 16));
7085         I915_WRITE(VBLANK(cpu_transcoder),
7086                    (adjusted_mode->crtc_vblank_start - 1) |
7087                    ((crtc_vblank_end - 1) << 16));
7088         I915_WRITE(VSYNC(cpu_transcoder),
7089                    (adjusted_mode->crtc_vsync_start - 1) |
7090                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7091
7092         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7093          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7094          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7095          * bits. */
7096         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7097             (pipe == PIPE_B || pipe == PIPE_C))
7098                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7099
7100 }
7101
7102 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7103 {
7104         struct drm_device *dev = intel_crtc->base.dev;
7105         struct drm_i915_private *dev_priv = to_i915(dev);
7106         enum pipe pipe = intel_crtc->pipe;
7107
7108         /* pipesrc controls the size that is scaled from, which should
7109          * always be the user's requested size.
7110          */
7111         I915_WRITE(PIPESRC(pipe),
7112                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7113                    (intel_crtc->config->pipe_src_h - 1));
7114 }
7115
7116 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7117                                    struct intel_crtc_state *pipe_config)
7118 {
7119         struct drm_device *dev = crtc->base.dev;
7120         struct drm_i915_private *dev_priv = to_i915(dev);
7121         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7122         uint32_t tmp;
7123
7124         tmp = I915_READ(HTOTAL(cpu_transcoder));
7125         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7126         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7127         tmp = I915_READ(HBLANK(cpu_transcoder));
7128         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7129         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7130         tmp = I915_READ(HSYNC(cpu_transcoder));
7131         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7132         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7133
7134         tmp = I915_READ(VTOTAL(cpu_transcoder));
7135         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7136         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7137         tmp = I915_READ(VBLANK(cpu_transcoder));
7138         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7139         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7140         tmp = I915_READ(VSYNC(cpu_transcoder));
7141         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7142         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7143
7144         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7145                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7146                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7147                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7148         }
7149 }
7150
7151 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7152                                     struct intel_crtc_state *pipe_config)
7153 {
7154         struct drm_device *dev = crtc->base.dev;
7155         struct drm_i915_private *dev_priv = to_i915(dev);
7156         u32 tmp;
7157
7158         tmp = I915_READ(PIPESRC(crtc->pipe));
7159         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7160         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7161
7162         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7163         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7164 }
7165
7166 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7167                                  struct intel_crtc_state *pipe_config)
7168 {
7169         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7170         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7171         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7172         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7173
7174         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7175         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7176         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7177         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7178
7179         mode->flags = pipe_config->base.adjusted_mode.flags;
7180         mode->type = DRM_MODE_TYPE_DRIVER;
7181
7182         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7183
7184         mode->hsync = drm_mode_hsync(mode);
7185         mode->vrefresh = drm_mode_vrefresh(mode);
7186         drm_mode_set_name(mode);
7187 }
7188
7189 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7190 {
7191         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7192         uint32_t pipeconf;
7193
7194         pipeconf = 0;
7195
7196         /* we keep both pipes enabled on 830 */
7197         if (IS_I830(dev_priv))
7198                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7199
7200         if (intel_crtc->config->double_wide)
7201                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7202
7203         /* only g4x and later have fancy bpc/dither controls */
7204         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7205             IS_CHERRYVIEW(dev_priv)) {
7206                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7207                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7208                         pipeconf |= PIPECONF_DITHER_EN |
7209                                     PIPECONF_DITHER_TYPE_SP;
7210
7211                 switch (intel_crtc->config->pipe_bpp) {
7212                 case 18:
7213                         pipeconf |= PIPECONF_6BPC;
7214                         break;
7215                 case 24:
7216                         pipeconf |= PIPECONF_8BPC;
7217                         break;
7218                 case 30:
7219                         pipeconf |= PIPECONF_10BPC;
7220                         break;
7221                 default:
7222                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7223                         BUG();
7224                 }
7225         }
7226
7227         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7228                 if (INTEL_GEN(dev_priv) < 4 ||
7229                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7230                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7231                 else
7232                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7233         } else
7234                 pipeconf |= PIPECONF_PROGRESSIVE;
7235
7236         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7237              intel_crtc->config->limited_color_range)
7238                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7239
7240         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7241         POSTING_READ(PIPECONF(intel_crtc->pipe));
7242 }
7243
7244 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7245                                    struct intel_crtc_state *crtc_state)
7246 {
7247         struct drm_device *dev = crtc->base.dev;
7248         struct drm_i915_private *dev_priv = to_i915(dev);
7249         const struct intel_limit *limit;
7250         int refclk = 48000;
7251
7252         memset(&crtc_state->dpll_hw_state, 0,
7253                sizeof(crtc_state->dpll_hw_state));
7254
7255         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7256                 if (intel_panel_use_ssc(dev_priv)) {
7257                         refclk = dev_priv->vbt.lvds_ssc_freq;
7258                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7259                 }
7260
7261                 limit = &intel_limits_i8xx_lvds;
7262         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7263                 limit = &intel_limits_i8xx_dvo;
7264         } else {
7265                 limit = &intel_limits_i8xx_dac;
7266         }
7267
7268         if (!crtc_state->clock_set &&
7269             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7270                                  refclk, NULL, &crtc_state->dpll)) {
7271                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7272                 return -EINVAL;
7273         }
7274
7275         i8xx_compute_dpll(crtc, crtc_state, NULL);
7276
7277         return 0;
7278 }
7279
7280 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7281                                   struct intel_crtc_state *crtc_state)
7282 {
7283         struct drm_device *dev = crtc->base.dev;
7284         struct drm_i915_private *dev_priv = to_i915(dev);
7285         const struct intel_limit *limit;
7286         int refclk = 96000;
7287
7288         memset(&crtc_state->dpll_hw_state, 0,
7289                sizeof(crtc_state->dpll_hw_state));
7290
7291         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7292                 if (intel_panel_use_ssc(dev_priv)) {
7293                         refclk = dev_priv->vbt.lvds_ssc_freq;
7294                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7295                 }
7296
7297                 if (intel_is_dual_link_lvds(dev))
7298                         limit = &intel_limits_g4x_dual_channel_lvds;
7299                 else
7300                         limit = &intel_limits_g4x_single_channel_lvds;
7301         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7302                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7303                 limit = &intel_limits_g4x_hdmi;
7304         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7305                 limit = &intel_limits_g4x_sdvo;
7306         } else {
7307                 /* The option is for other outputs */
7308                 limit = &intel_limits_i9xx_sdvo;
7309         }
7310
7311         if (!crtc_state->clock_set &&
7312             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7313                                 refclk, NULL, &crtc_state->dpll)) {
7314                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7315                 return -EINVAL;
7316         }
7317
7318         i9xx_compute_dpll(crtc, crtc_state, NULL);
7319
7320         return 0;
7321 }
7322
7323 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7324                                   struct intel_crtc_state *crtc_state)
7325 {
7326         struct drm_device *dev = crtc->base.dev;
7327         struct drm_i915_private *dev_priv = to_i915(dev);
7328         const struct intel_limit *limit;
7329         int refclk = 96000;
7330
7331         memset(&crtc_state->dpll_hw_state, 0,
7332                sizeof(crtc_state->dpll_hw_state));
7333
7334         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7335                 if (intel_panel_use_ssc(dev_priv)) {
7336                         refclk = dev_priv->vbt.lvds_ssc_freq;
7337                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7338                 }
7339
7340                 limit = &intel_limits_pineview_lvds;
7341         } else {
7342                 limit = &intel_limits_pineview_sdvo;
7343         }
7344
7345         if (!crtc_state->clock_set &&
7346             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7347                                 refclk, NULL, &crtc_state->dpll)) {
7348                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7349                 return -EINVAL;
7350         }
7351
7352         i9xx_compute_dpll(crtc, crtc_state, NULL);
7353
7354         return 0;
7355 }
7356
7357 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7358                                    struct intel_crtc_state *crtc_state)
7359 {
7360         struct drm_device *dev = crtc->base.dev;
7361         struct drm_i915_private *dev_priv = to_i915(dev);
7362         const struct intel_limit *limit;
7363         int refclk = 96000;
7364
7365         memset(&crtc_state->dpll_hw_state, 0,
7366                sizeof(crtc_state->dpll_hw_state));
7367
7368         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7369                 if (intel_panel_use_ssc(dev_priv)) {
7370                         refclk = dev_priv->vbt.lvds_ssc_freq;
7371                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7372                 }
7373
7374                 limit = &intel_limits_i9xx_lvds;
7375         } else {
7376                 limit = &intel_limits_i9xx_sdvo;
7377         }
7378
7379         if (!crtc_state->clock_set &&
7380             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7381                                  refclk, NULL, &crtc_state->dpll)) {
7382                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7383                 return -EINVAL;
7384         }
7385
7386         i9xx_compute_dpll(crtc, crtc_state, NULL);
7387
7388         return 0;
7389 }
7390
7391 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7392                                   struct intel_crtc_state *crtc_state)
7393 {
7394         int refclk = 100000;
7395         const struct intel_limit *limit = &intel_limits_chv;
7396
7397         memset(&crtc_state->dpll_hw_state, 0,
7398                sizeof(crtc_state->dpll_hw_state));
7399
7400         if (!crtc_state->clock_set &&
7401             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7402                                 refclk, NULL, &crtc_state->dpll)) {
7403                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7404                 return -EINVAL;
7405         }
7406
7407         chv_compute_dpll(crtc, crtc_state);
7408
7409         return 0;
7410 }
7411
7412 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7413                                   struct intel_crtc_state *crtc_state)
7414 {
7415         int refclk = 100000;
7416         const struct intel_limit *limit = &intel_limits_vlv;
7417
7418         memset(&crtc_state->dpll_hw_state, 0,
7419                sizeof(crtc_state->dpll_hw_state));
7420
7421         if (!crtc_state->clock_set &&
7422             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7423                                 refclk, NULL, &crtc_state->dpll)) {
7424                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7425                 return -EINVAL;
7426         }
7427
7428         vlv_compute_dpll(crtc, crtc_state);
7429
7430         return 0;
7431 }
7432
7433 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7434                                  struct intel_crtc_state *pipe_config)
7435 {
7436         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7437         uint32_t tmp;
7438
7439         if (INTEL_GEN(dev_priv) <= 3 &&
7440             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7441                 return;
7442
7443         tmp = I915_READ(PFIT_CONTROL);
7444         if (!(tmp & PFIT_ENABLE))
7445                 return;
7446
7447         /* Check whether the pfit is attached to our pipe. */
7448         if (INTEL_GEN(dev_priv) < 4) {
7449                 if (crtc->pipe != PIPE_B)
7450                         return;
7451         } else {
7452                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7453                         return;
7454         }
7455
7456         pipe_config->gmch_pfit.control = tmp;
7457         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7458 }
7459
7460 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7461                                struct intel_crtc_state *pipe_config)
7462 {
7463         struct drm_device *dev = crtc->base.dev;
7464         struct drm_i915_private *dev_priv = to_i915(dev);
7465         int pipe = pipe_config->cpu_transcoder;
7466         struct dpll clock;
7467         u32 mdiv;
7468         int refclk = 100000;
7469
7470         /* In case of DSI, DPLL will not be used */
7471         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7472                 return;
7473
7474         mutex_lock(&dev_priv->sb_lock);
7475         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7476         mutex_unlock(&dev_priv->sb_lock);
7477
7478         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7479         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7480         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7481         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7482         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7483
7484         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7485 }
7486
7487 static void
7488 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7489                               struct intel_initial_plane_config *plane_config)
7490 {
7491         struct drm_device *dev = crtc->base.dev;
7492         struct drm_i915_private *dev_priv = to_i915(dev);
7493         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7494         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7495         enum pipe pipe = crtc->pipe;
7496         u32 val, base, offset;
7497         int fourcc, pixel_format;
7498         unsigned int aligned_height;
7499         struct drm_framebuffer *fb;
7500         struct intel_framebuffer *intel_fb;
7501
7502         if (!plane->get_hw_state(plane))
7503                 return;
7504
7505         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7506         if (!intel_fb) {
7507                 DRM_DEBUG_KMS("failed to alloc fb\n");
7508                 return;
7509         }
7510
7511         fb = &intel_fb->base;
7512
7513         fb->dev = dev;
7514
7515         val = I915_READ(DSPCNTR(i9xx_plane));
7516
7517         if (INTEL_GEN(dev_priv) >= 4) {
7518                 if (val & DISPPLANE_TILED) {
7519                         plane_config->tiling = I915_TILING_X;
7520                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7521                 }
7522         }
7523
7524         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7525         fourcc = i9xx_format_to_fourcc(pixel_format);
7526         fb->format = drm_format_info(fourcc);
7527
7528         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7529                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7530                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7531         } else if (INTEL_GEN(dev_priv) >= 4) {
7532                 if (plane_config->tiling)
7533                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7534                 else
7535                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7536                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7537         } else {
7538                 base = I915_READ(DSPADDR(i9xx_plane));
7539         }
7540         plane_config->base = base;
7541
7542         val = I915_READ(PIPESRC(pipe));
7543         fb->width = ((val >> 16) & 0xfff) + 1;
7544         fb->height = ((val >> 0) & 0xfff) + 1;
7545
7546         val = I915_READ(DSPSTRIDE(i9xx_plane));
7547         fb->pitches[0] = val & 0xffffffc0;
7548
7549         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7550
7551         plane_config->size = fb->pitches[0] * aligned_height;
7552
7553         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7554                       crtc->base.name, plane->base.name, fb->width, fb->height,
7555                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7556                       plane_config->size);
7557
7558         plane_config->fb = intel_fb;
7559 }
7560
7561 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7562                                struct intel_crtc_state *pipe_config)
7563 {
7564         struct drm_device *dev = crtc->base.dev;
7565         struct drm_i915_private *dev_priv = to_i915(dev);
7566         int pipe = pipe_config->cpu_transcoder;
7567         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7568         struct dpll clock;
7569         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7570         int refclk = 100000;
7571
7572         /* In case of DSI, DPLL will not be used */
7573         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7574                 return;
7575
7576         mutex_lock(&dev_priv->sb_lock);
7577         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7578         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7579         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7580         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7581         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7582         mutex_unlock(&dev_priv->sb_lock);
7583
7584         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7585         clock.m2 = (pll_dw0 & 0xff) << 22;
7586         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7587                 clock.m2 |= pll_dw2 & 0x3fffff;
7588         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7589         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7590         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7591
7592         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7593 }
7594
7595 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7596                                  struct intel_crtc_state *pipe_config)
7597 {
7598         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7599         enum intel_display_power_domain power_domain;
7600         uint32_t tmp;
7601         bool ret;
7602
7603         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7604         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7605                 return false;
7606
7607         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7608         pipe_config->shared_dpll = NULL;
7609
7610         ret = false;
7611
7612         tmp = I915_READ(PIPECONF(crtc->pipe));
7613         if (!(tmp & PIPECONF_ENABLE))
7614                 goto out;
7615
7616         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7617             IS_CHERRYVIEW(dev_priv)) {
7618                 switch (tmp & PIPECONF_BPC_MASK) {
7619                 case PIPECONF_6BPC:
7620                         pipe_config->pipe_bpp = 18;
7621                         break;
7622                 case PIPECONF_8BPC:
7623                         pipe_config->pipe_bpp = 24;
7624                         break;
7625                 case PIPECONF_10BPC:
7626                         pipe_config->pipe_bpp = 30;
7627                         break;
7628                 default:
7629                         break;
7630                 }
7631         }
7632
7633         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7634             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7635                 pipe_config->limited_color_range = true;
7636
7637         if (INTEL_GEN(dev_priv) < 4)
7638                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7639
7640         intel_get_pipe_timings(crtc, pipe_config);
7641         intel_get_pipe_src_size(crtc, pipe_config);
7642
7643         i9xx_get_pfit_config(crtc, pipe_config);
7644
7645         if (INTEL_GEN(dev_priv) >= 4) {
7646                 /* No way to read it out on pipes B and C */
7647                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7648                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7649                 else
7650                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7651                 pipe_config->pixel_multiplier =
7652                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7653                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7654                 pipe_config->dpll_hw_state.dpll_md = tmp;
7655         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7656                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7657                 tmp = I915_READ(DPLL(crtc->pipe));
7658                 pipe_config->pixel_multiplier =
7659                         ((tmp & SDVO_MULTIPLIER_MASK)
7660                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7661         } else {
7662                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7663                  * port and will be fixed up in the encoder->get_config
7664                  * function. */
7665                 pipe_config->pixel_multiplier = 1;
7666         }
7667         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7668         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7669                 /*
7670                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7671                  * on 830. Filter it out here so that we don't
7672                  * report errors due to that.
7673                  */
7674                 if (IS_I830(dev_priv))
7675                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7676
7677                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7678                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7679         } else {
7680                 /* Mask out read-only status bits. */
7681                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7682                                                      DPLL_PORTC_READY_MASK |
7683                                                      DPLL_PORTB_READY_MASK);
7684         }
7685
7686         if (IS_CHERRYVIEW(dev_priv))
7687                 chv_crtc_clock_get(crtc, pipe_config);
7688         else if (IS_VALLEYVIEW(dev_priv))
7689                 vlv_crtc_clock_get(crtc, pipe_config);
7690         else
7691                 i9xx_crtc_clock_get(crtc, pipe_config);
7692
7693         /*
7694          * Normally the dotclock is filled in by the encoder .get_config()
7695          * but in case the pipe is enabled w/o any ports we need a sane
7696          * default.
7697          */
7698         pipe_config->base.adjusted_mode.crtc_clock =
7699                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7700
7701         ret = true;
7702
7703 out:
7704         intel_display_power_put(dev_priv, power_domain);
7705
7706         return ret;
7707 }
7708
7709 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7710 {
7711         struct intel_encoder *encoder;
7712         int i;
7713         u32 val, final;
7714         bool has_lvds = false;
7715         bool has_cpu_edp = false;
7716         bool has_panel = false;
7717         bool has_ck505 = false;
7718         bool can_ssc = false;
7719         bool using_ssc_source = false;
7720
7721         /* We need to take the global config into account */
7722         for_each_intel_encoder(&dev_priv->drm, encoder) {
7723                 switch (encoder->type) {
7724                 case INTEL_OUTPUT_LVDS:
7725                         has_panel = true;
7726                         has_lvds = true;
7727                         break;
7728                 case INTEL_OUTPUT_EDP:
7729                         has_panel = true;
7730                         if (encoder->port == PORT_A)
7731                                 has_cpu_edp = true;
7732                         break;
7733                 default:
7734                         break;
7735                 }
7736         }
7737
7738         if (HAS_PCH_IBX(dev_priv)) {
7739                 has_ck505 = dev_priv->vbt.display_clock_mode;
7740                 can_ssc = has_ck505;
7741         } else {
7742                 has_ck505 = false;
7743                 can_ssc = true;
7744         }
7745
7746         /* Check if any DPLLs are using the SSC source */
7747         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7748                 u32 temp = I915_READ(PCH_DPLL(i));
7749
7750                 if (!(temp & DPLL_VCO_ENABLE))
7751                         continue;
7752
7753                 if ((temp & PLL_REF_INPUT_MASK) ==
7754                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7755                         using_ssc_source = true;
7756                         break;
7757                 }
7758         }
7759
7760         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7761                       has_panel, has_lvds, has_ck505, using_ssc_source);
7762
7763         /* Ironlake: try to setup display ref clock before DPLL
7764          * enabling. This is only under driver's control after
7765          * PCH B stepping, previous chipset stepping should be
7766          * ignoring this setting.
7767          */
7768         val = I915_READ(PCH_DREF_CONTROL);
7769
7770         /* As we must carefully and slowly disable/enable each source in turn,
7771          * compute the final state we want first and check if we need to
7772          * make any changes at all.
7773          */
7774         final = val;
7775         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7776         if (has_ck505)
7777                 final |= DREF_NONSPREAD_CK505_ENABLE;
7778         else
7779                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7780
7781         final &= ~DREF_SSC_SOURCE_MASK;
7782         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7783         final &= ~DREF_SSC1_ENABLE;
7784
7785         if (has_panel) {
7786                 final |= DREF_SSC_SOURCE_ENABLE;
7787
7788                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7789                         final |= DREF_SSC1_ENABLE;
7790
7791                 if (has_cpu_edp) {
7792                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7793                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7794                         else
7795                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7796                 } else
7797                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7798         } else if (using_ssc_source) {
7799                 final |= DREF_SSC_SOURCE_ENABLE;
7800                 final |= DREF_SSC1_ENABLE;
7801         }
7802
7803         if (final == val)
7804                 return;
7805
7806         /* Always enable nonspread source */
7807         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7808
7809         if (has_ck505)
7810                 val |= DREF_NONSPREAD_CK505_ENABLE;
7811         else
7812                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7813
7814         if (has_panel) {
7815                 val &= ~DREF_SSC_SOURCE_MASK;
7816                 val |= DREF_SSC_SOURCE_ENABLE;
7817
7818                 /* SSC must be turned on before enabling the CPU output  */
7819                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7820                         DRM_DEBUG_KMS("Using SSC on panel\n");
7821                         val |= DREF_SSC1_ENABLE;
7822                 } else
7823                         val &= ~DREF_SSC1_ENABLE;
7824
7825                 /* Get SSC going before enabling the outputs */
7826                 I915_WRITE(PCH_DREF_CONTROL, val);
7827                 POSTING_READ(PCH_DREF_CONTROL);
7828                 udelay(200);
7829
7830                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7831
7832                 /* Enable CPU source on CPU attached eDP */
7833                 if (has_cpu_edp) {
7834                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7835                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7836                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7837                         } else
7838                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7839                 } else
7840                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7841
7842                 I915_WRITE(PCH_DREF_CONTROL, val);
7843                 POSTING_READ(PCH_DREF_CONTROL);
7844                 udelay(200);
7845         } else {
7846                 DRM_DEBUG_KMS("Disabling CPU source output\n");
7847
7848                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7849
7850                 /* Turn off CPU output */
7851                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7852
7853                 I915_WRITE(PCH_DREF_CONTROL, val);
7854                 POSTING_READ(PCH_DREF_CONTROL);
7855                 udelay(200);
7856
7857                 if (!using_ssc_source) {
7858                         DRM_DEBUG_KMS("Disabling SSC source\n");
7859
7860                         /* Turn off the SSC source */
7861                         val &= ~DREF_SSC_SOURCE_MASK;
7862                         val |= DREF_SSC_SOURCE_DISABLE;
7863
7864                         /* Turn off SSC1 */
7865                         val &= ~DREF_SSC1_ENABLE;
7866
7867                         I915_WRITE(PCH_DREF_CONTROL, val);
7868                         POSTING_READ(PCH_DREF_CONTROL);
7869                         udelay(200);
7870                 }
7871         }
7872
7873         BUG_ON(val != final);
7874 }
7875
7876 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7877 {
7878         uint32_t tmp;
7879
7880         tmp = I915_READ(SOUTH_CHICKEN2);
7881         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7882         I915_WRITE(SOUTH_CHICKEN2, tmp);
7883
7884         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
7885                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7886                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7887
7888         tmp = I915_READ(SOUTH_CHICKEN2);
7889         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7890         I915_WRITE(SOUTH_CHICKEN2, tmp);
7891
7892         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
7893                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7894                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7895 }
7896
7897 /* WaMPhyProgramming:hsw */
7898 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7899 {
7900         uint32_t tmp;
7901
7902         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7903         tmp &= ~(0xFF << 24);
7904         tmp |= (0x12 << 24);
7905         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
7906
7907         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
7908         tmp |= (1 << 11);
7909         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
7910
7911         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
7912         tmp |= (1 << 11);
7913         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
7914
7915         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
7916         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7917         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
7918
7919         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
7920         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7921         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
7922
7923         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
7924         tmp &= ~(7 << 13);
7925         tmp |= (5 << 13);
7926         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
7927
7928         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
7929         tmp &= ~(7 << 13);
7930         tmp |= (5 << 13);
7931         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
7932
7933         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
7934         tmp &= ~0xFF;
7935         tmp |= 0x1C;
7936         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
7937
7938         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
7939         tmp &= ~0xFF;
7940         tmp |= 0x1C;
7941         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
7942
7943         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
7944         tmp &= ~(0xFF << 16);
7945         tmp |= (0x1C << 16);
7946         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
7947
7948         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
7949         tmp &= ~(0xFF << 16);
7950         tmp |= (0x1C << 16);
7951         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
7952
7953         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
7954         tmp |= (1 << 27);
7955         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
7956
7957         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
7958         tmp |= (1 << 27);
7959         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
7960
7961         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
7962         tmp &= ~(0xF << 28);
7963         tmp |= (4 << 28);
7964         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
7965
7966         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
7967         tmp &= ~(0xF << 28);
7968         tmp |= (4 << 28);
7969         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
7970 }
7971
7972 /* Implements 3 different sequences from BSpec chapter "Display iCLK
7973  * Programming" based on the parameters passed:
7974  * - Sequence to enable CLKOUT_DP
7975  * - Sequence to enable CLKOUT_DP without spread
7976  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
7977  */
7978 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
7979                                  bool with_spread, bool with_fdi)
7980 {
7981         uint32_t reg, tmp;
7982
7983         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
7984                 with_spread = true;
7985         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
7986             with_fdi, "LP PCH doesn't have FDI\n"))
7987                 with_fdi = false;
7988
7989         mutex_lock(&dev_priv->sb_lock);
7990
7991         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7992         tmp &= ~SBI_SSCCTL_DISABLE;
7993         tmp |= SBI_SSCCTL_PATHALT;
7994         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7995
7996         udelay(24);
7997
7998         if (with_spread) {
7999                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8000                 tmp &= ~SBI_SSCCTL_PATHALT;
8001                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8002
8003                 if (with_fdi) {
8004                         lpt_reset_fdi_mphy(dev_priv);
8005                         lpt_program_fdi_mphy(dev_priv);
8006                 }
8007         }
8008
8009         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8010         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8011         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8012         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8013
8014         mutex_unlock(&dev_priv->sb_lock);
8015 }
8016
8017 /* Sequence to disable CLKOUT_DP */
8018 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8019 {
8020         uint32_t reg, tmp;
8021
8022         mutex_lock(&dev_priv->sb_lock);
8023
8024         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8025         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8026         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8027         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8028
8029         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8030         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8031                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8032                         tmp |= SBI_SSCCTL_PATHALT;
8033                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8034                         udelay(32);
8035                 }
8036                 tmp |= SBI_SSCCTL_DISABLE;
8037                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8038         }
8039
8040         mutex_unlock(&dev_priv->sb_lock);
8041 }
8042
8043 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8044
8045 static const uint16_t sscdivintphase[] = {
8046         [BEND_IDX( 50)] = 0x3B23,
8047         [BEND_IDX( 45)] = 0x3B23,
8048         [BEND_IDX( 40)] = 0x3C23,
8049         [BEND_IDX( 35)] = 0x3C23,
8050         [BEND_IDX( 30)] = 0x3D23,
8051         [BEND_IDX( 25)] = 0x3D23,
8052         [BEND_IDX( 20)] = 0x3E23,
8053         [BEND_IDX( 15)] = 0x3E23,
8054         [BEND_IDX( 10)] = 0x3F23,
8055         [BEND_IDX(  5)] = 0x3F23,
8056         [BEND_IDX(  0)] = 0x0025,
8057         [BEND_IDX( -5)] = 0x0025,
8058         [BEND_IDX(-10)] = 0x0125,
8059         [BEND_IDX(-15)] = 0x0125,
8060         [BEND_IDX(-20)] = 0x0225,
8061         [BEND_IDX(-25)] = 0x0225,
8062         [BEND_IDX(-30)] = 0x0325,
8063         [BEND_IDX(-35)] = 0x0325,
8064         [BEND_IDX(-40)] = 0x0425,
8065         [BEND_IDX(-45)] = 0x0425,
8066         [BEND_IDX(-50)] = 0x0525,
8067 };
8068
8069 /*
8070  * Bend CLKOUT_DP
8071  * steps -50 to 50 inclusive, in steps of 5
8072  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8073  * change in clock period = -(steps / 10) * 5.787 ps
8074  */
8075 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8076 {
8077         uint32_t tmp;
8078         int idx = BEND_IDX(steps);
8079
8080         if (WARN_ON(steps % 5 != 0))
8081                 return;
8082
8083         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8084                 return;
8085
8086         mutex_lock(&dev_priv->sb_lock);
8087
8088         if (steps % 10 != 0)
8089                 tmp = 0xAAAAAAAB;
8090         else
8091                 tmp = 0x00000000;
8092         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8093
8094         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8095         tmp &= 0xffff0000;
8096         tmp |= sscdivintphase[idx];
8097         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8098
8099         mutex_unlock(&dev_priv->sb_lock);
8100 }
8101
8102 #undef BEND_IDX
8103
8104 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8105 {
8106         struct intel_encoder *encoder;
8107         bool has_vga = false;
8108
8109         for_each_intel_encoder(&dev_priv->drm, encoder) {
8110                 switch (encoder->type) {
8111                 case INTEL_OUTPUT_ANALOG:
8112                         has_vga = true;
8113                         break;
8114                 default:
8115                         break;
8116                 }
8117         }
8118
8119         if (has_vga) {
8120                 lpt_bend_clkout_dp(dev_priv, 0);
8121                 lpt_enable_clkout_dp(dev_priv, true, true);
8122         } else {
8123                 lpt_disable_clkout_dp(dev_priv);
8124         }
8125 }
8126
8127 /*
8128  * Initialize reference clocks when the driver loads
8129  */
8130 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8131 {
8132         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8133                 ironlake_init_pch_refclk(dev_priv);
8134         else if (HAS_PCH_LPT(dev_priv))
8135                 lpt_init_pch_refclk(dev_priv);
8136 }
8137
8138 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8139 {
8140         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8141         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8142         int pipe = intel_crtc->pipe;
8143         uint32_t val;
8144
8145         val = 0;
8146
8147         switch (intel_crtc->config->pipe_bpp) {
8148         case 18:
8149                 val |= PIPECONF_6BPC;
8150                 break;
8151         case 24:
8152                 val |= PIPECONF_8BPC;
8153                 break;
8154         case 30:
8155                 val |= PIPECONF_10BPC;
8156                 break;
8157         case 36:
8158                 val |= PIPECONF_12BPC;
8159                 break;
8160         default:
8161                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8162                 BUG();
8163         }
8164
8165         if (intel_crtc->config->dither)
8166                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8167
8168         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8169                 val |= PIPECONF_INTERLACED_ILK;
8170         else
8171                 val |= PIPECONF_PROGRESSIVE;
8172
8173         if (intel_crtc->config->limited_color_range)
8174                 val |= PIPECONF_COLOR_RANGE_SELECT;
8175
8176         I915_WRITE(PIPECONF(pipe), val);
8177         POSTING_READ(PIPECONF(pipe));
8178 }
8179
8180 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8181 {
8182         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8183         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8184         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8185         u32 val = 0;
8186
8187         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8188                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8189
8190         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8191                 val |= PIPECONF_INTERLACED_ILK;
8192         else
8193                 val |= PIPECONF_PROGRESSIVE;
8194
8195         I915_WRITE(PIPECONF(cpu_transcoder), val);
8196         POSTING_READ(PIPECONF(cpu_transcoder));
8197 }
8198
8199 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8200 {
8201         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8202         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8203         struct intel_crtc_state *config = intel_crtc->config;
8204
8205         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8206                 u32 val = 0;
8207
8208                 switch (intel_crtc->config->pipe_bpp) {
8209                 case 18:
8210                         val |= PIPEMISC_DITHER_6_BPC;
8211                         break;
8212                 case 24:
8213                         val |= PIPEMISC_DITHER_8_BPC;
8214                         break;
8215                 case 30:
8216                         val |= PIPEMISC_DITHER_10_BPC;
8217                         break;
8218                 case 36:
8219                         val |= PIPEMISC_DITHER_12_BPC;
8220                         break;
8221                 default:
8222                         /* Case prevented by pipe_config_set_bpp. */
8223                         BUG();
8224                 }
8225
8226                 if (intel_crtc->config->dither)
8227                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8228
8229                 if (config->ycbcr420) {
8230                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8231                                 PIPEMISC_YUV420_ENABLE |
8232                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8233                 }
8234
8235                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8236         }
8237 }
8238
8239 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8240 {
8241         /*
8242          * Account for spread spectrum to avoid
8243          * oversubscribing the link. Max center spread
8244          * is 2.5%; use 5% for safety's sake.
8245          */
8246         u32 bps = target_clock * bpp * 21 / 20;
8247         return DIV_ROUND_UP(bps, link_bw * 8);
8248 }
8249
8250 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8251 {
8252         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8253 }
8254
8255 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8256                                   struct intel_crtc_state *crtc_state,
8257                                   struct dpll *reduced_clock)
8258 {
8259         struct drm_crtc *crtc = &intel_crtc->base;
8260         struct drm_device *dev = crtc->dev;
8261         struct drm_i915_private *dev_priv = to_i915(dev);
8262         u32 dpll, fp, fp2;
8263         int factor;
8264
8265         /* Enable autotuning of the PLL clock (if permissible) */
8266         factor = 21;
8267         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8268                 if ((intel_panel_use_ssc(dev_priv) &&
8269                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8270                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8271                         factor = 25;
8272         } else if (crtc_state->sdvo_tv_clock)
8273                 factor = 20;
8274
8275         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8276
8277         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8278                 fp |= FP_CB_TUNE;
8279
8280         if (reduced_clock) {
8281                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8282
8283                 if (reduced_clock->m < factor * reduced_clock->n)
8284                         fp2 |= FP_CB_TUNE;
8285         } else {
8286                 fp2 = fp;
8287         }
8288
8289         dpll = 0;
8290
8291         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8292                 dpll |= DPLLB_MODE_LVDS;
8293         else
8294                 dpll |= DPLLB_MODE_DAC_SERIAL;
8295
8296         dpll |= (crtc_state->pixel_multiplier - 1)
8297                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8298
8299         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8300             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8301                 dpll |= DPLL_SDVO_HIGH_SPEED;
8302
8303         if (intel_crtc_has_dp_encoder(crtc_state))
8304                 dpll |= DPLL_SDVO_HIGH_SPEED;
8305
8306         /*
8307          * The high speed IO clock is only really required for
8308          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8309          * possible to share the DPLL between CRT and HDMI. Enabling
8310          * the clock needlessly does no real harm, except use up a
8311          * bit of power potentially.
8312          *
8313          * We'll limit this to IVB with 3 pipes, since it has only two
8314          * DPLLs and so DPLL sharing is the only way to get three pipes
8315          * driving PCH ports at the same time. On SNB we could do this,
8316          * and potentially avoid enabling the second DPLL, but it's not
8317          * clear if it''s a win or loss power wise. No point in doing
8318          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8319          */
8320         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8321             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8322                 dpll |= DPLL_SDVO_HIGH_SPEED;
8323
8324         /* compute bitmask from p1 value */
8325         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8326         /* also FPA1 */
8327         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8328
8329         switch (crtc_state->dpll.p2) {
8330         case 5:
8331                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8332                 break;
8333         case 7:
8334                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8335                 break;
8336         case 10:
8337                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8338                 break;
8339         case 14:
8340                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8341                 break;
8342         }
8343
8344         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8345             intel_panel_use_ssc(dev_priv))
8346                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8347         else
8348                 dpll |= PLL_REF_INPUT_DREFCLK;
8349
8350         dpll |= DPLL_VCO_ENABLE;
8351
8352         crtc_state->dpll_hw_state.dpll = dpll;
8353         crtc_state->dpll_hw_state.fp0 = fp;
8354         crtc_state->dpll_hw_state.fp1 = fp2;
8355 }
8356
8357 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8358                                        struct intel_crtc_state *crtc_state)
8359 {
8360         struct drm_device *dev = crtc->base.dev;
8361         struct drm_i915_private *dev_priv = to_i915(dev);
8362         const struct intel_limit *limit;
8363         int refclk = 120000;
8364
8365         memset(&crtc_state->dpll_hw_state, 0,
8366                sizeof(crtc_state->dpll_hw_state));
8367
8368         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8369         if (!crtc_state->has_pch_encoder)
8370                 return 0;
8371
8372         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8373                 if (intel_panel_use_ssc(dev_priv)) {
8374                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8375                                       dev_priv->vbt.lvds_ssc_freq);
8376                         refclk = dev_priv->vbt.lvds_ssc_freq;
8377                 }
8378
8379                 if (intel_is_dual_link_lvds(dev)) {
8380                         if (refclk == 100000)
8381                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8382                         else
8383                                 limit = &intel_limits_ironlake_dual_lvds;
8384                 } else {
8385                         if (refclk == 100000)
8386                                 limit = &intel_limits_ironlake_single_lvds_100m;
8387                         else
8388                                 limit = &intel_limits_ironlake_single_lvds;
8389                 }
8390         } else {
8391                 limit = &intel_limits_ironlake_dac;
8392         }
8393
8394         if (!crtc_state->clock_set &&
8395             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8396                                 refclk, NULL, &crtc_state->dpll)) {
8397                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8398                 return -EINVAL;
8399         }
8400
8401         ironlake_compute_dpll(crtc, crtc_state, NULL);
8402
8403         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8404                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8405                                  pipe_name(crtc->pipe));
8406                 return -EINVAL;
8407         }
8408
8409         return 0;
8410 }
8411
8412 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8413                                          struct intel_link_m_n *m_n)
8414 {
8415         struct drm_device *dev = crtc->base.dev;
8416         struct drm_i915_private *dev_priv = to_i915(dev);
8417         enum pipe pipe = crtc->pipe;
8418
8419         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8420         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8421         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8422                 & ~TU_SIZE_MASK;
8423         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8424         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8425                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8426 }
8427
8428 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8429                                          enum transcoder transcoder,
8430                                          struct intel_link_m_n *m_n,
8431                                          struct intel_link_m_n *m2_n2)
8432 {
8433         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8434         enum pipe pipe = crtc->pipe;
8435
8436         if (INTEL_GEN(dev_priv) >= 5) {
8437                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8438                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8439                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8440                         & ~TU_SIZE_MASK;
8441                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8442                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8443                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8444                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8445                  * gen < 8) and if DRRS is supported (to make sure the
8446                  * registers are not unnecessarily read).
8447                  */
8448                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8449                         crtc->config->has_drrs) {
8450                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8451                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8452                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8453                                         & ~TU_SIZE_MASK;
8454                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8455                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8456                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8457                 }
8458         } else {
8459                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8460                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8461                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8462                         & ~TU_SIZE_MASK;
8463                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8464                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8465                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8466         }
8467 }
8468
8469 void intel_dp_get_m_n(struct intel_crtc *crtc,
8470                       struct intel_crtc_state *pipe_config)
8471 {
8472         if (pipe_config->has_pch_encoder)
8473                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8474         else
8475                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8476                                              &pipe_config->dp_m_n,
8477                                              &pipe_config->dp_m2_n2);
8478 }
8479
8480 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8481                                         struct intel_crtc_state *pipe_config)
8482 {
8483         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8484                                      &pipe_config->fdi_m_n, NULL);
8485 }
8486
8487 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8488                                     struct intel_crtc_state *pipe_config)
8489 {
8490         struct drm_device *dev = crtc->base.dev;
8491         struct drm_i915_private *dev_priv = to_i915(dev);
8492         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8493         uint32_t ps_ctrl = 0;
8494         int id = -1;
8495         int i;
8496
8497         /* find scaler attached to this pipe */
8498         for (i = 0; i < crtc->num_scalers; i++) {
8499                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8500                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8501                         id = i;
8502                         pipe_config->pch_pfit.enabled = true;
8503                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8504                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8505                         break;
8506                 }
8507         }
8508
8509         scaler_state->scaler_id = id;
8510         if (id >= 0) {
8511                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8512         } else {
8513                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8514         }
8515 }
8516
8517 static void
8518 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8519                                  struct intel_initial_plane_config *plane_config)
8520 {
8521         struct drm_device *dev = crtc->base.dev;
8522         struct drm_i915_private *dev_priv = to_i915(dev);
8523         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8524         enum plane_id plane_id = plane->id;
8525         enum pipe pipe = crtc->pipe;
8526         u32 val, base, offset, stride_mult, tiling, alpha;
8527         int fourcc, pixel_format;
8528         unsigned int aligned_height;
8529         struct drm_framebuffer *fb;
8530         struct intel_framebuffer *intel_fb;
8531
8532         if (!plane->get_hw_state(plane))
8533                 return;
8534
8535         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8536         if (!intel_fb) {
8537                 DRM_DEBUG_KMS("failed to alloc fb\n");
8538                 return;
8539         }
8540
8541         fb = &intel_fb->base;
8542
8543         fb->dev = dev;
8544
8545         val = I915_READ(PLANE_CTL(pipe, plane_id));
8546
8547         if (INTEL_GEN(dev_priv) >= 11)
8548                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8549         else
8550                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8551
8552         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8553                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8554                 alpha &= PLANE_COLOR_ALPHA_MASK;
8555         } else {
8556                 alpha = val & PLANE_CTL_ALPHA_MASK;
8557         }
8558
8559         fourcc = skl_format_to_fourcc(pixel_format,
8560                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8561         fb->format = drm_format_info(fourcc);
8562
8563         tiling = val & PLANE_CTL_TILED_MASK;
8564         switch (tiling) {
8565         case PLANE_CTL_TILED_LINEAR:
8566                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8567                 break;
8568         case PLANE_CTL_TILED_X:
8569                 plane_config->tiling = I915_TILING_X;
8570                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8571                 break;
8572         case PLANE_CTL_TILED_Y:
8573                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8574                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8575                 else
8576                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8577                 break;
8578         case PLANE_CTL_TILED_YF:
8579                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8580                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8581                 else
8582                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8583                 break;
8584         default:
8585                 MISSING_CASE(tiling);
8586                 goto error;
8587         }
8588
8589         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8590         plane_config->base = base;
8591
8592         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8593
8594         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8595         fb->height = ((val >> 16) & 0xfff) + 1;
8596         fb->width = ((val >> 0) & 0x1fff) + 1;
8597
8598         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8599         stride_mult = intel_fb_stride_alignment(fb, 0);
8600         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8601
8602         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8603
8604         plane_config->size = fb->pitches[0] * aligned_height;
8605
8606         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8607                       crtc->base.name, plane->base.name, fb->width, fb->height,
8608                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8609                       plane_config->size);
8610
8611         plane_config->fb = intel_fb;
8612         return;
8613
8614 error:
8615         kfree(intel_fb);
8616 }
8617
8618 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8619                                      struct intel_crtc_state *pipe_config)
8620 {
8621         struct drm_device *dev = crtc->base.dev;
8622         struct drm_i915_private *dev_priv = to_i915(dev);
8623         uint32_t tmp;
8624
8625         tmp = I915_READ(PF_CTL(crtc->pipe));
8626
8627         if (tmp & PF_ENABLE) {
8628                 pipe_config->pch_pfit.enabled = true;
8629                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8630                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8631
8632                 /* We currently do not free assignements of panel fitters on
8633                  * ivb/hsw (since we don't use the higher upscaling modes which
8634                  * differentiates them) so just WARN about this case for now. */
8635                 if (IS_GEN7(dev_priv)) {
8636                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8637                                 PF_PIPE_SEL_IVB(crtc->pipe));
8638                 }
8639         }
8640 }
8641
8642 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8643                                      struct intel_crtc_state *pipe_config)
8644 {
8645         struct drm_device *dev = crtc->base.dev;
8646         struct drm_i915_private *dev_priv = to_i915(dev);
8647         enum intel_display_power_domain power_domain;
8648         uint32_t tmp;
8649         bool ret;
8650
8651         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8652         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8653                 return false;
8654
8655         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8656         pipe_config->shared_dpll = NULL;
8657
8658         ret = false;
8659         tmp = I915_READ(PIPECONF(crtc->pipe));
8660         if (!(tmp & PIPECONF_ENABLE))
8661                 goto out;
8662
8663         switch (tmp & PIPECONF_BPC_MASK) {
8664         case PIPECONF_6BPC:
8665                 pipe_config->pipe_bpp = 18;
8666                 break;
8667         case PIPECONF_8BPC:
8668                 pipe_config->pipe_bpp = 24;
8669                 break;
8670         case PIPECONF_10BPC:
8671                 pipe_config->pipe_bpp = 30;
8672                 break;
8673         case PIPECONF_12BPC:
8674                 pipe_config->pipe_bpp = 36;
8675                 break;
8676         default:
8677                 break;
8678         }
8679
8680         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8681                 pipe_config->limited_color_range = true;
8682
8683         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8684                 struct intel_shared_dpll *pll;
8685                 enum intel_dpll_id pll_id;
8686
8687                 pipe_config->has_pch_encoder = true;
8688
8689                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8690                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8691                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8692
8693                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8694
8695                 if (HAS_PCH_IBX(dev_priv)) {
8696                         /*
8697                          * The pipe->pch transcoder and pch transcoder->pll
8698                          * mapping is fixed.
8699                          */
8700                         pll_id = (enum intel_dpll_id) crtc->pipe;
8701                 } else {
8702                         tmp = I915_READ(PCH_DPLL_SEL);
8703                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8704                                 pll_id = DPLL_ID_PCH_PLL_B;
8705                         else
8706                                 pll_id= DPLL_ID_PCH_PLL_A;
8707                 }
8708
8709                 pipe_config->shared_dpll =
8710                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8711                 pll = pipe_config->shared_dpll;
8712
8713                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
8714                                                  &pipe_config->dpll_hw_state));
8715
8716                 tmp = pipe_config->dpll_hw_state.dpll;
8717                 pipe_config->pixel_multiplier =
8718                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8719                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8720
8721                 ironlake_pch_clock_get(crtc, pipe_config);
8722         } else {
8723                 pipe_config->pixel_multiplier = 1;
8724         }
8725
8726         intel_get_pipe_timings(crtc, pipe_config);
8727         intel_get_pipe_src_size(crtc, pipe_config);
8728
8729         ironlake_get_pfit_config(crtc, pipe_config);
8730
8731         ret = true;
8732
8733 out:
8734         intel_display_power_put(dev_priv, power_domain);
8735
8736         return ret;
8737 }
8738
8739 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8740 {
8741         struct drm_device *dev = &dev_priv->drm;
8742         struct intel_crtc *crtc;
8743
8744         for_each_intel_crtc(dev, crtc)
8745                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8746                      pipe_name(crtc->pipe));
8747
8748         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL)),
8749                         "Display power well on\n");
8750         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8751         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8752         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8753         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8754         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8755              "CPU PWM1 enabled\n");
8756         if (IS_HASWELL(dev_priv))
8757                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8758                      "CPU PWM2 enabled\n");
8759         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8760              "PCH PWM1 enabled\n");
8761         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8762              "Utility pin enabled\n");
8763         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8764
8765         /*
8766          * In theory we can still leave IRQs enabled, as long as only the HPD
8767          * interrupts remain enabled. We used to check for that, but since it's
8768          * gen-specific and since we only disable LCPLL after we fully disable
8769          * the interrupts, the check below should be enough.
8770          */
8771         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8772 }
8773
8774 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8775 {
8776         if (IS_HASWELL(dev_priv))
8777                 return I915_READ(D_COMP_HSW);
8778         else
8779                 return I915_READ(D_COMP_BDW);
8780 }
8781
8782 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8783 {
8784         if (IS_HASWELL(dev_priv)) {
8785                 mutex_lock(&dev_priv->pcu_lock);
8786                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8787                                             val))
8788                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
8789                 mutex_unlock(&dev_priv->pcu_lock);
8790         } else {
8791                 I915_WRITE(D_COMP_BDW, val);
8792                 POSTING_READ(D_COMP_BDW);
8793         }
8794 }
8795
8796 /*
8797  * This function implements pieces of two sequences from BSpec:
8798  * - Sequence for display software to disable LCPLL
8799  * - Sequence for display software to allow package C8+
8800  * The steps implemented here are just the steps that actually touch the LCPLL
8801  * register. Callers should take care of disabling all the display engine
8802  * functions, doing the mode unset, fixing interrupts, etc.
8803  */
8804 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8805                               bool switch_to_fclk, bool allow_power_down)
8806 {
8807         uint32_t val;
8808
8809         assert_can_disable_lcpll(dev_priv);
8810
8811         val = I915_READ(LCPLL_CTL);
8812
8813         if (switch_to_fclk) {
8814                 val |= LCPLL_CD_SOURCE_FCLK;
8815                 I915_WRITE(LCPLL_CTL, val);
8816
8817                 if (wait_for_us(I915_READ(LCPLL_CTL) &
8818                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
8819                         DRM_ERROR("Switching to FCLK failed\n");
8820
8821                 val = I915_READ(LCPLL_CTL);
8822         }
8823
8824         val |= LCPLL_PLL_DISABLE;
8825         I915_WRITE(LCPLL_CTL, val);
8826         POSTING_READ(LCPLL_CTL);
8827
8828         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
8829                 DRM_ERROR("LCPLL still locked\n");
8830
8831         val = hsw_read_dcomp(dev_priv);
8832         val |= D_COMP_COMP_DISABLE;
8833         hsw_write_dcomp(dev_priv, val);
8834         ndelay(100);
8835
8836         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8837                      1))
8838                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8839
8840         if (allow_power_down) {
8841                 val = I915_READ(LCPLL_CTL);
8842                 val |= LCPLL_POWER_DOWN_ALLOW;
8843                 I915_WRITE(LCPLL_CTL, val);
8844                 POSTING_READ(LCPLL_CTL);
8845         }
8846 }
8847
8848 /*
8849  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8850  * source.
8851  */
8852 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8853 {
8854         uint32_t val;
8855
8856         val = I915_READ(LCPLL_CTL);
8857
8858         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8859                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8860                 return;
8861
8862         /*
8863          * Make sure we're not on PC8 state before disabling PC8, otherwise
8864          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8865          */
8866         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8867
8868         if (val & LCPLL_POWER_DOWN_ALLOW) {
8869                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8870                 I915_WRITE(LCPLL_CTL, val);
8871                 POSTING_READ(LCPLL_CTL);
8872         }
8873
8874         val = hsw_read_dcomp(dev_priv);
8875         val |= D_COMP_COMP_FORCE;
8876         val &= ~D_COMP_COMP_DISABLE;
8877         hsw_write_dcomp(dev_priv, val);
8878
8879         val = I915_READ(LCPLL_CTL);
8880         val &= ~LCPLL_PLL_DISABLE;
8881         I915_WRITE(LCPLL_CTL, val);
8882
8883         if (intel_wait_for_register(dev_priv,
8884                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
8885                                     5))
8886                 DRM_ERROR("LCPLL not locked yet\n");
8887
8888         if (val & LCPLL_CD_SOURCE_FCLK) {
8889                 val = I915_READ(LCPLL_CTL);
8890                 val &= ~LCPLL_CD_SOURCE_FCLK;
8891                 I915_WRITE(LCPLL_CTL, val);
8892
8893                 if (wait_for_us((I915_READ(LCPLL_CTL) &
8894                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8895                         DRM_ERROR("Switching back to LCPLL failed\n");
8896         }
8897
8898         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8899
8900         intel_update_cdclk(dev_priv);
8901         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
8902 }
8903
8904 /*
8905  * Package states C8 and deeper are really deep PC states that can only be
8906  * reached when all the devices on the system allow it, so even if the graphics
8907  * device allows PC8+, it doesn't mean the system will actually get to these
8908  * states. Our driver only allows PC8+ when going into runtime PM.
8909  *
8910  * The requirements for PC8+ are that all the outputs are disabled, the power
8911  * well is disabled and most interrupts are disabled, and these are also
8912  * requirements for runtime PM. When these conditions are met, we manually do
8913  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
8914  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
8915  * hang the machine.
8916  *
8917  * When we really reach PC8 or deeper states (not just when we allow it) we lose
8918  * the state of some registers, so when we come back from PC8+ we need to
8919  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
8920  * need to take care of the registers kept by RC6. Notice that this happens even
8921  * if we don't put the device in PCI D3 state (which is what currently happens
8922  * because of the runtime PM support).
8923  *
8924  * For more, read "Display Sequences for Package C8" on the hardware
8925  * documentation.
8926  */
8927 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
8928 {
8929         uint32_t val;
8930
8931         DRM_DEBUG_KMS("Enabling package C8+\n");
8932
8933         if (HAS_PCH_LPT_LP(dev_priv)) {
8934                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8935                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
8936                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8937         }
8938
8939         lpt_disable_clkout_dp(dev_priv);
8940         hsw_disable_lcpll(dev_priv, true, true);
8941 }
8942
8943 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
8944 {
8945         uint32_t val;
8946
8947         DRM_DEBUG_KMS("Disabling package C8+\n");
8948
8949         hsw_restore_lcpll(dev_priv);
8950         lpt_init_pch_refclk(dev_priv);
8951
8952         if (HAS_PCH_LPT_LP(dev_priv)) {
8953                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8954                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
8955                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8956         }
8957 }
8958
8959 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
8960                                       struct intel_crtc_state *crtc_state)
8961 {
8962         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
8963                 struct intel_encoder *encoder =
8964                         intel_ddi_get_crtc_new_encoder(crtc_state);
8965
8966                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
8967                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8968                                          pipe_name(crtc->pipe));
8969                         return -EINVAL;
8970                 }
8971         }
8972
8973         return 0;
8974 }
8975
8976 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
8977                                    enum port port,
8978                                    struct intel_crtc_state *pipe_config)
8979 {
8980         enum intel_dpll_id id;
8981         u32 temp;
8982
8983         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
8984         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
8985
8986         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
8987                 return;
8988
8989         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8990 }
8991
8992 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
8993                                 enum port port,
8994                                 struct intel_crtc_state *pipe_config)
8995 {
8996         enum intel_dpll_id id;
8997
8998         switch (port) {
8999         case PORT_A:
9000                 id = DPLL_ID_SKL_DPLL0;
9001                 break;
9002         case PORT_B:
9003                 id = DPLL_ID_SKL_DPLL1;
9004                 break;
9005         case PORT_C:
9006                 id = DPLL_ID_SKL_DPLL2;
9007                 break;
9008         default:
9009                 DRM_ERROR("Incorrect port type\n");
9010                 return;
9011         }
9012
9013         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9014 }
9015
9016 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9017                                 enum port port,
9018                                 struct intel_crtc_state *pipe_config)
9019 {
9020         enum intel_dpll_id id;
9021         u32 temp;
9022
9023         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9024         id = temp >> (port * 3 + 1);
9025
9026         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9027                 return;
9028
9029         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9030 }
9031
9032 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9033                                 enum port port,
9034                                 struct intel_crtc_state *pipe_config)
9035 {
9036         enum intel_dpll_id id;
9037         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9038
9039         switch (ddi_pll_sel) {
9040         case PORT_CLK_SEL_WRPLL1:
9041                 id = DPLL_ID_WRPLL1;
9042                 break;
9043         case PORT_CLK_SEL_WRPLL2:
9044                 id = DPLL_ID_WRPLL2;
9045                 break;
9046         case PORT_CLK_SEL_SPLL:
9047                 id = DPLL_ID_SPLL;
9048                 break;
9049         case PORT_CLK_SEL_LCPLL_810:
9050                 id = DPLL_ID_LCPLL_810;
9051                 break;
9052         case PORT_CLK_SEL_LCPLL_1350:
9053                 id = DPLL_ID_LCPLL_1350;
9054                 break;
9055         case PORT_CLK_SEL_LCPLL_2700:
9056                 id = DPLL_ID_LCPLL_2700;
9057                 break;
9058         default:
9059                 MISSING_CASE(ddi_pll_sel);
9060                 /* fall through */
9061         case PORT_CLK_SEL_NONE:
9062                 return;
9063         }
9064
9065         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9066 }
9067
9068 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9069                                      struct intel_crtc_state *pipe_config,
9070                                      u64 *power_domain_mask)
9071 {
9072         struct drm_device *dev = crtc->base.dev;
9073         struct drm_i915_private *dev_priv = to_i915(dev);
9074         enum intel_display_power_domain power_domain;
9075         u32 tmp;
9076
9077         /*
9078          * The pipe->transcoder mapping is fixed with the exception of the eDP
9079          * transcoder handled below.
9080          */
9081         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9082
9083         /*
9084          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9085          * consistency and less surprising code; it's in always on power).
9086          */
9087         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9088         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9089                 enum pipe trans_edp_pipe;
9090                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9091                 default:
9092                         WARN(1, "unknown pipe linked to edp transcoder\n");
9093                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9094                 case TRANS_DDI_EDP_INPUT_A_ON:
9095                         trans_edp_pipe = PIPE_A;
9096                         break;
9097                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9098                         trans_edp_pipe = PIPE_B;
9099                         break;
9100                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9101                         trans_edp_pipe = PIPE_C;
9102                         break;
9103                 }
9104
9105                 if (trans_edp_pipe == crtc->pipe)
9106                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9107         }
9108
9109         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9110         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9111                 return false;
9112         *power_domain_mask |= BIT_ULL(power_domain);
9113
9114         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9115
9116         return tmp & PIPECONF_ENABLE;
9117 }
9118
9119 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9120                                          struct intel_crtc_state *pipe_config,
9121                                          u64 *power_domain_mask)
9122 {
9123         struct drm_device *dev = crtc->base.dev;
9124         struct drm_i915_private *dev_priv = to_i915(dev);
9125         enum intel_display_power_domain power_domain;
9126         enum port port;
9127         enum transcoder cpu_transcoder;
9128         u32 tmp;
9129
9130         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9131                 if (port == PORT_A)
9132                         cpu_transcoder = TRANSCODER_DSI_A;
9133                 else
9134                         cpu_transcoder = TRANSCODER_DSI_C;
9135
9136                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9137                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9138                         continue;
9139                 *power_domain_mask |= BIT_ULL(power_domain);
9140
9141                 /*
9142                  * The PLL needs to be enabled with a valid divider
9143                  * configuration, otherwise accessing DSI registers will hang
9144                  * the machine. See BSpec North Display Engine
9145                  * registers/MIPI[BXT]. We can break out here early, since we
9146                  * need the same DSI PLL to be enabled for both DSI ports.
9147                  */
9148                 if (!intel_dsi_pll_is_enabled(dev_priv))
9149                         break;
9150
9151                 /* XXX: this works for video mode only */
9152                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9153                 if (!(tmp & DPI_ENABLE))
9154                         continue;
9155
9156                 tmp = I915_READ(MIPI_CTRL(port));
9157                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9158                         continue;
9159
9160                 pipe_config->cpu_transcoder = cpu_transcoder;
9161                 break;
9162         }
9163
9164         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9165 }
9166
9167 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9168                                        struct intel_crtc_state *pipe_config)
9169 {
9170         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9171         struct intel_shared_dpll *pll;
9172         enum port port;
9173         uint32_t tmp;
9174
9175         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9176
9177         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9178
9179         if (IS_CANNONLAKE(dev_priv))
9180                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9181         else if (IS_GEN9_BC(dev_priv))
9182                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9183         else if (IS_GEN9_LP(dev_priv))
9184                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9185         else
9186                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9187
9188         pll = pipe_config->shared_dpll;
9189         if (pll) {
9190                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9191                                                  &pipe_config->dpll_hw_state));
9192         }
9193
9194         /*
9195          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9196          * DDI E. So just check whether this pipe is wired to DDI E and whether
9197          * the PCH transcoder is on.
9198          */
9199         if (INTEL_GEN(dev_priv) < 9 &&
9200             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9201                 pipe_config->has_pch_encoder = true;
9202
9203                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9204                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9205                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9206
9207                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9208         }
9209 }
9210
9211 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9212                                     struct intel_crtc_state *pipe_config)
9213 {
9214         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9215         enum intel_display_power_domain power_domain;
9216         u64 power_domain_mask;
9217         bool active;
9218
9219         intel_crtc_init_scalers(crtc, pipe_config);
9220
9221         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9222         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9223                 return false;
9224         power_domain_mask = BIT_ULL(power_domain);
9225
9226         pipe_config->shared_dpll = NULL;
9227
9228         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9229
9230         if (IS_GEN9_LP(dev_priv) &&
9231             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9232                 WARN_ON(active);
9233                 active = true;
9234         }
9235
9236         if (!active)
9237                 goto out;
9238
9239         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9240                 haswell_get_ddi_port_state(crtc, pipe_config);
9241                 intel_get_pipe_timings(crtc, pipe_config);
9242         }
9243
9244         intel_get_pipe_src_size(crtc, pipe_config);
9245
9246         pipe_config->gamma_mode =
9247                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9248
9249         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
9250                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9251                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9252
9253                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10) {
9254                         bool blend_mode_420 = tmp &
9255                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9256
9257                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9258                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9259                             pipe_config->ycbcr420 != blend_mode_420)
9260                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9261                 } else if (clrspace_yuv) {
9262                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9263                 }
9264         }
9265
9266         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9267         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9268                 power_domain_mask |= BIT_ULL(power_domain);
9269                 if (INTEL_GEN(dev_priv) >= 9)
9270                         skylake_get_pfit_config(crtc, pipe_config);
9271                 else
9272                         ironlake_get_pfit_config(crtc, pipe_config);
9273         }
9274
9275         if (hsw_crtc_supports_ips(crtc)) {
9276                 if (IS_HASWELL(dev_priv))
9277                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9278                 else {
9279                         /*
9280                          * We cannot readout IPS state on broadwell, set to
9281                          * true so we can set it to a defined state on first
9282                          * commit.
9283                          */
9284                         pipe_config->ips_enabled = true;
9285                 }
9286         }
9287
9288         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9289             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9290                 pipe_config->pixel_multiplier =
9291                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9292         } else {
9293                 pipe_config->pixel_multiplier = 1;
9294         }
9295
9296 out:
9297         for_each_power_domain(power_domain, power_domain_mask)
9298                 intel_display_power_put(dev_priv, power_domain);
9299
9300         return active;
9301 }
9302
9303 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9304 {
9305         struct drm_i915_private *dev_priv =
9306                 to_i915(plane_state->base.plane->dev);
9307         const struct drm_framebuffer *fb = plane_state->base.fb;
9308         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9309         u32 base;
9310
9311         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9312                 base = obj->phys_handle->busaddr;
9313         else
9314                 base = intel_plane_ggtt_offset(plane_state);
9315
9316         base += plane_state->main.offset;
9317
9318         /* ILK+ do this automagically */
9319         if (HAS_GMCH_DISPLAY(dev_priv) &&
9320             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9321                 base += (plane_state->base.crtc_h *
9322                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9323
9324         return base;
9325 }
9326
9327 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9328 {
9329         int x = plane_state->base.crtc_x;
9330         int y = plane_state->base.crtc_y;
9331         u32 pos = 0;
9332
9333         if (x < 0) {
9334                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9335                 x = -x;
9336         }
9337         pos |= x << CURSOR_X_SHIFT;
9338
9339         if (y < 0) {
9340                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9341                 y = -y;
9342         }
9343         pos |= y << CURSOR_Y_SHIFT;
9344
9345         return pos;
9346 }
9347
9348 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9349 {
9350         const struct drm_mode_config *config =
9351                 &plane_state->base.plane->dev->mode_config;
9352         int width = plane_state->base.crtc_w;
9353         int height = plane_state->base.crtc_h;
9354
9355         return width > 0 && width <= config->cursor_width &&
9356                 height > 0 && height <= config->cursor_height;
9357 }
9358
9359 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9360                               struct intel_plane_state *plane_state)
9361 {
9362         const struct drm_framebuffer *fb = plane_state->base.fb;
9363         int src_x, src_y;
9364         u32 offset;
9365         int ret;
9366
9367         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9368                                                   &crtc_state->base,
9369                                                   DRM_PLANE_HELPER_NO_SCALING,
9370                                                   DRM_PLANE_HELPER_NO_SCALING,
9371                                                   true, true);
9372         if (ret)
9373                 return ret;
9374
9375         if (!fb)
9376                 return 0;
9377
9378         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9379                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9380                 return -EINVAL;
9381         }
9382
9383         src_x = plane_state->base.src_x >> 16;
9384         src_y = plane_state->base.src_y >> 16;
9385
9386         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9387         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9388
9389         if (src_x != 0 || src_y != 0) {
9390                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9391                 return -EINVAL;
9392         }
9393
9394         plane_state->main.offset = offset;
9395
9396         return 0;
9397 }
9398
9399 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9400                            const struct intel_plane_state *plane_state)
9401 {
9402         const struct drm_framebuffer *fb = plane_state->base.fb;
9403
9404         return CURSOR_ENABLE |
9405                 CURSOR_GAMMA_ENABLE |
9406                 CURSOR_FORMAT_ARGB |
9407                 CURSOR_STRIDE(fb->pitches[0]);
9408 }
9409
9410 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9411 {
9412         int width = plane_state->base.crtc_w;
9413
9414         /*
9415          * 845g/865g are only limited by the width of their cursors,
9416          * the height is arbitrary up to the precision of the register.
9417          */
9418         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9419 }
9420
9421 static int i845_check_cursor(struct intel_plane *plane,
9422                              struct intel_crtc_state *crtc_state,
9423                              struct intel_plane_state *plane_state)
9424 {
9425         const struct drm_framebuffer *fb = plane_state->base.fb;
9426         int ret;
9427
9428         ret = intel_check_cursor(crtc_state, plane_state);
9429         if (ret)
9430                 return ret;
9431
9432         /* if we want to turn off the cursor ignore width and height */
9433         if (!fb)
9434                 return 0;
9435
9436         /* Check for which cursor types we support */
9437         if (!i845_cursor_size_ok(plane_state)) {
9438                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9439                           plane_state->base.crtc_w,
9440                           plane_state->base.crtc_h);
9441                 return -EINVAL;
9442         }
9443
9444         switch (fb->pitches[0]) {
9445         case 256:
9446         case 512:
9447         case 1024:
9448         case 2048:
9449                 break;
9450         default:
9451                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9452                               fb->pitches[0]);
9453                 return -EINVAL;
9454         }
9455
9456         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9457
9458         return 0;
9459 }
9460
9461 static void i845_update_cursor(struct intel_plane *plane,
9462                                const struct intel_crtc_state *crtc_state,
9463                                const struct intel_plane_state *plane_state)
9464 {
9465         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9466         u32 cntl = 0, base = 0, pos = 0, size = 0;
9467         unsigned long irqflags;
9468
9469         if (plane_state && plane_state->base.visible) {
9470                 unsigned int width = plane_state->base.crtc_w;
9471                 unsigned int height = plane_state->base.crtc_h;
9472
9473                 cntl = plane_state->ctl;
9474                 size = (height << 12) | width;
9475
9476                 base = intel_cursor_base(plane_state);
9477                 pos = intel_cursor_position(plane_state);
9478         }
9479
9480         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9481
9482         /* On these chipsets we can only modify the base/size/stride
9483          * whilst the cursor is disabled.
9484          */
9485         if (plane->cursor.base != base ||
9486             plane->cursor.size != size ||
9487             plane->cursor.cntl != cntl) {
9488                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9489                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9490                 I915_WRITE_FW(CURSIZE, size);
9491                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9492                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9493
9494                 plane->cursor.base = base;
9495                 plane->cursor.size = size;
9496                 plane->cursor.cntl = cntl;
9497         } else {
9498                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9499         }
9500
9501         POSTING_READ_FW(CURCNTR(PIPE_A));
9502
9503         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9504 }
9505
9506 static void i845_disable_cursor(struct intel_plane *plane,
9507                                 struct intel_crtc *crtc)
9508 {
9509         i845_update_cursor(plane, NULL, NULL);
9510 }
9511
9512 static bool i845_cursor_get_hw_state(struct intel_plane *plane)
9513 {
9514         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9515         enum intel_display_power_domain power_domain;
9516         bool ret;
9517
9518         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9519         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9520                 return false;
9521
9522         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9523
9524         intel_display_power_put(dev_priv, power_domain);
9525
9526         return ret;
9527 }
9528
9529 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9530                            const struct intel_plane_state *plane_state)
9531 {
9532         struct drm_i915_private *dev_priv =
9533                 to_i915(plane_state->base.plane->dev);
9534         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9535         u32 cntl;
9536
9537         cntl = MCURSOR_GAMMA_ENABLE;
9538
9539         if (HAS_DDI(dev_priv))
9540                 cntl |= CURSOR_PIPE_CSC_ENABLE;
9541
9542         cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9543
9544         switch (plane_state->base.crtc_w) {
9545         case 64:
9546                 cntl |= CURSOR_MODE_64_ARGB_AX;
9547                 break;
9548         case 128:
9549                 cntl |= CURSOR_MODE_128_ARGB_AX;
9550                 break;
9551         case 256:
9552                 cntl |= CURSOR_MODE_256_ARGB_AX;
9553                 break;
9554         default:
9555                 MISSING_CASE(plane_state->base.crtc_w);
9556                 return 0;
9557         }
9558
9559         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9560                 cntl |= CURSOR_ROTATE_180;
9561
9562         return cntl;
9563 }
9564
9565 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9566 {
9567         struct drm_i915_private *dev_priv =
9568                 to_i915(plane_state->base.plane->dev);
9569         int width = plane_state->base.crtc_w;
9570         int height = plane_state->base.crtc_h;
9571
9572         if (!intel_cursor_size_ok(plane_state))
9573                 return false;
9574
9575         /* Cursor width is limited to a few power-of-two sizes */
9576         switch (width) {
9577         case 256:
9578         case 128:
9579         case 64:
9580                 break;
9581         default:
9582                 return false;
9583         }
9584
9585         /*
9586          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9587          * height from 8 lines up to the cursor width, when the
9588          * cursor is not rotated. Everything else requires square
9589          * cursors.
9590          */
9591         if (HAS_CUR_FBC(dev_priv) &&
9592             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9593                 if (height < 8 || height > width)
9594                         return false;
9595         } else {
9596                 if (height != width)
9597                         return false;
9598         }
9599
9600         return true;
9601 }
9602
9603 static int i9xx_check_cursor(struct intel_plane *plane,
9604                              struct intel_crtc_state *crtc_state,
9605                              struct intel_plane_state *plane_state)
9606 {
9607         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9608         const struct drm_framebuffer *fb = plane_state->base.fb;
9609         enum pipe pipe = plane->pipe;
9610         int ret;
9611
9612         ret = intel_check_cursor(crtc_state, plane_state);
9613         if (ret)
9614                 return ret;
9615
9616         /* if we want to turn off the cursor ignore width and height */
9617         if (!fb)
9618                 return 0;
9619
9620         /* Check for which cursor types we support */
9621         if (!i9xx_cursor_size_ok(plane_state)) {
9622                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9623                           plane_state->base.crtc_w,
9624                           plane_state->base.crtc_h);
9625                 return -EINVAL;
9626         }
9627
9628         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9629                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9630                               fb->pitches[0], plane_state->base.crtc_w);
9631                 return -EINVAL;
9632         }
9633
9634         /*
9635          * There's something wrong with the cursor on CHV pipe C.
9636          * If it straddles the left edge of the screen then
9637          * moving it away from the edge or disabling it often
9638          * results in a pipe underrun, and often that can lead to
9639          * dead pipe (constant underrun reported, and it scans
9640          * out just a solid color). To recover from that, the
9641          * display power well must be turned off and on again.
9642          * Refuse the put the cursor into that compromised position.
9643          */
9644         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9645             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9646                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9647                 return -EINVAL;
9648         }
9649
9650         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9651
9652         return 0;
9653 }
9654
9655 static void i9xx_update_cursor(struct intel_plane *plane,
9656                                const struct intel_crtc_state *crtc_state,
9657                                const struct intel_plane_state *plane_state)
9658 {
9659         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9660         enum pipe pipe = plane->pipe;
9661         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9662         unsigned long irqflags;
9663
9664         if (plane_state && plane_state->base.visible) {
9665                 cntl = plane_state->ctl;
9666
9667                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9668                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9669
9670                 base = intel_cursor_base(plane_state);
9671                 pos = intel_cursor_position(plane_state);
9672         }
9673
9674         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9675
9676         /*
9677          * On some platforms writing CURCNTR first will also
9678          * cause CURPOS to be armed by the CURBASE write.
9679          * Without the CURCNTR write the CURPOS write would
9680          * arm itself. Thus we always start the full update
9681          * with a CURCNTR write.
9682          *
9683          * On other platforms CURPOS always requires the
9684          * CURBASE write to arm the update. Additonally
9685          * a write to any of the cursor register will cancel
9686          * an already armed cursor update. Thus leaving out
9687          * the CURBASE write after CURPOS could lead to a
9688          * cursor that doesn't appear to move, or even change
9689          * shape. Thus we always write CURBASE.
9690          *
9691          * CURCNTR and CUR_FBC_CTL are always
9692          * armed by the CURBASE write only.
9693          */
9694         if (plane->cursor.base != base ||
9695             plane->cursor.size != fbc_ctl ||
9696             plane->cursor.cntl != cntl) {
9697                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9698                 if (HAS_CUR_FBC(dev_priv))
9699                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9700                 I915_WRITE_FW(CURPOS(pipe), pos);
9701                 I915_WRITE_FW(CURBASE(pipe), base);
9702
9703                 plane->cursor.base = base;
9704                 plane->cursor.size = fbc_ctl;
9705                 plane->cursor.cntl = cntl;
9706         } else {
9707                 I915_WRITE_FW(CURPOS(pipe), pos);
9708                 I915_WRITE_FW(CURBASE(pipe), base);
9709         }
9710
9711         POSTING_READ_FW(CURBASE(pipe));
9712
9713         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9714 }
9715
9716 static void i9xx_disable_cursor(struct intel_plane *plane,
9717                                 struct intel_crtc *crtc)
9718 {
9719         i9xx_update_cursor(plane, NULL, NULL);
9720 }
9721
9722 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane)
9723 {
9724         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9725         enum intel_display_power_domain power_domain;
9726         enum pipe pipe = plane->pipe;
9727         bool ret;
9728
9729         /*
9730          * Not 100% correct for planes that can move between pipes,
9731          * but that's only the case for gen2-3 which don't have any
9732          * display power wells.
9733          */
9734         power_domain = POWER_DOMAIN_PIPE(pipe);
9735         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9736                 return false;
9737
9738         ret = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
9739
9740         intel_display_power_put(dev_priv, power_domain);
9741
9742         return ret;
9743 }
9744
9745 /* VESA 640x480x72Hz mode to set on the pipe */
9746 static const struct drm_display_mode load_detect_mode = {
9747         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9748                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9749 };
9750
9751 struct drm_framebuffer *
9752 intel_framebuffer_create(struct drm_i915_gem_object *obj,
9753                          struct drm_mode_fb_cmd2 *mode_cmd)
9754 {
9755         struct intel_framebuffer *intel_fb;
9756         int ret;
9757
9758         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9759         if (!intel_fb)
9760                 return ERR_PTR(-ENOMEM);
9761
9762         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
9763         if (ret)
9764                 goto err;
9765
9766         return &intel_fb->base;
9767
9768 err:
9769         kfree(intel_fb);
9770         return ERR_PTR(ret);
9771 }
9772
9773 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
9774                                         struct drm_crtc *crtc)
9775 {
9776         struct drm_plane *plane;
9777         struct drm_plane_state *plane_state;
9778         int ret, i;
9779
9780         ret = drm_atomic_add_affected_planes(state, crtc);
9781         if (ret)
9782                 return ret;
9783
9784         for_each_new_plane_in_state(state, plane, plane_state, i) {
9785                 if (plane_state->crtc != crtc)
9786                         continue;
9787
9788                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
9789                 if (ret)
9790                         return ret;
9791
9792                 drm_atomic_set_fb_for_plane(plane_state, NULL);
9793         }
9794
9795         return 0;
9796 }
9797
9798 int intel_get_load_detect_pipe(struct drm_connector *connector,
9799                                const struct drm_display_mode *mode,
9800                                struct intel_load_detect_pipe *old,
9801                                struct drm_modeset_acquire_ctx *ctx)
9802 {
9803         struct intel_crtc *intel_crtc;
9804         struct intel_encoder *intel_encoder =
9805                 intel_attached_encoder(connector);
9806         struct drm_crtc *possible_crtc;
9807         struct drm_encoder *encoder = &intel_encoder->base;
9808         struct drm_crtc *crtc = NULL;
9809         struct drm_device *dev = encoder->dev;
9810         struct drm_i915_private *dev_priv = to_i915(dev);
9811         struct drm_mode_config *config = &dev->mode_config;
9812         struct drm_atomic_state *state = NULL, *restore_state = NULL;
9813         struct drm_connector_state *connector_state;
9814         struct intel_crtc_state *crtc_state;
9815         int ret, i = -1;
9816
9817         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9818                       connector->base.id, connector->name,
9819                       encoder->base.id, encoder->name);
9820
9821         old->restore_state = NULL;
9822
9823         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
9824
9825         /*
9826          * Algorithm gets a little messy:
9827          *
9828          *   - if the connector already has an assigned crtc, use it (but make
9829          *     sure it's on first)
9830          *
9831          *   - try to find the first unused crtc that can drive this connector,
9832          *     and use that if we find one
9833          */
9834
9835         /* See if we already have a CRTC for this connector */
9836         if (connector->state->crtc) {
9837                 crtc = connector->state->crtc;
9838
9839                 ret = drm_modeset_lock(&crtc->mutex, ctx);
9840                 if (ret)
9841                         goto fail;
9842
9843                 /* Make sure the crtc and connector are running */
9844                 goto found;
9845         }
9846
9847         /* Find an unused one (if possible) */
9848         for_each_crtc(dev, possible_crtc) {
9849                 i++;
9850                 if (!(encoder->possible_crtcs & (1 << i)))
9851                         continue;
9852
9853                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
9854                 if (ret)
9855                         goto fail;
9856
9857                 if (possible_crtc->state->enable) {
9858                         drm_modeset_unlock(&possible_crtc->mutex);
9859                         continue;
9860                 }
9861
9862                 crtc = possible_crtc;
9863                 break;
9864         }
9865
9866         /*
9867          * If we didn't find an unused CRTC, don't use any.
9868          */
9869         if (!crtc) {
9870                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
9871                 ret = -ENODEV;
9872                 goto fail;
9873         }
9874
9875 found:
9876         intel_crtc = to_intel_crtc(crtc);
9877
9878         state = drm_atomic_state_alloc(dev);
9879         restore_state = drm_atomic_state_alloc(dev);
9880         if (!state || !restore_state) {
9881                 ret = -ENOMEM;
9882                 goto fail;
9883         }
9884
9885         state->acquire_ctx = ctx;
9886         restore_state->acquire_ctx = ctx;
9887
9888         connector_state = drm_atomic_get_connector_state(state, connector);
9889         if (IS_ERR(connector_state)) {
9890                 ret = PTR_ERR(connector_state);
9891                 goto fail;
9892         }
9893
9894         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
9895         if (ret)
9896                 goto fail;
9897
9898         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9899         if (IS_ERR(crtc_state)) {
9900                 ret = PTR_ERR(crtc_state);
9901                 goto fail;
9902         }
9903
9904         crtc_state->base.active = crtc_state->base.enable = true;
9905
9906         if (!mode)
9907                 mode = &load_detect_mode;
9908
9909         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
9910         if (ret)
9911                 goto fail;
9912
9913         ret = intel_modeset_disable_planes(state, crtc);
9914         if (ret)
9915                 goto fail;
9916
9917         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
9918         if (!ret)
9919                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
9920         if (ret) {
9921                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
9922                 goto fail;
9923         }
9924
9925         ret = drm_atomic_commit(state);
9926         if (ret) {
9927                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
9928                 goto fail;
9929         }
9930
9931         old->restore_state = restore_state;
9932         drm_atomic_state_put(state);
9933
9934         /* let the connector get through one full cycle before testing */
9935         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
9936         return true;
9937
9938 fail:
9939         if (state) {
9940                 drm_atomic_state_put(state);
9941                 state = NULL;
9942         }
9943         if (restore_state) {
9944                 drm_atomic_state_put(restore_state);
9945                 restore_state = NULL;
9946         }
9947
9948         if (ret == -EDEADLK)
9949                 return ret;
9950
9951         return false;
9952 }
9953
9954 void intel_release_load_detect_pipe(struct drm_connector *connector,
9955                                     struct intel_load_detect_pipe *old,
9956                                     struct drm_modeset_acquire_ctx *ctx)
9957 {
9958         struct intel_encoder *intel_encoder =
9959                 intel_attached_encoder(connector);
9960         struct drm_encoder *encoder = &intel_encoder->base;
9961         struct drm_atomic_state *state = old->restore_state;
9962         int ret;
9963
9964         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9965                       connector->base.id, connector->name,
9966                       encoder->base.id, encoder->name);
9967
9968         if (!state)
9969                 return;
9970
9971         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
9972         if (ret)
9973                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
9974         drm_atomic_state_put(state);
9975 }
9976
9977 static int i9xx_pll_refclk(struct drm_device *dev,
9978                            const struct intel_crtc_state *pipe_config)
9979 {
9980         struct drm_i915_private *dev_priv = to_i915(dev);
9981         u32 dpll = pipe_config->dpll_hw_state.dpll;
9982
9983         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
9984                 return dev_priv->vbt.lvds_ssc_freq;
9985         else if (HAS_PCH_SPLIT(dev_priv))
9986                 return 120000;
9987         else if (!IS_GEN2(dev_priv))
9988                 return 96000;
9989         else
9990                 return 48000;
9991 }
9992
9993 /* Returns the clock of the currently programmed mode of the given pipe. */
9994 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
9995                                 struct intel_crtc_state *pipe_config)
9996 {
9997         struct drm_device *dev = crtc->base.dev;
9998         struct drm_i915_private *dev_priv = to_i915(dev);
9999         int pipe = pipe_config->cpu_transcoder;
10000         u32 dpll = pipe_config->dpll_hw_state.dpll;
10001         u32 fp;
10002         struct dpll clock;
10003         int port_clock;
10004         int refclk = i9xx_pll_refclk(dev, pipe_config);
10005
10006         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10007                 fp = pipe_config->dpll_hw_state.fp0;
10008         else
10009                 fp = pipe_config->dpll_hw_state.fp1;
10010
10011         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10012         if (IS_PINEVIEW(dev_priv)) {
10013                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10014                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10015         } else {
10016                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10017                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10018         }
10019
10020         if (!IS_GEN2(dev_priv)) {
10021                 if (IS_PINEVIEW(dev_priv))
10022                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10023                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10024                 else
10025                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10026                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10027
10028                 switch (dpll & DPLL_MODE_MASK) {
10029                 case DPLLB_MODE_DAC_SERIAL:
10030                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10031                                 5 : 10;
10032                         break;
10033                 case DPLLB_MODE_LVDS:
10034                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10035                                 7 : 14;
10036                         break;
10037                 default:
10038                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10039                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10040                         return;
10041                 }
10042
10043                 if (IS_PINEVIEW(dev_priv))
10044                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10045                 else
10046                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10047         } else {
10048                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10049                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10050
10051                 if (is_lvds) {
10052                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10053                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10054
10055                         if (lvds & LVDS_CLKB_POWER_UP)
10056                                 clock.p2 = 7;
10057                         else
10058                                 clock.p2 = 14;
10059                 } else {
10060                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10061                                 clock.p1 = 2;
10062                         else {
10063                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10064                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10065                         }
10066                         if (dpll & PLL_P2_DIVIDE_BY_4)
10067                                 clock.p2 = 4;
10068                         else
10069                                 clock.p2 = 2;
10070                 }
10071
10072                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10073         }
10074
10075         /*
10076          * This value includes pixel_multiplier. We will use
10077          * port_clock to compute adjusted_mode.crtc_clock in the
10078          * encoder's get_config() function.
10079          */
10080         pipe_config->port_clock = port_clock;
10081 }
10082
10083 int intel_dotclock_calculate(int link_freq,
10084                              const struct intel_link_m_n *m_n)
10085 {
10086         /*
10087          * The calculation for the data clock is:
10088          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10089          * But we want to avoid losing precison if possible, so:
10090          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10091          *
10092          * and the link clock is simpler:
10093          * link_clock = (m * link_clock) / n
10094          */
10095
10096         if (!m_n->link_n)
10097                 return 0;
10098
10099         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10100 }
10101
10102 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10103                                    struct intel_crtc_state *pipe_config)
10104 {
10105         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10106
10107         /* read out port_clock from the DPLL */
10108         i9xx_crtc_clock_get(crtc, pipe_config);
10109
10110         /*
10111          * In case there is an active pipe without active ports,
10112          * we may need some idea for the dotclock anyway.
10113          * Calculate one based on the FDI configuration.
10114          */
10115         pipe_config->base.adjusted_mode.crtc_clock =
10116                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10117                                          &pipe_config->fdi_m_n);
10118 }
10119
10120 /* Returns the currently programmed mode of the given encoder. */
10121 struct drm_display_mode *
10122 intel_encoder_current_mode(struct intel_encoder *encoder)
10123 {
10124         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10125         struct intel_crtc_state *crtc_state;
10126         struct drm_display_mode *mode;
10127         struct intel_crtc *crtc;
10128         enum pipe pipe;
10129
10130         if (!encoder->get_hw_state(encoder, &pipe))
10131                 return NULL;
10132
10133         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10134
10135         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10136         if (!mode)
10137                 return NULL;
10138
10139         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10140         if (!crtc_state) {
10141                 kfree(mode);
10142                 return NULL;
10143         }
10144
10145         crtc_state->base.crtc = &crtc->base;
10146
10147         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10148                 kfree(crtc_state);
10149                 kfree(mode);
10150                 return NULL;
10151         }
10152
10153         encoder->get_config(encoder, crtc_state);
10154
10155         intel_mode_from_pipe_config(mode, crtc_state);
10156
10157         kfree(crtc_state);
10158
10159         return mode;
10160 }
10161
10162 static void intel_crtc_destroy(struct drm_crtc *crtc)
10163 {
10164         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10165
10166         drm_crtc_cleanup(crtc);
10167         kfree(intel_crtc);
10168 }
10169
10170 /**
10171  * intel_wm_need_update - Check whether watermarks need updating
10172  * @plane: drm plane
10173  * @state: new plane state
10174  *
10175  * Check current plane state versus the new one to determine whether
10176  * watermarks need to be recalculated.
10177  *
10178  * Returns true or false.
10179  */
10180 static bool intel_wm_need_update(struct drm_plane *plane,
10181                                  struct drm_plane_state *state)
10182 {
10183         struct intel_plane_state *new = to_intel_plane_state(state);
10184         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10185
10186         /* Update watermarks on tiling or size changes. */
10187         if (new->base.visible != cur->base.visible)
10188                 return true;
10189
10190         if (!cur->base.fb || !new->base.fb)
10191                 return false;
10192
10193         if (cur->base.fb->modifier != new->base.fb->modifier ||
10194             cur->base.rotation != new->base.rotation ||
10195             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10196             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10197             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10198             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10199                 return true;
10200
10201         return false;
10202 }
10203
10204 static bool needs_scaling(const struct intel_plane_state *state)
10205 {
10206         int src_w = drm_rect_width(&state->base.src) >> 16;
10207         int src_h = drm_rect_height(&state->base.src) >> 16;
10208         int dst_w = drm_rect_width(&state->base.dst);
10209         int dst_h = drm_rect_height(&state->base.dst);
10210
10211         return (src_w != dst_w || src_h != dst_h);
10212 }
10213
10214 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10215                                     struct drm_crtc_state *crtc_state,
10216                                     const struct intel_plane_state *old_plane_state,
10217                                     struct drm_plane_state *plane_state)
10218 {
10219         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10220         struct drm_crtc *crtc = crtc_state->crtc;
10221         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10222         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10223         struct drm_device *dev = crtc->dev;
10224         struct drm_i915_private *dev_priv = to_i915(dev);
10225         bool mode_changed = needs_modeset(crtc_state);
10226         bool was_crtc_enabled = old_crtc_state->base.active;
10227         bool is_crtc_enabled = crtc_state->active;
10228         bool turn_off, turn_on, visible, was_visible;
10229         struct drm_framebuffer *fb = plane_state->fb;
10230         int ret;
10231
10232         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10233                 ret = skl_update_scaler_plane(
10234                         to_intel_crtc_state(crtc_state),
10235                         to_intel_plane_state(plane_state));
10236                 if (ret)
10237                         return ret;
10238         }
10239
10240         was_visible = old_plane_state->base.visible;
10241         visible = plane_state->visible;
10242
10243         if (!was_crtc_enabled && WARN_ON(was_visible))
10244                 was_visible = false;
10245
10246         /*
10247          * Visibility is calculated as if the crtc was on, but
10248          * after scaler setup everything depends on it being off
10249          * when the crtc isn't active.
10250          *
10251          * FIXME this is wrong for watermarks. Watermarks should also
10252          * be computed as if the pipe would be active. Perhaps move
10253          * per-plane wm computation to the .check_plane() hook, and
10254          * only combine the results from all planes in the current place?
10255          */
10256         if (!is_crtc_enabled) {
10257                 plane_state->visible = visible = false;
10258                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10259         }
10260
10261         if (!was_visible && !visible)
10262                 return 0;
10263
10264         if (fb != old_plane_state->base.fb)
10265                 pipe_config->fb_changed = true;
10266
10267         turn_off = was_visible && (!visible || mode_changed);
10268         turn_on = visible && (!was_visible || mode_changed);
10269
10270         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10271                          intel_crtc->base.base.id, intel_crtc->base.name,
10272                          plane->base.base.id, plane->base.name,
10273                          fb ? fb->base.id : -1);
10274
10275         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10276                          plane->base.base.id, plane->base.name,
10277                          was_visible, visible,
10278                          turn_off, turn_on, mode_changed);
10279
10280         if (turn_on) {
10281                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10282                         pipe_config->update_wm_pre = true;
10283
10284                 /* must disable cxsr around plane enable/disable */
10285                 if (plane->id != PLANE_CURSOR)
10286                         pipe_config->disable_cxsr = true;
10287         } else if (turn_off) {
10288                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10289                         pipe_config->update_wm_post = true;
10290
10291                 /* must disable cxsr around plane enable/disable */
10292                 if (plane->id != PLANE_CURSOR)
10293                         pipe_config->disable_cxsr = true;
10294         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10295                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10296                         /* FIXME bollocks */
10297                         pipe_config->update_wm_pre = true;
10298                         pipe_config->update_wm_post = true;
10299                 }
10300         }
10301
10302         if (visible || was_visible)
10303                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10304
10305         /*
10306          * WaCxSRDisabledForSpriteScaling:ivb
10307          *
10308          * cstate->update_wm was already set above, so this flag will
10309          * take effect when we commit and program watermarks.
10310          */
10311         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
10312             needs_scaling(to_intel_plane_state(plane_state)) &&
10313             !needs_scaling(old_plane_state))
10314                 pipe_config->disable_lp_wm = true;
10315
10316         return 0;
10317 }
10318
10319 static bool encoders_cloneable(const struct intel_encoder *a,
10320                                const struct intel_encoder *b)
10321 {
10322         /* masks could be asymmetric, so check both ways */
10323         return a == b || (a->cloneable & (1 << b->type) &&
10324                           b->cloneable & (1 << a->type));
10325 }
10326
10327 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10328                                          struct intel_crtc *crtc,
10329                                          struct intel_encoder *encoder)
10330 {
10331         struct intel_encoder *source_encoder;
10332         struct drm_connector *connector;
10333         struct drm_connector_state *connector_state;
10334         int i;
10335
10336         for_each_new_connector_in_state(state, connector, connector_state, i) {
10337                 if (connector_state->crtc != &crtc->base)
10338                         continue;
10339
10340                 source_encoder =
10341                         to_intel_encoder(connector_state->best_encoder);
10342                 if (!encoders_cloneable(encoder, source_encoder))
10343                         return false;
10344         }
10345
10346         return true;
10347 }
10348
10349 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10350                                    struct drm_crtc_state *crtc_state)
10351 {
10352         struct drm_device *dev = crtc->dev;
10353         struct drm_i915_private *dev_priv = to_i915(dev);
10354         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10355         struct intel_crtc_state *pipe_config =
10356                 to_intel_crtc_state(crtc_state);
10357         struct drm_atomic_state *state = crtc_state->state;
10358         int ret;
10359         bool mode_changed = needs_modeset(crtc_state);
10360
10361         if (mode_changed && !crtc_state->active)
10362                 pipe_config->update_wm_post = true;
10363
10364         if (mode_changed && crtc_state->enable &&
10365             dev_priv->display.crtc_compute_clock &&
10366             !WARN_ON(pipe_config->shared_dpll)) {
10367                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10368                                                            pipe_config);
10369                 if (ret)
10370                         return ret;
10371         }
10372
10373         if (crtc_state->color_mgmt_changed) {
10374                 ret = intel_color_check(crtc, crtc_state);
10375                 if (ret)
10376                         return ret;
10377
10378                 /*
10379                  * Changing color management on Intel hardware is
10380                  * handled as part of planes update.
10381                  */
10382                 crtc_state->planes_changed = true;
10383         }
10384
10385         ret = 0;
10386         if (dev_priv->display.compute_pipe_wm) {
10387                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10388                 if (ret) {
10389                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10390                         return ret;
10391                 }
10392         }
10393
10394         if (dev_priv->display.compute_intermediate_wm &&
10395             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10396                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10397                         return 0;
10398
10399                 /*
10400                  * Calculate 'intermediate' watermarks that satisfy both the
10401                  * old state and the new state.  We can program these
10402                  * immediately.
10403                  */
10404                 ret = dev_priv->display.compute_intermediate_wm(dev,
10405                                                                 intel_crtc,
10406                                                                 pipe_config);
10407                 if (ret) {
10408                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10409                         return ret;
10410                 }
10411         } else if (dev_priv->display.compute_intermediate_wm) {
10412                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10413                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10414         }
10415
10416         if (INTEL_GEN(dev_priv) >= 9) {
10417                 if (mode_changed)
10418                         ret = skl_update_scaler_crtc(pipe_config);
10419
10420                 if (!ret)
10421                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10422                                                             pipe_config);
10423                 if (!ret)
10424                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10425                                                          pipe_config);
10426         }
10427
10428         if (HAS_IPS(dev_priv))
10429                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10430
10431         return ret;
10432 }
10433
10434 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10435         .atomic_begin = intel_begin_crtc_commit,
10436         .atomic_flush = intel_finish_crtc_commit,
10437         .atomic_check = intel_crtc_atomic_check,
10438 };
10439
10440 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10441 {
10442         struct intel_connector *connector;
10443         struct drm_connector_list_iter conn_iter;
10444
10445         drm_connector_list_iter_begin(dev, &conn_iter);
10446         for_each_intel_connector_iter(connector, &conn_iter) {
10447                 if (connector->base.state->crtc)
10448                         drm_connector_unreference(&connector->base);
10449
10450                 if (connector->base.encoder) {
10451                         connector->base.state->best_encoder =
10452                                 connector->base.encoder;
10453                         connector->base.state->crtc =
10454                                 connector->base.encoder->crtc;
10455
10456                         drm_connector_reference(&connector->base);
10457                 } else {
10458                         connector->base.state->best_encoder = NULL;
10459                         connector->base.state->crtc = NULL;
10460                 }
10461         }
10462         drm_connector_list_iter_end(&conn_iter);
10463 }
10464
10465 static void
10466 connected_sink_compute_bpp(struct intel_connector *connector,
10467                            struct intel_crtc_state *pipe_config)
10468 {
10469         const struct drm_display_info *info = &connector->base.display_info;
10470         int bpp = pipe_config->pipe_bpp;
10471
10472         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10473                       connector->base.base.id,
10474                       connector->base.name);
10475
10476         /* Don't use an invalid EDID bpc value */
10477         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10478                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10479                               bpp, info->bpc * 3);
10480                 pipe_config->pipe_bpp = info->bpc * 3;
10481         }
10482
10483         /* Clamp bpp to 8 on screens without EDID 1.4 */
10484         if (info->bpc == 0 && bpp > 24) {
10485                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10486                               bpp);
10487                 pipe_config->pipe_bpp = 24;
10488         }
10489 }
10490
10491 static int
10492 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10493                           struct intel_crtc_state *pipe_config)
10494 {
10495         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10496         struct drm_atomic_state *state;
10497         struct drm_connector *connector;
10498         struct drm_connector_state *connector_state;
10499         int bpp, i;
10500
10501         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10502             IS_CHERRYVIEW(dev_priv)))
10503                 bpp = 10*3;
10504         else if (INTEL_GEN(dev_priv) >= 5)
10505                 bpp = 12*3;
10506         else
10507                 bpp = 8*3;
10508
10509
10510         pipe_config->pipe_bpp = bpp;
10511
10512         state = pipe_config->base.state;
10513
10514         /* Clamp display bpp to EDID value */
10515         for_each_new_connector_in_state(state, connector, connector_state, i) {
10516                 if (connector_state->crtc != &crtc->base)
10517                         continue;
10518
10519                 connected_sink_compute_bpp(to_intel_connector(connector),
10520                                            pipe_config);
10521         }
10522
10523         return bpp;
10524 }
10525
10526 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10527 {
10528         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10529                         "type: 0x%x flags: 0x%x\n",
10530                 mode->crtc_clock,
10531                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10532                 mode->crtc_hsync_end, mode->crtc_htotal,
10533                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10534                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10535 }
10536
10537 static inline void
10538 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10539                       unsigned int lane_count, struct intel_link_m_n *m_n)
10540 {
10541         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10542                       id, lane_count,
10543                       m_n->gmch_m, m_n->gmch_n,
10544                       m_n->link_m, m_n->link_n, m_n->tu);
10545 }
10546
10547 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10548
10549 static const char * const output_type_str[] = {
10550         OUTPUT_TYPE(UNUSED),
10551         OUTPUT_TYPE(ANALOG),
10552         OUTPUT_TYPE(DVO),
10553         OUTPUT_TYPE(SDVO),
10554         OUTPUT_TYPE(LVDS),
10555         OUTPUT_TYPE(TVOUT),
10556         OUTPUT_TYPE(HDMI),
10557         OUTPUT_TYPE(DP),
10558         OUTPUT_TYPE(EDP),
10559         OUTPUT_TYPE(DSI),
10560         OUTPUT_TYPE(DDI),
10561         OUTPUT_TYPE(DP_MST),
10562 };
10563
10564 #undef OUTPUT_TYPE
10565
10566 static void snprintf_output_types(char *buf, size_t len,
10567                                   unsigned int output_types)
10568 {
10569         char *str = buf;
10570         int i;
10571
10572         str[0] = '\0';
10573
10574         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
10575                 int r;
10576
10577                 if ((output_types & BIT(i)) == 0)
10578                         continue;
10579
10580                 r = snprintf(str, len, "%s%s",
10581                              str != buf ? "," : "", output_type_str[i]);
10582                 if (r >= len)
10583                         break;
10584                 str += r;
10585                 len -= r;
10586
10587                 output_types &= ~BIT(i);
10588         }
10589
10590         WARN_ON_ONCE(output_types != 0);
10591 }
10592
10593 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10594                                    struct intel_crtc_state *pipe_config,
10595                                    const char *context)
10596 {
10597         struct drm_device *dev = crtc->base.dev;
10598         struct drm_i915_private *dev_priv = to_i915(dev);
10599         struct drm_plane *plane;
10600         struct intel_plane *intel_plane;
10601         struct intel_plane_state *state;
10602         struct drm_framebuffer *fb;
10603         char buf[64];
10604
10605         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10606                       crtc->base.base.id, crtc->base.name, context);
10607
10608         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
10609         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
10610                       buf, pipe_config->output_types);
10611
10612         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
10613                       transcoder_name(pipe_config->cpu_transcoder),
10614                       pipe_config->pipe_bpp, pipe_config->dither);
10615
10616         if (pipe_config->has_pch_encoder)
10617                 intel_dump_m_n_config(pipe_config, "fdi",
10618                                       pipe_config->fdi_lanes,
10619                                       &pipe_config->fdi_m_n);
10620
10621         if (pipe_config->ycbcr420)
10622                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
10623
10624         if (intel_crtc_has_dp_encoder(pipe_config)) {
10625                 intel_dump_m_n_config(pipe_config, "dp m_n",
10626                                 pipe_config->lane_count, &pipe_config->dp_m_n);
10627                 if (pipe_config->has_drrs)
10628                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
10629                                               pipe_config->lane_count,
10630                                               &pipe_config->dp_m2_n2);
10631         }
10632
10633         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10634                       pipe_config->has_audio, pipe_config->has_infoframe);
10635
10636         DRM_DEBUG_KMS("requested mode:\n");
10637         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10638         DRM_DEBUG_KMS("adjusted mode:\n");
10639         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10640         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10641         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
10642                       pipe_config->port_clock,
10643                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
10644                       pipe_config->pixel_rate);
10645
10646         if (INTEL_GEN(dev_priv) >= 9)
10647                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
10648                               crtc->num_scalers,
10649                               pipe_config->scaler_state.scaler_users,
10650                               pipe_config->scaler_state.scaler_id);
10651
10652         if (HAS_GMCH_DISPLAY(dev_priv))
10653                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10654                               pipe_config->gmch_pfit.control,
10655                               pipe_config->gmch_pfit.pgm_ratios,
10656                               pipe_config->gmch_pfit.lvds_border_bits);
10657         else
10658                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10659                               pipe_config->pch_pfit.pos,
10660                               pipe_config->pch_pfit.size,
10661                               enableddisabled(pipe_config->pch_pfit.enabled));
10662
10663         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
10664                       pipe_config->ips_enabled, pipe_config->double_wide);
10665
10666         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
10667
10668         DRM_DEBUG_KMS("planes on this crtc\n");
10669         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
10670                 struct drm_format_name_buf format_name;
10671                 intel_plane = to_intel_plane(plane);
10672                 if (intel_plane->pipe != crtc->pipe)
10673                         continue;
10674
10675                 state = to_intel_plane_state(plane->state);
10676                 fb = state->base.fb;
10677                 if (!fb) {
10678                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
10679                                       plane->base.id, plane->name, state->scaler_id);
10680                         continue;
10681                 }
10682
10683                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
10684                               plane->base.id, plane->name,
10685                               fb->base.id, fb->width, fb->height,
10686                               drm_get_format_name(fb->format->format, &format_name));
10687                 if (INTEL_GEN(dev_priv) >= 9)
10688                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
10689                                       state->scaler_id,
10690                                       state->base.src.x1 >> 16,
10691                                       state->base.src.y1 >> 16,
10692                                       drm_rect_width(&state->base.src) >> 16,
10693                                       drm_rect_height(&state->base.src) >> 16,
10694                                       state->base.dst.x1, state->base.dst.y1,
10695                                       drm_rect_width(&state->base.dst),
10696                                       drm_rect_height(&state->base.dst));
10697         }
10698 }
10699
10700 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
10701 {
10702         struct drm_device *dev = state->dev;
10703         struct drm_connector *connector;
10704         struct drm_connector_list_iter conn_iter;
10705         unsigned int used_ports = 0;
10706         unsigned int used_mst_ports = 0;
10707
10708         /*
10709          * Walk the connector list instead of the encoder
10710          * list to detect the problem on ddi platforms
10711          * where there's just one encoder per digital port.
10712          */
10713         drm_connector_list_iter_begin(dev, &conn_iter);
10714         drm_for_each_connector_iter(connector, &conn_iter) {
10715                 struct drm_connector_state *connector_state;
10716                 struct intel_encoder *encoder;
10717
10718                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
10719                 if (!connector_state)
10720                         connector_state = connector->state;
10721
10722                 if (!connector_state->best_encoder)
10723                         continue;
10724
10725                 encoder = to_intel_encoder(connector_state->best_encoder);
10726
10727                 WARN_ON(!connector_state->crtc);
10728
10729                 switch (encoder->type) {
10730                         unsigned int port_mask;
10731                 case INTEL_OUTPUT_DDI:
10732                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
10733                                 break;
10734                 case INTEL_OUTPUT_DP:
10735                 case INTEL_OUTPUT_HDMI:
10736                 case INTEL_OUTPUT_EDP:
10737                         port_mask = 1 << encoder->port;
10738
10739                         /* the same port mustn't appear more than once */
10740                         if (used_ports & port_mask)
10741                                 return false;
10742
10743                         used_ports |= port_mask;
10744                         break;
10745                 case INTEL_OUTPUT_DP_MST:
10746                         used_mst_ports |=
10747                                 1 << encoder->port;
10748                         break;
10749                 default:
10750                         break;
10751                 }
10752         }
10753         drm_connector_list_iter_end(&conn_iter);
10754
10755         /* can't mix MST and SST/HDMI on the same port */
10756         if (used_ports & used_mst_ports)
10757                 return false;
10758
10759         return true;
10760 }
10761
10762 static void
10763 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
10764 {
10765         struct drm_i915_private *dev_priv =
10766                 to_i915(crtc_state->base.crtc->dev);
10767         struct intel_crtc_scaler_state scaler_state;
10768         struct intel_dpll_hw_state dpll_hw_state;
10769         struct intel_shared_dpll *shared_dpll;
10770         struct intel_crtc_wm_state wm_state;
10771         bool force_thru, ips_force_disable;
10772
10773         /* FIXME: before the switch to atomic started, a new pipe_config was
10774          * kzalloc'd. Code that depends on any field being zero should be
10775          * fixed, so that the crtc_state can be safely duplicated. For now,
10776          * only fields that are know to not cause problems are preserved. */
10777
10778         scaler_state = crtc_state->scaler_state;
10779         shared_dpll = crtc_state->shared_dpll;
10780         dpll_hw_state = crtc_state->dpll_hw_state;
10781         force_thru = crtc_state->pch_pfit.force_thru;
10782         ips_force_disable = crtc_state->ips_force_disable;
10783         if (IS_G4X(dev_priv) ||
10784             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10785                 wm_state = crtc_state->wm;
10786
10787         /* Keep base drm_crtc_state intact, only clear our extended struct */
10788         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
10789         memset(&crtc_state->base + 1, 0,
10790                sizeof(*crtc_state) - sizeof(crtc_state->base));
10791
10792         crtc_state->scaler_state = scaler_state;
10793         crtc_state->shared_dpll = shared_dpll;
10794         crtc_state->dpll_hw_state = dpll_hw_state;
10795         crtc_state->pch_pfit.force_thru = force_thru;
10796         crtc_state->ips_force_disable = ips_force_disable;
10797         if (IS_G4X(dev_priv) ||
10798             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10799                 crtc_state->wm = wm_state;
10800 }
10801
10802 static int
10803 intel_modeset_pipe_config(struct drm_crtc *crtc,
10804                           struct intel_crtc_state *pipe_config)
10805 {
10806         struct drm_atomic_state *state = pipe_config->base.state;
10807         struct intel_encoder *encoder;
10808         struct drm_connector *connector;
10809         struct drm_connector_state *connector_state;
10810         int base_bpp, ret = -EINVAL;
10811         int i;
10812         bool retry = true;
10813
10814         clear_intel_crtc_state(pipe_config);
10815
10816         pipe_config->cpu_transcoder =
10817                 (enum transcoder) to_intel_crtc(crtc)->pipe;
10818
10819         /*
10820          * Sanitize sync polarity flags based on requested ones. If neither
10821          * positive or negative polarity is requested, treat this as meaning
10822          * negative polarity.
10823          */
10824         if (!(pipe_config->base.adjusted_mode.flags &
10825               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
10826                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
10827
10828         if (!(pipe_config->base.adjusted_mode.flags &
10829               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
10830                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
10831
10832         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
10833                                              pipe_config);
10834         if (base_bpp < 0)
10835                 goto fail;
10836
10837         /*
10838          * Determine the real pipe dimensions. Note that stereo modes can
10839          * increase the actual pipe size due to the frame doubling and
10840          * insertion of additional space for blanks between the frame. This
10841          * is stored in the crtc timings. We use the requested mode to do this
10842          * computation to clearly distinguish it from the adjusted mode, which
10843          * can be changed by the connectors in the below retry loop.
10844          */
10845         drm_mode_get_hv_timing(&pipe_config->base.mode,
10846                                &pipe_config->pipe_src_w,
10847                                &pipe_config->pipe_src_h);
10848
10849         for_each_new_connector_in_state(state, connector, connector_state, i) {
10850                 if (connector_state->crtc != crtc)
10851                         continue;
10852
10853                 encoder = to_intel_encoder(connector_state->best_encoder);
10854
10855                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
10856                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
10857                         goto fail;
10858                 }
10859
10860                 /*
10861                  * Determine output_types before calling the .compute_config()
10862                  * hooks so that the hooks can use this information safely.
10863                  */
10864                 if (encoder->compute_output_type)
10865                         pipe_config->output_types |=
10866                                 BIT(encoder->compute_output_type(encoder, pipe_config,
10867                                                                  connector_state));
10868                 else
10869                         pipe_config->output_types |= BIT(encoder->type);
10870         }
10871
10872 encoder_retry:
10873         /* Ensure the port clock defaults are reset when retrying. */
10874         pipe_config->port_clock = 0;
10875         pipe_config->pixel_multiplier = 1;
10876
10877         /* Fill in default crtc timings, allow encoders to overwrite them. */
10878         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
10879                               CRTC_STEREO_DOUBLE);
10880
10881         /* Pass our mode to the connectors and the CRTC to give them a chance to
10882          * adjust it according to limitations or connector properties, and also
10883          * a chance to reject the mode entirely.
10884          */
10885         for_each_new_connector_in_state(state, connector, connector_state, i) {
10886                 if (connector_state->crtc != crtc)
10887                         continue;
10888
10889                 encoder = to_intel_encoder(connector_state->best_encoder);
10890
10891                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
10892                         DRM_DEBUG_KMS("Encoder config failure\n");
10893                         goto fail;
10894                 }
10895         }
10896
10897         /* Set default port clock if not overwritten by the encoder. Needs to be
10898          * done afterwards in case the encoder adjusts the mode. */
10899         if (!pipe_config->port_clock)
10900                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
10901                         * pipe_config->pixel_multiplier;
10902
10903         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
10904         if (ret < 0) {
10905                 DRM_DEBUG_KMS("CRTC fixup failed\n");
10906                 goto fail;
10907         }
10908
10909         if (ret == RETRY) {
10910                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
10911                         ret = -EINVAL;
10912                         goto fail;
10913                 }
10914
10915                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
10916                 retry = false;
10917                 goto encoder_retry;
10918         }
10919
10920         /* Dithering seems to not pass-through bits correctly when it should, so
10921          * only enable it on 6bpc panels and when its not a compliance
10922          * test requesting 6bpc video pattern.
10923          */
10924         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
10925                 !pipe_config->dither_force_disable;
10926         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
10927                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
10928
10929 fail:
10930         return ret;
10931 }
10932
10933 static bool intel_fuzzy_clock_check(int clock1, int clock2)
10934 {
10935         int diff;
10936
10937         if (clock1 == clock2)
10938                 return true;
10939
10940         if (!clock1 || !clock2)
10941                 return false;
10942
10943         diff = abs(clock1 - clock2);
10944
10945         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
10946                 return true;
10947
10948         return false;
10949 }
10950
10951 static bool
10952 intel_compare_m_n(unsigned int m, unsigned int n,
10953                   unsigned int m2, unsigned int n2,
10954                   bool exact)
10955 {
10956         if (m == m2 && n == n2)
10957                 return true;
10958
10959         if (exact || !m || !n || !m2 || !n2)
10960                 return false;
10961
10962         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
10963
10964         if (n > n2) {
10965                 while (n > n2) {
10966                         m2 <<= 1;
10967                         n2 <<= 1;
10968                 }
10969         } else if (n < n2) {
10970                 while (n < n2) {
10971                         m <<= 1;
10972                         n <<= 1;
10973                 }
10974         }
10975
10976         if (n != n2)
10977                 return false;
10978
10979         return intel_fuzzy_clock_check(m, m2);
10980 }
10981
10982 static bool
10983 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
10984                        struct intel_link_m_n *m2_n2,
10985                        bool adjust)
10986 {
10987         if (m_n->tu == m2_n2->tu &&
10988             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
10989                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
10990             intel_compare_m_n(m_n->link_m, m_n->link_n,
10991                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
10992                 if (adjust)
10993                         *m2_n2 = *m_n;
10994
10995                 return true;
10996         }
10997
10998         return false;
10999 }
11000
11001 static void __printf(3, 4)
11002 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11003 {
11004         char *level;
11005         unsigned int category;
11006         struct va_format vaf;
11007         va_list args;
11008
11009         if (adjust) {
11010                 level = KERN_DEBUG;
11011                 category = DRM_UT_KMS;
11012         } else {
11013                 level = KERN_ERR;
11014                 category = DRM_UT_NONE;
11015         }
11016
11017         va_start(args, format);
11018         vaf.fmt = format;
11019         vaf.va = &args;
11020
11021         drm_printk(level, category, "mismatch in %s %pV", name, &vaf);
11022
11023         va_end(args);
11024 }
11025
11026 static bool
11027 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11028                           struct intel_crtc_state *current_config,
11029                           struct intel_crtc_state *pipe_config,
11030                           bool adjust)
11031 {
11032         bool ret = true;
11033         bool fixup_inherited = adjust &&
11034                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11035                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11036
11037 #define PIPE_CONF_CHECK_X(name) \
11038         if (current_config->name != pipe_config->name) { \
11039                 pipe_config_err(adjust, __stringify(name), \
11040                           "(expected 0x%08x, found 0x%08x)\n", \
11041                           current_config->name, \
11042                           pipe_config->name); \
11043                 ret = false; \
11044         }
11045
11046 #define PIPE_CONF_CHECK_I(name) \
11047         if (current_config->name != pipe_config->name) { \
11048                 pipe_config_err(adjust, __stringify(name), \
11049                           "(expected %i, found %i)\n", \
11050                           current_config->name, \
11051                           pipe_config->name); \
11052                 ret = false; \
11053         }
11054
11055 #define PIPE_CONF_CHECK_BOOL(name)      \
11056         if (current_config->name != pipe_config->name) { \
11057                 pipe_config_err(adjust, __stringify(name), \
11058                           "(expected %s, found %s)\n", \
11059                           yesno(current_config->name), \
11060                           yesno(pipe_config->name)); \
11061                 ret = false; \
11062         }
11063
11064 /*
11065  * Checks state where we only read out the enabling, but not the entire
11066  * state itself (like full infoframes or ELD for audio). These states
11067  * require a full modeset on bootup to fix up.
11068  */
11069 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) \
11070         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11071                 PIPE_CONF_CHECK_BOOL(name); \
11072         } else { \
11073                 pipe_config_err(adjust, __stringify(name), \
11074                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11075                           yesno(current_config->name), \
11076                           yesno(pipe_config->name)); \
11077                 ret = false; \
11078         }
11079
11080 #define PIPE_CONF_CHECK_P(name) \
11081         if (current_config->name != pipe_config->name) { \
11082                 pipe_config_err(adjust, __stringify(name), \
11083                           "(expected %p, found %p)\n", \
11084                           current_config->name, \
11085                           pipe_config->name); \
11086                 ret = false; \
11087         }
11088
11089 #define PIPE_CONF_CHECK_M_N(name) \
11090         if (!intel_compare_link_m_n(&current_config->name, \
11091                                     &pipe_config->name,\
11092                                     adjust)) { \
11093                 pipe_config_err(adjust, __stringify(name), \
11094                           "(expected tu %i gmch %i/%i link %i/%i, " \
11095                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11096                           current_config->name.tu, \
11097                           current_config->name.gmch_m, \
11098                           current_config->name.gmch_n, \
11099                           current_config->name.link_m, \
11100                           current_config->name.link_n, \
11101                           pipe_config->name.tu, \
11102                           pipe_config->name.gmch_m, \
11103                           pipe_config->name.gmch_n, \
11104                           pipe_config->name.link_m, \
11105                           pipe_config->name.link_n); \
11106                 ret = false; \
11107         }
11108
11109 /* This is required for BDW+ where there is only one set of registers for
11110  * switching between high and low RR.
11111  * This macro can be used whenever a comparison has to be made between one
11112  * hw state and multiple sw state variables.
11113  */
11114 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
11115         if (!intel_compare_link_m_n(&current_config->name, \
11116                                     &pipe_config->name, adjust) && \
11117             !intel_compare_link_m_n(&current_config->alt_name, \
11118                                     &pipe_config->name, adjust)) { \
11119                 pipe_config_err(adjust, __stringify(name), \
11120                           "(expected tu %i gmch %i/%i link %i/%i, " \
11121                           "or tu %i gmch %i/%i link %i/%i, " \
11122                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11123                           current_config->name.tu, \
11124                           current_config->name.gmch_m, \
11125                           current_config->name.gmch_n, \
11126                           current_config->name.link_m, \
11127                           current_config->name.link_n, \
11128                           current_config->alt_name.tu, \
11129                           current_config->alt_name.gmch_m, \
11130                           current_config->alt_name.gmch_n, \
11131                           current_config->alt_name.link_m, \
11132                           current_config->alt_name.link_n, \
11133                           pipe_config->name.tu, \
11134                           pipe_config->name.gmch_m, \
11135                           pipe_config->name.gmch_n, \
11136                           pipe_config->name.link_m, \
11137                           pipe_config->name.link_n); \
11138                 ret = false; \
11139         }
11140
11141 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
11142         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11143                 pipe_config_err(adjust, __stringify(name), \
11144                           "(%x) (expected %i, found %i)\n", \
11145                           (mask), \
11146                           current_config->name & (mask), \
11147                           pipe_config->name & (mask)); \
11148                 ret = false; \
11149         }
11150
11151 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
11152         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11153                 pipe_config_err(adjust, __stringify(name), \
11154                           "(expected %i, found %i)\n", \
11155                           current_config->name, \
11156                           pipe_config->name); \
11157                 ret = false; \
11158         }
11159
11160 #define PIPE_CONF_QUIRK(quirk)  \
11161         ((current_config->quirks | pipe_config->quirks) & (quirk))
11162
11163         PIPE_CONF_CHECK_I(cpu_transcoder);
11164
11165         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11166         PIPE_CONF_CHECK_I(fdi_lanes);
11167         PIPE_CONF_CHECK_M_N(fdi_m_n);
11168
11169         PIPE_CONF_CHECK_I(lane_count);
11170         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11171
11172         if (INTEL_GEN(dev_priv) < 8) {
11173                 PIPE_CONF_CHECK_M_N(dp_m_n);
11174
11175                 if (current_config->has_drrs)
11176                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11177         } else
11178                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11179
11180         PIPE_CONF_CHECK_X(output_types);
11181
11182         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11183         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11184         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11185         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11186         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11187         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11188
11189         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11190         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11191         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11192         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11193         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11194         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11195
11196         PIPE_CONF_CHECK_I(pixel_multiplier);
11197         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11198         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11199             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11200                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11201
11202         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11203         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11204         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11205         PIPE_CONF_CHECK_BOOL(ycbcr420);
11206
11207         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11208
11209         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11210                               DRM_MODE_FLAG_INTERLACE);
11211
11212         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11213                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11214                                       DRM_MODE_FLAG_PHSYNC);
11215                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11216                                       DRM_MODE_FLAG_NHSYNC);
11217                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11218                                       DRM_MODE_FLAG_PVSYNC);
11219                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11220                                       DRM_MODE_FLAG_NVSYNC);
11221         }
11222
11223         PIPE_CONF_CHECK_X(gmch_pfit.control);
11224         /* pfit ratios are autocomputed by the hw on gen4+ */
11225         if (INTEL_GEN(dev_priv) < 4)
11226                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11227         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11228
11229         if (!adjust) {
11230                 PIPE_CONF_CHECK_I(pipe_src_w);
11231                 PIPE_CONF_CHECK_I(pipe_src_h);
11232
11233                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11234                 if (current_config->pch_pfit.enabled) {
11235                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11236                         PIPE_CONF_CHECK_X(pch_pfit.size);
11237                 }
11238
11239                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11240                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11241         }
11242
11243         PIPE_CONF_CHECK_BOOL(double_wide);
11244
11245         PIPE_CONF_CHECK_P(shared_dpll);
11246         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11247         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11248         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11249         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11250         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11251         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11252         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11253         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11254         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11255         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11256         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11257         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11258         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11259         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11260         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11261         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11262         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11263         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11264         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11265         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11266         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11267
11268         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11269         PIPE_CONF_CHECK_X(dsi_pll.div);
11270
11271         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11272                 PIPE_CONF_CHECK_I(pipe_bpp);
11273
11274         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11275         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11276
11277         PIPE_CONF_CHECK_I(min_voltage_level);
11278
11279 #undef PIPE_CONF_CHECK_X
11280 #undef PIPE_CONF_CHECK_I
11281 #undef PIPE_CONF_CHECK_BOOL
11282 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11283 #undef PIPE_CONF_CHECK_P
11284 #undef PIPE_CONF_CHECK_FLAGS
11285 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11286 #undef PIPE_CONF_QUIRK
11287
11288         return ret;
11289 }
11290
11291 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11292                                            const struct intel_crtc_state *pipe_config)
11293 {
11294         if (pipe_config->has_pch_encoder) {
11295                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11296                                                             &pipe_config->fdi_m_n);
11297                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11298
11299                 /*
11300                  * FDI already provided one idea for the dotclock.
11301                  * Yell if the encoder disagrees.
11302                  */
11303                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11304                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11305                      fdi_dotclock, dotclock);
11306         }
11307 }
11308
11309 static void verify_wm_state(struct drm_crtc *crtc,
11310                             struct drm_crtc_state *new_state)
11311 {
11312         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11313         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11314         struct skl_pipe_wm hw_wm, *sw_wm;
11315         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11316         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11317         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11318         const enum pipe pipe = intel_crtc->pipe;
11319         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11320
11321         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11322                 return;
11323
11324         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11325         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11326
11327         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11328         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11329
11330         /* planes */
11331         for_each_universal_plane(dev_priv, pipe, plane) {
11332                 hw_plane_wm = &hw_wm.planes[plane];
11333                 sw_plane_wm = &sw_wm->planes[plane];
11334
11335                 /* Watermarks */
11336                 for (level = 0; level <= max_level; level++) {
11337                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11338                                                 &sw_plane_wm->wm[level]))
11339                                 continue;
11340
11341                         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",
11342                                   pipe_name(pipe), plane + 1, level,
11343                                   sw_plane_wm->wm[level].plane_en,
11344                                   sw_plane_wm->wm[level].plane_res_b,
11345                                   sw_plane_wm->wm[level].plane_res_l,
11346                                   hw_plane_wm->wm[level].plane_en,
11347                                   hw_plane_wm->wm[level].plane_res_b,
11348                                   hw_plane_wm->wm[level].plane_res_l);
11349                 }
11350
11351                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11352                                          &sw_plane_wm->trans_wm)) {
11353                         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",
11354                                   pipe_name(pipe), plane + 1,
11355                                   sw_plane_wm->trans_wm.plane_en,
11356                                   sw_plane_wm->trans_wm.plane_res_b,
11357                                   sw_plane_wm->trans_wm.plane_res_l,
11358                                   hw_plane_wm->trans_wm.plane_en,
11359                                   hw_plane_wm->trans_wm.plane_res_b,
11360                                   hw_plane_wm->trans_wm.plane_res_l);
11361                 }
11362
11363                 /* DDB */
11364                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11365                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11366
11367                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11368                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11369                                   pipe_name(pipe), plane + 1,
11370                                   sw_ddb_entry->start, sw_ddb_entry->end,
11371                                   hw_ddb_entry->start, hw_ddb_entry->end);
11372                 }
11373         }
11374
11375         /*
11376          * cursor
11377          * If the cursor plane isn't active, we may not have updated it's ddb
11378          * allocation. In that case since the ddb allocation will be updated
11379          * once the plane becomes visible, we can skip this check
11380          */
11381         if (1) {
11382                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11383                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11384
11385                 /* Watermarks */
11386                 for (level = 0; level <= max_level; level++) {
11387                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11388                                                 &sw_plane_wm->wm[level]))
11389                                 continue;
11390
11391                         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",
11392                                   pipe_name(pipe), level,
11393                                   sw_plane_wm->wm[level].plane_en,
11394                                   sw_plane_wm->wm[level].plane_res_b,
11395                                   sw_plane_wm->wm[level].plane_res_l,
11396                                   hw_plane_wm->wm[level].plane_en,
11397                                   hw_plane_wm->wm[level].plane_res_b,
11398                                   hw_plane_wm->wm[level].plane_res_l);
11399                 }
11400
11401                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11402                                          &sw_plane_wm->trans_wm)) {
11403                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11404                                   pipe_name(pipe),
11405                                   sw_plane_wm->trans_wm.plane_en,
11406                                   sw_plane_wm->trans_wm.plane_res_b,
11407                                   sw_plane_wm->trans_wm.plane_res_l,
11408                                   hw_plane_wm->trans_wm.plane_en,
11409                                   hw_plane_wm->trans_wm.plane_res_b,
11410                                   hw_plane_wm->trans_wm.plane_res_l);
11411                 }
11412
11413                 /* DDB */
11414                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11415                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11416
11417                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11418                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11419                                   pipe_name(pipe),
11420                                   sw_ddb_entry->start, sw_ddb_entry->end,
11421                                   hw_ddb_entry->start, hw_ddb_entry->end);
11422                 }
11423         }
11424 }
11425
11426 static void
11427 verify_connector_state(struct drm_device *dev,
11428                        struct drm_atomic_state *state,
11429                        struct drm_crtc *crtc)
11430 {
11431         struct drm_connector *connector;
11432         struct drm_connector_state *new_conn_state;
11433         int i;
11434
11435         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11436                 struct drm_encoder *encoder = connector->encoder;
11437                 struct drm_crtc_state *crtc_state = NULL;
11438
11439                 if (new_conn_state->crtc != crtc)
11440                         continue;
11441
11442                 if (crtc)
11443                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11444
11445                 intel_connector_verify_state(crtc_state, new_conn_state);
11446
11447                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11448                      "connector's atomic encoder doesn't match legacy encoder\n");
11449         }
11450 }
11451
11452 static void
11453 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11454 {
11455         struct intel_encoder *encoder;
11456         struct drm_connector *connector;
11457         struct drm_connector_state *old_conn_state, *new_conn_state;
11458         int i;
11459
11460         for_each_intel_encoder(dev, encoder) {
11461                 bool enabled = false, found = false;
11462                 enum pipe pipe;
11463
11464                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11465                               encoder->base.base.id,
11466                               encoder->base.name);
11467
11468                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11469                                                    new_conn_state, i) {
11470                         if (old_conn_state->best_encoder == &encoder->base)
11471                                 found = true;
11472
11473                         if (new_conn_state->best_encoder != &encoder->base)
11474                                 continue;
11475                         found = enabled = true;
11476
11477                         I915_STATE_WARN(new_conn_state->crtc !=
11478                                         encoder->base.crtc,
11479                              "connector's crtc doesn't match encoder crtc\n");
11480                 }
11481
11482                 if (!found)
11483                         continue;
11484
11485                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11486                      "encoder's enabled state mismatch "
11487                      "(expected %i, found %i)\n",
11488                      !!encoder->base.crtc, enabled);
11489
11490                 if (!encoder->base.crtc) {
11491                         bool active;
11492
11493                         active = encoder->get_hw_state(encoder, &pipe);
11494                         I915_STATE_WARN(active,
11495                              "encoder detached but still enabled on pipe %c.\n",
11496                              pipe_name(pipe));
11497                 }
11498         }
11499 }
11500
11501 static void
11502 verify_crtc_state(struct drm_crtc *crtc,
11503                   struct drm_crtc_state *old_crtc_state,
11504                   struct drm_crtc_state *new_crtc_state)
11505 {
11506         struct drm_device *dev = crtc->dev;
11507         struct drm_i915_private *dev_priv = to_i915(dev);
11508         struct intel_encoder *encoder;
11509         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11510         struct intel_crtc_state *pipe_config, *sw_config;
11511         struct drm_atomic_state *old_state;
11512         bool active;
11513
11514         old_state = old_crtc_state->state;
11515         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11516         pipe_config = to_intel_crtc_state(old_crtc_state);
11517         memset(pipe_config, 0, sizeof(*pipe_config));
11518         pipe_config->base.crtc = crtc;
11519         pipe_config->base.state = old_state;
11520
11521         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11522
11523         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11524
11525         /* we keep both pipes enabled on 830 */
11526         if (IS_I830(dev_priv))
11527                 active = new_crtc_state->active;
11528
11529         I915_STATE_WARN(new_crtc_state->active != active,
11530              "crtc active state doesn't match with hw state "
11531              "(expected %i, found %i)\n", new_crtc_state->active, active);
11532
11533         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11534              "transitional active state does not match atomic hw state "
11535              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11536
11537         for_each_encoder_on_crtc(dev, crtc, encoder) {
11538                 enum pipe pipe;
11539
11540                 active = encoder->get_hw_state(encoder, &pipe);
11541                 I915_STATE_WARN(active != new_crtc_state->active,
11542                         "[ENCODER:%i] active %i with crtc active %i\n",
11543                         encoder->base.base.id, active, new_crtc_state->active);
11544
11545                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11546                                 "Encoder connected to wrong pipe %c\n",
11547                                 pipe_name(pipe));
11548
11549                 if (active)
11550                         encoder->get_config(encoder, pipe_config);
11551         }
11552
11553         intel_crtc_compute_pixel_rate(pipe_config);
11554
11555         if (!new_crtc_state->active)
11556                 return;
11557
11558         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11559
11560         sw_config = to_intel_crtc_state(new_crtc_state);
11561         if (!intel_pipe_config_compare(dev_priv, sw_config,
11562                                        pipe_config, false)) {
11563                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11564                 intel_dump_pipe_config(intel_crtc, pipe_config,
11565                                        "[hw state]");
11566                 intel_dump_pipe_config(intel_crtc, sw_config,
11567                                        "[sw state]");
11568         }
11569 }
11570
11571 static void
11572 intel_verify_planes(struct intel_atomic_state *state)
11573 {
11574         struct intel_plane *plane;
11575         const struct intel_plane_state *plane_state;
11576         int i;
11577
11578         for_each_new_intel_plane_in_state(state, plane,
11579                                           plane_state, i)
11580                 assert_plane(plane, plane_state->base.visible);
11581 }
11582
11583 static void
11584 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11585                          struct intel_shared_dpll *pll,
11586                          struct drm_crtc *crtc,
11587                          struct drm_crtc_state *new_state)
11588 {
11589         struct intel_dpll_hw_state dpll_hw_state;
11590         unsigned crtc_mask;
11591         bool active;
11592
11593         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11594
11595         DRM_DEBUG_KMS("%s\n", pll->name);
11596
11597         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
11598
11599         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
11600                 I915_STATE_WARN(!pll->on && pll->active_mask,
11601                      "pll in active use but not on in sw tracking\n");
11602                 I915_STATE_WARN(pll->on && !pll->active_mask,
11603                      "pll is on but not used by any active crtc\n");
11604                 I915_STATE_WARN(pll->on != active,
11605                      "pll on state mismatch (expected %i, found %i)\n",
11606                      pll->on, active);
11607         }
11608
11609         if (!crtc) {
11610                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
11611                                 "more active pll users than references: %x vs %x\n",
11612                                 pll->active_mask, pll->state.crtc_mask);
11613
11614                 return;
11615         }
11616
11617         crtc_mask = 1 << drm_crtc_index(crtc);
11618
11619         if (new_state->active)
11620                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
11621                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
11622                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11623         else
11624                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11625                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
11626                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11627
11628         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
11629                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
11630                         crtc_mask, pll->state.crtc_mask);
11631
11632         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
11633                                           &dpll_hw_state,
11634                                           sizeof(dpll_hw_state)),
11635                         "pll hw state mismatch\n");
11636 }
11637
11638 static void
11639 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
11640                          struct drm_crtc_state *old_crtc_state,
11641                          struct drm_crtc_state *new_crtc_state)
11642 {
11643         struct drm_i915_private *dev_priv = to_i915(dev);
11644         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
11645         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
11646
11647         if (new_state->shared_dpll)
11648                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
11649
11650         if (old_state->shared_dpll &&
11651             old_state->shared_dpll != new_state->shared_dpll) {
11652                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
11653                 struct intel_shared_dpll *pll = old_state->shared_dpll;
11654
11655                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11656                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
11657                                 pipe_name(drm_crtc_index(crtc)));
11658                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
11659                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
11660                                 pipe_name(drm_crtc_index(crtc)));
11661         }
11662 }
11663
11664 static void
11665 intel_modeset_verify_crtc(struct drm_crtc *crtc,
11666                           struct drm_atomic_state *state,
11667                           struct drm_crtc_state *old_state,
11668                           struct drm_crtc_state *new_state)
11669 {
11670         if (!needs_modeset(new_state) &&
11671             !to_intel_crtc_state(new_state)->update_pipe)
11672                 return;
11673
11674         verify_wm_state(crtc, new_state);
11675         verify_connector_state(crtc->dev, state, crtc);
11676         verify_crtc_state(crtc, old_state, new_state);
11677         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
11678 }
11679
11680 static void
11681 verify_disabled_dpll_state(struct drm_device *dev)
11682 {
11683         struct drm_i915_private *dev_priv = to_i915(dev);
11684         int i;
11685
11686         for (i = 0; i < dev_priv->num_shared_dpll; i++)
11687                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
11688 }
11689
11690 static void
11691 intel_modeset_verify_disabled(struct drm_device *dev,
11692                               struct drm_atomic_state *state)
11693 {
11694         verify_encoder_state(dev, state);
11695         verify_connector_state(dev, state, NULL);
11696         verify_disabled_dpll_state(dev);
11697 }
11698
11699 static void update_scanline_offset(struct intel_crtc *crtc)
11700 {
11701         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11702
11703         /*
11704          * The scanline counter increments at the leading edge of hsync.
11705          *
11706          * On most platforms it starts counting from vtotal-1 on the
11707          * first active line. That means the scanline counter value is
11708          * always one less than what we would expect. Ie. just after
11709          * start of vblank, which also occurs at start of hsync (on the
11710          * last active line), the scanline counter will read vblank_start-1.
11711          *
11712          * On gen2 the scanline counter starts counting from 1 instead
11713          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
11714          * to keep the value positive), instead of adding one.
11715          *
11716          * On HSW+ the behaviour of the scanline counter depends on the output
11717          * type. For DP ports it behaves like most other platforms, but on HDMI
11718          * there's an extra 1 line difference. So we need to add two instead of
11719          * one to the value.
11720          *
11721          * On VLV/CHV DSI the scanline counter would appear to increment
11722          * approx. 1/3 of a scanline before start of vblank. Unfortunately
11723          * that means we can't tell whether we're in vblank or not while
11724          * we're on that particular line. We must still set scanline_offset
11725          * to 1 so that the vblank timestamps come out correct when we query
11726          * the scanline counter from within the vblank interrupt handler.
11727          * However if queried just before the start of vblank we'll get an
11728          * answer that's slightly in the future.
11729          */
11730         if (IS_GEN2(dev_priv)) {
11731                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
11732                 int vtotal;
11733
11734                 vtotal = adjusted_mode->crtc_vtotal;
11735                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
11736                         vtotal /= 2;
11737
11738                 crtc->scanline_offset = vtotal - 1;
11739         } else if (HAS_DDI(dev_priv) &&
11740                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
11741                 crtc->scanline_offset = 2;
11742         } else
11743                 crtc->scanline_offset = 1;
11744 }
11745
11746 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
11747 {
11748         struct drm_device *dev = state->dev;
11749         struct drm_i915_private *dev_priv = to_i915(dev);
11750         struct drm_crtc *crtc;
11751         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11752         int i;
11753
11754         if (!dev_priv->display.crtc_compute_clock)
11755                 return;
11756
11757         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11758                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11759                 struct intel_shared_dpll *old_dpll =
11760                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
11761
11762                 if (!needs_modeset(new_crtc_state))
11763                         continue;
11764
11765                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
11766
11767                 if (!old_dpll)
11768                         continue;
11769
11770                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
11771         }
11772 }
11773
11774 /*
11775  * This implements the workaround described in the "notes" section of the mode
11776  * set sequence documentation. When going from no pipes or single pipe to
11777  * multiple pipes, and planes are enabled after the pipe, we need to wait at
11778  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
11779  */
11780 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
11781 {
11782         struct drm_crtc_state *crtc_state;
11783         struct intel_crtc *intel_crtc;
11784         struct drm_crtc *crtc;
11785         struct intel_crtc_state *first_crtc_state = NULL;
11786         struct intel_crtc_state *other_crtc_state = NULL;
11787         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
11788         int i;
11789
11790         /* look at all crtc's that are going to be enabled in during modeset */
11791         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
11792                 intel_crtc = to_intel_crtc(crtc);
11793
11794                 if (!crtc_state->active || !needs_modeset(crtc_state))
11795                         continue;
11796
11797                 if (first_crtc_state) {
11798                         other_crtc_state = to_intel_crtc_state(crtc_state);
11799                         break;
11800                 } else {
11801                         first_crtc_state = to_intel_crtc_state(crtc_state);
11802                         first_pipe = intel_crtc->pipe;
11803                 }
11804         }
11805
11806         /* No workaround needed? */
11807         if (!first_crtc_state)
11808                 return 0;
11809
11810         /* w/a possibly needed, check how many crtc's are already enabled. */
11811         for_each_intel_crtc(state->dev, intel_crtc) {
11812                 struct intel_crtc_state *pipe_config;
11813
11814                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
11815                 if (IS_ERR(pipe_config))
11816                         return PTR_ERR(pipe_config);
11817
11818                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
11819
11820                 if (!pipe_config->base.active ||
11821                     needs_modeset(&pipe_config->base))
11822                         continue;
11823
11824                 /* 2 or more enabled crtcs means no need for w/a */
11825                 if (enabled_pipe != INVALID_PIPE)
11826                         return 0;
11827
11828                 enabled_pipe = intel_crtc->pipe;
11829         }
11830
11831         if (enabled_pipe != INVALID_PIPE)
11832                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
11833         else if (other_crtc_state)
11834                 other_crtc_state->hsw_workaround_pipe = first_pipe;
11835
11836         return 0;
11837 }
11838
11839 static int intel_lock_all_pipes(struct drm_atomic_state *state)
11840 {
11841         struct drm_crtc *crtc;
11842
11843         /* Add all pipes to the state */
11844         for_each_crtc(state->dev, crtc) {
11845                 struct drm_crtc_state *crtc_state;
11846
11847                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11848                 if (IS_ERR(crtc_state))
11849                         return PTR_ERR(crtc_state);
11850         }
11851
11852         return 0;
11853 }
11854
11855 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
11856 {
11857         struct drm_crtc *crtc;
11858
11859         /*
11860          * Add all pipes to the state, and force
11861          * a modeset on all the active ones.
11862          */
11863         for_each_crtc(state->dev, crtc) {
11864                 struct drm_crtc_state *crtc_state;
11865                 int ret;
11866
11867                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11868                 if (IS_ERR(crtc_state))
11869                         return PTR_ERR(crtc_state);
11870
11871                 if (!crtc_state->active || needs_modeset(crtc_state))
11872                         continue;
11873
11874                 crtc_state->mode_changed = true;
11875
11876                 ret = drm_atomic_add_affected_connectors(state, crtc);
11877                 if (ret)
11878                         return ret;
11879
11880                 ret = drm_atomic_add_affected_planes(state, crtc);
11881                 if (ret)
11882                         return ret;
11883         }
11884
11885         return 0;
11886 }
11887
11888 static int intel_modeset_checks(struct drm_atomic_state *state)
11889 {
11890         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
11891         struct drm_i915_private *dev_priv = to_i915(state->dev);
11892         struct drm_crtc *crtc;
11893         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11894         int ret = 0, i;
11895
11896         if (!check_digital_port_conflicts(state)) {
11897                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
11898                 return -EINVAL;
11899         }
11900
11901         intel_state->modeset = true;
11902         intel_state->active_crtcs = dev_priv->active_crtcs;
11903         intel_state->cdclk.logical = dev_priv->cdclk.logical;
11904         intel_state->cdclk.actual = dev_priv->cdclk.actual;
11905
11906         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11907                 if (new_crtc_state->active)
11908                         intel_state->active_crtcs |= 1 << i;
11909                 else
11910                         intel_state->active_crtcs &= ~(1 << i);
11911
11912                 if (old_crtc_state->active != new_crtc_state->active)
11913                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
11914         }
11915
11916         /*
11917          * See if the config requires any additional preparation, e.g.
11918          * to adjust global state with pipes off.  We need to do this
11919          * here so we can get the modeset_pipe updated config for the new
11920          * mode set on this crtc.  For other crtcs we need to use the
11921          * adjusted_mode bits in the crtc directly.
11922          */
11923         if (dev_priv->display.modeset_calc_cdclk) {
11924                 ret = dev_priv->display.modeset_calc_cdclk(state);
11925                 if (ret < 0)
11926                         return ret;
11927
11928                 /*
11929                  * Writes to dev_priv->cdclk.logical must protected by
11930                  * holding all the crtc locks, even if we don't end up
11931                  * touching the hardware
11932                  */
11933                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
11934                                         &intel_state->cdclk.logical)) {
11935                         ret = intel_lock_all_pipes(state);
11936                         if (ret < 0)
11937                                 return ret;
11938                 }
11939
11940                 /* All pipes must be switched off while we change the cdclk. */
11941                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
11942                                               &intel_state->cdclk.actual)) {
11943                         ret = intel_modeset_all_pipes(state);
11944                         if (ret < 0)
11945                                 return ret;
11946                 }
11947
11948                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
11949                               intel_state->cdclk.logical.cdclk,
11950                               intel_state->cdclk.actual.cdclk);
11951                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
11952                               intel_state->cdclk.logical.voltage_level,
11953                               intel_state->cdclk.actual.voltage_level);
11954         } else {
11955                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
11956         }
11957
11958         intel_modeset_clear_plls(state);
11959
11960         if (IS_HASWELL(dev_priv))
11961                 return haswell_mode_set_planes_workaround(state);
11962
11963         return 0;
11964 }
11965
11966 /*
11967  * Handle calculation of various watermark data at the end of the atomic check
11968  * phase.  The code here should be run after the per-crtc and per-plane 'check'
11969  * handlers to ensure that all derived state has been updated.
11970  */
11971 static int calc_watermark_data(struct drm_atomic_state *state)
11972 {
11973         struct drm_device *dev = state->dev;
11974         struct drm_i915_private *dev_priv = to_i915(dev);
11975
11976         /* Is there platform-specific watermark information to calculate? */
11977         if (dev_priv->display.compute_global_watermarks)
11978                 return dev_priv->display.compute_global_watermarks(state);
11979
11980         return 0;
11981 }
11982
11983 /**
11984  * intel_atomic_check - validate state object
11985  * @dev: drm device
11986  * @state: state to validate
11987  */
11988 static int intel_atomic_check(struct drm_device *dev,
11989                               struct drm_atomic_state *state)
11990 {
11991         struct drm_i915_private *dev_priv = to_i915(dev);
11992         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
11993         struct drm_crtc *crtc;
11994         struct drm_crtc_state *old_crtc_state, *crtc_state;
11995         int ret, i;
11996         bool any_ms = false;
11997
11998         ret = drm_atomic_helper_check_modeset(dev, state);
11999         if (ret)
12000                 return ret;
12001
12002         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12003                 struct intel_crtc_state *pipe_config =
12004                         to_intel_crtc_state(crtc_state);
12005
12006                 /* Catch I915_MODE_FLAG_INHERITED */
12007                 if (crtc_state->mode.private_flags != old_crtc_state->mode.private_flags)
12008                         crtc_state->mode_changed = true;
12009
12010                 if (!needs_modeset(crtc_state))
12011                         continue;
12012
12013                 if (!crtc_state->enable) {
12014                         any_ms = true;
12015                         continue;
12016                 }
12017
12018                 /* FIXME: For only active_changed we shouldn't need to do any
12019                  * state recomputation at all. */
12020
12021                 ret = drm_atomic_add_affected_connectors(state, crtc);
12022                 if (ret)
12023                         return ret;
12024
12025                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12026                 if (ret) {
12027                         intel_dump_pipe_config(to_intel_crtc(crtc),
12028                                                pipe_config, "[failed]");
12029                         return ret;
12030                 }
12031
12032                 if (i915_modparams.fastboot &&
12033                     intel_pipe_config_compare(dev_priv,
12034                                         to_intel_crtc_state(old_crtc_state),
12035                                         pipe_config, true)) {
12036                         crtc_state->mode_changed = false;
12037                         pipe_config->update_pipe = true;
12038                 }
12039
12040                 if (needs_modeset(crtc_state))
12041                         any_ms = true;
12042
12043                 ret = drm_atomic_add_affected_planes(state, crtc);
12044                 if (ret)
12045                         return ret;
12046
12047                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12048                                        needs_modeset(crtc_state) ?
12049                                        "[modeset]" : "[fastset]");
12050         }
12051
12052         if (any_ms) {
12053                 ret = intel_modeset_checks(state);
12054
12055                 if (ret)
12056                         return ret;
12057         } else {
12058                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12059         }
12060
12061         ret = drm_atomic_helper_check_planes(dev, state);
12062         if (ret)
12063                 return ret;
12064
12065         intel_fbc_choose_crtc(dev_priv, intel_state);
12066         return calc_watermark_data(state);
12067 }
12068
12069 static int intel_atomic_prepare_commit(struct drm_device *dev,
12070                                        struct drm_atomic_state *state)
12071 {
12072         return drm_atomic_helper_prepare_planes(dev, state);
12073 }
12074
12075 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12076 {
12077         struct drm_device *dev = crtc->base.dev;
12078
12079         if (!dev->max_vblank_count)
12080                 return drm_crtc_accurate_vblank_count(&crtc->base);
12081
12082         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12083 }
12084
12085 static void intel_update_crtc(struct drm_crtc *crtc,
12086                               struct drm_atomic_state *state,
12087                               struct drm_crtc_state *old_crtc_state,
12088                               struct drm_crtc_state *new_crtc_state)
12089 {
12090         struct drm_device *dev = crtc->dev;
12091         struct drm_i915_private *dev_priv = to_i915(dev);
12092         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12093         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12094         bool modeset = needs_modeset(new_crtc_state);
12095
12096         if (modeset) {
12097                 update_scanline_offset(intel_crtc);
12098                 dev_priv->display.crtc_enable(pipe_config, state);
12099         } else {
12100                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12101                                        pipe_config);
12102         }
12103
12104         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12105                 intel_fbc_enable(
12106                     intel_crtc, pipe_config,
12107                     to_intel_plane_state(crtc->primary->state));
12108         }
12109
12110         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12111 }
12112
12113 static void intel_update_crtcs(struct drm_atomic_state *state)
12114 {
12115         struct drm_crtc *crtc;
12116         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12117         int i;
12118
12119         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12120                 if (!new_crtc_state->active)
12121                         continue;
12122
12123                 intel_update_crtc(crtc, state, old_crtc_state,
12124                                   new_crtc_state);
12125         }
12126 }
12127
12128 static void skl_update_crtcs(struct drm_atomic_state *state)
12129 {
12130         struct drm_i915_private *dev_priv = to_i915(state->dev);
12131         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12132         struct drm_crtc *crtc;
12133         struct intel_crtc *intel_crtc;
12134         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12135         struct intel_crtc_state *cstate;
12136         unsigned int updated = 0;
12137         bool progress;
12138         enum pipe pipe;
12139         int i;
12140
12141         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12142
12143         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12144                 /* ignore allocations for crtc's that have been turned off. */
12145                 if (new_crtc_state->active)
12146                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12147
12148         /*
12149          * Whenever the number of active pipes changes, we need to make sure we
12150          * update the pipes in the right order so that their ddb allocations
12151          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12152          * cause pipe underruns and other bad stuff.
12153          */
12154         do {
12155                 progress = false;
12156
12157                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12158                         bool vbl_wait = false;
12159                         unsigned int cmask = drm_crtc_mask(crtc);
12160
12161                         intel_crtc = to_intel_crtc(crtc);
12162                         cstate = to_intel_crtc_state(new_crtc_state);
12163                         pipe = intel_crtc->pipe;
12164
12165                         if (updated & cmask || !cstate->base.active)
12166                                 continue;
12167
12168                         if (skl_ddb_allocation_overlaps(dev_priv,
12169                                                         entries,
12170                                                         &cstate->wm.skl.ddb,
12171                                                         i))
12172                                 continue;
12173
12174                         updated |= cmask;
12175                         entries[i] = &cstate->wm.skl.ddb;
12176
12177                         /*
12178                          * If this is an already active pipe, it's DDB changed,
12179                          * and this isn't the last pipe that needs updating
12180                          * then we need to wait for a vblank to pass for the
12181                          * new ddb allocation to take effect.
12182                          */
12183                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12184                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12185                             !new_crtc_state->active_changed &&
12186                             intel_state->wm_results.dirty_pipes != updated)
12187                                 vbl_wait = true;
12188
12189                         intel_update_crtc(crtc, state, old_crtc_state,
12190                                           new_crtc_state);
12191
12192                         if (vbl_wait)
12193                                 intel_wait_for_vblank(dev_priv, pipe);
12194
12195                         progress = true;
12196                 }
12197         } while (progress);
12198 }
12199
12200 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12201 {
12202         struct intel_atomic_state *state, *next;
12203         struct llist_node *freed;
12204
12205         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12206         llist_for_each_entry_safe(state, next, freed, freed)
12207                 drm_atomic_state_put(&state->base);
12208 }
12209
12210 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12211 {
12212         struct drm_i915_private *dev_priv =
12213                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12214
12215         intel_atomic_helper_free_state(dev_priv);
12216 }
12217
12218 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12219 {
12220         struct wait_queue_entry wait_fence, wait_reset;
12221         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12222
12223         init_wait_entry(&wait_fence, 0);
12224         init_wait_entry(&wait_reset, 0);
12225         for (;;) {
12226                 prepare_to_wait(&intel_state->commit_ready.wait,
12227                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12228                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12229                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12230
12231
12232                 if (i915_sw_fence_done(&intel_state->commit_ready)
12233                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12234                         break;
12235
12236                 schedule();
12237         }
12238         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12239         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12240 }
12241
12242 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12243 {
12244         struct drm_device *dev = state->dev;
12245         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12246         struct drm_i915_private *dev_priv = to_i915(dev);
12247         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12248         struct drm_crtc *crtc;
12249         struct intel_crtc_state *intel_cstate;
12250         u64 put_domains[I915_MAX_PIPES] = {};
12251         int i;
12252
12253         intel_atomic_commit_fence_wait(intel_state);
12254
12255         drm_atomic_helper_wait_for_dependencies(state);
12256
12257         if (intel_state->modeset)
12258                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12259
12260         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12261                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12262
12263                 if (needs_modeset(new_crtc_state) ||
12264                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12265
12266                         put_domains[to_intel_crtc(crtc)->pipe] =
12267                                 modeset_get_crtc_power_domains(crtc,
12268                                         to_intel_crtc_state(new_crtc_state));
12269                 }
12270
12271                 if (!needs_modeset(new_crtc_state))
12272                         continue;
12273
12274                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12275                                        to_intel_crtc_state(new_crtc_state));
12276
12277                 if (old_crtc_state->active) {
12278                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
12279                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
12280                         intel_crtc->active = false;
12281                         intel_fbc_disable(intel_crtc);
12282                         intel_disable_shared_dpll(intel_crtc);
12283
12284                         /*
12285                          * Underruns don't always raise
12286                          * interrupts, so check manually.
12287                          */
12288                         intel_check_cpu_fifo_underruns(dev_priv);
12289                         intel_check_pch_fifo_underruns(dev_priv);
12290
12291                         if (!new_crtc_state->active) {
12292                                 /*
12293                                  * Make sure we don't call initial_watermarks
12294                                  * for ILK-style watermark updates.
12295                                  *
12296                                  * No clue what this is supposed to achieve.
12297                                  */
12298                                 if (INTEL_GEN(dev_priv) >= 9)
12299                                         dev_priv->display.initial_watermarks(intel_state,
12300                                                                              to_intel_crtc_state(new_crtc_state));
12301                         }
12302                 }
12303         }
12304
12305         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12306         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12307                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12308
12309         if (intel_state->modeset) {
12310                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12311
12312                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12313
12314                 /*
12315                  * SKL workaround: bspec recommends we disable the SAGV when we
12316                  * have more then one pipe enabled
12317                  */
12318                 if (!intel_can_enable_sagv(state))
12319                         intel_disable_sagv(dev_priv);
12320
12321                 intel_modeset_verify_disabled(dev, state);
12322         }
12323
12324         /* Complete the events for pipes that have now been disabled */
12325         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12326                 bool modeset = needs_modeset(new_crtc_state);
12327
12328                 /* Complete events for now disable pipes here. */
12329                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12330                         spin_lock_irq(&dev->event_lock);
12331                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12332                         spin_unlock_irq(&dev->event_lock);
12333
12334                         new_crtc_state->event = NULL;
12335                 }
12336         }
12337
12338         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12339         dev_priv->display.update_crtcs(state);
12340
12341         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12342          * already, but still need the state for the delayed optimization. To
12343          * fix this:
12344          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12345          * - schedule that vblank worker _before_ calling hw_done
12346          * - at the start of commit_tail, cancel it _synchrously
12347          * - switch over to the vblank wait helper in the core after that since
12348          *   we don't need out special handling any more.
12349          */
12350         drm_atomic_helper_wait_for_flip_done(dev, state);
12351
12352         /*
12353          * Now that the vblank has passed, we can go ahead and program the
12354          * optimal watermarks on platforms that need two-step watermark
12355          * programming.
12356          *
12357          * TODO: Move this (and other cleanup) to an async worker eventually.
12358          */
12359         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12360                 intel_cstate = to_intel_crtc_state(new_crtc_state);
12361
12362                 if (dev_priv->display.optimize_watermarks)
12363                         dev_priv->display.optimize_watermarks(intel_state,
12364                                                               intel_cstate);
12365         }
12366
12367         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12368                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12369
12370                 if (put_domains[i])
12371                         modeset_put_power_domains(dev_priv, put_domains[i]);
12372
12373                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12374         }
12375
12376         if (intel_state->modeset)
12377                 intel_verify_planes(intel_state);
12378
12379         if (intel_state->modeset && intel_can_enable_sagv(state))
12380                 intel_enable_sagv(dev_priv);
12381
12382         drm_atomic_helper_commit_hw_done(state);
12383
12384         if (intel_state->modeset) {
12385                 /* As one of the primary mmio accessors, KMS has a high
12386                  * likelihood of triggering bugs in unclaimed access. After we
12387                  * finish modesetting, see if an error has been flagged, and if
12388                  * so enable debugging for the next modeset - and hope we catch
12389                  * the culprit.
12390                  */
12391                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12392                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12393         }
12394
12395         drm_atomic_helper_cleanup_planes(dev, state);
12396
12397         drm_atomic_helper_commit_cleanup_done(state);
12398
12399         drm_atomic_state_put(state);
12400
12401         intel_atomic_helper_free_state(dev_priv);
12402 }
12403
12404 static void intel_atomic_commit_work(struct work_struct *work)
12405 {
12406         struct drm_atomic_state *state =
12407                 container_of(work, struct drm_atomic_state, commit_work);
12408
12409         intel_atomic_commit_tail(state);
12410 }
12411
12412 static int __i915_sw_fence_call
12413 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12414                           enum i915_sw_fence_notify notify)
12415 {
12416         struct intel_atomic_state *state =
12417                 container_of(fence, struct intel_atomic_state, commit_ready);
12418
12419         switch (notify) {
12420         case FENCE_COMPLETE:
12421                 /* we do blocking waits in the worker, nothing to do here */
12422                 break;
12423         case FENCE_FREE:
12424                 {
12425                         struct intel_atomic_helper *helper =
12426                                 &to_i915(state->base.dev)->atomic_helper;
12427
12428                         if (llist_add(&state->freed, &helper->free_list))
12429                                 schedule_work(&helper->free_work);
12430                         break;
12431                 }
12432         }
12433
12434         return NOTIFY_DONE;
12435 }
12436
12437 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12438 {
12439         struct drm_plane_state *old_plane_state, *new_plane_state;
12440         struct drm_plane *plane;
12441         int i;
12442
12443         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12444                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12445                                   intel_fb_obj(new_plane_state->fb),
12446                                   to_intel_plane(plane)->frontbuffer_bit);
12447 }
12448
12449 /**
12450  * intel_atomic_commit - commit validated state object
12451  * @dev: DRM device
12452  * @state: the top-level driver state object
12453  * @nonblock: nonblocking commit
12454  *
12455  * This function commits a top-level state object that has been validated
12456  * with drm_atomic_helper_check().
12457  *
12458  * RETURNS
12459  * Zero for success or -errno.
12460  */
12461 static int intel_atomic_commit(struct drm_device *dev,
12462                                struct drm_atomic_state *state,
12463                                bool nonblock)
12464 {
12465         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12466         struct drm_i915_private *dev_priv = to_i915(dev);
12467         int ret = 0;
12468
12469         drm_atomic_state_get(state);
12470         i915_sw_fence_init(&intel_state->commit_ready,
12471                            intel_atomic_commit_ready);
12472
12473         /*
12474          * The intel_legacy_cursor_update() fast path takes care
12475          * of avoiding the vblank waits for simple cursor
12476          * movement and flips. For cursor on/off and size changes,
12477          * we want to perform the vblank waits so that watermark
12478          * updates happen during the correct frames. Gen9+ have
12479          * double buffered watermarks and so shouldn't need this.
12480          *
12481          * Unset state->legacy_cursor_update before the call to
12482          * drm_atomic_helper_setup_commit() because otherwise
12483          * drm_atomic_helper_wait_for_flip_done() is a noop and
12484          * we get FIFO underruns because we didn't wait
12485          * for vblank.
12486          *
12487          * FIXME doing watermarks and fb cleanup from a vblank worker
12488          * (assuming we had any) would solve these problems.
12489          */
12490         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12491                 struct intel_crtc_state *new_crtc_state;
12492                 struct intel_crtc *crtc;
12493                 int i;
12494
12495                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12496                         if (new_crtc_state->wm.need_postvbl_update ||
12497                             new_crtc_state->update_wm_post)
12498                                 state->legacy_cursor_update = false;
12499         }
12500
12501         ret = intel_atomic_prepare_commit(dev, state);
12502         if (ret) {
12503                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12504                 i915_sw_fence_commit(&intel_state->commit_ready);
12505                 return ret;
12506         }
12507
12508         ret = drm_atomic_helper_setup_commit(state, nonblock);
12509         if (!ret)
12510                 ret = drm_atomic_helper_swap_state(state, true);
12511
12512         if (ret) {
12513                 i915_sw_fence_commit(&intel_state->commit_ready);
12514
12515                 drm_atomic_helper_cleanup_planes(dev, state);
12516                 return ret;
12517         }
12518         dev_priv->wm.distrust_bios_wm = false;
12519         intel_shared_dpll_swap_state(state);
12520         intel_atomic_track_fbs(state);
12521
12522         if (intel_state->modeset) {
12523                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12524                        sizeof(intel_state->min_cdclk));
12525                 memcpy(dev_priv->min_voltage_level,
12526                        intel_state->min_voltage_level,
12527                        sizeof(intel_state->min_voltage_level));
12528                 dev_priv->active_crtcs = intel_state->active_crtcs;
12529                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12530                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12531         }
12532
12533         drm_atomic_state_get(state);
12534         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12535
12536         i915_sw_fence_commit(&intel_state->commit_ready);
12537         if (nonblock && intel_state->modeset) {
12538                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12539         } else if (nonblock) {
12540                 queue_work(system_unbound_wq, &state->commit_work);
12541         } else {
12542                 if (intel_state->modeset)
12543                         flush_workqueue(dev_priv->modeset_wq);
12544                 intel_atomic_commit_tail(state);
12545         }
12546
12547         return 0;
12548 }
12549
12550 static const struct drm_crtc_funcs intel_crtc_funcs = {
12551         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12552         .set_config = drm_atomic_helper_set_config,
12553         .destroy = intel_crtc_destroy,
12554         .page_flip = drm_atomic_helper_page_flip,
12555         .atomic_duplicate_state = intel_crtc_duplicate_state,
12556         .atomic_destroy_state = intel_crtc_destroy_state,
12557         .set_crc_source = intel_crtc_set_crc_source,
12558 };
12559
12560 struct wait_rps_boost {
12561         struct wait_queue_entry wait;
12562
12563         struct drm_crtc *crtc;
12564         struct drm_i915_gem_request *request;
12565 };
12566
12567 static int do_rps_boost(struct wait_queue_entry *_wait,
12568                         unsigned mode, int sync, void *key)
12569 {
12570         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
12571         struct drm_i915_gem_request *rq = wait->request;
12572
12573         /*
12574          * If we missed the vblank, but the request is already running it
12575          * is reasonable to assume that it will complete before the next
12576          * vblank without our intervention, so leave RPS alone.
12577          */
12578         if (!i915_gem_request_started(rq))
12579                 gen6_rps_boost(rq, NULL);
12580         i915_gem_request_put(rq);
12581
12582         drm_crtc_vblank_put(wait->crtc);
12583
12584         list_del(&wait->wait.entry);
12585         kfree(wait);
12586         return 1;
12587 }
12588
12589 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
12590                                        struct dma_fence *fence)
12591 {
12592         struct wait_rps_boost *wait;
12593
12594         if (!dma_fence_is_i915(fence))
12595                 return;
12596
12597         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
12598                 return;
12599
12600         if (drm_crtc_vblank_get(crtc))
12601                 return;
12602
12603         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
12604         if (!wait) {
12605                 drm_crtc_vblank_put(crtc);
12606                 return;
12607         }
12608
12609         wait->request = to_request(dma_fence_get(fence));
12610         wait->crtc = crtc;
12611
12612         wait->wait.func = do_rps_boost;
12613         wait->wait.flags = 0;
12614
12615         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
12616 }
12617
12618 /**
12619  * intel_prepare_plane_fb - Prepare fb for usage on plane
12620  * @plane: drm plane to prepare for
12621  * @fb: framebuffer to prepare for presentation
12622  *
12623  * Prepares a framebuffer for usage on a display plane.  Generally this
12624  * involves pinning the underlying object and updating the frontbuffer tracking
12625  * bits.  Some older platforms need special physical address handling for
12626  * cursor planes.
12627  *
12628  * Must be called with struct_mutex held.
12629  *
12630  * Returns 0 on success, negative error code on failure.
12631  */
12632 int
12633 intel_prepare_plane_fb(struct drm_plane *plane,
12634                        struct drm_plane_state *new_state)
12635 {
12636         struct intel_atomic_state *intel_state =
12637                 to_intel_atomic_state(new_state->state);
12638         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12639         struct drm_framebuffer *fb = new_state->fb;
12640         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12641         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
12642         int ret;
12643
12644         if (old_obj) {
12645                 struct drm_crtc_state *crtc_state =
12646                         drm_atomic_get_existing_crtc_state(new_state->state,
12647                                                            plane->state->crtc);
12648
12649                 /* Big Hammer, we also need to ensure that any pending
12650                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
12651                  * current scanout is retired before unpinning the old
12652                  * framebuffer. Note that we rely on userspace rendering
12653                  * into the buffer attached to the pipe they are waiting
12654                  * on. If not, userspace generates a GPU hang with IPEHR
12655                  * point to the MI_WAIT_FOR_EVENT.
12656                  *
12657                  * This should only fail upon a hung GPU, in which case we
12658                  * can safely continue.
12659                  */
12660                 if (needs_modeset(crtc_state)) {
12661                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12662                                                               old_obj->resv, NULL,
12663                                                               false, 0,
12664                                                               GFP_KERNEL);
12665                         if (ret < 0)
12666                                 return ret;
12667                 }
12668         }
12669
12670         if (new_state->fence) { /* explicit fencing */
12671                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
12672                                                     new_state->fence,
12673                                                     I915_FENCE_TIMEOUT,
12674                                                     GFP_KERNEL);
12675                 if (ret < 0)
12676                         return ret;
12677         }
12678
12679         if (!obj)
12680                 return 0;
12681
12682         ret = i915_gem_object_pin_pages(obj);
12683         if (ret)
12684                 return ret;
12685
12686         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
12687         if (ret) {
12688                 i915_gem_object_unpin_pages(obj);
12689                 return ret;
12690         }
12691
12692         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12693             INTEL_INFO(dev_priv)->cursor_needs_physical) {
12694                 const int align = intel_cursor_alignment(dev_priv);
12695
12696                 ret = i915_gem_object_attach_phys(obj, align);
12697         } else {
12698                 struct i915_vma *vma;
12699
12700                 vma = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
12701                 if (!IS_ERR(vma))
12702                         to_intel_plane_state(new_state)->vma = vma;
12703                 else
12704                         ret =  PTR_ERR(vma);
12705         }
12706
12707         i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
12708
12709         mutex_unlock(&dev_priv->drm.struct_mutex);
12710         i915_gem_object_unpin_pages(obj);
12711         if (ret)
12712                 return ret;
12713
12714         if (!new_state->fence) { /* implicit fencing */
12715                 struct dma_fence *fence;
12716
12717                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12718                                                       obj->resv, NULL,
12719                                                       false, I915_FENCE_TIMEOUT,
12720                                                       GFP_KERNEL);
12721                 if (ret < 0)
12722                         return ret;
12723
12724                 fence = reservation_object_get_excl_rcu(obj->resv);
12725                 if (fence) {
12726                         add_rps_boost_after_vblank(new_state->crtc, fence);
12727                         dma_fence_put(fence);
12728                 }
12729         } else {
12730                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
12731         }
12732
12733         return 0;
12734 }
12735
12736 /**
12737  * intel_cleanup_plane_fb - Cleans up an fb after plane use
12738  * @plane: drm plane to clean up for
12739  * @fb: old framebuffer that was on plane
12740  *
12741  * Cleans up a framebuffer that has just been removed from a plane.
12742  *
12743  * Must be called with struct_mutex held.
12744  */
12745 void
12746 intel_cleanup_plane_fb(struct drm_plane *plane,
12747                        struct drm_plane_state *old_state)
12748 {
12749         struct i915_vma *vma;
12750
12751         /* Should only be called after a successful intel_prepare_plane_fb()! */
12752         vma = fetch_and_zero(&to_intel_plane_state(old_state)->vma);
12753         if (vma) {
12754                 mutex_lock(&plane->dev->struct_mutex);
12755                 intel_unpin_fb_vma(vma);
12756                 mutex_unlock(&plane->dev->struct_mutex);
12757         }
12758 }
12759
12760 int
12761 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
12762 {
12763         struct drm_i915_private *dev_priv;
12764         int max_scale;
12765         int crtc_clock, max_dotclk;
12766
12767         if (!intel_crtc || !crtc_state->base.enable)
12768                 return DRM_PLANE_HELPER_NO_SCALING;
12769
12770         dev_priv = to_i915(intel_crtc->base.dev);
12771
12772         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
12773         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
12774
12775         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
12776                 max_dotclk *= 2;
12777
12778         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
12779                 return DRM_PLANE_HELPER_NO_SCALING;
12780
12781         /*
12782          * skl max scale is lower of:
12783          *    close to 3 but not 3, -1 is for that purpose
12784          *            or
12785          *    cdclk/crtc_clock
12786          */
12787         max_scale = min((1 << 16) * 3 - 1,
12788                         (1 << 8) * ((max_dotclk << 8) / crtc_clock));
12789
12790         return max_scale;
12791 }
12792
12793 static int
12794 intel_check_primary_plane(struct intel_plane *plane,
12795                           struct intel_crtc_state *crtc_state,
12796                           struct intel_plane_state *state)
12797 {
12798         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12799         struct drm_crtc *crtc = state->base.crtc;
12800         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
12801         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
12802         bool can_position = false;
12803         int ret;
12804
12805         if (INTEL_GEN(dev_priv) >= 9) {
12806                 /* use scaler when colorkey is not required */
12807                 if (!state->ckey.flags) {
12808                         min_scale = 1;
12809                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
12810                 }
12811                 can_position = true;
12812         }
12813
12814         ret = drm_atomic_helper_check_plane_state(&state->base,
12815                                                   &crtc_state->base,
12816                                                   min_scale, max_scale,
12817                                                   can_position, true);
12818         if (ret)
12819                 return ret;
12820
12821         if (!state->base.fb)
12822                 return 0;
12823
12824         if (INTEL_GEN(dev_priv) >= 9) {
12825                 ret = skl_check_plane_surface(crtc_state, state);
12826                 if (ret)
12827                         return ret;
12828
12829                 state->ctl = skl_plane_ctl(crtc_state, state);
12830         } else {
12831                 ret = i9xx_check_plane_surface(state);
12832                 if (ret)
12833                         return ret;
12834
12835                 state->ctl = i9xx_plane_ctl(crtc_state, state);
12836         }
12837
12838         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
12839                 state->color_ctl = glk_plane_color_ctl(crtc_state, state);
12840
12841         return 0;
12842 }
12843
12844 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
12845                                     struct drm_crtc_state *old_crtc_state)
12846 {
12847         struct drm_device *dev = crtc->dev;
12848         struct drm_i915_private *dev_priv = to_i915(dev);
12849         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12850         struct intel_crtc_state *old_intel_cstate =
12851                 to_intel_crtc_state(old_crtc_state);
12852         struct intel_atomic_state *old_intel_state =
12853                 to_intel_atomic_state(old_crtc_state->state);
12854         struct intel_crtc_state *intel_cstate =
12855                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
12856         bool modeset = needs_modeset(&intel_cstate->base);
12857
12858         if (!modeset &&
12859             (intel_cstate->base.color_mgmt_changed ||
12860              intel_cstate->update_pipe)) {
12861                 intel_color_set_csc(&intel_cstate->base);
12862                 intel_color_load_luts(&intel_cstate->base);
12863         }
12864
12865         /* Perform vblank evasion around commit operation */
12866         intel_pipe_update_start(intel_cstate);
12867
12868         if (modeset)
12869                 goto out;
12870
12871         if (intel_cstate->update_pipe)
12872                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
12873         else if (INTEL_GEN(dev_priv) >= 9)
12874                 skl_detach_scalers(intel_crtc);
12875
12876 out:
12877         if (dev_priv->display.atomic_update_watermarks)
12878                 dev_priv->display.atomic_update_watermarks(old_intel_state,
12879                                                            intel_cstate);
12880 }
12881
12882 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
12883                                      struct drm_crtc_state *old_crtc_state)
12884 {
12885         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12886         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12887         struct intel_atomic_state *old_intel_state =
12888                 to_intel_atomic_state(old_crtc_state->state);
12889         struct intel_crtc_state *new_crtc_state =
12890                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
12891
12892         intel_pipe_update_end(new_crtc_state);
12893
12894         if (new_crtc_state->update_pipe &&
12895             !needs_modeset(&new_crtc_state->base) &&
12896             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED) {
12897                 if (!IS_GEN2(dev_priv))
12898                         intel_set_cpu_fifo_underrun_reporting(dev_priv, intel_crtc->pipe, true);
12899
12900                 if (new_crtc_state->has_pch_encoder) {
12901                         enum pipe pch_transcoder =
12902                                 intel_crtc_pch_transcoder(intel_crtc);
12903
12904                         intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
12905                 }
12906         }
12907 }
12908
12909 /**
12910  * intel_plane_destroy - destroy a plane
12911  * @plane: plane to destroy
12912  *
12913  * Common destruction function for all types of planes (primary, cursor,
12914  * sprite).
12915  */
12916 void intel_plane_destroy(struct drm_plane *plane)
12917 {
12918         drm_plane_cleanup(plane);
12919         kfree(to_intel_plane(plane));
12920 }
12921
12922 static bool i8xx_mod_supported(uint32_t format, uint64_t modifier)
12923 {
12924         switch (format) {
12925         case DRM_FORMAT_C8:
12926         case DRM_FORMAT_RGB565:
12927         case DRM_FORMAT_XRGB1555:
12928         case DRM_FORMAT_XRGB8888:
12929                 return modifier == DRM_FORMAT_MOD_LINEAR ||
12930                         modifier == I915_FORMAT_MOD_X_TILED;
12931         default:
12932                 return false;
12933         }
12934 }
12935
12936 static bool i965_mod_supported(uint32_t format, uint64_t modifier)
12937 {
12938         switch (format) {
12939         case DRM_FORMAT_C8:
12940         case DRM_FORMAT_RGB565:
12941         case DRM_FORMAT_XRGB8888:
12942         case DRM_FORMAT_XBGR8888:
12943         case DRM_FORMAT_XRGB2101010:
12944         case DRM_FORMAT_XBGR2101010:
12945                 return modifier == DRM_FORMAT_MOD_LINEAR ||
12946                         modifier == I915_FORMAT_MOD_X_TILED;
12947         default:
12948                 return false;
12949         }
12950 }
12951
12952 static bool skl_mod_supported(uint32_t format, uint64_t modifier)
12953 {
12954         switch (format) {
12955         case DRM_FORMAT_XRGB8888:
12956         case DRM_FORMAT_XBGR8888:
12957         case DRM_FORMAT_ARGB8888:
12958         case DRM_FORMAT_ABGR8888:
12959                 if (modifier == I915_FORMAT_MOD_Yf_TILED_CCS ||
12960                     modifier == I915_FORMAT_MOD_Y_TILED_CCS)
12961                         return true;
12962                 /* fall through */
12963         case DRM_FORMAT_RGB565:
12964         case DRM_FORMAT_XRGB2101010:
12965         case DRM_FORMAT_XBGR2101010:
12966         case DRM_FORMAT_YUYV:
12967         case DRM_FORMAT_YVYU:
12968         case DRM_FORMAT_UYVY:
12969         case DRM_FORMAT_VYUY:
12970                 if (modifier == I915_FORMAT_MOD_Yf_TILED)
12971                         return true;
12972                 /* fall through */
12973         case DRM_FORMAT_C8:
12974                 if (modifier == DRM_FORMAT_MOD_LINEAR ||
12975                     modifier == I915_FORMAT_MOD_X_TILED ||
12976                     modifier == I915_FORMAT_MOD_Y_TILED)
12977                         return true;
12978                 /* fall through */
12979         default:
12980                 return false;
12981         }
12982 }
12983
12984 static bool intel_primary_plane_format_mod_supported(struct drm_plane *plane,
12985                                                      uint32_t format,
12986                                                      uint64_t modifier)
12987 {
12988         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12989
12990         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
12991                 return false;
12992
12993         if ((modifier >> 56) != DRM_FORMAT_MOD_VENDOR_INTEL &&
12994             modifier != DRM_FORMAT_MOD_LINEAR)
12995                 return false;
12996
12997         if (INTEL_GEN(dev_priv) >= 9)
12998                 return skl_mod_supported(format, modifier);
12999         else if (INTEL_GEN(dev_priv) >= 4)
13000                 return i965_mod_supported(format, modifier);
13001         else
13002                 return i8xx_mod_supported(format, modifier);
13003 }
13004
13005 static bool intel_cursor_plane_format_mod_supported(struct drm_plane *plane,
13006                                                     uint32_t format,
13007                                                     uint64_t modifier)
13008 {
13009         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13010                 return false;
13011
13012         return modifier == DRM_FORMAT_MOD_LINEAR && format == DRM_FORMAT_ARGB8888;
13013 }
13014
13015 static struct drm_plane_funcs intel_plane_funcs = {
13016         .update_plane = drm_atomic_helper_update_plane,
13017         .disable_plane = drm_atomic_helper_disable_plane,
13018         .destroy = intel_plane_destroy,
13019         .atomic_get_property = intel_plane_atomic_get_property,
13020         .atomic_set_property = intel_plane_atomic_set_property,
13021         .atomic_duplicate_state = intel_plane_duplicate_state,
13022         .atomic_destroy_state = intel_plane_destroy_state,
13023         .format_mod_supported = intel_primary_plane_format_mod_supported,
13024 };
13025
13026 static int
13027 intel_legacy_cursor_update(struct drm_plane *plane,
13028                            struct drm_crtc *crtc,
13029                            struct drm_framebuffer *fb,
13030                            int crtc_x, int crtc_y,
13031                            unsigned int crtc_w, unsigned int crtc_h,
13032                            uint32_t src_x, uint32_t src_y,
13033                            uint32_t src_w, uint32_t src_h,
13034                            struct drm_modeset_acquire_ctx *ctx)
13035 {
13036         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13037         int ret;
13038         struct drm_plane_state *old_plane_state, *new_plane_state;
13039         struct intel_plane *intel_plane = to_intel_plane(plane);
13040         struct drm_framebuffer *old_fb;
13041         struct drm_crtc_state *crtc_state = crtc->state;
13042         struct i915_vma *old_vma, *vma;
13043
13044         /*
13045          * When crtc is inactive or there is a modeset pending,
13046          * wait for it to complete in the slowpath
13047          */
13048         if (!crtc_state->active || needs_modeset(crtc_state) ||
13049             to_intel_crtc_state(crtc_state)->update_pipe)
13050                 goto slow;
13051
13052         old_plane_state = plane->state;
13053         /*
13054          * Don't do an async update if there is an outstanding commit modifying
13055          * the plane.  This prevents our async update's changes from getting
13056          * overridden by a previous synchronous update's state.
13057          */
13058         if (old_plane_state->commit &&
13059             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13060                 goto slow;
13061
13062         /*
13063          * If any parameters change that may affect watermarks,
13064          * take the slowpath. Only changing fb or position should be
13065          * in the fastpath.
13066          */
13067         if (old_plane_state->crtc != crtc ||
13068             old_plane_state->src_w != src_w ||
13069             old_plane_state->src_h != src_h ||
13070             old_plane_state->crtc_w != crtc_w ||
13071             old_plane_state->crtc_h != crtc_h ||
13072             !old_plane_state->fb != !fb)
13073                 goto slow;
13074
13075         new_plane_state = intel_plane_duplicate_state(plane);
13076         if (!new_plane_state)
13077                 return -ENOMEM;
13078
13079         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13080
13081         new_plane_state->src_x = src_x;
13082         new_plane_state->src_y = src_y;
13083         new_plane_state->src_w = src_w;
13084         new_plane_state->src_h = src_h;
13085         new_plane_state->crtc_x = crtc_x;
13086         new_plane_state->crtc_y = crtc_y;
13087         new_plane_state->crtc_w = crtc_w;
13088         new_plane_state->crtc_h = crtc_h;
13089
13090         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13091                                                   to_intel_crtc_state(crtc->state), /* FIXME need a new crtc state? */
13092                                                   to_intel_plane_state(plane->state),
13093                                                   to_intel_plane_state(new_plane_state));
13094         if (ret)
13095                 goto out_free;
13096
13097         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13098         if (ret)
13099                 goto out_free;
13100
13101         if (INTEL_INFO(dev_priv)->cursor_needs_physical) {
13102                 int align = intel_cursor_alignment(dev_priv);
13103
13104                 ret = i915_gem_object_attach_phys(intel_fb_obj(fb), align);
13105                 if (ret) {
13106                         DRM_DEBUG_KMS("failed to attach phys object\n");
13107                         goto out_unlock;
13108                 }
13109         } else {
13110                 vma = intel_pin_and_fence_fb_obj(fb, new_plane_state->rotation);
13111                 if (IS_ERR(vma)) {
13112                         DRM_DEBUG_KMS("failed to pin object\n");
13113
13114                         ret = PTR_ERR(vma);
13115                         goto out_unlock;
13116                 }
13117
13118                 to_intel_plane_state(new_plane_state)->vma = vma;
13119         }
13120
13121         old_fb = old_plane_state->fb;
13122
13123         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13124                           intel_plane->frontbuffer_bit);
13125
13126         /* Swap plane state */
13127         plane->state = new_plane_state;
13128
13129         if (plane->state->visible) {
13130                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13131                 intel_plane->update_plane(intel_plane,
13132                                           to_intel_crtc_state(crtc->state),
13133                                           to_intel_plane_state(plane->state));
13134         } else {
13135                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13136                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13137         }
13138
13139         old_vma = fetch_and_zero(&to_intel_plane_state(old_plane_state)->vma);
13140         if (old_vma)
13141                 intel_unpin_fb_vma(old_vma);
13142
13143 out_unlock:
13144         mutex_unlock(&dev_priv->drm.struct_mutex);
13145 out_free:
13146         if (ret)
13147                 intel_plane_destroy_state(plane, new_plane_state);
13148         else
13149                 intel_plane_destroy_state(plane, old_plane_state);
13150         return ret;
13151
13152 slow:
13153         return drm_atomic_helper_update_plane(plane, crtc, fb,
13154                                               crtc_x, crtc_y, crtc_w, crtc_h,
13155                                               src_x, src_y, src_w, src_h, ctx);
13156 }
13157
13158 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13159         .update_plane = intel_legacy_cursor_update,
13160         .disable_plane = drm_atomic_helper_disable_plane,
13161         .destroy = intel_plane_destroy,
13162         .atomic_get_property = intel_plane_atomic_get_property,
13163         .atomic_set_property = intel_plane_atomic_set_property,
13164         .atomic_duplicate_state = intel_plane_duplicate_state,
13165         .atomic_destroy_state = intel_plane_destroy_state,
13166         .format_mod_supported = intel_cursor_plane_format_mod_supported,
13167 };
13168
13169 static struct intel_plane *
13170 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13171 {
13172         struct intel_plane *primary = NULL;
13173         struct intel_plane_state *state = NULL;
13174         const uint32_t *intel_primary_formats;
13175         unsigned int supported_rotations;
13176         unsigned int num_formats;
13177         const uint64_t *modifiers;
13178         int ret;
13179
13180         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13181         if (!primary) {
13182                 ret = -ENOMEM;
13183                 goto fail;
13184         }
13185
13186         state = intel_create_plane_state(&primary->base);
13187         if (!state) {
13188                 ret = -ENOMEM;
13189                 goto fail;
13190         }
13191
13192         primary->base.state = &state->base;
13193
13194         primary->can_scale = false;
13195         primary->max_downscale = 1;
13196         if (INTEL_GEN(dev_priv) >= 9) {
13197                 primary->can_scale = true;
13198                 state->scaler_id = -1;
13199         }
13200         primary->pipe = pipe;
13201         /*
13202          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13203          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13204          */
13205         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13206                 primary->i9xx_plane = (enum i9xx_plane_id) !pipe;
13207         else
13208                 primary->i9xx_plane = (enum i9xx_plane_id) pipe;
13209         primary->id = PLANE_PRIMARY;
13210         primary->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, primary->id);
13211         primary->check_plane = intel_check_primary_plane;
13212
13213         if (INTEL_GEN(dev_priv) >= 9) {
13214                 intel_primary_formats = skl_primary_formats;
13215                 num_formats = ARRAY_SIZE(skl_primary_formats);
13216
13217                 if (skl_plane_has_ccs(dev_priv, pipe, PLANE_PRIMARY))
13218                         modifiers = skl_format_modifiers_ccs;
13219                 else
13220                         modifiers = skl_format_modifiers_noccs;
13221
13222                 primary->update_plane = skl_update_plane;
13223                 primary->disable_plane = skl_disable_plane;
13224                 primary->get_hw_state = skl_plane_get_hw_state;
13225         } else if (INTEL_GEN(dev_priv) >= 4) {
13226                 intel_primary_formats = i965_primary_formats;
13227                 num_formats = ARRAY_SIZE(i965_primary_formats);
13228                 modifiers = i9xx_format_modifiers;
13229
13230                 primary->update_plane = i9xx_update_plane;
13231                 primary->disable_plane = i9xx_disable_plane;
13232                 primary->get_hw_state = i9xx_plane_get_hw_state;
13233         } else {
13234                 intel_primary_formats = i8xx_primary_formats;
13235                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13236                 modifiers = i9xx_format_modifiers;
13237
13238                 primary->update_plane = i9xx_update_plane;
13239                 primary->disable_plane = i9xx_disable_plane;
13240                 primary->get_hw_state = i9xx_plane_get_hw_state;
13241         }
13242
13243         if (INTEL_GEN(dev_priv) >= 9)
13244                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13245                                                0, &intel_plane_funcs,
13246                                                intel_primary_formats, num_formats,
13247                                                modifiers,
13248                                                DRM_PLANE_TYPE_PRIMARY,
13249                                                "plane 1%c", pipe_name(pipe));
13250         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13251                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13252                                                0, &intel_plane_funcs,
13253                                                intel_primary_formats, num_formats,
13254                                                modifiers,
13255                                                DRM_PLANE_TYPE_PRIMARY,
13256                                                "primary %c", pipe_name(pipe));
13257         else
13258                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13259                                                0, &intel_plane_funcs,
13260                                                intel_primary_formats, num_formats,
13261                                                modifiers,
13262                                                DRM_PLANE_TYPE_PRIMARY,
13263                                                "plane %c",
13264                                                plane_name(primary->i9xx_plane));
13265         if (ret)
13266                 goto fail;
13267
13268         if (INTEL_GEN(dev_priv) >= 10) {
13269                 supported_rotations =
13270                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13271                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270 |
13272                         DRM_MODE_REFLECT_X;
13273         } else if (INTEL_GEN(dev_priv) >= 9) {
13274                 supported_rotations =
13275                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13276                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13277         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13278                 supported_rotations =
13279                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13280                         DRM_MODE_REFLECT_X;
13281         } else if (INTEL_GEN(dev_priv) >= 4) {
13282                 supported_rotations =
13283                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13284         } else {
13285                 supported_rotations = DRM_MODE_ROTATE_0;
13286         }
13287
13288         if (INTEL_GEN(dev_priv) >= 4)
13289                 drm_plane_create_rotation_property(&primary->base,
13290                                                    DRM_MODE_ROTATE_0,
13291                                                    supported_rotations);
13292
13293         if (INTEL_GEN(dev_priv) >= 9)
13294                 drm_plane_create_color_properties(&primary->base,
13295                                                   BIT(DRM_COLOR_YCBCR_BT601) |
13296                                                   BIT(DRM_COLOR_YCBCR_BT709),
13297                                                   BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
13298                                                   BIT(DRM_COLOR_YCBCR_FULL_RANGE),
13299                                                   DRM_COLOR_YCBCR_BT709,
13300                                                   DRM_COLOR_YCBCR_LIMITED_RANGE);
13301
13302         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13303
13304         return primary;
13305
13306 fail:
13307         kfree(state);
13308         kfree(primary);
13309
13310         return ERR_PTR(ret);
13311 }
13312
13313 static struct intel_plane *
13314 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13315                           enum pipe pipe)
13316 {
13317         struct intel_plane *cursor = NULL;
13318         struct intel_plane_state *state = NULL;
13319         int ret;
13320
13321         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13322         if (!cursor) {
13323                 ret = -ENOMEM;
13324                 goto fail;
13325         }
13326
13327         state = intel_create_plane_state(&cursor->base);
13328         if (!state) {
13329                 ret = -ENOMEM;
13330                 goto fail;
13331         }
13332
13333         cursor->base.state = &state->base;
13334
13335         cursor->can_scale = false;
13336         cursor->max_downscale = 1;
13337         cursor->pipe = pipe;
13338         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13339         cursor->id = PLANE_CURSOR;
13340         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13341
13342         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13343                 cursor->update_plane = i845_update_cursor;
13344                 cursor->disable_plane = i845_disable_cursor;
13345                 cursor->get_hw_state = i845_cursor_get_hw_state;
13346                 cursor->check_plane = i845_check_cursor;
13347         } else {
13348                 cursor->update_plane = i9xx_update_cursor;
13349                 cursor->disable_plane = i9xx_disable_cursor;
13350                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13351                 cursor->check_plane = i9xx_check_cursor;
13352         }
13353
13354         cursor->cursor.base = ~0;
13355         cursor->cursor.cntl = ~0;
13356
13357         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13358                 cursor->cursor.size = ~0;
13359
13360         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13361                                        0, &intel_cursor_plane_funcs,
13362                                        intel_cursor_formats,
13363                                        ARRAY_SIZE(intel_cursor_formats),
13364                                        cursor_format_modifiers,
13365                                        DRM_PLANE_TYPE_CURSOR,
13366                                        "cursor %c", pipe_name(pipe));
13367         if (ret)
13368                 goto fail;
13369
13370         if (INTEL_GEN(dev_priv) >= 4)
13371                 drm_plane_create_rotation_property(&cursor->base,
13372                                                    DRM_MODE_ROTATE_0,
13373                                                    DRM_MODE_ROTATE_0 |
13374                                                    DRM_MODE_ROTATE_180);
13375
13376         if (INTEL_GEN(dev_priv) >= 9)
13377                 state->scaler_id = -1;
13378
13379         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13380
13381         return cursor;
13382
13383 fail:
13384         kfree(state);
13385         kfree(cursor);
13386
13387         return ERR_PTR(ret);
13388 }
13389
13390 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13391                                     struct intel_crtc_state *crtc_state)
13392 {
13393         struct intel_crtc_scaler_state *scaler_state =
13394                 &crtc_state->scaler_state;
13395         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13396         int i;
13397
13398         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13399         if (!crtc->num_scalers)
13400                 return;
13401
13402         for (i = 0; i < crtc->num_scalers; i++) {
13403                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13404
13405                 scaler->in_use = 0;
13406                 scaler->mode = PS_SCALER_MODE_DYN;
13407         }
13408
13409         scaler_state->scaler_id = -1;
13410 }
13411
13412 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13413 {
13414         struct intel_crtc *intel_crtc;
13415         struct intel_crtc_state *crtc_state = NULL;
13416         struct intel_plane *primary = NULL;
13417         struct intel_plane *cursor = NULL;
13418         int sprite, ret;
13419
13420         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13421         if (!intel_crtc)
13422                 return -ENOMEM;
13423
13424         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13425         if (!crtc_state) {
13426                 ret = -ENOMEM;
13427                 goto fail;
13428         }
13429         intel_crtc->config = crtc_state;
13430         intel_crtc->base.state = &crtc_state->base;
13431         crtc_state->base.crtc = &intel_crtc->base;
13432
13433         primary = intel_primary_plane_create(dev_priv, pipe);
13434         if (IS_ERR(primary)) {
13435                 ret = PTR_ERR(primary);
13436                 goto fail;
13437         }
13438         intel_crtc->plane_ids_mask |= BIT(primary->id);
13439
13440         for_each_sprite(dev_priv, pipe, sprite) {
13441                 struct intel_plane *plane;
13442
13443                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13444                 if (IS_ERR(plane)) {
13445                         ret = PTR_ERR(plane);
13446                         goto fail;
13447                 }
13448                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13449         }
13450
13451         cursor = intel_cursor_plane_create(dev_priv, pipe);
13452         if (IS_ERR(cursor)) {
13453                 ret = PTR_ERR(cursor);
13454                 goto fail;
13455         }
13456         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13457
13458         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13459                                         &primary->base, &cursor->base,
13460                                         &intel_crtc_funcs,
13461                                         "pipe %c", pipe_name(pipe));
13462         if (ret)
13463                 goto fail;
13464
13465         intel_crtc->pipe = pipe;
13466
13467         /* initialize shared scalers */
13468         intel_crtc_init_scalers(intel_crtc, crtc_state);
13469
13470         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13471                dev_priv->plane_to_crtc_mapping[primary->i9xx_plane] != NULL);
13472         dev_priv->plane_to_crtc_mapping[primary->i9xx_plane] = intel_crtc;
13473         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = intel_crtc;
13474
13475         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13476
13477         intel_color_init(&intel_crtc->base);
13478
13479         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13480
13481         return 0;
13482
13483 fail:
13484         /*
13485          * drm_mode_config_cleanup() will free up any
13486          * crtcs/planes already initialized.
13487          */
13488         kfree(crtc_state);
13489         kfree(intel_crtc);
13490
13491         return ret;
13492 }
13493
13494 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13495 {
13496         struct drm_device *dev = connector->base.dev;
13497
13498         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13499
13500         if (!connector->base.state->crtc)
13501                 return INVALID_PIPE;
13502
13503         return to_intel_crtc(connector->base.state->crtc)->pipe;
13504 }
13505
13506 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
13507                                 struct drm_file *file)
13508 {
13509         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13510         struct drm_crtc *drmmode_crtc;
13511         struct intel_crtc *crtc;
13512
13513         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
13514         if (!drmmode_crtc)
13515                 return -ENOENT;
13516
13517         crtc = to_intel_crtc(drmmode_crtc);
13518         pipe_from_crtc_id->pipe = crtc->pipe;
13519
13520         return 0;
13521 }
13522
13523 static int intel_encoder_clones(struct intel_encoder *encoder)
13524 {
13525         struct drm_device *dev = encoder->base.dev;
13526         struct intel_encoder *source_encoder;
13527         int index_mask = 0;
13528         int entry = 0;
13529
13530         for_each_intel_encoder(dev, source_encoder) {
13531                 if (encoders_cloneable(encoder, source_encoder))
13532                         index_mask |= (1 << entry);
13533
13534                 entry++;
13535         }
13536
13537         return index_mask;
13538 }
13539
13540 static bool has_edp_a(struct drm_i915_private *dev_priv)
13541 {
13542         if (!IS_MOBILE(dev_priv))
13543                 return false;
13544
13545         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13546                 return false;
13547
13548         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13549                 return false;
13550
13551         return true;
13552 }
13553
13554 static bool intel_crt_present(struct drm_i915_private *dev_priv)
13555 {
13556         if (INTEL_GEN(dev_priv) >= 9)
13557                 return false;
13558
13559         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
13560                 return false;
13561
13562         if (IS_CHERRYVIEW(dev_priv))
13563                 return false;
13564
13565         if (HAS_PCH_LPT_H(dev_priv) &&
13566             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
13567                 return false;
13568
13569         /* DDI E can't be used if DDI A requires 4 lanes */
13570         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
13571                 return false;
13572
13573         if (!dev_priv->vbt.int_crt_support)
13574                 return false;
13575
13576         return true;
13577 }
13578
13579 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
13580 {
13581         int pps_num;
13582         int pps_idx;
13583
13584         if (HAS_DDI(dev_priv))
13585                 return;
13586         /*
13587          * This w/a is needed at least on CPT/PPT, but to be sure apply it
13588          * everywhere where registers can be write protected.
13589          */
13590         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13591                 pps_num = 2;
13592         else
13593                 pps_num = 1;
13594
13595         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
13596                 u32 val = I915_READ(PP_CONTROL(pps_idx));
13597
13598                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
13599                 I915_WRITE(PP_CONTROL(pps_idx), val);
13600         }
13601 }
13602
13603 static void intel_pps_init(struct drm_i915_private *dev_priv)
13604 {
13605         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
13606                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
13607         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13608                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
13609         else
13610                 dev_priv->pps_mmio_base = PPS_BASE;
13611
13612         intel_pps_unlock_regs_wa(dev_priv);
13613 }
13614
13615 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
13616 {
13617         struct intel_encoder *encoder;
13618         bool dpd_is_edp = false;
13619
13620         intel_pps_init(dev_priv);
13621
13622         /*
13623          * intel_edp_init_connector() depends on this completing first, to
13624          * prevent the registeration of both eDP and LVDS and the incorrect
13625          * sharing of the PPS.
13626          */
13627         intel_lvds_init(dev_priv);
13628
13629         if (intel_crt_present(dev_priv))
13630                 intel_crt_init(dev_priv);
13631
13632         if (IS_GEN9_LP(dev_priv)) {
13633                 /*
13634                  * FIXME: Broxton doesn't support port detection via the
13635                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13636                  * detect the ports.
13637                  */
13638                 intel_ddi_init(dev_priv, PORT_A);
13639                 intel_ddi_init(dev_priv, PORT_B);
13640                 intel_ddi_init(dev_priv, PORT_C);
13641
13642                 intel_dsi_init(dev_priv);
13643         } else if (HAS_DDI(dev_priv)) {
13644                 int found;
13645
13646                 /*
13647                  * Haswell uses DDI functions to detect digital outputs.
13648                  * On SKL pre-D0 the strap isn't connected, so we assume
13649                  * it's there.
13650                  */
13651                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
13652                 /* WaIgnoreDDIAStrap: skl */
13653                 if (found || IS_GEN9_BC(dev_priv))
13654                         intel_ddi_init(dev_priv, PORT_A);
13655
13656                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
13657                  * register */
13658                 found = I915_READ(SFUSE_STRAP);
13659
13660                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13661                         intel_ddi_init(dev_priv, PORT_B);
13662                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13663                         intel_ddi_init(dev_priv, PORT_C);
13664                 if (found & SFUSE_STRAP_DDID_DETECTED)
13665                         intel_ddi_init(dev_priv, PORT_D);
13666                 if (found & SFUSE_STRAP_DDIF_DETECTED)
13667                         intel_ddi_init(dev_priv, PORT_F);
13668                 /*
13669                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
13670                  */
13671                 if (IS_GEN9_BC(dev_priv) &&
13672                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
13673                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
13674                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
13675                         intel_ddi_init(dev_priv, PORT_E);
13676
13677         } else if (HAS_PCH_SPLIT(dev_priv)) {
13678                 int found;
13679                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
13680
13681                 if (has_edp_a(dev_priv))
13682                         intel_dp_init(dev_priv, DP_A, PORT_A);
13683
13684                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13685                         /* PCH SDVOB multiplex with HDMIB */
13686                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
13687                         if (!found)
13688                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
13689                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13690                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
13691                 }
13692
13693                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13694                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
13695
13696                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13697                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
13698
13699                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13700                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
13701
13702                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13703                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
13704         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
13705                 bool has_edp, has_port;
13706
13707                 /*
13708                  * The DP_DETECTED bit is the latched state of the DDC
13709                  * SDA pin at boot. However since eDP doesn't require DDC
13710                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13711                  * eDP ports may have been muxed to an alternate function.
13712                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13713                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13714                  * detect eDP ports.
13715                  *
13716                  * Sadly the straps seem to be missing sometimes even for HDMI
13717                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
13718                  * and VBT for the presence of the port. Additionally we can't
13719                  * trust the port type the VBT declares as we've seen at least
13720                  * HDMI ports that the VBT claim are DP or eDP.
13721                  */
13722                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
13723                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
13724                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
13725                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
13726                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
13727                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
13728
13729                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
13730                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
13731                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
13732                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
13733                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
13734                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
13735
13736                 if (IS_CHERRYVIEW(dev_priv)) {
13737                         /*
13738                          * eDP not supported on port D,
13739                          * so no need to worry about it
13740                          */
13741                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
13742                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
13743                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
13744                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
13745                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
13746                 }
13747
13748                 intel_dsi_init(dev_priv);
13749         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
13750                 bool found = false;
13751
13752                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13753                         DRM_DEBUG_KMS("probing SDVOB\n");
13754                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
13755                         if (!found && IS_G4X(dev_priv)) {
13756                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
13757                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
13758                         }
13759
13760                         if (!found && IS_G4X(dev_priv))
13761                                 intel_dp_init(dev_priv, DP_B, PORT_B);
13762                 }
13763
13764                 /* Before G4X SDVOC doesn't have its own detect register */
13765
13766                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13767                         DRM_DEBUG_KMS("probing SDVOC\n");
13768                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
13769                 }
13770
13771                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
13772
13773                         if (IS_G4X(dev_priv)) {
13774                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
13775                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
13776                         }
13777                         if (IS_G4X(dev_priv))
13778                                 intel_dp_init(dev_priv, DP_C, PORT_C);
13779                 }
13780
13781                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
13782                         intel_dp_init(dev_priv, DP_D, PORT_D);
13783         } else if (IS_GEN2(dev_priv))
13784                 intel_dvo_init(dev_priv);
13785
13786         if (SUPPORTS_TV(dev_priv))
13787                 intel_tv_init(dev_priv);
13788
13789         intel_psr_init(dev_priv);
13790
13791         for_each_intel_encoder(&dev_priv->drm, encoder) {
13792                 encoder->base.possible_crtcs = encoder->crtc_mask;
13793                 encoder->base.possible_clones =
13794                         intel_encoder_clones(encoder);
13795         }
13796
13797         intel_init_pch_refclk(dev_priv);
13798
13799         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
13800 }
13801
13802 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
13803 {
13804         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13805
13806         drm_framebuffer_cleanup(fb);
13807
13808         i915_gem_object_lock(intel_fb->obj);
13809         WARN_ON(!intel_fb->obj->framebuffer_references--);
13810         i915_gem_object_unlock(intel_fb->obj);
13811
13812         i915_gem_object_put(intel_fb->obj);
13813
13814         kfree(intel_fb);
13815 }
13816
13817 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
13818                                                 struct drm_file *file,
13819                                                 unsigned int *handle)
13820 {
13821         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13822         struct drm_i915_gem_object *obj = intel_fb->obj;
13823
13824         if (obj->userptr.mm) {
13825                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
13826                 return -EINVAL;
13827         }
13828
13829         return drm_gem_handle_create(file, &obj->base, handle);
13830 }
13831
13832 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
13833                                         struct drm_file *file,
13834                                         unsigned flags, unsigned color,
13835                                         struct drm_clip_rect *clips,
13836                                         unsigned num_clips)
13837 {
13838         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13839
13840         i915_gem_object_flush_if_display(obj);
13841         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13842
13843         return 0;
13844 }
13845
13846 static const struct drm_framebuffer_funcs intel_fb_funcs = {
13847         .destroy = intel_user_framebuffer_destroy,
13848         .create_handle = intel_user_framebuffer_create_handle,
13849         .dirty = intel_user_framebuffer_dirty,
13850 };
13851
13852 static
13853 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
13854                          uint64_t fb_modifier, uint32_t pixel_format)
13855 {
13856         u32 gen = INTEL_GEN(dev_priv);
13857
13858         if (gen >= 9) {
13859                 int cpp = drm_format_plane_cpp(pixel_format, 0);
13860
13861                 /* "The stride in bytes must not exceed the of the size of 8K
13862                  *  pixels and 32K bytes."
13863                  */
13864                 return min(8192 * cpp, 32768);
13865         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
13866                 return 32*1024;
13867         } else if (gen >= 4) {
13868                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13869                         return 16*1024;
13870                 else
13871                         return 32*1024;
13872         } else if (gen >= 3) {
13873                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13874                         return 8*1024;
13875                 else
13876                         return 16*1024;
13877         } else {
13878                 /* XXX DSPC is limited to 4k tiled */
13879                 return 8*1024;
13880         }
13881 }
13882
13883 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
13884                                   struct drm_i915_gem_object *obj,
13885                                   struct drm_mode_fb_cmd2 *mode_cmd)
13886 {
13887         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
13888         struct drm_framebuffer *fb = &intel_fb->base;
13889         struct drm_format_name_buf format_name;
13890         u32 pitch_limit;
13891         unsigned int tiling, stride;
13892         int ret = -EINVAL;
13893         int i;
13894
13895         i915_gem_object_lock(obj);
13896         obj->framebuffer_references++;
13897         tiling = i915_gem_object_get_tiling(obj);
13898         stride = i915_gem_object_get_stride(obj);
13899         i915_gem_object_unlock(obj);
13900
13901         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
13902                 /*
13903                  * If there's a fence, enforce that
13904                  * the fb modifier and tiling mode match.
13905                  */
13906                 if (tiling != I915_TILING_NONE &&
13907                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
13908                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
13909                         goto err;
13910                 }
13911         } else {
13912                 if (tiling == I915_TILING_X) {
13913                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
13914                 } else if (tiling == I915_TILING_Y) {
13915                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
13916                         goto err;
13917                 }
13918         }
13919
13920         /* Passed in modifier sanity checking. */
13921         switch (mode_cmd->modifier[0]) {
13922         case I915_FORMAT_MOD_Y_TILED_CCS:
13923         case I915_FORMAT_MOD_Yf_TILED_CCS:
13924                 switch (mode_cmd->pixel_format) {
13925                 case DRM_FORMAT_XBGR8888:
13926                 case DRM_FORMAT_ABGR8888:
13927                 case DRM_FORMAT_XRGB8888:
13928                 case DRM_FORMAT_ARGB8888:
13929                         break;
13930                 default:
13931                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
13932                         goto err;
13933                 }
13934                 /* fall through */
13935         case I915_FORMAT_MOD_Y_TILED:
13936         case I915_FORMAT_MOD_Yf_TILED:
13937                 if (INTEL_GEN(dev_priv) < 9) {
13938                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
13939                                       mode_cmd->modifier[0]);
13940                         goto err;
13941                 }
13942         case DRM_FORMAT_MOD_LINEAR:
13943         case I915_FORMAT_MOD_X_TILED:
13944                 break;
13945         default:
13946                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
13947                               mode_cmd->modifier[0]);
13948                 goto err;
13949         }
13950
13951         /*
13952          * gen2/3 display engine uses the fence if present,
13953          * so the tiling mode must match the fb modifier exactly.
13954          */
13955         if (INTEL_INFO(dev_priv)->gen < 4 &&
13956             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
13957                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
13958                 goto err;
13959         }
13960
13961         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
13962                                            mode_cmd->pixel_format);
13963         if (mode_cmd->pitches[0] > pitch_limit) {
13964                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
13965                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
13966                               "tiled" : "linear",
13967                               mode_cmd->pitches[0], pitch_limit);
13968                 goto err;
13969         }
13970
13971         /*
13972          * If there's a fence, enforce that
13973          * the fb pitch and fence stride match.
13974          */
13975         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
13976                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
13977                               mode_cmd->pitches[0], stride);
13978                 goto err;
13979         }
13980
13981         /* Reject formats not supported by any plane early. */
13982         switch (mode_cmd->pixel_format) {
13983         case DRM_FORMAT_C8:
13984         case DRM_FORMAT_RGB565:
13985         case DRM_FORMAT_XRGB8888:
13986         case DRM_FORMAT_ARGB8888:
13987                 break;
13988         case DRM_FORMAT_XRGB1555:
13989                 if (INTEL_GEN(dev_priv) > 3) {
13990                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
13991                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
13992                         goto err;
13993                 }
13994                 break;
13995         case DRM_FORMAT_ABGR8888:
13996                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
13997                     INTEL_GEN(dev_priv) < 9) {
13998                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
13999                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14000                         goto err;
14001                 }
14002                 break;
14003         case DRM_FORMAT_XBGR8888:
14004         case DRM_FORMAT_XRGB2101010:
14005         case DRM_FORMAT_XBGR2101010:
14006                 if (INTEL_GEN(dev_priv) < 4) {
14007                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14008                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14009                         goto err;
14010                 }
14011                 break;
14012         case DRM_FORMAT_ABGR2101010:
14013                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14014                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14015                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14016                         goto err;
14017                 }
14018                 break;
14019         case DRM_FORMAT_YUYV:
14020         case DRM_FORMAT_UYVY:
14021         case DRM_FORMAT_YVYU:
14022         case DRM_FORMAT_VYUY:
14023                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14024                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14025                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14026                         goto err;
14027                 }
14028                 break;
14029         default:
14030                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14031                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14032                 goto err;
14033         }
14034
14035         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14036         if (mode_cmd->offsets[0] != 0)
14037                 goto err;
14038
14039         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14040
14041         for (i = 0; i < fb->format->num_planes; i++) {
14042                 u32 stride_alignment;
14043
14044                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14045                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14046                         goto err;
14047                 }
14048
14049                 stride_alignment = intel_fb_stride_alignment(fb, i);
14050
14051                 /*
14052                  * Display WA #0531: skl,bxt,kbl,glk
14053                  *
14054                  * Render decompression and plane width > 3840
14055                  * combined with horizontal panning requires the
14056                  * plane stride to be a multiple of 4. We'll just
14057                  * require the entire fb to accommodate that to avoid
14058                  * potential runtime errors at plane configuration time.
14059                  */
14060                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14061                     (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
14062                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS))
14063                         stride_alignment *= 4;
14064
14065                 if (fb->pitches[i] & (stride_alignment - 1)) {
14066                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14067                                       i, fb->pitches[i], stride_alignment);
14068                         goto err;
14069                 }
14070         }
14071
14072         intel_fb->obj = obj;
14073
14074         ret = intel_fill_fb_info(dev_priv, fb);
14075         if (ret)
14076                 goto err;
14077
14078         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14079         if (ret) {
14080                 DRM_ERROR("framebuffer init failed %d\n", ret);
14081                 goto err;
14082         }
14083
14084         return 0;
14085
14086 err:
14087         i915_gem_object_lock(obj);
14088         obj->framebuffer_references--;
14089         i915_gem_object_unlock(obj);
14090         return ret;
14091 }
14092
14093 static struct drm_framebuffer *
14094 intel_user_framebuffer_create(struct drm_device *dev,
14095                               struct drm_file *filp,
14096                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14097 {
14098         struct drm_framebuffer *fb;
14099         struct drm_i915_gem_object *obj;
14100         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14101
14102         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14103         if (!obj)
14104                 return ERR_PTR(-ENOENT);
14105
14106         fb = intel_framebuffer_create(obj, &mode_cmd);
14107         if (IS_ERR(fb))
14108                 i915_gem_object_put(obj);
14109
14110         return fb;
14111 }
14112
14113 static void intel_atomic_state_free(struct drm_atomic_state *state)
14114 {
14115         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14116
14117         drm_atomic_state_default_release(state);
14118
14119         i915_sw_fence_fini(&intel_state->commit_ready);
14120
14121         kfree(state);
14122 }
14123
14124 static enum drm_mode_status
14125 intel_mode_valid(struct drm_device *dev,
14126                  const struct drm_display_mode *mode)
14127 {
14128         if (mode->vscan > 1)
14129                 return MODE_NO_VSCAN;
14130
14131         if (mode->flags & DRM_MODE_FLAG_DBLSCAN)
14132                 return MODE_NO_DBLESCAN;
14133
14134         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14135                 return MODE_H_ILLEGAL;
14136
14137         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14138                            DRM_MODE_FLAG_NCSYNC |
14139                            DRM_MODE_FLAG_PCSYNC))
14140                 return MODE_HSYNC;
14141
14142         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14143                            DRM_MODE_FLAG_PIXMUX |
14144                            DRM_MODE_FLAG_CLKDIV2))
14145                 return MODE_BAD;
14146
14147         return MODE_OK;
14148 }
14149
14150 static const struct drm_mode_config_funcs intel_mode_funcs = {
14151         .fb_create = intel_user_framebuffer_create,
14152         .get_format_info = intel_get_format_info,
14153         .output_poll_changed = intel_fbdev_output_poll_changed,
14154         .mode_valid = intel_mode_valid,
14155         .atomic_check = intel_atomic_check,
14156         .atomic_commit = intel_atomic_commit,
14157         .atomic_state_alloc = intel_atomic_state_alloc,
14158         .atomic_state_clear = intel_atomic_state_clear,
14159         .atomic_state_free = intel_atomic_state_free,
14160 };
14161
14162 /**
14163  * intel_init_display_hooks - initialize the display modesetting hooks
14164  * @dev_priv: device private
14165  */
14166 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14167 {
14168         intel_init_cdclk_hooks(dev_priv);
14169
14170         if (INTEL_INFO(dev_priv)->gen >= 9) {
14171                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14172                 dev_priv->display.get_initial_plane_config =
14173                         skylake_get_initial_plane_config;
14174                 dev_priv->display.crtc_compute_clock =
14175                         haswell_crtc_compute_clock;
14176                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14177                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14178         } else if (HAS_DDI(dev_priv)) {
14179                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14180                 dev_priv->display.get_initial_plane_config =
14181                         i9xx_get_initial_plane_config;
14182                 dev_priv->display.crtc_compute_clock =
14183                         haswell_crtc_compute_clock;
14184                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14185                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14186         } else if (HAS_PCH_SPLIT(dev_priv)) {
14187                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14188                 dev_priv->display.get_initial_plane_config =
14189                         i9xx_get_initial_plane_config;
14190                 dev_priv->display.crtc_compute_clock =
14191                         ironlake_crtc_compute_clock;
14192                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14193                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14194         } else if (IS_CHERRYVIEW(dev_priv)) {
14195                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14196                 dev_priv->display.get_initial_plane_config =
14197                         i9xx_get_initial_plane_config;
14198                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14199                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14200                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14201         } else if (IS_VALLEYVIEW(dev_priv)) {
14202                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14203                 dev_priv->display.get_initial_plane_config =
14204                         i9xx_get_initial_plane_config;
14205                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14206                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14207                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14208         } else if (IS_G4X(dev_priv)) {
14209                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14210                 dev_priv->display.get_initial_plane_config =
14211                         i9xx_get_initial_plane_config;
14212                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14213                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14214                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14215         } else if (IS_PINEVIEW(dev_priv)) {
14216                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14217                 dev_priv->display.get_initial_plane_config =
14218                         i9xx_get_initial_plane_config;
14219                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14220                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14221                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14222         } else if (!IS_GEN2(dev_priv)) {
14223                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14224                 dev_priv->display.get_initial_plane_config =
14225                         i9xx_get_initial_plane_config;
14226                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14227                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14228                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14229         } else {
14230                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14231                 dev_priv->display.get_initial_plane_config =
14232                         i9xx_get_initial_plane_config;
14233                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14234                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14235                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14236         }
14237
14238         if (IS_GEN5(dev_priv)) {
14239                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14240         } else if (IS_GEN6(dev_priv)) {
14241                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14242         } else if (IS_IVYBRIDGE(dev_priv)) {
14243                 /* FIXME: detect B0+ stepping and use auto training */
14244                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14245         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14246                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14247         }
14248
14249         if (INTEL_GEN(dev_priv) >= 9)
14250                 dev_priv->display.update_crtcs = skl_update_crtcs;
14251         else
14252                 dev_priv->display.update_crtcs = intel_update_crtcs;
14253 }
14254
14255 /*
14256  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14257  */
14258 static void quirk_ssc_force_disable(struct drm_device *dev)
14259 {
14260         struct drm_i915_private *dev_priv = to_i915(dev);
14261         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14262         DRM_INFO("applying lvds SSC disable quirk\n");
14263 }
14264
14265 /*
14266  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14267  * brightness value
14268  */
14269 static void quirk_invert_brightness(struct drm_device *dev)
14270 {
14271         struct drm_i915_private *dev_priv = to_i915(dev);
14272         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14273         DRM_INFO("applying inverted panel brightness quirk\n");
14274 }
14275
14276 /* Some VBT's incorrectly indicate no backlight is present */
14277 static void quirk_backlight_present(struct drm_device *dev)
14278 {
14279         struct drm_i915_private *dev_priv = to_i915(dev);
14280         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14281         DRM_INFO("applying backlight present quirk\n");
14282 }
14283
14284 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14285  * which is 300 ms greater than eDP spec T12 min.
14286  */
14287 static void quirk_increase_t12_delay(struct drm_device *dev)
14288 {
14289         struct drm_i915_private *dev_priv = to_i915(dev);
14290
14291         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14292         DRM_INFO("Applying T12 delay quirk\n");
14293 }
14294
14295 struct intel_quirk {
14296         int device;
14297         int subsystem_vendor;
14298         int subsystem_device;
14299         void (*hook)(struct drm_device *dev);
14300 };
14301
14302 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14303 struct intel_dmi_quirk {
14304         void (*hook)(struct drm_device *dev);
14305         const struct dmi_system_id (*dmi_id_list)[];
14306 };
14307
14308 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14309 {
14310         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14311         return 1;
14312 }
14313
14314 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14315         {
14316                 .dmi_id_list = &(const struct dmi_system_id[]) {
14317                         {
14318                                 .callback = intel_dmi_reverse_brightness,
14319                                 .ident = "NCR Corporation",
14320                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14321                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14322                                 },
14323                         },
14324                         { }  /* terminating entry */
14325                 },
14326                 .hook = quirk_invert_brightness,
14327         },
14328 };
14329
14330 static struct intel_quirk intel_quirks[] = {
14331         /* Lenovo U160 cannot use SSC on LVDS */
14332         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14333
14334         /* Sony Vaio Y cannot use SSC on LVDS */
14335         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14336
14337         /* Acer Aspire 5734Z must invert backlight brightness */
14338         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14339
14340         /* Acer/eMachines G725 */
14341         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14342
14343         /* Acer/eMachines e725 */
14344         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14345
14346         /* Acer/Packard Bell NCL20 */
14347         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14348
14349         /* Acer Aspire 4736Z */
14350         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14351
14352         /* Acer Aspire 5336 */
14353         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14354
14355         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14356         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14357
14358         /* Acer C720 Chromebook (Core i3 4005U) */
14359         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14360
14361         /* Apple Macbook 2,1 (Core 2 T7400) */
14362         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14363
14364         /* Apple Macbook 4,1 */
14365         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14366
14367         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14368         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14369
14370         /* HP Chromebook 14 (Celeron 2955U) */
14371         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14372
14373         /* Dell Chromebook 11 */
14374         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14375
14376         /* Dell Chromebook 11 (2015 version) */
14377         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14378
14379         /* Toshiba Satellite P50-C-18C */
14380         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14381 };
14382
14383 static void intel_init_quirks(struct drm_device *dev)
14384 {
14385         struct pci_dev *d = dev->pdev;
14386         int i;
14387
14388         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14389                 struct intel_quirk *q = &intel_quirks[i];
14390
14391                 if (d->device == q->device &&
14392                     (d->subsystem_vendor == q->subsystem_vendor ||
14393                      q->subsystem_vendor == PCI_ANY_ID) &&
14394                     (d->subsystem_device == q->subsystem_device ||
14395                      q->subsystem_device == PCI_ANY_ID))
14396                         q->hook(dev);
14397         }
14398         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14399                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14400                         intel_dmi_quirks[i].hook(dev);
14401         }
14402 }
14403
14404 /* Disable the VGA plane that we never use */
14405 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14406 {
14407         struct pci_dev *pdev = dev_priv->drm.pdev;
14408         u8 sr1;
14409         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14410
14411         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14412         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14413         outb(SR01, VGA_SR_INDEX);
14414         sr1 = inb(VGA_SR_DATA);
14415         outb(sr1 | 1<<5, VGA_SR_DATA);
14416         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14417         udelay(300);
14418
14419         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14420         POSTING_READ(vga_reg);
14421 }
14422
14423 void intel_modeset_init_hw(struct drm_device *dev)
14424 {
14425         struct drm_i915_private *dev_priv = to_i915(dev);
14426
14427         intel_update_cdclk(dev_priv);
14428         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
14429         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14430 }
14431
14432 /*
14433  * Calculate what we think the watermarks should be for the state we've read
14434  * out of the hardware and then immediately program those watermarks so that
14435  * we ensure the hardware settings match our internal state.
14436  *
14437  * We can calculate what we think WM's should be by creating a duplicate of the
14438  * current state (which was constructed during hardware readout) and running it
14439  * through the atomic check code to calculate new watermark values in the
14440  * state object.
14441  */
14442 static void sanitize_watermarks(struct drm_device *dev)
14443 {
14444         struct drm_i915_private *dev_priv = to_i915(dev);
14445         struct drm_atomic_state *state;
14446         struct intel_atomic_state *intel_state;
14447         struct drm_crtc *crtc;
14448         struct drm_crtc_state *cstate;
14449         struct drm_modeset_acquire_ctx ctx;
14450         int ret;
14451         int i;
14452
14453         /* Only supported on platforms that use atomic watermark design */
14454         if (!dev_priv->display.optimize_watermarks)
14455                 return;
14456
14457         /*
14458          * We need to hold connection_mutex before calling duplicate_state so
14459          * that the connector loop is protected.
14460          */
14461         drm_modeset_acquire_init(&ctx, 0);
14462 retry:
14463         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14464         if (ret == -EDEADLK) {
14465                 drm_modeset_backoff(&ctx);
14466                 goto retry;
14467         } else if (WARN_ON(ret)) {
14468                 goto fail;
14469         }
14470
14471         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14472         if (WARN_ON(IS_ERR(state)))
14473                 goto fail;
14474
14475         intel_state = to_intel_atomic_state(state);
14476
14477         /*
14478          * Hardware readout is the only time we don't want to calculate
14479          * intermediate watermarks (since we don't trust the current
14480          * watermarks).
14481          */
14482         if (!HAS_GMCH_DISPLAY(dev_priv))
14483                 intel_state->skip_intermediate_wm = true;
14484
14485         ret = intel_atomic_check(dev, state);
14486         if (ret) {
14487                 /*
14488                  * If we fail here, it means that the hardware appears to be
14489                  * programmed in a way that shouldn't be possible, given our
14490                  * understanding of watermark requirements.  This might mean a
14491                  * mistake in the hardware readout code or a mistake in the
14492                  * watermark calculations for a given platform.  Raise a WARN
14493                  * so that this is noticeable.
14494                  *
14495                  * If this actually happens, we'll have to just leave the
14496                  * BIOS-programmed watermarks untouched and hope for the best.
14497                  */
14498                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14499                 goto put_state;
14500         }
14501
14502         /* Write calculated watermark values back */
14503         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14504                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14505
14506                 cs->wm.need_postvbl_update = true;
14507                 dev_priv->display.optimize_watermarks(intel_state, cs);
14508
14509                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
14510         }
14511
14512 put_state:
14513         drm_atomic_state_put(state);
14514 fail:
14515         drm_modeset_drop_locks(&ctx);
14516         drm_modeset_acquire_fini(&ctx);
14517 }
14518
14519 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
14520 {
14521         if (IS_GEN5(dev_priv)) {
14522                 u32 fdi_pll_clk =
14523                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
14524
14525                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
14526         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
14527                 dev_priv->fdi_pll_freq = 270000;
14528         } else {
14529                 return;
14530         }
14531
14532         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
14533 }
14534
14535 int intel_modeset_init(struct drm_device *dev)
14536 {
14537         struct drm_i915_private *dev_priv = to_i915(dev);
14538         struct i915_ggtt *ggtt = &dev_priv->ggtt;
14539         enum pipe pipe;
14540         struct intel_crtc *crtc;
14541
14542         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
14543
14544         drm_mode_config_init(dev);
14545
14546         dev->mode_config.min_width = 0;
14547         dev->mode_config.min_height = 0;
14548
14549         dev->mode_config.preferred_depth = 24;
14550         dev->mode_config.prefer_shadow = 1;
14551
14552         dev->mode_config.allow_fb_modifiers = true;
14553
14554         dev->mode_config.funcs = &intel_mode_funcs;
14555
14556         init_llist_head(&dev_priv->atomic_helper.free_list);
14557         INIT_WORK(&dev_priv->atomic_helper.free_work,
14558                   intel_atomic_helper_free_state_worker);
14559
14560         intel_init_quirks(dev);
14561
14562         intel_init_pm(dev_priv);
14563
14564         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14565                 return 0;
14566
14567         /*
14568          * There may be no VBT; and if the BIOS enabled SSC we can
14569          * just keep using it to avoid unnecessary flicker.  Whereas if the
14570          * BIOS isn't using it, don't assume it will work even if the VBT
14571          * indicates as much.
14572          */
14573         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
14574                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14575                                             DREF_SSC1_ENABLE);
14576
14577                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
14578                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
14579                                      bios_lvds_use_ssc ? "en" : "dis",
14580                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
14581                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
14582                 }
14583         }
14584
14585         if (IS_GEN2(dev_priv)) {
14586                 dev->mode_config.max_width = 2048;
14587                 dev->mode_config.max_height = 2048;
14588         } else if (IS_GEN3(dev_priv)) {
14589                 dev->mode_config.max_width = 4096;
14590                 dev->mode_config.max_height = 4096;
14591         } else {
14592                 dev->mode_config.max_width = 8192;
14593                 dev->mode_config.max_height = 8192;
14594         }
14595
14596         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14597                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
14598                 dev->mode_config.cursor_height = 1023;
14599         } else if (IS_GEN2(dev_priv)) {
14600                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14601                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14602         } else {
14603                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14604                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14605         }
14606
14607         dev->mode_config.fb_base = ggtt->gmadr.start;
14608
14609         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14610                       INTEL_INFO(dev_priv)->num_pipes,
14611                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
14612
14613         for_each_pipe(dev_priv, pipe) {
14614                 int ret;
14615
14616                 ret = intel_crtc_init(dev_priv, pipe);
14617                 if (ret) {
14618                         drm_mode_config_cleanup(dev);
14619                         return ret;
14620                 }
14621         }
14622
14623         intel_shared_dpll_init(dev);
14624         intel_update_fdi_pll_freq(dev_priv);
14625
14626         intel_update_czclk(dev_priv);
14627         intel_modeset_init_hw(dev);
14628
14629         if (dev_priv->max_cdclk_freq == 0)
14630                 intel_update_max_cdclk(dev_priv);
14631
14632         /* Just disable it once at startup */
14633         i915_disable_vga(dev_priv);
14634         intel_setup_outputs(dev_priv);
14635
14636         drm_modeset_lock_all(dev);
14637         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
14638         drm_modeset_unlock_all(dev);
14639
14640         for_each_intel_crtc(dev, crtc) {
14641                 struct intel_initial_plane_config plane_config = {};
14642
14643                 if (!crtc->active)
14644                         continue;
14645
14646                 /*
14647                  * Note that reserving the BIOS fb up front prevents us
14648                  * from stuffing other stolen allocations like the ring
14649                  * on top.  This prevents some ugliness at boot time, and
14650                  * can even allow for smooth boot transitions if the BIOS
14651                  * fb is large enough for the active pipe configuration.
14652                  */
14653                 dev_priv->display.get_initial_plane_config(crtc,
14654                                                            &plane_config);
14655
14656                 /*
14657                  * If the fb is shared between multiple heads, we'll
14658                  * just get the first one.
14659                  */
14660                 intel_find_initial_plane_obj(crtc, &plane_config);
14661         }
14662
14663         /*
14664          * Make sure hardware watermarks really match the state we read out.
14665          * Note that we need to do this after reconstructing the BIOS fb's
14666          * since the watermark calculation done here will use pstate->fb.
14667          */
14668         if (!HAS_GMCH_DISPLAY(dev_priv))
14669                 sanitize_watermarks(dev);
14670
14671         return 0;
14672 }
14673
14674 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14675 {
14676         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14677         /* 640x480@60Hz, ~25175 kHz */
14678         struct dpll clock = {
14679                 .m1 = 18,
14680                 .m2 = 7,
14681                 .p1 = 13,
14682                 .p2 = 4,
14683                 .n = 2,
14684         };
14685         u32 dpll, fp;
14686         int i;
14687
14688         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
14689
14690         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
14691                       pipe_name(pipe), clock.vco, clock.dot);
14692
14693         fp = i9xx_dpll_compute_fp(&clock);
14694         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
14695                 DPLL_VGA_MODE_DIS |
14696                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
14697                 PLL_P2_DIVIDE_BY_4 |
14698                 PLL_REF_INPUT_DREFCLK |
14699                 DPLL_VCO_ENABLE;
14700
14701         I915_WRITE(FP0(pipe), fp);
14702         I915_WRITE(FP1(pipe), fp);
14703
14704         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
14705         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
14706         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
14707         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
14708         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
14709         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
14710         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
14711
14712         /*
14713          * Apparently we need to have VGA mode enabled prior to changing
14714          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
14715          * dividers, even though the register value does change.
14716          */
14717         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
14718         I915_WRITE(DPLL(pipe), dpll);
14719
14720         /* Wait for the clocks to stabilize. */
14721         POSTING_READ(DPLL(pipe));
14722         udelay(150);
14723
14724         /* The pixel multiplier can only be updated once the
14725          * DPLL is enabled and the clocks are stable.
14726          *
14727          * So write it again.
14728          */
14729         I915_WRITE(DPLL(pipe), dpll);
14730
14731         /* We do this three times for luck */
14732         for (i = 0; i < 3 ; i++) {
14733                 I915_WRITE(DPLL(pipe), dpll);
14734                 POSTING_READ(DPLL(pipe));
14735                 udelay(150); /* wait for warmup */
14736         }
14737
14738         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
14739         POSTING_READ(PIPECONF(pipe));
14740
14741         intel_wait_for_pipe_scanline_moving(crtc);
14742 }
14743
14744 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14745 {
14746         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14747
14748         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
14749                       pipe_name(pipe));
14750
14751         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
14752         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
14753         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
14754         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & CURSOR_MODE);
14755         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & CURSOR_MODE);
14756
14757         I915_WRITE(PIPECONF(pipe), 0);
14758         POSTING_READ(PIPECONF(pipe));
14759
14760         intel_wait_for_pipe_scanline_stopped(crtc);
14761
14762         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
14763         POSTING_READ(DPLL(pipe));
14764 }
14765
14766 static bool intel_plane_mapping_ok(struct intel_crtc *crtc,
14767                                    struct intel_plane *plane)
14768 {
14769         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14770         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
14771         u32 val = I915_READ(DSPCNTR(i9xx_plane));
14772
14773         return (val & DISPLAY_PLANE_ENABLE) == 0 ||
14774                 (val & DISPPLANE_SEL_PIPE_MASK) == DISPPLANE_SEL_PIPE(crtc->pipe);
14775 }
14776
14777 static void
14778 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
14779 {
14780         struct intel_crtc *crtc;
14781
14782         if (INTEL_GEN(dev_priv) >= 4)
14783                 return;
14784
14785         for_each_intel_crtc(&dev_priv->drm, crtc) {
14786                 struct intel_plane *plane =
14787                         to_intel_plane(crtc->base.primary);
14788
14789                 if (intel_plane_mapping_ok(crtc, plane))
14790                         continue;
14791
14792                 DRM_DEBUG_KMS("%s attached to the wrong pipe, disabling plane\n",
14793                               plane->base.name);
14794                 intel_plane_disable_noatomic(crtc, plane);
14795         }
14796 }
14797
14798 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
14799 {
14800         struct drm_device *dev = crtc->base.dev;
14801         struct intel_encoder *encoder;
14802
14803         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14804                 return true;
14805
14806         return false;
14807 }
14808
14809 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
14810 {
14811         struct drm_device *dev = encoder->base.dev;
14812         struct intel_connector *connector;
14813
14814         for_each_connector_on_encoder(dev, &encoder->base, connector)
14815                 return connector;
14816
14817         return NULL;
14818 }
14819
14820 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
14821                               enum pipe pch_transcoder)
14822 {
14823         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
14824                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
14825 }
14826
14827 static void intel_sanitize_crtc(struct intel_crtc *crtc,
14828                                 struct drm_modeset_acquire_ctx *ctx)
14829 {
14830         struct drm_device *dev = crtc->base.dev;
14831         struct drm_i915_private *dev_priv = to_i915(dev);
14832         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
14833
14834         /* Clear any frame start delays used for debugging left by the BIOS */
14835         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
14836                 i915_reg_t reg = PIPECONF(cpu_transcoder);
14837
14838                 I915_WRITE(reg,
14839                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14840         }
14841
14842         /* restore vblank interrupts to correct state */
14843         drm_crtc_vblank_reset(&crtc->base);
14844         if (crtc->active) {
14845                 struct intel_plane *plane;
14846
14847                 drm_crtc_vblank_on(&crtc->base);
14848
14849                 /* Disable everything but the primary plane */
14850                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
14851                         const struct intel_plane_state *plane_state =
14852                                 to_intel_plane_state(plane->base.state);
14853
14854                         if (plane_state->base.visible &&
14855                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
14856                                 intel_plane_disable_noatomic(crtc, plane);
14857                 }
14858         }
14859
14860         /* Adjust the state of the output pipe according to whether we
14861          * have active connectors/encoders. */
14862         if (crtc->active && !intel_crtc_has_encoders(crtc))
14863                 intel_crtc_disable_noatomic(&crtc->base, ctx);
14864
14865         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
14866                 /*
14867                  * We start out with underrun reporting disabled to avoid races.
14868                  * For correct bookkeeping mark this on active crtcs.
14869                  *
14870                  * Also on gmch platforms we dont have any hardware bits to
14871                  * disable the underrun reporting. Which means we need to start
14872                  * out with underrun reporting disabled also on inactive pipes,
14873                  * since otherwise we'll complain about the garbage we read when
14874                  * e.g. coming up after runtime pm.
14875                  *
14876                  * No protection against concurrent access is required - at
14877                  * worst a fifo underrun happens which also sets this to false.
14878                  */
14879                 crtc->cpu_fifo_underrun_disabled = true;
14880                 /*
14881                  * We track the PCH trancoder underrun reporting state
14882                  * within the crtc. With crtc for pipe A housing the underrun
14883                  * reporting state for PCH transcoder A, crtc for pipe B housing
14884                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
14885                  * and marking underrun reporting as disabled for the non-existing
14886                  * PCH transcoders B and C would prevent enabling the south
14887                  * error interrupt (see cpt_can_enable_serr_int()).
14888                  */
14889                 if (has_pch_trancoder(dev_priv, crtc->pipe))
14890                         crtc->pch_fifo_underrun_disabled = true;
14891         }
14892 }
14893
14894 static void intel_sanitize_encoder(struct intel_encoder *encoder)
14895 {
14896         struct intel_connector *connector;
14897
14898         /* We need to check both for a crtc link (meaning that the
14899          * encoder is active and trying to read from a pipe) and the
14900          * pipe itself being active. */
14901         bool has_active_crtc = encoder->base.crtc &&
14902                 to_intel_crtc(encoder->base.crtc)->active;
14903
14904         connector = intel_encoder_find_connector(encoder);
14905         if (connector && !has_active_crtc) {
14906                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
14907                               encoder->base.base.id,
14908                               encoder->base.name);
14909
14910                 /* Connector is active, but has no active pipe. This is
14911                  * fallout from our resume register restoring. Disable
14912                  * the encoder manually again. */
14913                 if (encoder->base.crtc) {
14914                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
14915
14916                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
14917                                       encoder->base.base.id,
14918                                       encoder->base.name);
14919                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
14920                         if (encoder->post_disable)
14921                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
14922                 }
14923                 encoder->base.crtc = NULL;
14924
14925                 /* Inconsistent output/port/pipe state happens presumably due to
14926                  * a bug in one of the get_hw_state functions. Or someplace else
14927                  * in our code, like the register restore mess on resume. Clamp
14928                  * things to off as a safer default. */
14929
14930                 connector->base.dpms = DRM_MODE_DPMS_OFF;
14931                 connector->base.encoder = NULL;
14932         }
14933 }
14934
14935 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
14936 {
14937         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14938
14939         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
14940                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
14941                 i915_disable_vga(dev_priv);
14942         }
14943 }
14944
14945 void i915_redisable_vga(struct drm_i915_private *dev_priv)
14946 {
14947         /* This function can be called both from intel_modeset_setup_hw_state or
14948          * at a very early point in our resume sequence, where the power well
14949          * structures are not yet restored. Since this function is at a very
14950          * paranoid "someone might have enabled VGA while we were not looking"
14951          * level, just check if the power well is enabled instead of trying to
14952          * follow the "don't touch the power well if we don't need it" policy
14953          * the rest of the driver uses. */
14954         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
14955                 return;
14956
14957         i915_redisable_vga_power_on(dev_priv);
14958
14959         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
14960 }
14961
14962 /* FIXME read out full plane state for all planes */
14963 static void readout_plane_state(struct intel_crtc *crtc)
14964 {
14965         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14966         struct intel_crtc_state *crtc_state =
14967                 to_intel_crtc_state(crtc->base.state);
14968         struct intel_plane *plane;
14969
14970         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
14971                 struct intel_plane_state *plane_state =
14972                         to_intel_plane_state(plane->base.state);
14973                 bool visible = plane->get_hw_state(plane);
14974
14975                 intel_set_plane_visible(crtc_state, plane_state, visible);
14976         }
14977 }
14978
14979 static void intel_modeset_readout_hw_state(struct drm_device *dev)
14980 {
14981         struct drm_i915_private *dev_priv = to_i915(dev);
14982         enum pipe pipe;
14983         struct intel_crtc *crtc;
14984         struct intel_encoder *encoder;
14985         struct intel_connector *connector;
14986         struct drm_connector_list_iter conn_iter;
14987         int i;
14988
14989         dev_priv->active_crtcs = 0;
14990
14991         for_each_intel_crtc(dev, crtc) {
14992                 struct intel_crtc_state *crtc_state =
14993                         to_intel_crtc_state(crtc->base.state);
14994
14995                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
14996                 memset(crtc_state, 0, sizeof(*crtc_state));
14997                 crtc_state->base.crtc = &crtc->base;
14998
14999                 crtc_state->base.active = crtc_state->base.enable =
15000                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15001
15002                 crtc->base.enabled = crtc_state->base.enable;
15003                 crtc->active = crtc_state->base.active;
15004
15005                 if (crtc_state->base.active)
15006                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15007
15008                 readout_plane_state(crtc);
15009
15010                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15011                               crtc->base.base.id, crtc->base.name,
15012                               enableddisabled(crtc_state->base.active));
15013         }
15014
15015         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15016                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15017
15018                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15019                                                   &pll->state.hw_state);
15020                 pll->state.crtc_mask = 0;
15021                 for_each_intel_crtc(dev, crtc) {
15022                         struct intel_crtc_state *crtc_state =
15023                                 to_intel_crtc_state(crtc->base.state);
15024
15025                         if (crtc_state->base.active &&
15026                             crtc_state->shared_dpll == pll)
15027                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15028                 }
15029                 pll->active_mask = pll->state.crtc_mask;
15030
15031                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15032                               pll->name, pll->state.crtc_mask, pll->on);
15033         }
15034
15035         for_each_intel_encoder(dev, encoder) {
15036                 pipe = 0;
15037
15038                 if (encoder->get_hw_state(encoder, &pipe)) {
15039                         struct intel_crtc_state *crtc_state;
15040
15041                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15042                         crtc_state = to_intel_crtc_state(crtc->base.state);
15043
15044                         encoder->base.crtc = &crtc->base;
15045                         encoder->get_config(encoder, crtc_state);
15046                 } else {
15047                         encoder->base.crtc = NULL;
15048                 }
15049
15050                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15051                               encoder->base.base.id, encoder->base.name,
15052                               enableddisabled(encoder->base.crtc),
15053                               pipe_name(pipe));
15054         }
15055
15056         drm_connector_list_iter_begin(dev, &conn_iter);
15057         for_each_intel_connector_iter(connector, &conn_iter) {
15058                 if (connector->get_hw_state(connector)) {
15059                         connector->base.dpms = DRM_MODE_DPMS_ON;
15060
15061                         encoder = connector->encoder;
15062                         connector->base.encoder = &encoder->base;
15063
15064                         if (encoder->base.crtc &&
15065                             encoder->base.crtc->state->active) {
15066                                 /*
15067                                  * This has to be done during hardware readout
15068                                  * because anything calling .crtc_disable may
15069                                  * rely on the connector_mask being accurate.
15070                                  */
15071                                 encoder->base.crtc->state->connector_mask |=
15072                                         1 << drm_connector_index(&connector->base);
15073                                 encoder->base.crtc->state->encoder_mask |=
15074                                         1 << drm_encoder_index(&encoder->base);
15075                         }
15076
15077                 } else {
15078                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15079                         connector->base.encoder = NULL;
15080                 }
15081                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15082                               connector->base.base.id, connector->base.name,
15083                               enableddisabled(connector->base.encoder));
15084         }
15085         drm_connector_list_iter_end(&conn_iter);
15086
15087         for_each_intel_crtc(dev, crtc) {
15088                 struct intel_crtc_state *crtc_state =
15089                         to_intel_crtc_state(crtc->base.state);
15090                 int min_cdclk = 0;
15091
15092                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15093                 if (crtc_state->base.active) {
15094                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15095                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15096                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15097
15098                         /*
15099                          * The initial mode needs to be set in order to keep
15100                          * the atomic core happy. It wants a valid mode if the
15101                          * crtc's enabled, so we do the above call.
15102                          *
15103                          * But we don't set all the derived state fully, hence
15104                          * set a flag to indicate that a full recalculation is
15105                          * needed on the next commit.
15106                          */
15107                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15108
15109                         intel_crtc_compute_pixel_rate(crtc_state);
15110
15111                         if (dev_priv->display.modeset_calc_cdclk) {
15112                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15113                                 if (WARN_ON(min_cdclk < 0))
15114                                         min_cdclk = 0;
15115                         }
15116
15117                         drm_calc_timestamping_constants(&crtc->base,
15118                                                         &crtc_state->base.adjusted_mode);
15119                         update_scanline_offset(crtc);
15120                 }
15121
15122                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15123                 dev_priv->min_voltage_level[crtc->pipe] =
15124                         crtc_state->min_voltage_level;
15125
15126                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15127         }
15128 }
15129
15130 static void
15131 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15132 {
15133         struct intel_encoder *encoder;
15134
15135         for_each_intel_encoder(&dev_priv->drm, encoder) {
15136                 u64 get_domains;
15137                 enum intel_display_power_domain domain;
15138
15139                 if (!encoder->get_power_domains)
15140                         continue;
15141
15142                 get_domains = encoder->get_power_domains(encoder);
15143                 for_each_power_domain(domain, get_domains)
15144                         intel_display_power_get(dev_priv, domain);
15145         }
15146 }
15147
15148 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15149 {
15150         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15151         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15152                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15153                            DARBF_GATING_DIS);
15154
15155         if (IS_HASWELL(dev_priv)) {
15156                 /*
15157                  * WaRsPkgCStateDisplayPMReq:hsw
15158                  * System hang if this isn't done before disabling all planes!
15159                  */
15160                 I915_WRITE(CHICKEN_PAR1_1,
15161                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15162         }
15163 }
15164
15165 /* Scan out the current hw modeset state,
15166  * and sanitizes it to the current state
15167  */
15168 static void
15169 intel_modeset_setup_hw_state(struct drm_device *dev,
15170                              struct drm_modeset_acquire_ctx *ctx)
15171 {
15172         struct drm_i915_private *dev_priv = to_i915(dev);
15173         enum pipe pipe;
15174         struct intel_crtc *crtc;
15175         struct intel_encoder *encoder;
15176         int i;
15177
15178         intel_early_display_was(dev_priv);
15179         intel_modeset_readout_hw_state(dev);
15180
15181         /* HW state is read out, now we need to sanitize this mess. */
15182         get_encoder_power_domains(dev_priv);
15183
15184         intel_sanitize_plane_mapping(dev_priv);
15185
15186         for_each_intel_encoder(dev, encoder) {
15187                 intel_sanitize_encoder(encoder);
15188         }
15189
15190         for_each_pipe(dev_priv, pipe) {
15191                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15192
15193                 intel_sanitize_crtc(crtc, ctx);
15194                 intel_dump_pipe_config(crtc, crtc->config,
15195                                        "[setup_hw_state]");
15196         }
15197
15198         intel_modeset_update_connector_atomic_state(dev);
15199
15200         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15201                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15202
15203                 if (!pll->on || pll->active_mask)
15204                         continue;
15205
15206                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15207
15208                 pll->funcs.disable(dev_priv, pll);
15209                 pll->on = false;
15210         }
15211
15212         if (IS_G4X(dev_priv)) {
15213                 g4x_wm_get_hw_state(dev);
15214                 g4x_wm_sanitize(dev_priv);
15215         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15216                 vlv_wm_get_hw_state(dev);
15217                 vlv_wm_sanitize(dev_priv);
15218         } else if (INTEL_GEN(dev_priv) >= 9) {
15219                 skl_wm_get_hw_state(dev);
15220         } else if (HAS_PCH_SPLIT(dev_priv)) {
15221                 ilk_wm_get_hw_state(dev);
15222         }
15223
15224         for_each_intel_crtc(dev, crtc) {
15225                 u64 put_domains;
15226
15227                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15228                 if (WARN_ON(put_domains))
15229                         modeset_put_power_domains(dev_priv, put_domains);
15230         }
15231         intel_display_set_init_power(dev_priv, false);
15232
15233         intel_power_domains_verify_state(dev_priv);
15234
15235         intel_fbc_init_pipe_state(dev_priv);
15236 }
15237
15238 void intel_display_resume(struct drm_device *dev)
15239 {
15240         struct drm_i915_private *dev_priv = to_i915(dev);
15241         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15242         struct drm_modeset_acquire_ctx ctx;
15243         int ret;
15244
15245         dev_priv->modeset_restore_state = NULL;
15246         if (state)
15247                 state->acquire_ctx = &ctx;
15248
15249         drm_modeset_acquire_init(&ctx, 0);
15250
15251         while (1) {
15252                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15253                 if (ret != -EDEADLK)
15254                         break;
15255
15256                 drm_modeset_backoff(&ctx);
15257         }
15258
15259         if (!ret)
15260                 ret = __intel_display_resume(dev, state, &ctx);
15261
15262         intel_enable_ipc(dev_priv);
15263         drm_modeset_drop_locks(&ctx);
15264         drm_modeset_acquire_fini(&ctx);
15265
15266         if (ret)
15267                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15268         if (state)
15269                 drm_atomic_state_put(state);
15270 }
15271
15272 int intel_connector_register(struct drm_connector *connector)
15273 {
15274         struct intel_connector *intel_connector = to_intel_connector(connector);
15275         int ret;
15276
15277         ret = intel_backlight_device_register(intel_connector);
15278         if (ret)
15279                 goto err;
15280
15281         return 0;
15282
15283 err:
15284         return ret;
15285 }
15286
15287 void intel_connector_unregister(struct drm_connector *connector)
15288 {
15289         struct intel_connector *intel_connector = to_intel_connector(connector);
15290
15291         intel_backlight_device_unregister(intel_connector);
15292         intel_panel_destroy_backlight(connector);
15293 }
15294
15295 static void intel_hpd_poll_fini(struct drm_device *dev)
15296 {
15297         struct intel_connector *connector;
15298         struct drm_connector_list_iter conn_iter;
15299
15300         /* Kill all the work that may have been queued by hpd. */
15301         drm_connector_list_iter_begin(dev, &conn_iter);
15302         for_each_intel_connector_iter(connector, &conn_iter) {
15303                 if (connector->modeset_retry_work.func)
15304                         cancel_work_sync(&connector->modeset_retry_work);
15305                 if (connector->hdcp_shim) {
15306                         cancel_delayed_work_sync(&connector->hdcp_check_work);
15307                         cancel_work_sync(&connector->hdcp_prop_work);
15308                 }
15309         }
15310         drm_connector_list_iter_end(&conn_iter);
15311 }
15312
15313 void intel_modeset_cleanup(struct drm_device *dev)
15314 {
15315         struct drm_i915_private *dev_priv = to_i915(dev);
15316
15317         flush_work(&dev_priv->atomic_helper.free_work);
15318         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15319
15320         intel_disable_gt_powersave(dev_priv);
15321
15322         /*
15323          * Interrupts and polling as the first thing to avoid creating havoc.
15324          * Too much stuff here (turning of connectors, ...) would
15325          * experience fancy races otherwise.
15326          */
15327         intel_irq_uninstall(dev_priv);
15328
15329         /*
15330          * Due to the hpd irq storm handling the hotplug work can re-arm the
15331          * poll handlers. Hence disable polling after hpd handling is shut down.
15332          */
15333         intel_hpd_poll_fini(dev);
15334
15335         /* poll work can call into fbdev, hence clean that up afterwards */
15336         intel_fbdev_fini(dev_priv);
15337
15338         intel_unregister_dsm_handler();
15339
15340         intel_fbc_global_disable(dev_priv);
15341
15342         /* flush any delayed tasks or pending work */
15343         flush_scheduled_work();
15344
15345         drm_mode_config_cleanup(dev);
15346
15347         intel_cleanup_overlay(dev_priv);
15348
15349         intel_cleanup_gt_powersave(dev_priv);
15350
15351         intel_teardown_gmbus(dev_priv);
15352
15353         destroy_workqueue(dev_priv->modeset_wq);
15354 }
15355
15356 void intel_connector_attach_encoder(struct intel_connector *connector,
15357                                     struct intel_encoder *encoder)
15358 {
15359         connector->encoder = encoder;
15360         drm_mode_connector_attach_encoder(&connector->base,
15361                                           &encoder->base);
15362 }
15363
15364 /*
15365  * set vga decode state - true == enable VGA decode
15366  */
15367 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15368 {
15369         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15370         u16 gmch_ctrl;
15371
15372         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15373                 DRM_ERROR("failed to read control word\n");
15374                 return -EIO;
15375         }
15376
15377         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15378                 return 0;
15379
15380         if (state)
15381                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15382         else
15383                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15384
15385         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15386                 DRM_ERROR("failed to write control word\n");
15387                 return -EIO;
15388         }
15389
15390         return 0;
15391 }
15392
15393 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15394
15395 struct intel_display_error_state {
15396
15397         u32 power_well_driver;
15398
15399         int num_transcoders;
15400
15401         struct intel_cursor_error_state {
15402                 u32 control;
15403                 u32 position;
15404                 u32 base;
15405                 u32 size;
15406         } cursor[I915_MAX_PIPES];
15407
15408         struct intel_pipe_error_state {
15409                 bool power_domain_on;
15410                 u32 source;
15411                 u32 stat;
15412         } pipe[I915_MAX_PIPES];
15413
15414         struct intel_plane_error_state {
15415                 u32 control;
15416                 u32 stride;
15417                 u32 size;
15418                 u32 pos;
15419                 u32 addr;
15420                 u32 surface;
15421                 u32 tile_offset;
15422         } plane[I915_MAX_PIPES];
15423
15424         struct intel_transcoder_error_state {
15425                 bool power_domain_on;
15426                 enum transcoder cpu_transcoder;
15427
15428                 u32 conf;
15429
15430                 u32 htotal;
15431                 u32 hblank;
15432                 u32 hsync;
15433                 u32 vtotal;
15434                 u32 vblank;
15435                 u32 vsync;
15436         } transcoder[4];
15437 };
15438
15439 struct intel_display_error_state *
15440 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15441 {
15442         struct intel_display_error_state *error;
15443         int transcoders[] = {
15444                 TRANSCODER_A,
15445                 TRANSCODER_B,
15446                 TRANSCODER_C,
15447                 TRANSCODER_EDP,
15448         };
15449         int i;
15450
15451         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15452                 return NULL;
15453
15454         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15455         if (error == NULL)
15456                 return NULL;
15457
15458         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15459                 error->power_well_driver =
15460                         I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL));
15461
15462         for_each_pipe(dev_priv, i) {
15463                 error->pipe[i].power_domain_on =
15464                         __intel_display_power_is_enabled(dev_priv,
15465                                                          POWER_DOMAIN_PIPE(i));
15466                 if (!error->pipe[i].power_domain_on)
15467                         continue;
15468
15469                 error->cursor[i].control = I915_READ(CURCNTR(i));
15470                 error->cursor[i].position = I915_READ(CURPOS(i));
15471                 error->cursor[i].base = I915_READ(CURBASE(i));
15472
15473                 error->plane[i].control = I915_READ(DSPCNTR(i));
15474                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15475                 if (INTEL_GEN(dev_priv) <= 3) {
15476                         error->plane[i].size = I915_READ(DSPSIZE(i));
15477                         error->plane[i].pos = I915_READ(DSPPOS(i));
15478                 }
15479                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15480                         error->plane[i].addr = I915_READ(DSPADDR(i));
15481                 if (INTEL_GEN(dev_priv) >= 4) {
15482                         error->plane[i].surface = I915_READ(DSPSURF(i));
15483                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15484                 }
15485
15486                 error->pipe[i].source = I915_READ(PIPESRC(i));
15487
15488                 if (HAS_GMCH_DISPLAY(dev_priv))
15489                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15490         }
15491
15492         /* Note: this does not include DSI transcoders. */
15493         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15494         if (HAS_DDI(dev_priv))
15495                 error->num_transcoders++; /* Account for eDP. */
15496
15497         for (i = 0; i < error->num_transcoders; i++) {
15498                 enum transcoder cpu_transcoder = transcoders[i];
15499
15500                 error->transcoder[i].power_domain_on =
15501                         __intel_display_power_is_enabled(dev_priv,
15502                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15503                 if (!error->transcoder[i].power_domain_on)
15504                         continue;
15505
15506                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15507
15508                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15509                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15510                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15511                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15512                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15513                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15514                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15515         }
15516
15517         return error;
15518 }
15519
15520 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15521
15522 void
15523 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15524                                 struct intel_display_error_state *error)
15525 {
15526         struct drm_i915_private *dev_priv = m->i915;
15527         int i;
15528
15529         if (!error)
15530                 return;
15531
15532         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
15533         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15534                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15535                            error->power_well_driver);
15536         for_each_pipe(dev_priv, i) {
15537                 err_printf(m, "Pipe [%d]:\n", i);
15538                 err_printf(m, "  Power: %s\n",
15539                            onoff(error->pipe[i].power_domain_on));
15540                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15541                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15542
15543                 err_printf(m, "Plane [%d]:\n", i);
15544                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15545                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15546                 if (INTEL_GEN(dev_priv) <= 3) {
15547                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15548                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15549                 }
15550                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15551                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15552                 if (INTEL_GEN(dev_priv) >= 4) {
15553                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15554                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15555                 }
15556
15557                 err_printf(m, "Cursor [%d]:\n", i);
15558                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15559                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15560                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15561         }
15562
15563         for (i = 0; i < error->num_transcoders; i++) {
15564                 err_printf(m, "CPU transcoder: %s\n",
15565                            transcoder_name(error->transcoder[i].cpu_transcoder));
15566                 err_printf(m, "  Power: %s\n",
15567                            onoff(error->transcoder[i].power_domain_on));
15568                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15569                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15570                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15571                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15572                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15573                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15574                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15575         }
15576 }
15577
15578 #endif