b0bb8adcf26ffc28027add383efb7d45d05653da
[linux-2.6-microblaze.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/module.h>
28 #include <linux/input.h>
29 #include <linux/i2c.h>
30 #include <linux/kernel.h>
31 #include <linux/slab.h>
32 #include <linux/vgaarb.h>
33 #include <drm/drm_edid.h>
34 #include <drm/i915_drm.h>
35 #include <drm/drm_atomic.h>
36 #include <drm/drm_atomic_helper.h>
37 #include <drm/drm_dp_helper.h>
38 #include <drm/drm_crtc_helper.h>
39 #include <drm/drm_plane_helper.h>
40 #include <drm/drm_rect.h>
41 #include <drm/drm_atomic_uapi.h>
42 #include <linux/intel-iommu.h>
43 #include <linux/reservation.h>
44
45 #include "intel_drv.h"
46 #include "intel_dsi.h"
47 #include "intel_frontbuffer.h"
48
49 #include "i915_drv.h"
50 #include "i915_gem_clflush.h"
51 #include "i915_reset.h"
52 #include "i915_trace.h"
53
54 /* Primary plane formats for gen <= 3 */
55 static const u32 i8xx_primary_formats[] = {
56         DRM_FORMAT_C8,
57         DRM_FORMAT_RGB565,
58         DRM_FORMAT_XRGB1555,
59         DRM_FORMAT_XRGB8888,
60 };
61
62 /* Primary plane formats for gen >= 4 */
63 static const u32 i965_primary_formats[] = {
64         DRM_FORMAT_C8,
65         DRM_FORMAT_RGB565,
66         DRM_FORMAT_XRGB8888,
67         DRM_FORMAT_XBGR8888,
68         DRM_FORMAT_XRGB2101010,
69         DRM_FORMAT_XBGR2101010,
70 };
71
72 static const u64 i9xx_format_modifiers[] = {
73         I915_FORMAT_MOD_X_TILED,
74         DRM_FORMAT_MOD_LINEAR,
75         DRM_FORMAT_MOD_INVALID
76 };
77
78 /* Cursor formats */
79 static const u32 intel_cursor_formats[] = {
80         DRM_FORMAT_ARGB8888,
81 };
82
83 static const u64 cursor_format_modifiers[] = {
84         DRM_FORMAT_MOD_LINEAR,
85         DRM_FORMAT_MOD_INVALID
86 };
87
88 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
89                                 struct intel_crtc_state *pipe_config);
90 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
91                                    struct intel_crtc_state *pipe_config);
92
93 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
94                                   struct drm_i915_gem_object *obj,
95                                   struct drm_mode_fb_cmd2 *mode_cmd);
96 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state);
97 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state);
98 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
99                                          const struct intel_link_m_n *m_n,
100                                          const struct intel_link_m_n *m2_n2);
101 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state);
102 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state);
103 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state);
104 static void haswell_set_pipemisc(const struct intel_crtc_state *crtc_state);
105 static void vlv_prepare_pll(struct intel_crtc *crtc,
106                             const struct intel_crtc_state *pipe_config);
107 static void chv_prepare_pll(struct intel_crtc *crtc,
108                             const struct intel_crtc_state *pipe_config);
109 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
110 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
111 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
112                                     struct intel_crtc_state *crtc_state);
113 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state);
114 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state);
115 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state);
116 static void intel_modeset_setup_hw_state(struct drm_device *dev,
117                                          struct drm_modeset_acquire_ctx *ctx);
118 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
119
120 struct intel_limit {
121         struct {
122                 int min, max;
123         } dot, vco, n, m, m1, m2, p, p1;
124
125         struct {
126                 int dot_limit;
127                 int p2_slow, p2_fast;
128         } p2;
129 };
130
131 /* returns HPLL frequency in kHz */
132 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
133 {
134         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
135
136         /* Obtain SKU information */
137         mutex_lock(&dev_priv->sb_lock);
138         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
139                 CCK_FUSE_HPLL_FREQ_MASK;
140         mutex_unlock(&dev_priv->sb_lock);
141
142         return vco_freq[hpll_freq] * 1000;
143 }
144
145 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
146                       const char *name, u32 reg, int ref_freq)
147 {
148         u32 val;
149         int divider;
150
151         mutex_lock(&dev_priv->sb_lock);
152         val = vlv_cck_read(dev_priv, reg);
153         mutex_unlock(&dev_priv->sb_lock);
154
155         divider = val & CCK_FREQUENCY_VALUES;
156
157         WARN((val & CCK_FREQUENCY_STATUS) !=
158              (divider << CCK_FREQUENCY_STATUS_SHIFT),
159              "%s change in progress\n", name);
160
161         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
162 }
163
164 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
165                            const char *name, u32 reg)
166 {
167         if (dev_priv->hpll_freq == 0)
168                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
169
170         return vlv_get_cck_clock(dev_priv, name, reg,
171                                  dev_priv->hpll_freq);
172 }
173
174 static void intel_update_czclk(struct drm_i915_private *dev_priv)
175 {
176         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
177                 return;
178
179         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
180                                                       CCK_CZ_CLOCK_CONTROL);
181
182         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
183 }
184
185 static inline u32 /* units of 100MHz */
186 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
187                     const struct intel_crtc_state *pipe_config)
188 {
189         if (HAS_DDI(dev_priv))
190                 return pipe_config->port_clock; /* SPLL */
191         else
192                 return dev_priv->fdi_pll_freq;
193 }
194
195 static const struct intel_limit intel_limits_i8xx_dac = {
196         .dot = { .min = 25000, .max = 350000 },
197         .vco = { .min = 908000, .max = 1512000 },
198         .n = { .min = 2, .max = 16 },
199         .m = { .min = 96, .max = 140 },
200         .m1 = { .min = 18, .max = 26 },
201         .m2 = { .min = 6, .max = 16 },
202         .p = { .min = 4, .max = 128 },
203         .p1 = { .min = 2, .max = 33 },
204         .p2 = { .dot_limit = 165000,
205                 .p2_slow = 4, .p2_fast = 2 },
206 };
207
208 static const struct intel_limit intel_limits_i8xx_dvo = {
209         .dot = { .min = 25000, .max = 350000 },
210         .vco = { .min = 908000, .max = 1512000 },
211         .n = { .min = 2, .max = 16 },
212         .m = { .min = 96, .max = 140 },
213         .m1 = { .min = 18, .max = 26 },
214         .m2 = { .min = 6, .max = 16 },
215         .p = { .min = 4, .max = 128 },
216         .p1 = { .min = 2, .max = 33 },
217         .p2 = { .dot_limit = 165000,
218                 .p2_slow = 4, .p2_fast = 4 },
219 };
220
221 static const struct intel_limit intel_limits_i8xx_lvds = {
222         .dot = { .min = 25000, .max = 350000 },
223         .vco = { .min = 908000, .max = 1512000 },
224         .n = { .min = 2, .max = 16 },
225         .m = { .min = 96, .max = 140 },
226         .m1 = { .min = 18, .max = 26 },
227         .m2 = { .min = 6, .max = 16 },
228         .p = { .min = 4, .max = 128 },
229         .p1 = { .min = 1, .max = 6 },
230         .p2 = { .dot_limit = 165000,
231                 .p2_slow = 14, .p2_fast = 7 },
232 };
233
234 static const struct intel_limit intel_limits_i9xx_sdvo = {
235         .dot = { .min = 20000, .max = 400000 },
236         .vco = { .min = 1400000, .max = 2800000 },
237         .n = { .min = 1, .max = 6 },
238         .m = { .min = 70, .max = 120 },
239         .m1 = { .min = 8, .max = 18 },
240         .m2 = { .min = 3, .max = 7 },
241         .p = { .min = 5, .max = 80 },
242         .p1 = { .min = 1, .max = 8 },
243         .p2 = { .dot_limit = 200000,
244                 .p2_slow = 10, .p2_fast = 5 },
245 };
246
247 static const struct intel_limit intel_limits_i9xx_lvds = {
248         .dot = { .min = 20000, .max = 400000 },
249         .vco = { .min = 1400000, .max = 2800000 },
250         .n = { .min = 1, .max = 6 },
251         .m = { .min = 70, .max = 120 },
252         .m1 = { .min = 8, .max = 18 },
253         .m2 = { .min = 3, .max = 7 },
254         .p = { .min = 7, .max = 98 },
255         .p1 = { .min = 1, .max = 8 },
256         .p2 = { .dot_limit = 112000,
257                 .p2_slow = 14, .p2_fast = 7 },
258 };
259
260
261 static const struct intel_limit intel_limits_g4x_sdvo = {
262         .dot = { .min = 25000, .max = 270000 },
263         .vco = { .min = 1750000, .max = 3500000},
264         .n = { .min = 1, .max = 4 },
265         .m = { .min = 104, .max = 138 },
266         .m1 = { .min = 17, .max = 23 },
267         .m2 = { .min = 5, .max = 11 },
268         .p = { .min = 10, .max = 30 },
269         .p1 = { .min = 1, .max = 3},
270         .p2 = { .dot_limit = 270000,
271                 .p2_slow = 10,
272                 .p2_fast = 10
273         },
274 };
275
276 static const struct intel_limit intel_limits_g4x_hdmi = {
277         .dot = { .min = 22000, .max = 400000 },
278         .vco = { .min = 1750000, .max = 3500000},
279         .n = { .min = 1, .max = 4 },
280         .m = { .min = 104, .max = 138 },
281         .m1 = { .min = 16, .max = 23 },
282         .m2 = { .min = 5, .max = 11 },
283         .p = { .min = 5, .max = 80 },
284         .p1 = { .min = 1, .max = 8},
285         .p2 = { .dot_limit = 165000,
286                 .p2_slow = 10, .p2_fast = 5 },
287 };
288
289 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
290         .dot = { .min = 20000, .max = 115000 },
291         .vco = { .min = 1750000, .max = 3500000 },
292         .n = { .min = 1, .max = 3 },
293         .m = { .min = 104, .max = 138 },
294         .m1 = { .min = 17, .max = 23 },
295         .m2 = { .min = 5, .max = 11 },
296         .p = { .min = 28, .max = 112 },
297         .p1 = { .min = 2, .max = 8 },
298         .p2 = { .dot_limit = 0,
299                 .p2_slow = 14, .p2_fast = 14
300         },
301 };
302
303 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
304         .dot = { .min = 80000, .max = 224000 },
305         .vco = { .min = 1750000, .max = 3500000 },
306         .n = { .min = 1, .max = 3 },
307         .m = { .min = 104, .max = 138 },
308         .m1 = { .min = 17, .max = 23 },
309         .m2 = { .min = 5, .max = 11 },
310         .p = { .min = 14, .max = 42 },
311         .p1 = { .min = 2, .max = 6 },
312         .p2 = { .dot_limit = 0,
313                 .p2_slow = 7, .p2_fast = 7
314         },
315 };
316
317 static const struct intel_limit intel_limits_pineview_sdvo = {
318         .dot = { .min = 20000, .max = 400000},
319         .vco = { .min = 1700000, .max = 3500000 },
320         /* Pineview's Ncounter is a ring counter */
321         .n = { .min = 3, .max = 6 },
322         .m = { .min = 2, .max = 256 },
323         /* Pineview only has one combined m divider, which we treat as m2. */
324         .m1 = { .min = 0, .max = 0 },
325         .m2 = { .min = 0, .max = 254 },
326         .p = { .min = 5, .max = 80 },
327         .p1 = { .min = 1, .max = 8 },
328         .p2 = { .dot_limit = 200000,
329                 .p2_slow = 10, .p2_fast = 5 },
330 };
331
332 static const struct intel_limit intel_limits_pineview_lvds = {
333         .dot = { .min = 20000, .max = 400000 },
334         .vco = { .min = 1700000, .max = 3500000 },
335         .n = { .min = 3, .max = 6 },
336         .m = { .min = 2, .max = 256 },
337         .m1 = { .min = 0, .max = 0 },
338         .m2 = { .min = 0, .max = 254 },
339         .p = { .min = 7, .max = 112 },
340         .p1 = { .min = 1, .max = 8 },
341         .p2 = { .dot_limit = 112000,
342                 .p2_slow = 14, .p2_fast = 14 },
343 };
344
345 /* Ironlake / Sandybridge
346  *
347  * We calculate clock using (register_value + 2) for N/M1/M2, so here
348  * the range value for them is (actual_value - 2).
349  */
350 static const struct intel_limit intel_limits_ironlake_dac = {
351         .dot = { .min = 25000, .max = 350000 },
352         .vco = { .min = 1760000, .max = 3510000 },
353         .n = { .min = 1, .max = 5 },
354         .m = { .min = 79, .max = 127 },
355         .m1 = { .min = 12, .max = 22 },
356         .m2 = { .min = 5, .max = 9 },
357         .p = { .min = 5, .max = 80 },
358         .p1 = { .min = 1, .max = 8 },
359         .p2 = { .dot_limit = 225000,
360                 .p2_slow = 10, .p2_fast = 5 },
361 };
362
363 static const struct intel_limit intel_limits_ironlake_single_lvds = {
364         .dot = { .min = 25000, .max = 350000 },
365         .vco = { .min = 1760000, .max = 3510000 },
366         .n = { .min = 1, .max = 3 },
367         .m = { .min = 79, .max = 118 },
368         .m1 = { .min = 12, .max = 22 },
369         .m2 = { .min = 5, .max = 9 },
370         .p = { .min = 28, .max = 112 },
371         .p1 = { .min = 2, .max = 8 },
372         .p2 = { .dot_limit = 225000,
373                 .p2_slow = 14, .p2_fast = 14 },
374 };
375
376 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
377         .dot = { .min = 25000, .max = 350000 },
378         .vco = { .min = 1760000, .max = 3510000 },
379         .n = { .min = 1, .max = 3 },
380         .m = { .min = 79, .max = 127 },
381         .m1 = { .min = 12, .max = 22 },
382         .m2 = { .min = 5, .max = 9 },
383         .p = { .min = 14, .max = 56 },
384         .p1 = { .min = 2, .max = 8 },
385         .p2 = { .dot_limit = 225000,
386                 .p2_slow = 7, .p2_fast = 7 },
387 };
388
389 /* LVDS 100mhz refclk limits. */
390 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
391         .dot = { .min = 25000, .max = 350000 },
392         .vco = { .min = 1760000, .max = 3510000 },
393         .n = { .min = 1, .max = 2 },
394         .m = { .min = 79, .max = 126 },
395         .m1 = { .min = 12, .max = 22 },
396         .m2 = { .min = 5, .max = 9 },
397         .p = { .min = 28, .max = 112 },
398         .p1 = { .min = 2, .max = 8 },
399         .p2 = { .dot_limit = 225000,
400                 .p2_slow = 14, .p2_fast = 14 },
401 };
402
403 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
404         .dot = { .min = 25000, .max = 350000 },
405         .vco = { .min = 1760000, .max = 3510000 },
406         .n = { .min = 1, .max = 3 },
407         .m = { .min = 79, .max = 126 },
408         .m1 = { .min = 12, .max = 22 },
409         .m2 = { .min = 5, .max = 9 },
410         .p = { .min = 14, .max = 42 },
411         .p1 = { .min = 2, .max = 6 },
412         .p2 = { .dot_limit = 225000,
413                 .p2_slow = 7, .p2_fast = 7 },
414 };
415
416 static const struct intel_limit intel_limits_vlv = {
417          /*
418           * These are the data rate limits (measured in fast clocks)
419           * since those are the strictest limits we have. The fast
420           * clock and actual rate limits are more relaxed, so checking
421           * them would make no difference.
422           */
423         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
424         .vco = { .min = 4000000, .max = 6000000 },
425         .n = { .min = 1, .max = 7 },
426         .m1 = { .min = 2, .max = 3 },
427         .m2 = { .min = 11, .max = 156 },
428         .p1 = { .min = 2, .max = 3 },
429         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
430 };
431
432 static const struct intel_limit intel_limits_chv = {
433         /*
434          * These are the data rate limits (measured in fast clocks)
435          * since those are the strictest limits we have.  The fast
436          * clock and actual rate limits are more relaxed, so checking
437          * them would make no difference.
438          */
439         .dot = { .min = 25000 * 5, .max = 540000 * 5},
440         .vco = { .min = 4800000, .max = 6480000 },
441         .n = { .min = 1, .max = 1 },
442         .m1 = { .min = 2, .max = 2 },
443         .m2 = { .min = 24 << 22, .max = 175 << 22 },
444         .p1 = { .min = 2, .max = 4 },
445         .p2 = { .p2_slow = 1, .p2_fast = 14 },
446 };
447
448 static const struct intel_limit intel_limits_bxt = {
449         /* FIXME: find real dot limits */
450         .dot = { .min = 0, .max = INT_MAX },
451         .vco = { .min = 4800000, .max = 6700000 },
452         .n = { .min = 1, .max = 1 },
453         .m1 = { .min = 2, .max = 2 },
454         /* FIXME: find real m2 limits */
455         .m2 = { .min = 2 << 22, .max = 255 << 22 },
456         .p1 = { .min = 2, .max = 4 },
457         .p2 = { .p2_slow = 1, .p2_fast = 20 },
458 };
459
460 static void
461 skl_wa_clkgate(struct drm_i915_private *dev_priv, int pipe, bool enable)
462 {
463         if (enable)
464                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
465                            DUPS1_GATING_DIS | DUPS2_GATING_DIS);
466         else
467                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
468                            I915_READ(CLKGATE_DIS_PSL(pipe)) &
469                            ~(DUPS1_GATING_DIS | DUPS2_GATING_DIS));
470 }
471
472 static bool
473 needs_modeset(const struct drm_crtc_state *state)
474 {
475         return drm_atomic_crtc_needs_modeset(state);
476 }
477
478 /*
479  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
480  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
481  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
482  * The helpers' return value is the rate of the clock that is fed to the
483  * display engine's pipe which can be the above fast dot clock rate or a
484  * divided-down version of it.
485  */
486 /* m1 is reserved as 0 in Pineview, n is a ring counter */
487 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
488 {
489         clock->m = clock->m2 + 2;
490         clock->p = clock->p1 * clock->p2;
491         if (WARN_ON(clock->n == 0 || clock->p == 0))
492                 return 0;
493         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
494         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
495
496         return clock->dot;
497 }
498
499 static u32 i9xx_dpll_compute_m(struct dpll *dpll)
500 {
501         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
502 }
503
504 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
505 {
506         clock->m = i9xx_dpll_compute_m(clock);
507         clock->p = clock->p1 * clock->p2;
508         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
509                 return 0;
510         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
511         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
512
513         return clock->dot;
514 }
515
516 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
517 {
518         clock->m = clock->m1 * clock->m2;
519         clock->p = clock->p1 * clock->p2;
520         if (WARN_ON(clock->n == 0 || clock->p == 0))
521                 return 0;
522         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
523         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
524
525         return clock->dot / 5;
526 }
527
528 int chv_calc_dpll_params(int refclk, struct dpll *clock)
529 {
530         clock->m = clock->m1 * clock->m2;
531         clock->p = clock->p1 * clock->p2;
532         if (WARN_ON(clock->n == 0 || clock->p == 0))
533                 return 0;
534         clock->vco = DIV_ROUND_CLOSEST_ULL((u64)refclk * clock->m,
535                                            clock->n << 22);
536         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
537
538         return clock->dot / 5;
539 }
540
541 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
542
543 /*
544  * Returns whether the given set of divisors are valid for a given refclk with
545  * the given connectors.
546  */
547 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
548                                const struct intel_limit *limit,
549                                const struct dpll *clock)
550 {
551         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
552                 INTELPllInvalid("n out of range\n");
553         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
554                 INTELPllInvalid("p1 out of range\n");
555         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
556                 INTELPllInvalid("m2 out of range\n");
557         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
558                 INTELPllInvalid("m1 out of range\n");
559
560         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
561             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
562                 if (clock->m1 <= clock->m2)
563                         INTELPllInvalid("m1 <= m2\n");
564
565         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
566             !IS_GEN9_LP(dev_priv)) {
567                 if (clock->p < limit->p.min || limit->p.max < clock->p)
568                         INTELPllInvalid("p out of range\n");
569                 if (clock->m < limit->m.min || limit->m.max < clock->m)
570                         INTELPllInvalid("m out of range\n");
571         }
572
573         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
574                 INTELPllInvalid("vco out of range\n");
575         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
576          * connector, etc., rather than just a single range.
577          */
578         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
579                 INTELPllInvalid("dot out of range\n");
580
581         return true;
582 }
583
584 static int
585 i9xx_select_p2_div(const struct intel_limit *limit,
586                    const struct intel_crtc_state *crtc_state,
587                    int target)
588 {
589         struct drm_device *dev = crtc_state->base.crtc->dev;
590
591         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
592                 /*
593                  * For LVDS just rely on its current settings for dual-channel.
594                  * We haven't figured out how to reliably set up different
595                  * single/dual channel state, if we even can.
596                  */
597                 if (intel_is_dual_link_lvds(dev))
598                         return limit->p2.p2_fast;
599                 else
600                         return limit->p2.p2_slow;
601         } else {
602                 if (target < limit->p2.dot_limit)
603                         return limit->p2.p2_slow;
604                 else
605                         return limit->p2.p2_fast;
606         }
607 }
608
609 /*
610  * Returns a set of divisors for the desired target clock with the given
611  * refclk, or FALSE.  The returned values represent the clock equation:
612  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
613  *
614  * Target and reference clocks are specified in kHz.
615  *
616  * If match_clock is provided, then best_clock P divider must match the P
617  * divider from @match_clock used for LVDS downclocking.
618  */
619 static bool
620 i9xx_find_best_dpll(const struct intel_limit *limit,
621                     struct intel_crtc_state *crtc_state,
622                     int target, int refclk, struct dpll *match_clock,
623                     struct dpll *best_clock)
624 {
625         struct drm_device *dev = crtc_state->base.crtc->dev;
626         struct dpll clock;
627         int err = target;
628
629         memset(best_clock, 0, sizeof(*best_clock));
630
631         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
632
633         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
634              clock.m1++) {
635                 for (clock.m2 = limit->m2.min;
636                      clock.m2 <= limit->m2.max; clock.m2++) {
637                         if (clock.m2 >= clock.m1)
638                                 break;
639                         for (clock.n = limit->n.min;
640                              clock.n <= limit->n.max; clock.n++) {
641                                 for (clock.p1 = limit->p1.min;
642                                         clock.p1 <= limit->p1.max; clock.p1++) {
643                                         int this_err;
644
645                                         i9xx_calc_dpll_params(refclk, &clock);
646                                         if (!intel_PLL_is_valid(to_i915(dev),
647                                                                 limit,
648                                                                 &clock))
649                                                 continue;
650                                         if (match_clock &&
651                                             clock.p != match_clock->p)
652                                                 continue;
653
654                                         this_err = abs(clock.dot - target);
655                                         if (this_err < err) {
656                                                 *best_clock = clock;
657                                                 err = this_err;
658                                         }
659                                 }
660                         }
661                 }
662         }
663
664         return (err != target);
665 }
666
667 /*
668  * Returns a set of divisors for the desired target clock with the given
669  * refclk, or FALSE.  The returned values represent the clock equation:
670  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
671  *
672  * Target and reference clocks are specified in kHz.
673  *
674  * If match_clock is provided, then best_clock P divider must match the P
675  * divider from @match_clock used for LVDS downclocking.
676  */
677 static bool
678 pnv_find_best_dpll(const struct intel_limit *limit,
679                    struct intel_crtc_state *crtc_state,
680                    int target, int refclk, struct dpll *match_clock,
681                    struct dpll *best_clock)
682 {
683         struct drm_device *dev = crtc_state->base.crtc->dev;
684         struct dpll clock;
685         int err = target;
686
687         memset(best_clock, 0, sizeof(*best_clock));
688
689         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
690
691         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
692              clock.m1++) {
693                 for (clock.m2 = limit->m2.min;
694                      clock.m2 <= limit->m2.max; clock.m2++) {
695                         for (clock.n = limit->n.min;
696                              clock.n <= limit->n.max; clock.n++) {
697                                 for (clock.p1 = limit->p1.min;
698                                         clock.p1 <= limit->p1.max; clock.p1++) {
699                                         int this_err;
700
701                                         pnv_calc_dpll_params(refclk, &clock);
702                                         if (!intel_PLL_is_valid(to_i915(dev),
703                                                                 limit,
704                                                                 &clock))
705                                                 continue;
706                                         if (match_clock &&
707                                             clock.p != match_clock->p)
708                                                 continue;
709
710                                         this_err = abs(clock.dot - target);
711                                         if (this_err < err) {
712                                                 *best_clock = clock;
713                                                 err = this_err;
714                                         }
715                                 }
716                         }
717                 }
718         }
719
720         return (err != target);
721 }
722
723 /*
724  * Returns a set of divisors for the desired target clock with the given
725  * refclk, or FALSE.  The returned values represent the clock equation:
726  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
727  *
728  * Target and reference clocks are specified in kHz.
729  *
730  * If match_clock is provided, then best_clock P divider must match the P
731  * divider from @match_clock used for LVDS downclocking.
732  */
733 static bool
734 g4x_find_best_dpll(const struct intel_limit *limit,
735                    struct intel_crtc_state *crtc_state,
736                    int target, int refclk, struct dpll *match_clock,
737                    struct dpll *best_clock)
738 {
739         struct drm_device *dev = crtc_state->base.crtc->dev;
740         struct dpll clock;
741         int max_n;
742         bool found = false;
743         /* approximately equals target * 0.00585 */
744         int err_most = (target >> 8) + (target >> 9);
745
746         memset(best_clock, 0, sizeof(*best_clock));
747
748         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
749
750         max_n = limit->n.max;
751         /* based on hardware requirement, prefer smaller n to precision */
752         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
753                 /* based on hardware requirement, prefere larger m1,m2 */
754                 for (clock.m1 = limit->m1.max;
755                      clock.m1 >= limit->m1.min; clock.m1--) {
756                         for (clock.m2 = limit->m2.max;
757                              clock.m2 >= limit->m2.min; clock.m2--) {
758                                 for (clock.p1 = limit->p1.max;
759                                      clock.p1 >= limit->p1.min; clock.p1--) {
760                                         int this_err;
761
762                                         i9xx_calc_dpll_params(refclk, &clock);
763                                         if (!intel_PLL_is_valid(to_i915(dev),
764                                                                 limit,
765                                                                 &clock))
766                                                 continue;
767
768                                         this_err = abs(clock.dot - target);
769                                         if (this_err < err_most) {
770                                                 *best_clock = clock;
771                                                 err_most = this_err;
772                                                 max_n = clock.n;
773                                                 found = true;
774                                         }
775                                 }
776                         }
777                 }
778         }
779         return found;
780 }
781
782 /*
783  * Check if the calculated PLL configuration is more optimal compared to the
784  * best configuration and error found so far. Return the calculated error.
785  */
786 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
787                                const struct dpll *calculated_clock,
788                                const struct dpll *best_clock,
789                                unsigned int best_error_ppm,
790                                unsigned int *error_ppm)
791 {
792         /*
793          * For CHV ignore the error and consider only the P value.
794          * Prefer a bigger P value based on HW requirements.
795          */
796         if (IS_CHERRYVIEW(to_i915(dev))) {
797                 *error_ppm = 0;
798
799                 return calculated_clock->p > best_clock->p;
800         }
801
802         if (WARN_ON_ONCE(!target_freq))
803                 return false;
804
805         *error_ppm = div_u64(1000000ULL *
806                                 abs(target_freq - calculated_clock->dot),
807                              target_freq);
808         /*
809          * Prefer a better P value over a better (smaller) error if the error
810          * is small. Ensure this preference for future configurations too by
811          * setting the error to 0.
812          */
813         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
814                 *error_ppm = 0;
815
816                 return true;
817         }
818
819         return *error_ppm + 10 < best_error_ppm;
820 }
821
822 /*
823  * Returns a set of divisors for the desired target clock with the given
824  * refclk, or FALSE.  The returned values represent the clock equation:
825  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
826  */
827 static bool
828 vlv_find_best_dpll(const struct intel_limit *limit,
829                    struct intel_crtc_state *crtc_state,
830                    int target, int refclk, struct dpll *match_clock,
831                    struct dpll *best_clock)
832 {
833         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
834         struct drm_device *dev = crtc->base.dev;
835         struct dpll clock;
836         unsigned int bestppm = 1000000;
837         /* min update 19.2 MHz */
838         int max_n = min(limit->n.max, refclk / 19200);
839         bool found = false;
840
841         target *= 5; /* fast clock */
842
843         memset(best_clock, 0, sizeof(*best_clock));
844
845         /* based on hardware requirement, prefer smaller n to precision */
846         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
847                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
848                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
849                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
850                                 clock.p = clock.p1 * clock.p2;
851                                 /* based on hardware requirement, prefer bigger m1,m2 values */
852                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
853                                         unsigned int ppm;
854
855                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
856                                                                      refclk * clock.m1);
857
858                                         vlv_calc_dpll_params(refclk, &clock);
859
860                                         if (!intel_PLL_is_valid(to_i915(dev),
861                                                                 limit,
862                                                                 &clock))
863                                                 continue;
864
865                                         if (!vlv_PLL_is_optimal(dev, target,
866                                                                 &clock,
867                                                                 best_clock,
868                                                                 bestppm, &ppm))
869                                                 continue;
870
871                                         *best_clock = clock;
872                                         bestppm = ppm;
873                                         found = true;
874                                 }
875                         }
876                 }
877         }
878
879         return found;
880 }
881
882 /*
883  * Returns a set of divisors for the desired target clock with the given
884  * refclk, or FALSE.  The returned values represent the clock equation:
885  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
886  */
887 static bool
888 chv_find_best_dpll(const struct intel_limit *limit,
889                    struct intel_crtc_state *crtc_state,
890                    int target, int refclk, struct dpll *match_clock,
891                    struct dpll *best_clock)
892 {
893         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
894         struct drm_device *dev = crtc->base.dev;
895         unsigned int best_error_ppm;
896         struct dpll clock;
897         u64 m2;
898         int found = false;
899
900         memset(best_clock, 0, sizeof(*best_clock));
901         best_error_ppm = 1000000;
902
903         /*
904          * Based on hardware doc, the n always set to 1, and m1 always
905          * set to 2.  If requires to support 200Mhz refclk, we need to
906          * revisit this because n may not 1 anymore.
907          */
908         clock.n = 1, clock.m1 = 2;
909         target *= 5;    /* fast clock */
910
911         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
912                 for (clock.p2 = limit->p2.p2_fast;
913                                 clock.p2 >= limit->p2.p2_slow;
914                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
915                         unsigned int error_ppm;
916
917                         clock.p = clock.p1 * clock.p2;
918
919                         m2 = DIV_ROUND_CLOSEST_ULL(((u64)target * clock.p *
920                                         clock.n) << 22, refclk * clock.m1);
921
922                         if (m2 > INT_MAX/clock.m1)
923                                 continue;
924
925                         clock.m2 = m2;
926
927                         chv_calc_dpll_params(refclk, &clock);
928
929                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
930                                 continue;
931
932                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
933                                                 best_error_ppm, &error_ppm))
934                                 continue;
935
936                         *best_clock = clock;
937                         best_error_ppm = error_ppm;
938                         found = true;
939                 }
940         }
941
942         return found;
943 }
944
945 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
946                         struct dpll *best_clock)
947 {
948         int refclk = 100000;
949         const struct intel_limit *limit = &intel_limits_bxt;
950
951         return chv_find_best_dpll(limit, crtc_state,
952                                   target_clock, refclk, NULL, best_clock);
953 }
954
955 bool intel_crtc_active(struct intel_crtc *crtc)
956 {
957         /* Be paranoid as we can arrive here with only partial
958          * state retrieved from the hardware during setup.
959          *
960          * We can ditch the adjusted_mode.crtc_clock check as soon
961          * as Haswell has gained clock readout/fastboot support.
962          *
963          * We can ditch the crtc->primary->state->fb check as soon as we can
964          * properly reconstruct framebuffers.
965          *
966          * FIXME: The intel_crtc->active here should be switched to
967          * crtc->state->active once we have proper CRTC states wired up
968          * for atomic.
969          */
970         return crtc->active && crtc->base.primary->state->fb &&
971                 crtc->config->base.adjusted_mode.crtc_clock;
972 }
973
974 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
975                                              enum pipe pipe)
976 {
977         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
978
979         return crtc->config->cpu_transcoder;
980 }
981
982 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
983                                     enum pipe pipe)
984 {
985         i915_reg_t reg = PIPEDSL(pipe);
986         u32 line1, line2;
987         u32 line_mask;
988
989         if (IS_GEN(dev_priv, 2))
990                 line_mask = DSL_LINEMASK_GEN2;
991         else
992                 line_mask = DSL_LINEMASK_GEN3;
993
994         line1 = I915_READ(reg) & line_mask;
995         msleep(5);
996         line2 = I915_READ(reg) & line_mask;
997
998         return line1 != line2;
999 }
1000
1001 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1002 {
1003         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1004         enum pipe pipe = crtc->pipe;
1005
1006         /* Wait for the display line to settle/start moving */
1007         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1008                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1009                           pipe_name(pipe), onoff(state));
1010 }
1011
1012 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1013 {
1014         wait_for_pipe_scanline_moving(crtc, false);
1015 }
1016
1017 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1018 {
1019         wait_for_pipe_scanline_moving(crtc, true);
1020 }
1021
1022 static void
1023 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1024 {
1025         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1026         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1027
1028         if (INTEL_GEN(dev_priv) >= 4) {
1029                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1030                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1031
1032                 /* Wait for the Pipe State to go off */
1033                 if (intel_wait_for_register(dev_priv,
1034                                             reg, I965_PIPECONF_ACTIVE, 0,
1035                                             100))
1036                         WARN(1, "pipe_off wait timed out\n");
1037         } else {
1038                 intel_wait_for_pipe_scanline_stopped(crtc);
1039         }
1040 }
1041
1042 /* Only for pre-ILK configs */
1043 void assert_pll(struct drm_i915_private *dev_priv,
1044                 enum pipe pipe, bool state)
1045 {
1046         u32 val;
1047         bool cur_state;
1048
1049         val = I915_READ(DPLL(pipe));
1050         cur_state = !!(val & DPLL_VCO_ENABLE);
1051         I915_STATE_WARN(cur_state != state,
1052              "PLL state assertion failure (expected %s, current %s)\n",
1053                         onoff(state), onoff(cur_state));
1054 }
1055
1056 /* XXX: the dsi pll is shared between MIPI DSI ports */
1057 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1058 {
1059         u32 val;
1060         bool cur_state;
1061
1062         mutex_lock(&dev_priv->sb_lock);
1063         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1064         mutex_unlock(&dev_priv->sb_lock);
1065
1066         cur_state = val & DSI_PLL_VCO_EN;
1067         I915_STATE_WARN(cur_state != state,
1068              "DSI PLL state assertion failure (expected %s, current %s)\n",
1069                         onoff(state), onoff(cur_state));
1070 }
1071
1072 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1073                           enum pipe pipe, bool state)
1074 {
1075         bool cur_state;
1076         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1077                                                                       pipe);
1078
1079         if (HAS_DDI(dev_priv)) {
1080                 /* DDI does not have a specific FDI_TX register */
1081                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1082                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1083         } else {
1084                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1085                 cur_state = !!(val & FDI_TX_ENABLE);
1086         }
1087         I915_STATE_WARN(cur_state != state,
1088              "FDI TX state assertion failure (expected %s, current %s)\n",
1089                         onoff(state), onoff(cur_state));
1090 }
1091 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1092 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1093
1094 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1095                           enum pipe pipe, bool state)
1096 {
1097         u32 val;
1098         bool cur_state;
1099
1100         val = I915_READ(FDI_RX_CTL(pipe));
1101         cur_state = !!(val & FDI_RX_ENABLE);
1102         I915_STATE_WARN(cur_state != state,
1103              "FDI RX state assertion failure (expected %s, current %s)\n",
1104                         onoff(state), onoff(cur_state));
1105 }
1106 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1107 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1108
1109 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1110                                       enum pipe pipe)
1111 {
1112         u32 val;
1113
1114         /* ILK FDI PLL is always enabled */
1115         if (IS_GEN(dev_priv, 5))
1116                 return;
1117
1118         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1119         if (HAS_DDI(dev_priv))
1120                 return;
1121
1122         val = I915_READ(FDI_TX_CTL(pipe));
1123         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1124 }
1125
1126 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1127                        enum pipe pipe, bool state)
1128 {
1129         u32 val;
1130         bool cur_state;
1131
1132         val = I915_READ(FDI_RX_CTL(pipe));
1133         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1134         I915_STATE_WARN(cur_state != state,
1135              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1136                         onoff(state), onoff(cur_state));
1137 }
1138
1139 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1140 {
1141         i915_reg_t pp_reg;
1142         u32 val;
1143         enum pipe panel_pipe = INVALID_PIPE;
1144         bool locked = true;
1145
1146         if (WARN_ON(HAS_DDI(dev_priv)))
1147                 return;
1148
1149         if (HAS_PCH_SPLIT(dev_priv)) {
1150                 u32 port_sel;
1151
1152                 pp_reg = PP_CONTROL(0);
1153                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1154
1155                 switch (port_sel) {
1156                 case PANEL_PORT_SELECT_LVDS:
1157                         intel_lvds_port_enabled(dev_priv, PCH_LVDS, &panel_pipe);
1158                         break;
1159                 case PANEL_PORT_SELECT_DPA:
1160                         intel_dp_port_enabled(dev_priv, DP_A, PORT_A, &panel_pipe);
1161                         break;
1162                 case PANEL_PORT_SELECT_DPC:
1163                         intel_dp_port_enabled(dev_priv, PCH_DP_C, PORT_C, &panel_pipe);
1164                         break;
1165                 case PANEL_PORT_SELECT_DPD:
1166                         intel_dp_port_enabled(dev_priv, PCH_DP_D, PORT_D, &panel_pipe);
1167                         break;
1168                 default:
1169                         MISSING_CASE(port_sel);
1170                         break;
1171                 }
1172         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1173                 /* presumably write lock depends on pipe, not port select */
1174                 pp_reg = PP_CONTROL(pipe);
1175                 panel_pipe = pipe;
1176         } else {
1177                 u32 port_sel;
1178
1179                 pp_reg = PP_CONTROL(0);
1180                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1181
1182                 WARN_ON(port_sel != PANEL_PORT_SELECT_LVDS);
1183                 intel_lvds_port_enabled(dev_priv, LVDS, &panel_pipe);
1184         }
1185
1186         val = I915_READ(pp_reg);
1187         if (!(val & PANEL_POWER_ON) ||
1188             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1189                 locked = false;
1190
1191         I915_STATE_WARN(panel_pipe == pipe && locked,
1192              "panel assertion failure, pipe %c regs locked\n",
1193              pipe_name(pipe));
1194 }
1195
1196 void assert_pipe(struct drm_i915_private *dev_priv,
1197                  enum pipe pipe, bool state)
1198 {
1199         bool cur_state;
1200         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1201                                                                       pipe);
1202         enum intel_display_power_domain power_domain;
1203         intel_wakeref_t wakeref;
1204
1205         /* we keep both pipes enabled on 830 */
1206         if (IS_I830(dev_priv))
1207                 state = true;
1208
1209         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1210         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
1211         if (wakeref) {
1212                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1213                 cur_state = !!(val & PIPECONF_ENABLE);
1214
1215                 intel_display_power_put(dev_priv, power_domain, wakeref);
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         enum pipe pipe;
1228         bool cur_state;
1229
1230         cur_state = plane->get_hw_state(plane, &pipe);
1231
1232         I915_STATE_WARN(cur_state != state,
1233                         "%s assertion failure (expected %s, current %s)\n",
1234                         plane->base.name, onoff(state), onoff(cur_state));
1235 }
1236
1237 #define assert_plane_enabled(p) assert_plane(p, true)
1238 #define assert_plane_disabled(p) assert_plane(p, false)
1239
1240 static void assert_planes_disabled(struct intel_crtc *crtc)
1241 {
1242         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1243         struct intel_plane *plane;
1244
1245         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1246                 assert_plane_disabled(plane);
1247 }
1248
1249 static void assert_vblank_disabled(struct drm_crtc *crtc)
1250 {
1251         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1252                 drm_crtc_vblank_put(crtc);
1253 }
1254
1255 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1256                                     enum pipe pipe)
1257 {
1258         u32 val;
1259         bool enabled;
1260
1261         val = I915_READ(PCH_TRANSCONF(pipe));
1262         enabled = !!(val & TRANS_ENABLE);
1263         I915_STATE_WARN(enabled,
1264              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1265              pipe_name(pipe));
1266 }
1267
1268 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1269                                    enum pipe pipe, enum port port,
1270                                    i915_reg_t dp_reg)
1271 {
1272         enum pipe port_pipe;
1273         bool state;
1274
1275         state = intel_dp_port_enabled(dev_priv, dp_reg, port, &port_pipe);
1276
1277         I915_STATE_WARN(state && port_pipe == pipe,
1278                         "PCH DP %c enabled on transcoder %c, should be disabled\n",
1279                         port_name(port), pipe_name(pipe));
1280
1281         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1282                         "IBX PCH DP %c still using transcoder B\n",
1283                         port_name(port));
1284 }
1285
1286 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1287                                      enum pipe pipe, enum port port,
1288                                      i915_reg_t hdmi_reg)
1289 {
1290         enum pipe port_pipe;
1291         bool state;
1292
1293         state = intel_sdvo_port_enabled(dev_priv, hdmi_reg, &port_pipe);
1294
1295         I915_STATE_WARN(state && port_pipe == pipe,
1296                         "PCH HDMI %c enabled on transcoder %c, should be disabled\n",
1297                         port_name(port), pipe_name(pipe));
1298
1299         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1300                         "IBX PCH HDMI %c still using transcoder B\n",
1301                         port_name(port));
1302 }
1303
1304 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1305                                       enum pipe pipe)
1306 {
1307         enum pipe port_pipe;
1308
1309         assert_pch_dp_disabled(dev_priv, pipe, PORT_B, PCH_DP_B);
1310         assert_pch_dp_disabled(dev_priv, pipe, PORT_C, PCH_DP_C);
1311         assert_pch_dp_disabled(dev_priv, pipe, PORT_D, PCH_DP_D);
1312
1313         I915_STATE_WARN(intel_crt_port_enabled(dev_priv, PCH_ADPA, &port_pipe) &&
1314                         port_pipe == pipe,
1315                         "PCH VGA enabled on transcoder %c, should be disabled\n",
1316                         pipe_name(pipe));
1317
1318         I915_STATE_WARN(intel_lvds_port_enabled(dev_priv, PCH_LVDS, &port_pipe) &&
1319                         port_pipe == pipe,
1320                         "PCH LVDS enabled on transcoder %c, should be disabled\n",
1321                         pipe_name(pipe));
1322
1323         /* PCH SDVOB multiplex with HDMIB */
1324         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_B, PCH_HDMIB);
1325         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_C, PCH_HDMIC);
1326         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_D, PCH_HDMID);
1327 }
1328
1329 static void _vlv_enable_pll(struct intel_crtc *crtc,
1330                             const struct intel_crtc_state *pipe_config)
1331 {
1332         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1333         enum pipe pipe = crtc->pipe;
1334
1335         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1336         POSTING_READ(DPLL(pipe));
1337         udelay(150);
1338
1339         if (intel_wait_for_register(dev_priv,
1340                                     DPLL(pipe),
1341                                     DPLL_LOCK_VLV,
1342                                     DPLL_LOCK_VLV,
1343                                     1))
1344                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1345 }
1346
1347 static void vlv_enable_pll(struct intel_crtc *crtc,
1348                            const struct intel_crtc_state *pipe_config)
1349 {
1350         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1351         enum pipe pipe = crtc->pipe;
1352
1353         assert_pipe_disabled(dev_priv, pipe);
1354
1355         /* PLL is protected by panel, make sure we can write it */
1356         assert_panel_unlocked(dev_priv, pipe);
1357
1358         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1359                 _vlv_enable_pll(crtc, pipe_config);
1360
1361         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1362         POSTING_READ(DPLL_MD(pipe));
1363 }
1364
1365
1366 static void _chv_enable_pll(struct intel_crtc *crtc,
1367                             const struct intel_crtc_state *pipe_config)
1368 {
1369         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1370         enum pipe pipe = crtc->pipe;
1371         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1372         u32 tmp;
1373
1374         mutex_lock(&dev_priv->sb_lock);
1375
1376         /* Enable back the 10bit clock to display controller */
1377         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1378         tmp |= DPIO_DCLKP_EN;
1379         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1380
1381         mutex_unlock(&dev_priv->sb_lock);
1382
1383         /*
1384          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1385          */
1386         udelay(1);
1387
1388         /* Enable PLL */
1389         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1390
1391         /* Check PLL is locked */
1392         if (intel_wait_for_register(dev_priv,
1393                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1394                                     1))
1395                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1396 }
1397
1398 static void chv_enable_pll(struct intel_crtc *crtc,
1399                            const struct intel_crtc_state *pipe_config)
1400 {
1401         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1402         enum pipe pipe = crtc->pipe;
1403
1404         assert_pipe_disabled(dev_priv, pipe);
1405
1406         /* PLL is protected by panel, make sure we can write it */
1407         assert_panel_unlocked(dev_priv, pipe);
1408
1409         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1410                 _chv_enable_pll(crtc, pipe_config);
1411
1412         if (pipe != PIPE_A) {
1413                 /*
1414                  * WaPixelRepeatModeFixForC0:chv
1415                  *
1416                  * DPLLCMD is AWOL. Use chicken bits to propagate
1417                  * the value from DPLLBMD to either pipe B or C.
1418                  */
1419                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1420                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1421                 I915_WRITE(CBR4_VLV, 0);
1422                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1423
1424                 /*
1425                  * DPLLB VGA mode also seems to cause problems.
1426                  * We should always have it disabled.
1427                  */
1428                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1429         } else {
1430                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1431                 POSTING_READ(DPLL_MD(pipe));
1432         }
1433 }
1434
1435 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1436 {
1437         struct intel_crtc *crtc;
1438         int count = 0;
1439
1440         for_each_intel_crtc(&dev_priv->drm, crtc) {
1441                 count += crtc->base.state->active &&
1442                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1443         }
1444
1445         return count;
1446 }
1447
1448 static void i9xx_enable_pll(struct intel_crtc *crtc,
1449                             const struct intel_crtc_state *crtc_state)
1450 {
1451         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1452         i915_reg_t reg = DPLL(crtc->pipe);
1453         u32 dpll = crtc_state->dpll_hw_state.dpll;
1454         int i;
1455
1456         assert_pipe_disabled(dev_priv, crtc->pipe);
1457
1458         /* PLL is protected by panel, make sure we can write it */
1459         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1460                 assert_panel_unlocked(dev_priv, crtc->pipe);
1461
1462         /* Enable DVO 2x clock on both PLLs if necessary */
1463         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1464                 /*
1465                  * It appears to be important that we don't enable this
1466                  * for the current pipe before otherwise configuring the
1467                  * PLL. No idea how this should be handled if multiple
1468                  * DVO outputs are enabled simultaneosly.
1469                  */
1470                 dpll |= DPLL_DVO_2X_MODE;
1471                 I915_WRITE(DPLL(!crtc->pipe),
1472                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1473         }
1474
1475         /*
1476          * Apparently we need to have VGA mode enabled prior to changing
1477          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1478          * dividers, even though the register value does change.
1479          */
1480         I915_WRITE(reg, 0);
1481
1482         I915_WRITE(reg, dpll);
1483
1484         /* Wait for the clocks to stabilize. */
1485         POSTING_READ(reg);
1486         udelay(150);
1487
1488         if (INTEL_GEN(dev_priv) >= 4) {
1489                 I915_WRITE(DPLL_MD(crtc->pipe),
1490                            crtc_state->dpll_hw_state.dpll_md);
1491         } else {
1492                 /* The pixel multiplier can only be updated once the
1493                  * DPLL is enabled and the clocks are stable.
1494                  *
1495                  * So write it again.
1496                  */
1497                 I915_WRITE(reg, dpll);
1498         }
1499
1500         /* We do this three times for luck */
1501         for (i = 0; i < 3; i++) {
1502                 I915_WRITE(reg, dpll);
1503                 POSTING_READ(reg);
1504                 udelay(150); /* wait for warmup */
1505         }
1506 }
1507
1508 static void i9xx_disable_pll(const struct intel_crtc_state *crtc_state)
1509 {
1510         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1511         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1512         enum pipe pipe = crtc->pipe;
1513
1514         /* Disable DVO 2x clock on both PLLs if necessary */
1515         if (IS_I830(dev_priv) &&
1516             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO) &&
1517             !intel_num_dvo_pipes(dev_priv)) {
1518                 I915_WRITE(DPLL(PIPE_B),
1519                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1520                 I915_WRITE(DPLL(PIPE_A),
1521                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1522         }
1523
1524         /* Don't disable pipe or pipe PLLs if needed */
1525         if (IS_I830(dev_priv))
1526                 return;
1527
1528         /* Make sure the pipe isn't still relying on us */
1529         assert_pipe_disabled(dev_priv, pipe);
1530
1531         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1532         POSTING_READ(DPLL(pipe));
1533 }
1534
1535 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1536 {
1537         u32 val;
1538
1539         /* Make sure the pipe isn't still relying on us */
1540         assert_pipe_disabled(dev_priv, pipe);
1541
1542         val = DPLL_INTEGRATED_REF_CLK_VLV |
1543                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1544         if (pipe != PIPE_A)
1545                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1546
1547         I915_WRITE(DPLL(pipe), val);
1548         POSTING_READ(DPLL(pipe));
1549 }
1550
1551 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1552 {
1553         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1554         u32 val;
1555
1556         /* Make sure the pipe isn't still relying on us */
1557         assert_pipe_disabled(dev_priv, pipe);
1558
1559         val = DPLL_SSC_REF_CLK_CHV |
1560                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1561         if (pipe != PIPE_A)
1562                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1563
1564         I915_WRITE(DPLL(pipe), val);
1565         POSTING_READ(DPLL(pipe));
1566
1567         mutex_lock(&dev_priv->sb_lock);
1568
1569         /* Disable 10bit clock to display controller */
1570         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1571         val &= ~DPIO_DCLKP_EN;
1572         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1573
1574         mutex_unlock(&dev_priv->sb_lock);
1575 }
1576
1577 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1578                          struct intel_digital_port *dport,
1579                          unsigned int expected_mask)
1580 {
1581         u32 port_mask;
1582         i915_reg_t dpll_reg;
1583
1584         switch (dport->base.port) {
1585         case PORT_B:
1586                 port_mask = DPLL_PORTB_READY_MASK;
1587                 dpll_reg = DPLL(0);
1588                 break;
1589         case PORT_C:
1590                 port_mask = DPLL_PORTC_READY_MASK;
1591                 dpll_reg = DPLL(0);
1592                 expected_mask <<= 4;
1593                 break;
1594         case PORT_D:
1595                 port_mask = DPLL_PORTD_READY_MASK;
1596                 dpll_reg = DPIO_PHY_STATUS;
1597                 break;
1598         default:
1599                 BUG();
1600         }
1601
1602         if (intel_wait_for_register(dev_priv,
1603                                     dpll_reg, port_mask, expected_mask,
1604                                     1000))
1605                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1606                      port_name(dport->base.port),
1607                      I915_READ(dpll_reg) & port_mask, expected_mask);
1608 }
1609
1610 static void ironlake_enable_pch_transcoder(const struct intel_crtc_state *crtc_state)
1611 {
1612         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1613         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1614         enum pipe pipe = crtc->pipe;
1615         i915_reg_t reg;
1616         u32 val, pipeconf_val;
1617
1618         /* Make sure PCH DPLL is enabled */
1619         assert_shared_dpll_enabled(dev_priv, crtc_state->shared_dpll);
1620
1621         /* FDI must be feeding us bits for PCH ports */
1622         assert_fdi_tx_enabled(dev_priv, pipe);
1623         assert_fdi_rx_enabled(dev_priv, pipe);
1624
1625         if (HAS_PCH_CPT(dev_priv)) {
1626                 /* Workaround: Set the timing override bit before enabling the
1627                  * pch transcoder. */
1628                 reg = TRANS_CHICKEN2(pipe);
1629                 val = I915_READ(reg);
1630                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1631                 I915_WRITE(reg, val);
1632         }
1633
1634         reg = PCH_TRANSCONF(pipe);
1635         val = I915_READ(reg);
1636         pipeconf_val = I915_READ(PIPECONF(pipe));
1637
1638         if (HAS_PCH_IBX(dev_priv)) {
1639                 /*
1640                  * Make the BPC in transcoder be consistent with
1641                  * that in pipeconf reg. For HDMI we must use 8bpc
1642                  * here for both 8bpc and 12bpc.
1643                  */
1644                 val &= ~PIPECONF_BPC_MASK;
1645                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
1646                         val |= PIPECONF_8BPC;
1647                 else
1648                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1649         }
1650
1651         val &= ~TRANS_INTERLACE_MASK;
1652         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1653                 if (HAS_PCH_IBX(dev_priv) &&
1654                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
1655                         val |= TRANS_LEGACY_INTERLACED_ILK;
1656                 else
1657                         val |= TRANS_INTERLACED;
1658         else
1659                 val |= TRANS_PROGRESSIVE;
1660
1661         I915_WRITE(reg, val | TRANS_ENABLE);
1662         if (intel_wait_for_register(dev_priv,
1663                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1664                                     100))
1665                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1666 }
1667
1668 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1669                                       enum transcoder cpu_transcoder)
1670 {
1671         u32 val, pipeconf_val;
1672
1673         /* FDI must be feeding us bits for PCH ports */
1674         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1675         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1676
1677         /* Workaround: set timing override bit. */
1678         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1679         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1680         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1681
1682         val = TRANS_ENABLE;
1683         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1684
1685         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1686             PIPECONF_INTERLACED_ILK)
1687                 val |= TRANS_INTERLACED;
1688         else
1689                 val |= TRANS_PROGRESSIVE;
1690
1691         I915_WRITE(LPT_TRANSCONF, val);
1692         if (intel_wait_for_register(dev_priv,
1693                                     LPT_TRANSCONF,
1694                                     TRANS_STATE_ENABLE,
1695                                     TRANS_STATE_ENABLE,
1696                                     100))
1697                 DRM_ERROR("Failed to enable PCH transcoder\n");
1698 }
1699
1700 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1701                                             enum pipe pipe)
1702 {
1703         i915_reg_t reg;
1704         u32 val;
1705
1706         /* FDI relies on the transcoder */
1707         assert_fdi_tx_disabled(dev_priv, pipe);
1708         assert_fdi_rx_disabled(dev_priv, pipe);
1709
1710         /* Ports must be off as well */
1711         assert_pch_ports_disabled(dev_priv, pipe);
1712
1713         reg = PCH_TRANSCONF(pipe);
1714         val = I915_READ(reg);
1715         val &= ~TRANS_ENABLE;
1716         I915_WRITE(reg, val);
1717         /* wait for PCH transcoder off, transcoder state */
1718         if (intel_wait_for_register(dev_priv,
1719                                     reg, TRANS_STATE_ENABLE, 0,
1720                                     50))
1721                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1722
1723         if (HAS_PCH_CPT(dev_priv)) {
1724                 /* Workaround: Clear the timing override chicken bit again. */
1725                 reg = TRANS_CHICKEN2(pipe);
1726                 val = I915_READ(reg);
1727                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1728                 I915_WRITE(reg, val);
1729         }
1730 }
1731
1732 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1733 {
1734         u32 val;
1735
1736         val = I915_READ(LPT_TRANSCONF);
1737         val &= ~TRANS_ENABLE;
1738         I915_WRITE(LPT_TRANSCONF, val);
1739         /* wait for PCH transcoder off, transcoder state */
1740         if (intel_wait_for_register(dev_priv,
1741                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1742                                     50))
1743                 DRM_ERROR("Failed to disable PCH transcoder\n");
1744
1745         /* Workaround: clear timing override bit. */
1746         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1747         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1748         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1749 }
1750
1751 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1752 {
1753         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1754
1755         if (HAS_PCH_LPT(dev_priv))
1756                 return PIPE_A;
1757         else
1758                 return crtc->pipe;
1759 }
1760
1761 static u32 intel_crtc_max_vblank_count(const struct intel_crtc_state *crtc_state)
1762 {
1763         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
1764
1765         /*
1766          * On i965gm the hardware frame counter reads
1767          * zero when the TV encoder is enabled :(
1768          */
1769         if (IS_I965GM(dev_priv) &&
1770             (crtc_state->output_types & BIT(INTEL_OUTPUT_TVOUT)))
1771                 return 0;
1772
1773         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
1774                 return 0xffffffff; /* full 32 bit counter */
1775         else if (INTEL_GEN(dev_priv) >= 3)
1776                 return 0xffffff; /* only 24 bits of frame count */
1777         else
1778                 return 0; /* Gen2 doesn't have a hardware frame counter */
1779 }
1780
1781 static void intel_crtc_vblank_on(const struct intel_crtc_state *crtc_state)
1782 {
1783         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1784
1785         drm_crtc_set_max_vblank_count(&crtc->base,
1786                                       intel_crtc_max_vblank_count(crtc_state));
1787         drm_crtc_vblank_on(&crtc->base);
1788 }
1789
1790 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1791 {
1792         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1793         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1794         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1795         enum pipe pipe = crtc->pipe;
1796         i915_reg_t reg;
1797         u32 val;
1798
1799         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1800
1801         assert_planes_disabled(crtc);
1802
1803         /*
1804          * A pipe without a PLL won't actually be able to drive bits from
1805          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1806          * need the check.
1807          */
1808         if (HAS_GMCH_DISPLAY(dev_priv)) {
1809                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1810                         assert_dsi_pll_enabled(dev_priv);
1811                 else
1812                         assert_pll_enabled(dev_priv, pipe);
1813         } else {
1814                 if (new_crtc_state->has_pch_encoder) {
1815                         /* if driving the PCH, we need FDI enabled */
1816                         assert_fdi_rx_pll_enabled(dev_priv,
1817                                                   intel_crtc_pch_transcoder(crtc));
1818                         assert_fdi_tx_pll_enabled(dev_priv,
1819                                                   (enum pipe) cpu_transcoder);
1820                 }
1821                 /* FIXME: assert CPU port conditions for SNB+ */
1822         }
1823
1824         reg = PIPECONF(cpu_transcoder);
1825         val = I915_READ(reg);
1826         if (val & PIPECONF_ENABLE) {
1827                 /* we keep both pipes enabled on 830 */
1828                 WARN_ON(!IS_I830(dev_priv));
1829                 return;
1830         }
1831
1832         I915_WRITE(reg, val | PIPECONF_ENABLE);
1833         POSTING_READ(reg);
1834
1835         /*
1836          * Until the pipe starts PIPEDSL reads will return a stale value,
1837          * which causes an apparent vblank timestamp jump when PIPEDSL
1838          * resets to its proper value. That also messes up the frame count
1839          * when it's derived from the timestamps. So let's wait for the
1840          * pipe to start properly before we call drm_crtc_vblank_on()
1841          */
1842         if (intel_crtc_max_vblank_count(new_crtc_state) == 0)
1843                 intel_wait_for_pipe_scanline_moving(crtc);
1844 }
1845
1846 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1847 {
1848         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1849         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1850         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1851         enum pipe pipe = crtc->pipe;
1852         i915_reg_t reg;
1853         u32 val;
1854
1855         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1856
1857         /*
1858          * Make sure planes won't keep trying to pump pixels to us,
1859          * or we might hang the display.
1860          */
1861         assert_planes_disabled(crtc);
1862
1863         reg = PIPECONF(cpu_transcoder);
1864         val = I915_READ(reg);
1865         if ((val & PIPECONF_ENABLE) == 0)
1866                 return;
1867
1868         /*
1869          * Double wide has implications for planes
1870          * so best keep it disabled when not needed.
1871          */
1872         if (old_crtc_state->double_wide)
1873                 val &= ~PIPECONF_DOUBLE_WIDE;
1874
1875         /* Don't disable pipe or pipe PLLs if needed */
1876         if (!IS_I830(dev_priv))
1877                 val &= ~PIPECONF_ENABLE;
1878
1879         I915_WRITE(reg, val);
1880         if ((val & PIPECONF_ENABLE) == 0)
1881                 intel_wait_for_pipe_off(old_crtc_state);
1882 }
1883
1884 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1885 {
1886         return IS_GEN(dev_priv, 2) ? 2048 : 4096;
1887 }
1888
1889 static unsigned int
1890 intel_tile_width_bytes(const struct drm_framebuffer *fb, int color_plane)
1891 {
1892         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1893         unsigned int cpp = fb->format->cpp[color_plane];
1894
1895         switch (fb->modifier) {
1896         case DRM_FORMAT_MOD_LINEAR:
1897                 return cpp;
1898         case I915_FORMAT_MOD_X_TILED:
1899                 if (IS_GEN(dev_priv, 2))
1900                         return 128;
1901                 else
1902                         return 512;
1903         case I915_FORMAT_MOD_Y_TILED_CCS:
1904                 if (color_plane == 1)
1905                         return 128;
1906                 /* fall through */
1907         case I915_FORMAT_MOD_Y_TILED:
1908                 if (IS_GEN(dev_priv, 2) || HAS_128_BYTE_Y_TILING(dev_priv))
1909                         return 128;
1910                 else
1911                         return 512;
1912         case I915_FORMAT_MOD_Yf_TILED_CCS:
1913                 if (color_plane == 1)
1914                         return 128;
1915                 /* fall through */
1916         case I915_FORMAT_MOD_Yf_TILED:
1917                 switch (cpp) {
1918                 case 1:
1919                         return 64;
1920                 case 2:
1921                 case 4:
1922                         return 128;
1923                 case 8:
1924                 case 16:
1925                         return 256;
1926                 default:
1927                         MISSING_CASE(cpp);
1928                         return cpp;
1929                 }
1930                 break;
1931         default:
1932                 MISSING_CASE(fb->modifier);
1933                 return cpp;
1934         }
1935 }
1936
1937 static unsigned int
1938 intel_tile_height(const struct drm_framebuffer *fb, int color_plane)
1939 {
1940         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
1941                 return 1;
1942         else
1943                 return intel_tile_size(to_i915(fb->dev)) /
1944                         intel_tile_width_bytes(fb, color_plane);
1945 }
1946
1947 /* Return the tile dimensions in pixel units */
1948 static void intel_tile_dims(const struct drm_framebuffer *fb, int color_plane,
1949                             unsigned int *tile_width,
1950                             unsigned int *tile_height)
1951 {
1952         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, color_plane);
1953         unsigned int cpp = fb->format->cpp[color_plane];
1954
1955         *tile_width = tile_width_bytes / cpp;
1956         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1957 }
1958
1959 unsigned int
1960 intel_fb_align_height(const struct drm_framebuffer *fb,
1961                       int color_plane, unsigned int height)
1962 {
1963         unsigned int tile_height = intel_tile_height(fb, color_plane);
1964
1965         return ALIGN(height, tile_height);
1966 }
1967
1968 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
1969 {
1970         unsigned int size = 0;
1971         int i;
1972
1973         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
1974                 size += rot_info->plane[i].width * rot_info->plane[i].height;
1975
1976         return size;
1977 }
1978
1979 static void
1980 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
1981                         const struct drm_framebuffer *fb,
1982                         unsigned int rotation)
1983 {
1984         view->type = I915_GGTT_VIEW_NORMAL;
1985         if (drm_rotation_90_or_270(rotation)) {
1986                 view->type = I915_GGTT_VIEW_ROTATED;
1987                 view->rotated = to_intel_framebuffer(fb)->rot_info;
1988         }
1989 }
1990
1991 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
1992 {
1993         if (IS_I830(dev_priv))
1994                 return 16 * 1024;
1995         else if (IS_I85X(dev_priv))
1996                 return 256;
1997         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
1998                 return 32;
1999         else
2000                 return 4 * 1024;
2001 }
2002
2003 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2004 {
2005         if (INTEL_GEN(dev_priv) >= 9)
2006                 return 256 * 1024;
2007         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2008                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2009                 return 128 * 1024;
2010         else if (INTEL_GEN(dev_priv) >= 4)
2011                 return 4 * 1024;
2012         else
2013                 return 0;
2014 }
2015
2016 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2017                                          int color_plane)
2018 {
2019         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2020
2021         /* AUX_DIST needs only 4K alignment */
2022         if (color_plane == 1)
2023                 return 4096;
2024
2025         switch (fb->modifier) {
2026         case DRM_FORMAT_MOD_LINEAR:
2027                 return intel_linear_alignment(dev_priv);
2028         case I915_FORMAT_MOD_X_TILED:
2029                 if (INTEL_GEN(dev_priv) >= 9)
2030                         return 256 * 1024;
2031                 return 0;
2032         case I915_FORMAT_MOD_Y_TILED_CCS:
2033         case I915_FORMAT_MOD_Yf_TILED_CCS:
2034         case I915_FORMAT_MOD_Y_TILED:
2035         case I915_FORMAT_MOD_Yf_TILED:
2036                 return 1 * 1024 * 1024;
2037         default:
2038                 MISSING_CASE(fb->modifier);
2039                 return 0;
2040         }
2041 }
2042
2043 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2044 {
2045         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2046         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2047
2048         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2049 }
2050
2051 struct i915_vma *
2052 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2053                            const struct i915_ggtt_view *view,
2054                            bool uses_fence,
2055                            unsigned long *out_flags)
2056 {
2057         struct drm_device *dev = fb->dev;
2058         struct drm_i915_private *dev_priv = to_i915(dev);
2059         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2060         intel_wakeref_t wakeref;
2061         struct i915_vma *vma;
2062         unsigned int pinctl;
2063         u32 alignment;
2064
2065         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2066
2067         alignment = intel_surf_alignment(fb, 0);
2068
2069         /* Note that the w/a also requires 64 PTE of padding following the
2070          * bo. We currently fill all unused PTE with the shadow page and so
2071          * we should always have valid PTE following the scanout preventing
2072          * the VT-d warning.
2073          */
2074         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2075                 alignment = 256 * 1024;
2076
2077         /*
2078          * Global gtt pte registers are special registers which actually forward
2079          * writes to a chunk of system memory. Which means that there is no risk
2080          * that the register values disappear as soon as we call
2081          * intel_runtime_pm_put(), so it is correct to wrap only the
2082          * pin/unpin/fence and not more.
2083          */
2084         wakeref = intel_runtime_pm_get(dev_priv);
2085
2086         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2087
2088         pinctl = 0;
2089
2090         /* Valleyview is definitely limited to scanning out the first
2091          * 512MiB. Lets presume this behaviour was inherited from the
2092          * g4x display engine and that all earlier gen are similarly
2093          * limited. Testing suggests that it is a little more
2094          * complicated than this. For example, Cherryview appears quite
2095          * happy to scanout from anywhere within its global aperture.
2096          */
2097         if (HAS_GMCH_DISPLAY(dev_priv))
2098                 pinctl |= PIN_MAPPABLE;
2099
2100         vma = i915_gem_object_pin_to_display_plane(obj,
2101                                                    alignment, view, pinctl);
2102         if (IS_ERR(vma))
2103                 goto err;
2104
2105         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2106                 int ret;
2107
2108                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2109                  * fence, whereas 965+ only requires a fence if using
2110                  * framebuffer compression.  For simplicity, we always, when
2111                  * possible, install a fence as the cost is not that onerous.
2112                  *
2113                  * If we fail to fence the tiled scanout, then either the
2114                  * modeset will reject the change (which is highly unlikely as
2115                  * the affected systems, all but one, do not have unmappable
2116                  * space) or we will not be able to enable full powersaving
2117                  * techniques (also likely not to apply due to various limits
2118                  * FBC and the like impose on the size of the buffer, which
2119                  * presumably we violated anyway with this unmappable buffer).
2120                  * Anyway, it is presumably better to stumble onwards with
2121                  * something and try to run the system in a "less than optimal"
2122                  * mode that matches the user configuration.
2123                  */
2124                 ret = i915_vma_pin_fence(vma);
2125                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2126                         i915_gem_object_unpin_from_display_plane(vma);
2127                         vma = ERR_PTR(ret);
2128                         goto err;
2129                 }
2130
2131                 if (ret == 0 && vma->fence)
2132                         *out_flags |= PLANE_HAS_FENCE;
2133         }
2134
2135         i915_vma_get(vma);
2136 err:
2137         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2138
2139         intel_runtime_pm_put(dev_priv, wakeref);
2140         return vma;
2141 }
2142
2143 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2144 {
2145         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2146
2147         if (flags & PLANE_HAS_FENCE)
2148                 i915_vma_unpin_fence(vma);
2149         i915_gem_object_unpin_from_display_plane(vma);
2150         i915_vma_put(vma);
2151 }
2152
2153 static int intel_fb_pitch(const struct drm_framebuffer *fb, int color_plane,
2154                           unsigned int rotation)
2155 {
2156         if (drm_rotation_90_or_270(rotation))
2157                 return to_intel_framebuffer(fb)->rotated[color_plane].pitch;
2158         else
2159                 return fb->pitches[color_plane];
2160 }
2161
2162 /*
2163  * Convert the x/y offsets into a linear offset.
2164  * Only valid with 0/180 degree rotation, which is fine since linear
2165  * offset is only used with linear buffers on pre-hsw and tiled buffers
2166  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2167  */
2168 u32 intel_fb_xy_to_linear(int x, int y,
2169                           const struct intel_plane_state *state,
2170                           int color_plane)
2171 {
2172         const struct drm_framebuffer *fb = state->base.fb;
2173         unsigned int cpp = fb->format->cpp[color_plane];
2174         unsigned int pitch = state->color_plane[color_plane].stride;
2175
2176         return y * pitch + x * cpp;
2177 }
2178
2179 /*
2180  * Add the x/y offsets derived from fb->offsets[] to the user
2181  * specified plane src x/y offsets. The resulting x/y offsets
2182  * specify the start of scanout from the beginning of the gtt mapping.
2183  */
2184 void intel_add_fb_offsets(int *x, int *y,
2185                           const struct intel_plane_state *state,
2186                           int color_plane)
2187
2188 {
2189         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2190         unsigned int rotation = state->base.rotation;
2191
2192         if (drm_rotation_90_or_270(rotation)) {
2193                 *x += intel_fb->rotated[color_plane].x;
2194                 *y += intel_fb->rotated[color_plane].y;
2195         } else {
2196                 *x += intel_fb->normal[color_plane].x;
2197                 *y += intel_fb->normal[color_plane].y;
2198         }
2199 }
2200
2201 static u32 intel_adjust_tile_offset(int *x, int *y,
2202                                     unsigned int tile_width,
2203                                     unsigned int tile_height,
2204                                     unsigned int tile_size,
2205                                     unsigned int pitch_tiles,
2206                                     u32 old_offset,
2207                                     u32 new_offset)
2208 {
2209         unsigned int pitch_pixels = pitch_tiles * tile_width;
2210         unsigned int tiles;
2211
2212         WARN_ON(old_offset & (tile_size - 1));
2213         WARN_ON(new_offset & (tile_size - 1));
2214         WARN_ON(new_offset > old_offset);
2215
2216         tiles = (old_offset - new_offset) / tile_size;
2217
2218         *y += tiles / pitch_tiles * tile_height;
2219         *x += tiles % pitch_tiles * tile_width;
2220
2221         /* minimize x in case it got needlessly big */
2222         *y += *x / pitch_pixels * tile_height;
2223         *x %= pitch_pixels;
2224
2225         return new_offset;
2226 }
2227
2228 static bool is_surface_linear(u64 modifier, int color_plane)
2229 {
2230         return modifier == DRM_FORMAT_MOD_LINEAR;
2231 }
2232
2233 static u32 intel_adjust_aligned_offset(int *x, int *y,
2234                                        const struct drm_framebuffer *fb,
2235                                        int color_plane,
2236                                        unsigned int rotation,
2237                                        unsigned int pitch,
2238                                        u32 old_offset, u32 new_offset)
2239 {
2240         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2241         unsigned int cpp = fb->format->cpp[color_plane];
2242
2243         WARN_ON(new_offset > old_offset);
2244
2245         if (!is_surface_linear(fb->modifier, color_plane)) {
2246                 unsigned int tile_size, tile_width, tile_height;
2247                 unsigned int pitch_tiles;
2248
2249                 tile_size = intel_tile_size(dev_priv);
2250                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2251
2252                 if (drm_rotation_90_or_270(rotation)) {
2253                         pitch_tiles = pitch / tile_height;
2254                         swap(tile_width, tile_height);
2255                 } else {
2256                         pitch_tiles = pitch / (tile_width * cpp);
2257                 }
2258
2259                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2260                                          tile_size, pitch_tiles,
2261                                          old_offset, new_offset);
2262         } else {
2263                 old_offset += *y * pitch + *x * cpp;
2264
2265                 *y = (old_offset - new_offset) / pitch;
2266                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2267         }
2268
2269         return new_offset;
2270 }
2271
2272 /*
2273  * Adjust the tile offset by moving the difference into
2274  * the x/y offsets.
2275  */
2276 static u32 intel_plane_adjust_aligned_offset(int *x, int *y,
2277                                              const struct intel_plane_state *state,
2278                                              int color_plane,
2279                                              u32 old_offset, u32 new_offset)
2280 {
2281         return intel_adjust_aligned_offset(x, y, state->base.fb, color_plane,
2282                                            state->base.rotation,
2283                                            state->color_plane[color_plane].stride,
2284                                            old_offset, new_offset);
2285 }
2286
2287 /*
2288  * Computes the aligned offset to the base tile and adjusts
2289  * x, y. bytes per pixel is assumed to be a power-of-two.
2290  *
2291  * In the 90/270 rotated case, x and y are assumed
2292  * to be already rotated to match the rotated GTT view, and
2293  * pitch is the tile_height aligned framebuffer height.
2294  *
2295  * This function is used when computing the derived information
2296  * under intel_framebuffer, so using any of that information
2297  * here is not allowed. Anything under drm_framebuffer can be
2298  * used. This is why the user has to pass in the pitch since it
2299  * is specified in the rotated orientation.
2300  */
2301 static u32 intel_compute_aligned_offset(struct drm_i915_private *dev_priv,
2302                                         int *x, int *y,
2303                                         const struct drm_framebuffer *fb,
2304                                         int color_plane,
2305                                         unsigned int pitch,
2306                                         unsigned int rotation,
2307                                         u32 alignment)
2308 {
2309         unsigned int cpp = fb->format->cpp[color_plane];
2310         u32 offset, offset_aligned;
2311
2312         if (alignment)
2313                 alignment--;
2314
2315         if (!is_surface_linear(fb->modifier, color_plane)) {
2316                 unsigned int tile_size, tile_width, tile_height;
2317                 unsigned int tile_rows, tiles, pitch_tiles;
2318
2319                 tile_size = intel_tile_size(dev_priv);
2320                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2321
2322                 if (drm_rotation_90_or_270(rotation)) {
2323                         pitch_tiles = pitch / tile_height;
2324                         swap(tile_width, tile_height);
2325                 } else {
2326                         pitch_tiles = pitch / (tile_width * cpp);
2327                 }
2328
2329                 tile_rows = *y / tile_height;
2330                 *y %= tile_height;
2331
2332                 tiles = *x / tile_width;
2333                 *x %= tile_width;
2334
2335                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2336                 offset_aligned = offset & ~alignment;
2337
2338                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2339                                          tile_size, pitch_tiles,
2340                                          offset, offset_aligned);
2341         } else {
2342                 offset = *y * pitch + *x * cpp;
2343                 offset_aligned = offset & ~alignment;
2344
2345                 *y = (offset & alignment) / pitch;
2346                 *x = ((offset & alignment) - *y * pitch) / cpp;
2347         }
2348
2349         return offset_aligned;
2350 }
2351
2352 static u32 intel_plane_compute_aligned_offset(int *x, int *y,
2353                                               const struct intel_plane_state *state,
2354                                               int color_plane)
2355 {
2356         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2357         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2358         const struct drm_framebuffer *fb = state->base.fb;
2359         unsigned int rotation = state->base.rotation;
2360         int pitch = state->color_plane[color_plane].stride;
2361         u32 alignment;
2362
2363         if (intel_plane->id == PLANE_CURSOR)
2364                 alignment = intel_cursor_alignment(dev_priv);
2365         else
2366                 alignment = intel_surf_alignment(fb, color_plane);
2367
2368         return intel_compute_aligned_offset(dev_priv, x, y, fb, color_plane,
2369                                             pitch, rotation, alignment);
2370 }
2371
2372 /* Convert the fb->offset[] into x/y offsets */
2373 static int intel_fb_offset_to_xy(int *x, int *y,
2374                                  const struct drm_framebuffer *fb,
2375                                  int color_plane)
2376 {
2377         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2378         unsigned int height;
2379
2380         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2381             fb->offsets[color_plane] % intel_tile_size(dev_priv)) {
2382                 DRM_DEBUG_KMS("Misaligned offset 0x%08x for color plane %d\n",
2383                               fb->offsets[color_plane], color_plane);
2384                 return -EINVAL;
2385         }
2386
2387         height = drm_framebuffer_plane_height(fb->height, fb, color_plane);
2388         height = ALIGN(height, intel_tile_height(fb, color_plane));
2389
2390         /* Catch potential overflows early */
2391         if (add_overflows_t(u32, mul_u32_u32(height, fb->pitches[color_plane]),
2392                             fb->offsets[color_plane])) {
2393                 DRM_DEBUG_KMS("Bad offset 0x%08x or pitch %d for color plane %d\n",
2394                               fb->offsets[color_plane], fb->pitches[color_plane],
2395                               color_plane);
2396                 return -ERANGE;
2397         }
2398
2399         *x = 0;
2400         *y = 0;
2401
2402         intel_adjust_aligned_offset(x, y,
2403                                     fb, color_plane, DRM_MODE_ROTATE_0,
2404                                     fb->pitches[color_plane],
2405                                     fb->offsets[color_plane], 0);
2406
2407         return 0;
2408 }
2409
2410 static unsigned int intel_fb_modifier_to_tiling(u64 fb_modifier)
2411 {
2412         switch (fb_modifier) {
2413         case I915_FORMAT_MOD_X_TILED:
2414                 return I915_TILING_X;
2415         case I915_FORMAT_MOD_Y_TILED:
2416         case I915_FORMAT_MOD_Y_TILED_CCS:
2417                 return I915_TILING_Y;
2418         default:
2419                 return I915_TILING_NONE;
2420         }
2421 }
2422
2423 /*
2424  * From the Sky Lake PRM:
2425  * "The Color Control Surface (CCS) contains the compression status of
2426  *  the cache-line pairs. The compression state of the cache-line pair
2427  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2428  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2429  *  cache-line-pairs. CCS is always Y tiled."
2430  *
2431  * Since cache line pairs refers to horizontally adjacent cache lines,
2432  * each cache line in the CCS corresponds to an area of 32x16 cache
2433  * lines on the main surface. Since each pixel is 4 bytes, this gives
2434  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2435  * main surface.
2436  */
2437 static const struct drm_format_info ccs_formats[] = {
2438         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2439         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2440         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2441         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2442 };
2443
2444 static const struct drm_format_info *
2445 lookup_format_info(const struct drm_format_info formats[],
2446                    int num_formats, u32 format)
2447 {
2448         int i;
2449
2450         for (i = 0; i < num_formats; i++) {
2451                 if (formats[i].format == format)
2452                         return &formats[i];
2453         }
2454
2455         return NULL;
2456 }
2457
2458 static const struct drm_format_info *
2459 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2460 {
2461         switch (cmd->modifier[0]) {
2462         case I915_FORMAT_MOD_Y_TILED_CCS:
2463         case I915_FORMAT_MOD_Yf_TILED_CCS:
2464                 return lookup_format_info(ccs_formats,
2465                                           ARRAY_SIZE(ccs_formats),
2466                                           cmd->pixel_format);
2467         default:
2468                 return NULL;
2469         }
2470 }
2471
2472 bool is_ccs_modifier(u64 modifier)
2473 {
2474         return modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2475                modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
2476 }
2477
2478 static int
2479 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2480                    struct drm_framebuffer *fb)
2481 {
2482         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2483         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2484         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2485         u32 gtt_offset_rotated = 0;
2486         unsigned int max_size = 0;
2487         int i, num_planes = fb->format->num_planes;
2488         unsigned int tile_size = intel_tile_size(dev_priv);
2489
2490         for (i = 0; i < num_planes; i++) {
2491                 unsigned int width, height;
2492                 unsigned int cpp, size;
2493                 u32 offset;
2494                 int x, y;
2495                 int ret;
2496
2497                 cpp = fb->format->cpp[i];
2498                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2499                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2500
2501                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2502                 if (ret) {
2503                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2504                                       i, fb->offsets[i]);
2505                         return ret;
2506                 }
2507
2508                 if (is_ccs_modifier(fb->modifier) && i == 1) {
2509                         int hsub = fb->format->hsub;
2510                         int vsub = fb->format->vsub;
2511                         int tile_width, tile_height;
2512                         int main_x, main_y;
2513                         int ccs_x, ccs_y;
2514
2515                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2516                         tile_width *= hsub;
2517                         tile_height *= vsub;
2518
2519                         ccs_x = (x * hsub) % tile_width;
2520                         ccs_y = (y * vsub) % tile_height;
2521                         main_x = intel_fb->normal[0].x % tile_width;
2522                         main_y = intel_fb->normal[0].y % tile_height;
2523
2524                         /*
2525                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2526                          * x/y offsets must match between CCS and the main surface.
2527                          */
2528                         if (main_x != ccs_x || main_y != ccs_y) {
2529                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2530                                               main_x, main_y,
2531                                               ccs_x, ccs_y,
2532                                               intel_fb->normal[0].x,
2533                                               intel_fb->normal[0].y,
2534                                               x, y);
2535                                 return -EINVAL;
2536                         }
2537                 }
2538
2539                 /*
2540                  * The fence (if used) is aligned to the start of the object
2541                  * so having the framebuffer wrap around across the edge of the
2542                  * fenced region doesn't really work. We have no API to configure
2543                  * the fence start offset within the object (nor could we probably
2544                  * on gen2/3). So it's just easier if we just require that the
2545                  * fb layout agrees with the fence layout. We already check that the
2546                  * fb stride matches the fence stride elsewhere.
2547                  */
2548                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2549                     (x + width) * cpp > fb->pitches[i]) {
2550                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2551                                       i, fb->offsets[i]);
2552                         return -EINVAL;
2553                 }
2554
2555                 /*
2556                  * First pixel of the framebuffer from
2557                  * the start of the normal gtt mapping.
2558                  */
2559                 intel_fb->normal[i].x = x;
2560                 intel_fb->normal[i].y = y;
2561
2562                 offset = intel_compute_aligned_offset(dev_priv, &x, &y, fb, i,
2563                                                       fb->pitches[i],
2564                                                       DRM_MODE_ROTATE_0,
2565                                                       tile_size);
2566                 offset /= tile_size;
2567
2568                 if (!is_surface_linear(fb->modifier, i)) {
2569                         unsigned int tile_width, tile_height;
2570                         unsigned int pitch_tiles;
2571                         struct drm_rect r;
2572
2573                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2574
2575                         rot_info->plane[i].offset = offset;
2576                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2577                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2578                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2579
2580                         intel_fb->rotated[i].pitch =
2581                                 rot_info->plane[i].height * tile_height;
2582
2583                         /* how many tiles does this plane need */
2584                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2585                         /*
2586                          * If the plane isn't horizontally tile aligned,
2587                          * we need one more tile.
2588                          */
2589                         if (x != 0)
2590                                 size++;
2591
2592                         /* rotate the x/y offsets to match the GTT view */
2593                         r.x1 = x;
2594                         r.y1 = y;
2595                         r.x2 = x + width;
2596                         r.y2 = y + height;
2597                         drm_rect_rotate(&r,
2598                                         rot_info->plane[i].width * tile_width,
2599                                         rot_info->plane[i].height * tile_height,
2600                                         DRM_MODE_ROTATE_270);
2601                         x = r.x1;
2602                         y = r.y1;
2603
2604                         /* rotate the tile dimensions to match the GTT view */
2605                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2606                         swap(tile_width, tile_height);
2607
2608                         /*
2609                          * We only keep the x/y offsets, so push all of the
2610                          * gtt offset into the x/y offsets.
2611                          */
2612                         intel_adjust_tile_offset(&x, &y,
2613                                                  tile_width, tile_height,
2614                                                  tile_size, pitch_tiles,
2615                                                  gtt_offset_rotated * tile_size, 0);
2616
2617                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2618
2619                         /*
2620                          * First pixel of the framebuffer from
2621                          * the start of the rotated gtt mapping.
2622                          */
2623                         intel_fb->rotated[i].x = x;
2624                         intel_fb->rotated[i].y = y;
2625                 } else {
2626                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2627                                             x * cpp, tile_size);
2628                 }
2629
2630                 /* how many tiles in total needed in the bo */
2631                 max_size = max(max_size, offset + size);
2632         }
2633
2634         if (mul_u32_u32(max_size, tile_size) > obj->base.size) {
2635                 DRM_DEBUG_KMS("fb too big for bo (need %llu bytes, have %zu bytes)\n",
2636                               mul_u32_u32(max_size, tile_size), obj->base.size);
2637                 return -EINVAL;
2638         }
2639
2640         return 0;
2641 }
2642
2643 static int i9xx_format_to_fourcc(int format)
2644 {
2645         switch (format) {
2646         case DISPPLANE_8BPP:
2647                 return DRM_FORMAT_C8;
2648         case DISPPLANE_BGRX555:
2649                 return DRM_FORMAT_XRGB1555;
2650         case DISPPLANE_BGRX565:
2651                 return DRM_FORMAT_RGB565;
2652         default:
2653         case DISPPLANE_BGRX888:
2654                 return DRM_FORMAT_XRGB8888;
2655         case DISPPLANE_RGBX888:
2656                 return DRM_FORMAT_XBGR8888;
2657         case DISPPLANE_BGRX101010:
2658                 return DRM_FORMAT_XRGB2101010;
2659         case DISPPLANE_RGBX101010:
2660                 return DRM_FORMAT_XBGR2101010;
2661         }
2662 }
2663
2664 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2665 {
2666         switch (format) {
2667         case PLANE_CTL_FORMAT_RGB_565:
2668                 return DRM_FORMAT_RGB565;
2669         case PLANE_CTL_FORMAT_NV12:
2670                 return DRM_FORMAT_NV12;
2671         default:
2672         case PLANE_CTL_FORMAT_XRGB_8888:
2673                 if (rgb_order) {
2674                         if (alpha)
2675                                 return DRM_FORMAT_ABGR8888;
2676                         else
2677                                 return DRM_FORMAT_XBGR8888;
2678                 } else {
2679                         if (alpha)
2680                                 return DRM_FORMAT_ARGB8888;
2681                         else
2682                                 return DRM_FORMAT_XRGB8888;
2683                 }
2684         case PLANE_CTL_FORMAT_XRGB_2101010:
2685                 if (rgb_order)
2686                         return DRM_FORMAT_XBGR2101010;
2687                 else
2688                         return DRM_FORMAT_XRGB2101010;
2689         }
2690 }
2691
2692 static bool
2693 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2694                               struct intel_initial_plane_config *plane_config)
2695 {
2696         struct drm_device *dev = crtc->base.dev;
2697         struct drm_i915_private *dev_priv = to_i915(dev);
2698         struct drm_i915_gem_object *obj = NULL;
2699         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2700         struct drm_framebuffer *fb = &plane_config->fb->base;
2701         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2702         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2703                                     PAGE_SIZE);
2704
2705         size_aligned -= base_aligned;
2706
2707         if (plane_config->size == 0)
2708                 return false;
2709
2710         /* If the FB is too big, just don't use it since fbdev is not very
2711          * important and we should probably use that space with FBC or other
2712          * features. */
2713         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2714                 return false;
2715
2716         switch (fb->modifier) {
2717         case DRM_FORMAT_MOD_LINEAR:
2718         case I915_FORMAT_MOD_X_TILED:
2719         case I915_FORMAT_MOD_Y_TILED:
2720                 break;
2721         default:
2722                 DRM_DEBUG_DRIVER("Unsupported modifier for initial FB: 0x%llx\n",
2723                                  fb->modifier);
2724                 return false;
2725         }
2726
2727         mutex_lock(&dev->struct_mutex);
2728         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2729                                                              base_aligned,
2730                                                              base_aligned,
2731                                                              size_aligned);
2732         mutex_unlock(&dev->struct_mutex);
2733         if (!obj)
2734                 return false;
2735
2736         switch (plane_config->tiling) {
2737         case I915_TILING_NONE:
2738                 break;
2739         case I915_TILING_X:
2740         case I915_TILING_Y:
2741                 obj->tiling_and_stride = fb->pitches[0] | plane_config->tiling;
2742                 break;
2743         default:
2744                 MISSING_CASE(plane_config->tiling);
2745                 return false;
2746         }
2747
2748         mode_cmd.pixel_format = fb->format->format;
2749         mode_cmd.width = fb->width;
2750         mode_cmd.height = fb->height;
2751         mode_cmd.pitches[0] = fb->pitches[0];
2752         mode_cmd.modifier[0] = fb->modifier;
2753         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2754
2755         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2756                 DRM_DEBUG_KMS("intel fb init failed\n");
2757                 goto out_unref_obj;
2758         }
2759
2760
2761         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2762         return true;
2763
2764 out_unref_obj:
2765         i915_gem_object_put(obj);
2766         return false;
2767 }
2768
2769 static void
2770 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2771                         struct intel_plane_state *plane_state,
2772                         bool visible)
2773 {
2774         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2775
2776         plane_state->base.visible = visible;
2777
2778         if (visible)
2779                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
2780         else
2781                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
2782 }
2783
2784 static void fixup_active_planes(struct intel_crtc_state *crtc_state)
2785 {
2786         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
2787         struct drm_plane *plane;
2788
2789         /*
2790          * Active_planes aliases if multiple "primary" or cursor planes
2791          * have been used on the same (or wrong) pipe. plane_mask uses
2792          * unique ids, hence we can use that to reconstruct active_planes.
2793          */
2794         crtc_state->active_planes = 0;
2795
2796         drm_for_each_plane_mask(plane, &dev_priv->drm,
2797                                 crtc_state->base.plane_mask)
2798                 crtc_state->active_planes |= BIT(to_intel_plane(plane)->id);
2799 }
2800
2801 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2802                                          struct intel_plane *plane)
2803 {
2804         struct intel_crtc_state *crtc_state =
2805                 to_intel_crtc_state(crtc->base.state);
2806         struct intel_plane_state *plane_state =
2807                 to_intel_plane_state(plane->base.state);
2808
2809         DRM_DEBUG_KMS("Disabling [PLANE:%d:%s] on [CRTC:%d:%s]\n",
2810                       plane->base.base.id, plane->base.name,
2811                       crtc->base.base.id, crtc->base.name);
2812
2813         intel_set_plane_visible(crtc_state, plane_state, false);
2814         fixup_active_planes(crtc_state);
2815
2816         if (plane->id == PLANE_PRIMARY)
2817                 intel_pre_disable_primary_noatomic(&crtc->base);
2818
2819         trace_intel_disable_plane(&plane->base, crtc);
2820         plane->disable_plane(plane, crtc_state);
2821 }
2822
2823 static void
2824 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2825                              struct intel_initial_plane_config *plane_config)
2826 {
2827         struct drm_device *dev = intel_crtc->base.dev;
2828         struct drm_i915_private *dev_priv = to_i915(dev);
2829         struct drm_crtc *c;
2830         struct drm_i915_gem_object *obj;
2831         struct drm_plane *primary = intel_crtc->base.primary;
2832         struct drm_plane_state *plane_state = primary->state;
2833         struct intel_plane *intel_plane = to_intel_plane(primary);
2834         struct intel_plane_state *intel_state =
2835                 to_intel_plane_state(plane_state);
2836         struct drm_framebuffer *fb;
2837
2838         if (!plane_config->fb)
2839                 return;
2840
2841         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2842                 fb = &plane_config->fb->base;
2843                 goto valid_fb;
2844         }
2845
2846         kfree(plane_config->fb);
2847
2848         /*
2849          * Failed to alloc the obj, check to see if we should share
2850          * an fb with another CRTC instead
2851          */
2852         for_each_crtc(dev, c) {
2853                 struct intel_plane_state *state;
2854
2855                 if (c == &intel_crtc->base)
2856                         continue;
2857
2858                 if (!to_intel_crtc(c)->active)
2859                         continue;
2860
2861                 state = to_intel_plane_state(c->primary->state);
2862                 if (!state->vma)
2863                         continue;
2864
2865                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2866                         fb = state->base.fb;
2867                         drm_framebuffer_get(fb);
2868                         goto valid_fb;
2869                 }
2870         }
2871
2872         /*
2873          * We've failed to reconstruct the BIOS FB.  Current display state
2874          * indicates that the primary plane is visible, but has a NULL FB,
2875          * which will lead to problems later if we don't fix it up.  The
2876          * simplest solution is to just disable the primary plane now and
2877          * pretend the BIOS never had it enabled.
2878          */
2879         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2880
2881         return;
2882
2883 valid_fb:
2884         intel_state->base.rotation = plane_config->rotation;
2885         intel_fill_fb_ggtt_view(&intel_state->view, fb,
2886                                 intel_state->base.rotation);
2887         intel_state->color_plane[0].stride =
2888                 intel_fb_pitch(fb, 0, intel_state->base.rotation);
2889
2890         mutex_lock(&dev->struct_mutex);
2891         intel_state->vma =
2892                 intel_pin_and_fence_fb_obj(fb,
2893                                            &intel_state->view,
2894                                            intel_plane_uses_fence(intel_state),
2895                                            &intel_state->flags);
2896         mutex_unlock(&dev->struct_mutex);
2897         if (IS_ERR(intel_state->vma)) {
2898                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2899                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2900
2901                 intel_state->vma = NULL;
2902                 drm_framebuffer_put(fb);
2903                 return;
2904         }
2905
2906         obj = intel_fb_obj(fb);
2907         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
2908
2909         plane_state->src_x = 0;
2910         plane_state->src_y = 0;
2911         plane_state->src_w = fb->width << 16;
2912         plane_state->src_h = fb->height << 16;
2913
2914         plane_state->crtc_x = 0;
2915         plane_state->crtc_y = 0;
2916         plane_state->crtc_w = fb->width;
2917         plane_state->crtc_h = fb->height;
2918
2919         intel_state->base.src = drm_plane_state_src(plane_state);
2920         intel_state->base.dst = drm_plane_state_dest(plane_state);
2921
2922         if (i915_gem_object_is_tiled(obj))
2923                 dev_priv->preserve_bios_swizzle = true;
2924
2925         plane_state->fb = fb;
2926         plane_state->crtc = &intel_crtc->base;
2927
2928         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2929                   &obj->frontbuffer_bits);
2930 }
2931
2932 static int skl_max_plane_width(const struct drm_framebuffer *fb,
2933                                int color_plane,
2934                                unsigned int rotation)
2935 {
2936         int cpp = fb->format->cpp[color_plane];
2937
2938         switch (fb->modifier) {
2939         case DRM_FORMAT_MOD_LINEAR:
2940         case I915_FORMAT_MOD_X_TILED:
2941                 switch (cpp) {
2942                 case 8:
2943                         return 4096;
2944                 case 4:
2945                 case 2:
2946                 case 1:
2947                         return 8192;
2948                 default:
2949                         MISSING_CASE(cpp);
2950                         break;
2951                 }
2952                 break;
2953         case I915_FORMAT_MOD_Y_TILED_CCS:
2954         case I915_FORMAT_MOD_Yf_TILED_CCS:
2955                 /* FIXME AUX plane? */
2956         case I915_FORMAT_MOD_Y_TILED:
2957         case I915_FORMAT_MOD_Yf_TILED:
2958                 switch (cpp) {
2959                 case 8:
2960                         return 2048;
2961                 case 4:
2962                         return 4096;
2963                 case 2:
2964                 case 1:
2965                         return 8192;
2966                 default:
2967                         MISSING_CASE(cpp);
2968                         break;
2969                 }
2970                 break;
2971         default:
2972                 MISSING_CASE(fb->modifier);
2973         }
2974
2975         return 2048;
2976 }
2977
2978 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2979                                            int main_x, int main_y, u32 main_offset)
2980 {
2981         const struct drm_framebuffer *fb = plane_state->base.fb;
2982         int hsub = fb->format->hsub;
2983         int vsub = fb->format->vsub;
2984         int aux_x = plane_state->color_plane[1].x;
2985         int aux_y = plane_state->color_plane[1].y;
2986         u32 aux_offset = plane_state->color_plane[1].offset;
2987         u32 alignment = intel_surf_alignment(fb, 1);
2988
2989         while (aux_offset >= main_offset && aux_y <= main_y) {
2990                 int x, y;
2991
2992                 if (aux_x == main_x && aux_y == main_y)
2993                         break;
2994
2995                 if (aux_offset == 0)
2996                         break;
2997
2998                 x = aux_x / hsub;
2999                 y = aux_y / vsub;
3000                 aux_offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 1,
3001                                                                aux_offset, aux_offset - alignment);
3002                 aux_x = x * hsub + aux_x % hsub;
3003                 aux_y = y * vsub + aux_y % vsub;
3004         }
3005
3006         if (aux_x != main_x || aux_y != main_y)
3007                 return false;
3008
3009         plane_state->color_plane[1].offset = aux_offset;
3010         plane_state->color_plane[1].x = aux_x;
3011         plane_state->color_plane[1].y = aux_y;
3012
3013         return true;
3014 }
3015
3016 static int skl_check_main_surface(struct intel_plane_state *plane_state)
3017 {
3018         const struct drm_framebuffer *fb = plane_state->base.fb;
3019         unsigned int rotation = plane_state->base.rotation;
3020         int x = plane_state->base.src.x1 >> 16;
3021         int y = plane_state->base.src.y1 >> 16;
3022         int w = drm_rect_width(&plane_state->base.src) >> 16;
3023         int h = drm_rect_height(&plane_state->base.src) >> 16;
3024         int max_width = skl_max_plane_width(fb, 0, rotation);
3025         int max_height = 4096;
3026         u32 alignment, offset, aux_offset = plane_state->color_plane[1].offset;
3027
3028         if (w > max_width || h > max_height) {
3029                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
3030                               w, h, max_width, max_height);
3031                 return -EINVAL;
3032         }
3033
3034         intel_add_fb_offsets(&x, &y, plane_state, 0);
3035         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 0);
3036         alignment = intel_surf_alignment(fb, 0);
3037
3038         /*
3039          * AUX surface offset is specified as the distance from the
3040          * main surface offset, and it must be non-negative. Make
3041          * sure that is what we will get.
3042          */
3043         if (offset > aux_offset)
3044                 offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3045                                                            offset, aux_offset & ~(alignment - 1));
3046
3047         /*
3048          * When using an X-tiled surface, the plane blows up
3049          * if the x offset + width exceed the stride.
3050          *
3051          * TODO: linear and Y-tiled seem fine, Yf untested,
3052          */
3053         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3054                 int cpp = fb->format->cpp[0];
3055
3056                 while ((x + w) * cpp > plane_state->color_plane[0].stride) {
3057                         if (offset == 0) {
3058                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3059                                 return -EINVAL;
3060                         }
3061
3062                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3063                                                                    offset, offset - alignment);
3064                 }
3065         }
3066
3067         /*
3068          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3069          * they match with the main surface x/y offsets.
3070          */
3071         if (is_ccs_modifier(fb->modifier)) {
3072                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3073                         if (offset == 0)
3074                                 break;
3075
3076                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3077                                                                    offset, offset - alignment);
3078                 }
3079
3080                 if (x != plane_state->color_plane[1].x || y != plane_state->color_plane[1].y) {
3081                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3082                         return -EINVAL;
3083                 }
3084         }
3085
3086         plane_state->color_plane[0].offset = offset;
3087         plane_state->color_plane[0].x = x;
3088         plane_state->color_plane[0].y = y;
3089
3090         return 0;
3091 }
3092
3093 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3094 {
3095         const struct drm_framebuffer *fb = plane_state->base.fb;
3096         unsigned int rotation = plane_state->base.rotation;
3097         int max_width = skl_max_plane_width(fb, 1, rotation);
3098         int max_height = 4096;
3099         int x = plane_state->base.src.x1 >> 17;
3100         int y = plane_state->base.src.y1 >> 17;
3101         int w = drm_rect_width(&plane_state->base.src) >> 17;
3102         int h = drm_rect_height(&plane_state->base.src) >> 17;
3103         u32 offset;
3104
3105         intel_add_fb_offsets(&x, &y, plane_state, 1);
3106         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3107
3108         /* FIXME not quite sure how/if these apply to the chroma plane */
3109         if (w > max_width || h > max_height) {
3110                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3111                               w, h, max_width, max_height);
3112                 return -EINVAL;
3113         }
3114
3115         plane_state->color_plane[1].offset = offset;
3116         plane_state->color_plane[1].x = x;
3117         plane_state->color_plane[1].y = y;
3118
3119         return 0;
3120 }
3121
3122 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3123 {
3124         const struct drm_framebuffer *fb = plane_state->base.fb;
3125         int src_x = plane_state->base.src.x1 >> 16;
3126         int src_y = plane_state->base.src.y1 >> 16;
3127         int hsub = fb->format->hsub;
3128         int vsub = fb->format->vsub;
3129         int x = src_x / hsub;
3130         int y = src_y / vsub;
3131         u32 offset;
3132
3133         intel_add_fb_offsets(&x, &y, plane_state, 1);
3134         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3135
3136         plane_state->color_plane[1].offset = offset;
3137         plane_state->color_plane[1].x = x * hsub + src_x % hsub;
3138         plane_state->color_plane[1].y = y * vsub + src_y % vsub;
3139
3140         return 0;
3141 }
3142
3143 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3144 {
3145         const struct drm_framebuffer *fb = plane_state->base.fb;
3146         unsigned int rotation = plane_state->base.rotation;
3147         int ret;
3148
3149         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3150         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3151         plane_state->color_plane[1].stride = intel_fb_pitch(fb, 1, rotation);
3152
3153         ret = intel_plane_check_stride(plane_state);
3154         if (ret)
3155                 return ret;
3156
3157         if (!plane_state->base.visible)
3158                 return 0;
3159
3160         /* Rotate src coordinates to match rotated GTT view */
3161         if (drm_rotation_90_or_270(rotation))
3162                 drm_rect_rotate(&plane_state->base.src,
3163                                 fb->width << 16, fb->height << 16,
3164                                 DRM_MODE_ROTATE_270);
3165
3166         /*
3167          * Handle the AUX surface first since
3168          * the main surface setup depends on it.
3169          */
3170         if (fb->format->format == DRM_FORMAT_NV12) {
3171                 ret = skl_check_nv12_aux_surface(plane_state);
3172                 if (ret)
3173                         return ret;
3174         } else if (is_ccs_modifier(fb->modifier)) {
3175                 ret = skl_check_ccs_aux_surface(plane_state);
3176                 if (ret)
3177                         return ret;
3178         } else {
3179                 plane_state->color_plane[1].offset = ~0xfff;
3180                 plane_state->color_plane[1].x = 0;
3181                 plane_state->color_plane[1].y = 0;
3182         }
3183
3184         ret = skl_check_main_surface(plane_state);
3185         if (ret)
3186                 return ret;
3187
3188         return 0;
3189 }
3190
3191 unsigned int
3192 i9xx_plane_max_stride(struct intel_plane *plane,
3193                       u32 pixel_format, u64 modifier,
3194                       unsigned int rotation)
3195 {
3196         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3197
3198         if (!HAS_GMCH_DISPLAY(dev_priv)) {
3199                 return 32*1024;
3200         } else if (INTEL_GEN(dev_priv) >= 4) {
3201                 if (modifier == I915_FORMAT_MOD_X_TILED)
3202                         return 16*1024;
3203                 else
3204                         return 32*1024;
3205         } else if (INTEL_GEN(dev_priv) >= 3) {
3206                 if (modifier == I915_FORMAT_MOD_X_TILED)
3207                         return 8*1024;
3208                 else
3209                         return 16*1024;
3210         } else {
3211                 if (plane->i9xx_plane == PLANE_C)
3212                         return 4*1024;
3213                 else
3214                         return 8*1024;
3215         }
3216 }
3217
3218 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3219                           const struct intel_plane_state *plane_state)
3220 {
3221         struct drm_i915_private *dev_priv =
3222                 to_i915(plane_state->base.plane->dev);
3223         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3224         const struct drm_framebuffer *fb = plane_state->base.fb;
3225         unsigned int rotation = plane_state->base.rotation;
3226         u32 dspcntr;
3227
3228         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3229
3230         if (IS_G4X(dev_priv) || IS_GEN(dev_priv, 5) ||
3231             IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
3232                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3233
3234         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3235                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3236
3237         if (INTEL_GEN(dev_priv) < 5)
3238                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3239
3240         switch (fb->format->format) {
3241         case DRM_FORMAT_C8:
3242                 dspcntr |= DISPPLANE_8BPP;
3243                 break;
3244         case DRM_FORMAT_XRGB1555:
3245                 dspcntr |= DISPPLANE_BGRX555;
3246                 break;
3247         case DRM_FORMAT_RGB565:
3248                 dspcntr |= DISPPLANE_BGRX565;
3249                 break;
3250         case DRM_FORMAT_XRGB8888:
3251                 dspcntr |= DISPPLANE_BGRX888;
3252                 break;
3253         case DRM_FORMAT_XBGR8888:
3254                 dspcntr |= DISPPLANE_RGBX888;
3255                 break;
3256         case DRM_FORMAT_XRGB2101010:
3257                 dspcntr |= DISPPLANE_BGRX101010;
3258                 break;
3259         case DRM_FORMAT_XBGR2101010:
3260                 dspcntr |= DISPPLANE_RGBX101010;
3261                 break;
3262         default:
3263                 MISSING_CASE(fb->format->format);
3264                 return 0;
3265         }
3266
3267         if (INTEL_GEN(dev_priv) >= 4 &&
3268             fb->modifier == I915_FORMAT_MOD_X_TILED)
3269                 dspcntr |= DISPPLANE_TILED;
3270
3271         if (rotation & DRM_MODE_ROTATE_180)
3272                 dspcntr |= DISPPLANE_ROTATE_180;
3273
3274         if (rotation & DRM_MODE_REFLECT_X)
3275                 dspcntr |= DISPPLANE_MIRROR;
3276
3277         return dspcntr;
3278 }
3279
3280 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3281 {
3282         struct drm_i915_private *dev_priv =
3283                 to_i915(plane_state->base.plane->dev);
3284         const struct drm_framebuffer *fb = plane_state->base.fb;
3285         unsigned int rotation = plane_state->base.rotation;
3286         int src_x = plane_state->base.src.x1 >> 16;
3287         int src_y = plane_state->base.src.y1 >> 16;
3288         u32 offset;
3289         int ret;
3290
3291         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3292         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3293
3294         ret = intel_plane_check_stride(plane_state);
3295         if (ret)
3296                 return ret;
3297
3298         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3299
3300         if (INTEL_GEN(dev_priv) >= 4)
3301                 offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
3302                                                             plane_state, 0);
3303         else
3304                 offset = 0;
3305
3306         /* HSW/BDW do this automagically in hardware */
3307         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3308                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3309                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3310
3311                 if (rotation & DRM_MODE_ROTATE_180) {
3312                         src_x += src_w - 1;
3313                         src_y += src_h - 1;
3314                 } else if (rotation & DRM_MODE_REFLECT_X) {
3315                         src_x += src_w - 1;
3316                 }
3317         }
3318
3319         plane_state->color_plane[0].offset = offset;
3320         plane_state->color_plane[0].x = src_x;
3321         plane_state->color_plane[0].y = src_y;
3322
3323         return 0;
3324 }
3325
3326 static int
3327 i9xx_plane_check(struct intel_crtc_state *crtc_state,
3328                  struct intel_plane_state *plane_state)
3329 {
3330         int ret;
3331
3332         ret = chv_plane_check_rotation(plane_state);
3333         if (ret)
3334                 return ret;
3335
3336         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
3337                                                   &crtc_state->base,
3338                                                   DRM_PLANE_HELPER_NO_SCALING,
3339                                                   DRM_PLANE_HELPER_NO_SCALING,
3340                                                   false, true);
3341         if (ret)
3342                 return ret;
3343
3344         if (!plane_state->base.visible)
3345                 return 0;
3346
3347         ret = intel_plane_check_src_coordinates(plane_state);
3348         if (ret)
3349                 return ret;
3350
3351         ret = i9xx_check_plane_surface(plane_state);
3352         if (ret)
3353                 return ret;
3354
3355         plane_state->ctl = i9xx_plane_ctl(crtc_state, plane_state);
3356
3357         return 0;
3358 }
3359
3360 static void i9xx_update_plane(struct intel_plane *plane,
3361                               const struct intel_crtc_state *crtc_state,
3362                               const struct intel_plane_state *plane_state)
3363 {
3364         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3365         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3366         u32 linear_offset;
3367         u32 dspcntr = plane_state->ctl;
3368         int x = plane_state->color_plane[0].x;
3369         int y = plane_state->color_plane[0].y;
3370         unsigned long irqflags;
3371         u32 dspaddr_offset;
3372
3373         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3374
3375         if (INTEL_GEN(dev_priv) >= 4)
3376                 dspaddr_offset = plane_state->color_plane[0].offset;
3377         else
3378                 dspaddr_offset = linear_offset;
3379
3380         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3381
3382         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), plane_state->color_plane[0].stride);
3383
3384         if (INTEL_GEN(dev_priv) < 4) {
3385                 /* pipesrc and dspsize control the size that is scaled from,
3386                  * which should always be the user's requested size.
3387                  */
3388                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3389                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3390                               ((crtc_state->pipe_src_h - 1) << 16) |
3391                               (crtc_state->pipe_src_w - 1));
3392         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3393                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3394                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3395                               ((crtc_state->pipe_src_h - 1) << 16) |
3396                               (crtc_state->pipe_src_w - 1));
3397                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3398         }
3399
3400         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3401                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3402         } else if (INTEL_GEN(dev_priv) >= 4) {
3403                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3404                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3405         }
3406
3407         /*
3408          * The control register self-arms if the plane was previously
3409          * disabled. Try to make the plane enable atomic by writing
3410          * the control register just before the surface register.
3411          */
3412         I915_WRITE_FW(DSPCNTR(i9xx_plane), dspcntr);
3413         if (INTEL_GEN(dev_priv) >= 4)
3414                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3415                               intel_plane_ggtt_offset(plane_state) +
3416                               dspaddr_offset);
3417         else
3418                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3419                               intel_plane_ggtt_offset(plane_state) +
3420                               dspaddr_offset);
3421
3422         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3423 }
3424
3425 static void i9xx_disable_plane(struct intel_plane *plane,
3426                                const struct intel_crtc_state *crtc_state)
3427 {
3428         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3429         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3430         unsigned long irqflags;
3431
3432         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3433
3434         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3435         if (INTEL_GEN(dev_priv) >= 4)
3436                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3437         else
3438                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3439
3440         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3441 }
3442
3443 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3444                                     enum pipe *pipe)
3445 {
3446         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3447         enum intel_display_power_domain power_domain;
3448         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3449         intel_wakeref_t wakeref;
3450         bool ret;
3451         u32 val;
3452
3453         /*
3454          * Not 100% correct for planes that can move between pipes,
3455          * but that's only the case for gen2-4 which don't have any
3456          * display power wells.
3457          */
3458         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3459         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
3460         if (!wakeref)
3461                 return false;
3462
3463         val = I915_READ(DSPCNTR(i9xx_plane));
3464
3465         ret = val & DISPLAY_PLANE_ENABLE;
3466
3467         if (INTEL_GEN(dev_priv) >= 5)
3468                 *pipe = plane->pipe;
3469         else
3470                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3471                         DISPPLANE_SEL_PIPE_SHIFT;
3472
3473         intel_display_power_put(dev_priv, power_domain, wakeref);
3474
3475         return ret;
3476 }
3477
3478 static u32
3479 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int color_plane)
3480 {
3481         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3482                 return 64;
3483         else
3484                 return intel_tile_width_bytes(fb, color_plane);
3485 }
3486
3487 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3488 {
3489         struct drm_device *dev = intel_crtc->base.dev;
3490         struct drm_i915_private *dev_priv = to_i915(dev);
3491
3492         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3493         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3494         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3495 }
3496
3497 /*
3498  * This function detaches (aka. unbinds) unused scalers in hardware
3499  */
3500 static void skl_detach_scalers(const struct intel_crtc_state *crtc_state)
3501 {
3502         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3503         const struct intel_crtc_scaler_state *scaler_state =
3504                 &crtc_state->scaler_state;
3505         int i;
3506
3507         /* loop through and disable scalers that aren't in use */
3508         for (i = 0; i < intel_crtc->num_scalers; i++) {
3509                 if (!scaler_state->scalers[i].in_use)
3510                         skl_detach_scaler(intel_crtc, i);
3511         }
3512 }
3513
3514 static unsigned int skl_plane_stride_mult(const struct drm_framebuffer *fb,
3515                                           int color_plane, unsigned int rotation)
3516 {
3517         /*
3518          * The stride is either expressed as a multiple of 64 bytes chunks for
3519          * linear buffers or in number of tiles for tiled buffers.
3520          */
3521         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3522                 return 64;
3523         else if (drm_rotation_90_or_270(rotation))
3524                 return intel_tile_height(fb, color_plane);
3525         else
3526                 return intel_tile_width_bytes(fb, color_plane);
3527 }
3528
3529 u32 skl_plane_stride(const struct intel_plane_state *plane_state,
3530                      int color_plane)
3531 {
3532         const struct drm_framebuffer *fb = plane_state->base.fb;
3533         unsigned int rotation = plane_state->base.rotation;
3534         u32 stride = plane_state->color_plane[color_plane].stride;
3535
3536         if (color_plane >= fb->format->num_planes)
3537                 return 0;
3538
3539         return stride / skl_plane_stride_mult(fb, color_plane, rotation);
3540 }
3541
3542 static u32 skl_plane_ctl_format(u32 pixel_format)
3543 {
3544         switch (pixel_format) {
3545         case DRM_FORMAT_C8:
3546                 return PLANE_CTL_FORMAT_INDEXED;
3547         case DRM_FORMAT_RGB565:
3548                 return PLANE_CTL_FORMAT_RGB_565;
3549         case DRM_FORMAT_XBGR8888:
3550         case DRM_FORMAT_ABGR8888:
3551                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3552         case DRM_FORMAT_XRGB8888:
3553         case DRM_FORMAT_ARGB8888:
3554                 return PLANE_CTL_FORMAT_XRGB_8888;
3555         case DRM_FORMAT_XRGB2101010:
3556                 return PLANE_CTL_FORMAT_XRGB_2101010;
3557         case DRM_FORMAT_XBGR2101010:
3558                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3559         case DRM_FORMAT_YUYV:
3560                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3561         case DRM_FORMAT_YVYU:
3562                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3563         case DRM_FORMAT_UYVY:
3564                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3565         case DRM_FORMAT_VYUY:
3566                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3567         case DRM_FORMAT_NV12:
3568                 return PLANE_CTL_FORMAT_NV12;
3569         default:
3570                 MISSING_CASE(pixel_format);
3571         }
3572
3573         return 0;
3574 }
3575
3576 static u32 skl_plane_ctl_alpha(const struct intel_plane_state *plane_state)
3577 {
3578         if (!plane_state->base.fb->format->has_alpha)
3579                 return PLANE_CTL_ALPHA_DISABLE;
3580
3581         switch (plane_state->base.pixel_blend_mode) {
3582         case DRM_MODE_BLEND_PIXEL_NONE:
3583                 return PLANE_CTL_ALPHA_DISABLE;
3584         case DRM_MODE_BLEND_PREMULTI:
3585                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3586         case DRM_MODE_BLEND_COVERAGE:
3587                 return PLANE_CTL_ALPHA_HW_PREMULTIPLY;
3588         default:
3589                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3590                 return PLANE_CTL_ALPHA_DISABLE;
3591         }
3592 }
3593
3594 static u32 glk_plane_color_ctl_alpha(const struct intel_plane_state *plane_state)
3595 {
3596         if (!plane_state->base.fb->format->has_alpha)
3597                 return PLANE_COLOR_ALPHA_DISABLE;
3598
3599         switch (plane_state->base.pixel_blend_mode) {
3600         case DRM_MODE_BLEND_PIXEL_NONE:
3601                 return PLANE_COLOR_ALPHA_DISABLE;
3602         case DRM_MODE_BLEND_PREMULTI:
3603                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3604         case DRM_MODE_BLEND_COVERAGE:
3605                 return PLANE_COLOR_ALPHA_HW_PREMULTIPLY;
3606         default:
3607                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3608                 return PLANE_COLOR_ALPHA_DISABLE;
3609         }
3610 }
3611
3612 static u32 skl_plane_ctl_tiling(u64 fb_modifier)
3613 {
3614         switch (fb_modifier) {
3615         case DRM_FORMAT_MOD_LINEAR:
3616                 break;
3617         case I915_FORMAT_MOD_X_TILED:
3618                 return PLANE_CTL_TILED_X;
3619         case I915_FORMAT_MOD_Y_TILED:
3620                 return PLANE_CTL_TILED_Y;
3621         case I915_FORMAT_MOD_Y_TILED_CCS:
3622                 return PLANE_CTL_TILED_Y | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3623         case I915_FORMAT_MOD_Yf_TILED:
3624                 return PLANE_CTL_TILED_YF;
3625         case I915_FORMAT_MOD_Yf_TILED_CCS:
3626                 return PLANE_CTL_TILED_YF | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3627         default:
3628                 MISSING_CASE(fb_modifier);
3629         }
3630
3631         return 0;
3632 }
3633
3634 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3635 {
3636         switch (rotate) {
3637         case DRM_MODE_ROTATE_0:
3638                 break;
3639         /*
3640          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3641          * while i915 HW rotation is clockwise, thats why this swapping.
3642          */
3643         case DRM_MODE_ROTATE_90:
3644                 return PLANE_CTL_ROTATE_270;
3645         case DRM_MODE_ROTATE_180:
3646                 return PLANE_CTL_ROTATE_180;
3647         case DRM_MODE_ROTATE_270:
3648                 return PLANE_CTL_ROTATE_90;
3649         default:
3650                 MISSING_CASE(rotate);
3651         }
3652
3653         return 0;
3654 }
3655
3656 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3657 {
3658         switch (reflect) {
3659         case 0:
3660                 break;
3661         case DRM_MODE_REFLECT_X:
3662                 return PLANE_CTL_FLIP_HORIZONTAL;
3663         case DRM_MODE_REFLECT_Y:
3664         default:
3665                 MISSING_CASE(reflect);
3666         }
3667
3668         return 0;
3669 }
3670
3671 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3672                   const struct intel_plane_state *plane_state)
3673 {
3674         struct drm_i915_private *dev_priv =
3675                 to_i915(plane_state->base.plane->dev);
3676         const struct drm_framebuffer *fb = plane_state->base.fb;
3677         unsigned int rotation = plane_state->base.rotation;
3678         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3679         u32 plane_ctl;
3680
3681         plane_ctl = PLANE_CTL_ENABLE;
3682
3683         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3684                 plane_ctl |= skl_plane_ctl_alpha(plane_state);
3685                 plane_ctl |=
3686                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3687                         PLANE_CTL_PIPE_CSC_ENABLE |
3688                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3689
3690                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3691                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3692
3693                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3694                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3695         }
3696
3697         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3698         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3699         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3700
3701         if (INTEL_GEN(dev_priv) >= 10)
3702                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3703                                                 DRM_MODE_REFLECT_MASK);
3704
3705         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3706                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3707         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3708                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3709
3710         return plane_ctl;
3711 }
3712
3713 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3714                         const struct intel_plane_state *plane_state)
3715 {
3716         struct drm_i915_private *dev_priv =
3717                 to_i915(plane_state->base.plane->dev);
3718         const struct drm_framebuffer *fb = plane_state->base.fb;
3719         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3720         u32 plane_color_ctl = 0;
3721
3722         if (INTEL_GEN(dev_priv) < 11) {
3723                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3724                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3725         }
3726         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3727         plane_color_ctl |= glk_plane_color_ctl_alpha(plane_state);
3728
3729         if (fb->format->is_yuv && !icl_is_hdr_plane(plane)) {
3730                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3731                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3732                 else
3733                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3734
3735                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3736                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3737         } else if (fb->format->is_yuv) {
3738                 plane_color_ctl |= PLANE_COLOR_INPUT_CSC_ENABLE;
3739         }
3740
3741         return plane_color_ctl;
3742 }
3743
3744 static int
3745 __intel_display_resume(struct drm_device *dev,
3746                        struct drm_atomic_state *state,
3747                        struct drm_modeset_acquire_ctx *ctx)
3748 {
3749         struct drm_crtc_state *crtc_state;
3750         struct drm_crtc *crtc;
3751         int i, ret;
3752
3753         intel_modeset_setup_hw_state(dev, ctx);
3754         i915_redisable_vga(to_i915(dev));
3755
3756         if (!state)
3757                 return 0;
3758
3759         /*
3760          * We've duplicated the state, pointers to the old state are invalid.
3761          *
3762          * Don't attempt to use the old state until we commit the duplicated state.
3763          */
3764         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3765                 /*
3766                  * Force recalculation even if we restore
3767                  * current state. With fast modeset this may not result
3768                  * in a modeset when the state is compatible.
3769                  */
3770                 crtc_state->mode_changed = true;
3771         }
3772
3773         /* ignore any reset values/BIOS leftovers in the WM registers */
3774         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3775                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3776
3777         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3778
3779         WARN_ON(ret == -EDEADLK);
3780         return ret;
3781 }
3782
3783 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3784 {
3785         return (INTEL_INFO(dev_priv)->gpu_reset_clobbers_display &&
3786                 intel_has_gpu_reset(dev_priv));
3787 }
3788
3789 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3790 {
3791         struct drm_device *dev = &dev_priv->drm;
3792         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3793         struct drm_atomic_state *state;
3794         int ret;
3795
3796         /* reset doesn't touch the display */
3797         if (!i915_modparams.force_reset_modeset_test &&
3798             !gpu_reset_clobbers_display(dev_priv))
3799                 return;
3800
3801         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3802         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3803         wake_up_all(&dev_priv->gpu_error.wait_queue);
3804
3805         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3806                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3807                 i915_gem_set_wedged(dev_priv);
3808         }
3809
3810         /*
3811          * Need mode_config.mutex so that we don't
3812          * trample ongoing ->detect() and whatnot.
3813          */
3814         mutex_lock(&dev->mode_config.mutex);
3815         drm_modeset_acquire_init(ctx, 0);
3816         while (1) {
3817                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3818                 if (ret != -EDEADLK)
3819                         break;
3820
3821                 drm_modeset_backoff(ctx);
3822         }
3823         /*
3824          * Disabling the crtcs gracefully seems nicer. Also the
3825          * g33 docs say we should at least disable all the planes.
3826          */
3827         state = drm_atomic_helper_duplicate_state(dev, ctx);
3828         if (IS_ERR(state)) {
3829                 ret = PTR_ERR(state);
3830                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3831                 return;
3832         }
3833
3834         ret = drm_atomic_helper_disable_all(dev, ctx);
3835         if (ret) {
3836                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3837                 drm_atomic_state_put(state);
3838                 return;
3839         }
3840
3841         dev_priv->modeset_restore_state = state;
3842         state->acquire_ctx = ctx;
3843 }
3844
3845 void intel_finish_reset(struct drm_i915_private *dev_priv)
3846 {
3847         struct drm_device *dev = &dev_priv->drm;
3848         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3849         struct drm_atomic_state *state;
3850         int ret;
3851
3852         /* reset doesn't touch the display */
3853         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
3854                 return;
3855
3856         state = fetch_and_zero(&dev_priv->modeset_restore_state);
3857         if (!state)
3858                 goto unlock;
3859
3860         /* reset doesn't touch the display */
3861         if (!gpu_reset_clobbers_display(dev_priv)) {
3862                 /* for testing only restore the display */
3863                 ret = __intel_display_resume(dev, state, ctx);
3864                 if (ret)
3865                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3866         } else {
3867                 /*
3868                  * The display has been reset as well,
3869                  * so need a full re-initialization.
3870                  */
3871                 intel_runtime_pm_disable_interrupts(dev_priv);
3872                 intel_runtime_pm_enable_interrupts(dev_priv);
3873
3874                 intel_pps_unlock_regs_wa(dev_priv);
3875                 intel_modeset_init_hw(dev);
3876                 intel_init_clock_gating(dev_priv);
3877
3878                 spin_lock_irq(&dev_priv->irq_lock);
3879                 if (dev_priv->display.hpd_irq_setup)
3880                         dev_priv->display.hpd_irq_setup(dev_priv);
3881                 spin_unlock_irq(&dev_priv->irq_lock);
3882
3883                 ret = __intel_display_resume(dev, state, ctx);
3884                 if (ret)
3885                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3886
3887                 intel_hpd_init(dev_priv);
3888         }
3889
3890         drm_atomic_state_put(state);
3891 unlock:
3892         drm_modeset_drop_locks(ctx);
3893         drm_modeset_acquire_fini(ctx);
3894         mutex_unlock(&dev->mode_config.mutex);
3895
3896         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3897 }
3898
3899 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3900                                      const struct intel_crtc_state *new_crtc_state)
3901 {
3902         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3903         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3904
3905         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3906         crtc->base.mode = new_crtc_state->base.mode;
3907
3908         /*
3909          * Update pipe size and adjust fitter if needed: the reason for this is
3910          * that in compute_mode_changes we check the native mode (not the pfit
3911          * mode) to see if we can flip rather than do a full mode set. In the
3912          * fastboot case, we'll flip, but if we don't update the pipesrc and
3913          * pfit state, we'll end up with a big fb scanned out into the wrong
3914          * sized surface.
3915          */
3916
3917         I915_WRITE(PIPESRC(crtc->pipe),
3918                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3919                    (new_crtc_state->pipe_src_h - 1));
3920
3921         /* on skylake this is done by detaching scalers */
3922         if (INTEL_GEN(dev_priv) >= 9) {
3923                 skl_detach_scalers(new_crtc_state);
3924
3925                 if (new_crtc_state->pch_pfit.enabled)
3926                         skylake_pfit_enable(new_crtc_state);
3927         } else if (HAS_PCH_SPLIT(dev_priv)) {
3928                 if (new_crtc_state->pch_pfit.enabled)
3929                         ironlake_pfit_enable(new_crtc_state);
3930                 else if (old_crtc_state->pch_pfit.enabled)
3931                         ironlake_pfit_disable(old_crtc_state);
3932         }
3933
3934         /*
3935          * We don't (yet) allow userspace to control the pipe background color,
3936          * so force it to black, but apply pipe gamma and CSC so that its
3937          * handling will match how we program our planes.
3938          */
3939         if (INTEL_GEN(dev_priv) >= 9)
3940                 I915_WRITE(SKL_BOTTOM_COLOR(crtc->pipe),
3941                            SKL_BOTTOM_COLOR_GAMMA_ENABLE |
3942                            SKL_BOTTOM_COLOR_CSC_ENABLE);
3943 }
3944
3945 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3946 {
3947         struct drm_device *dev = crtc->base.dev;
3948         struct drm_i915_private *dev_priv = to_i915(dev);
3949         int pipe = crtc->pipe;
3950         i915_reg_t reg;
3951         u32 temp;
3952
3953         /* enable normal train */
3954         reg = FDI_TX_CTL(pipe);
3955         temp = I915_READ(reg);
3956         if (IS_IVYBRIDGE(dev_priv)) {
3957                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3958                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3959         } else {
3960                 temp &= ~FDI_LINK_TRAIN_NONE;
3961                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3962         }
3963         I915_WRITE(reg, temp);
3964
3965         reg = FDI_RX_CTL(pipe);
3966         temp = I915_READ(reg);
3967         if (HAS_PCH_CPT(dev_priv)) {
3968                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3969                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3970         } else {
3971                 temp &= ~FDI_LINK_TRAIN_NONE;
3972                 temp |= FDI_LINK_TRAIN_NONE;
3973         }
3974         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3975
3976         /* wait one idle pattern time */
3977         POSTING_READ(reg);
3978         udelay(1000);
3979
3980         /* IVB wants error correction enabled */
3981         if (IS_IVYBRIDGE(dev_priv))
3982                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3983                            FDI_FE_ERRC_ENABLE);
3984 }
3985
3986 /* The FDI link training functions for ILK/Ibexpeak. */
3987 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3988                                     const struct intel_crtc_state *crtc_state)
3989 {
3990         struct drm_device *dev = crtc->base.dev;
3991         struct drm_i915_private *dev_priv = to_i915(dev);
3992         int pipe = crtc->pipe;
3993         i915_reg_t reg;
3994         u32 temp, tries;
3995
3996         /* FDI needs bits from pipe first */
3997         assert_pipe_enabled(dev_priv, pipe);
3998
3999         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4000            for train result */
4001         reg = FDI_RX_IMR(pipe);
4002         temp = I915_READ(reg);
4003         temp &= ~FDI_RX_SYMBOL_LOCK;
4004         temp &= ~FDI_RX_BIT_LOCK;
4005         I915_WRITE(reg, temp);
4006         I915_READ(reg);
4007         udelay(150);
4008
4009         /* enable CPU FDI TX and PCH FDI RX */
4010         reg = FDI_TX_CTL(pipe);
4011         temp = I915_READ(reg);
4012         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4013         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4014         temp &= ~FDI_LINK_TRAIN_NONE;
4015         temp |= FDI_LINK_TRAIN_PATTERN_1;
4016         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4017
4018         reg = FDI_RX_CTL(pipe);
4019         temp = I915_READ(reg);
4020         temp &= ~FDI_LINK_TRAIN_NONE;
4021         temp |= FDI_LINK_TRAIN_PATTERN_1;
4022         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4023
4024         POSTING_READ(reg);
4025         udelay(150);
4026
4027         /* Ironlake workaround, enable clock pointer after FDI enable*/
4028         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4029         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
4030                    FDI_RX_PHASE_SYNC_POINTER_EN);
4031
4032         reg = FDI_RX_IIR(pipe);
4033         for (tries = 0; tries < 5; tries++) {
4034                 temp = I915_READ(reg);
4035                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4036
4037                 if ((temp & FDI_RX_BIT_LOCK)) {
4038                         DRM_DEBUG_KMS("FDI train 1 done.\n");
4039                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4040                         break;
4041                 }
4042         }
4043         if (tries == 5)
4044                 DRM_ERROR("FDI train 1 fail!\n");
4045
4046         /* Train 2 */
4047         reg = FDI_TX_CTL(pipe);
4048         temp = I915_READ(reg);
4049         temp &= ~FDI_LINK_TRAIN_NONE;
4050         temp |= FDI_LINK_TRAIN_PATTERN_2;
4051         I915_WRITE(reg, temp);
4052
4053         reg = FDI_RX_CTL(pipe);
4054         temp = I915_READ(reg);
4055         temp &= ~FDI_LINK_TRAIN_NONE;
4056         temp |= FDI_LINK_TRAIN_PATTERN_2;
4057         I915_WRITE(reg, temp);
4058
4059         POSTING_READ(reg);
4060         udelay(150);
4061
4062         reg = FDI_RX_IIR(pipe);
4063         for (tries = 0; tries < 5; tries++) {
4064                 temp = I915_READ(reg);
4065                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4066
4067                 if (temp & FDI_RX_SYMBOL_LOCK) {
4068                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4069                         DRM_DEBUG_KMS("FDI train 2 done.\n");
4070                         break;
4071                 }
4072         }
4073         if (tries == 5)
4074                 DRM_ERROR("FDI train 2 fail!\n");
4075
4076         DRM_DEBUG_KMS("FDI train done\n");
4077
4078 }
4079
4080 static const int snb_b_fdi_train_param[] = {
4081         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4082         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4083         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4084         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4085 };
4086
4087 /* The FDI link training functions for SNB/Cougarpoint. */
4088 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4089                                 const struct intel_crtc_state *crtc_state)
4090 {
4091         struct drm_device *dev = crtc->base.dev;
4092         struct drm_i915_private *dev_priv = to_i915(dev);
4093         int pipe = crtc->pipe;
4094         i915_reg_t reg;
4095         u32 temp, i, retry;
4096
4097         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4098            for train result */
4099         reg = FDI_RX_IMR(pipe);
4100         temp = I915_READ(reg);
4101         temp &= ~FDI_RX_SYMBOL_LOCK;
4102         temp &= ~FDI_RX_BIT_LOCK;
4103         I915_WRITE(reg, temp);
4104
4105         POSTING_READ(reg);
4106         udelay(150);
4107
4108         /* enable CPU FDI TX and PCH FDI RX */
4109         reg = FDI_TX_CTL(pipe);
4110         temp = I915_READ(reg);
4111         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4112         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4113         temp &= ~FDI_LINK_TRAIN_NONE;
4114         temp |= FDI_LINK_TRAIN_PATTERN_1;
4115         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4116         /* SNB-B */
4117         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4118         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4119
4120         I915_WRITE(FDI_RX_MISC(pipe),
4121                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4122
4123         reg = FDI_RX_CTL(pipe);
4124         temp = I915_READ(reg);
4125         if (HAS_PCH_CPT(dev_priv)) {
4126                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4127                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4128         } else {
4129                 temp &= ~FDI_LINK_TRAIN_NONE;
4130                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4131         }
4132         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4133
4134         POSTING_READ(reg);
4135         udelay(150);
4136
4137         for (i = 0; i < 4; i++) {
4138                 reg = FDI_TX_CTL(pipe);
4139                 temp = I915_READ(reg);
4140                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4141                 temp |= snb_b_fdi_train_param[i];
4142                 I915_WRITE(reg, temp);
4143
4144                 POSTING_READ(reg);
4145                 udelay(500);
4146
4147                 for (retry = 0; retry < 5; retry++) {
4148                         reg = FDI_RX_IIR(pipe);
4149                         temp = I915_READ(reg);
4150                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4151                         if (temp & FDI_RX_BIT_LOCK) {
4152                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4153                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4154                                 break;
4155                         }
4156                         udelay(50);
4157                 }
4158                 if (retry < 5)
4159                         break;
4160         }
4161         if (i == 4)
4162                 DRM_ERROR("FDI train 1 fail!\n");
4163
4164         /* Train 2 */
4165         reg = FDI_TX_CTL(pipe);
4166         temp = I915_READ(reg);
4167         temp &= ~FDI_LINK_TRAIN_NONE;
4168         temp |= FDI_LINK_TRAIN_PATTERN_2;
4169         if (IS_GEN(dev_priv, 6)) {
4170                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4171                 /* SNB-B */
4172                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4173         }
4174         I915_WRITE(reg, temp);
4175
4176         reg = FDI_RX_CTL(pipe);
4177         temp = I915_READ(reg);
4178         if (HAS_PCH_CPT(dev_priv)) {
4179                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4180                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4181         } else {
4182                 temp &= ~FDI_LINK_TRAIN_NONE;
4183                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4184         }
4185         I915_WRITE(reg, temp);
4186
4187         POSTING_READ(reg);
4188         udelay(150);
4189
4190         for (i = 0; i < 4; i++) {
4191                 reg = FDI_TX_CTL(pipe);
4192                 temp = I915_READ(reg);
4193                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4194                 temp |= snb_b_fdi_train_param[i];
4195                 I915_WRITE(reg, temp);
4196
4197                 POSTING_READ(reg);
4198                 udelay(500);
4199
4200                 for (retry = 0; retry < 5; retry++) {
4201                         reg = FDI_RX_IIR(pipe);
4202                         temp = I915_READ(reg);
4203                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4204                         if (temp & FDI_RX_SYMBOL_LOCK) {
4205                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4206                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4207                                 break;
4208                         }
4209                         udelay(50);
4210                 }
4211                 if (retry < 5)
4212                         break;
4213         }
4214         if (i == 4)
4215                 DRM_ERROR("FDI train 2 fail!\n");
4216
4217         DRM_DEBUG_KMS("FDI train done.\n");
4218 }
4219
4220 /* Manual link training for Ivy Bridge A0 parts */
4221 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4222                                       const struct intel_crtc_state *crtc_state)
4223 {
4224         struct drm_device *dev = crtc->base.dev;
4225         struct drm_i915_private *dev_priv = to_i915(dev);
4226         int pipe = crtc->pipe;
4227         i915_reg_t reg;
4228         u32 temp, i, j;
4229
4230         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4231            for train result */
4232         reg = FDI_RX_IMR(pipe);
4233         temp = I915_READ(reg);
4234         temp &= ~FDI_RX_SYMBOL_LOCK;
4235         temp &= ~FDI_RX_BIT_LOCK;
4236         I915_WRITE(reg, temp);
4237
4238         POSTING_READ(reg);
4239         udelay(150);
4240
4241         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4242                       I915_READ(FDI_RX_IIR(pipe)));
4243
4244         /* Try each vswing and preemphasis setting twice before moving on */
4245         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4246                 /* disable first in case we need to retry */
4247                 reg = FDI_TX_CTL(pipe);
4248                 temp = I915_READ(reg);
4249                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4250                 temp &= ~FDI_TX_ENABLE;
4251                 I915_WRITE(reg, temp);
4252
4253                 reg = FDI_RX_CTL(pipe);
4254                 temp = I915_READ(reg);
4255                 temp &= ~FDI_LINK_TRAIN_AUTO;
4256                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4257                 temp &= ~FDI_RX_ENABLE;
4258                 I915_WRITE(reg, temp);
4259
4260                 /* enable CPU FDI TX and PCH FDI RX */
4261                 reg = FDI_TX_CTL(pipe);
4262                 temp = I915_READ(reg);
4263                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4264                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4265                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4266                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4267                 temp |= snb_b_fdi_train_param[j/2];
4268                 temp |= FDI_COMPOSITE_SYNC;
4269                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4270
4271                 I915_WRITE(FDI_RX_MISC(pipe),
4272                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4273
4274                 reg = FDI_RX_CTL(pipe);
4275                 temp = I915_READ(reg);
4276                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4277                 temp |= FDI_COMPOSITE_SYNC;
4278                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4279
4280                 POSTING_READ(reg);
4281                 udelay(1); /* should be 0.5us */
4282
4283                 for (i = 0; i < 4; i++) {
4284                         reg = FDI_RX_IIR(pipe);
4285                         temp = I915_READ(reg);
4286                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4287
4288                         if (temp & FDI_RX_BIT_LOCK ||
4289                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4290                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4291                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4292                                               i);
4293                                 break;
4294                         }
4295                         udelay(1); /* should be 0.5us */
4296                 }
4297                 if (i == 4) {
4298                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4299                         continue;
4300                 }
4301
4302                 /* Train 2 */
4303                 reg = FDI_TX_CTL(pipe);
4304                 temp = I915_READ(reg);
4305                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4306                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4307                 I915_WRITE(reg, temp);
4308
4309                 reg = FDI_RX_CTL(pipe);
4310                 temp = I915_READ(reg);
4311                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4312                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4313                 I915_WRITE(reg, temp);
4314
4315                 POSTING_READ(reg);
4316                 udelay(2); /* should be 1.5us */
4317
4318                 for (i = 0; i < 4; i++) {
4319                         reg = FDI_RX_IIR(pipe);
4320                         temp = I915_READ(reg);
4321                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4322
4323                         if (temp & FDI_RX_SYMBOL_LOCK ||
4324                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4325                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4326                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4327                                               i);
4328                                 goto train_done;
4329                         }
4330                         udelay(2); /* should be 1.5us */
4331                 }
4332                 if (i == 4)
4333                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4334         }
4335
4336 train_done:
4337         DRM_DEBUG_KMS("FDI train done.\n");
4338 }
4339
4340 static void ironlake_fdi_pll_enable(const struct intel_crtc_state *crtc_state)
4341 {
4342         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4343         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4344         int pipe = intel_crtc->pipe;
4345         i915_reg_t reg;
4346         u32 temp;
4347
4348         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4349         reg = FDI_RX_CTL(pipe);
4350         temp = I915_READ(reg);
4351         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4352         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4353         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4354         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4355
4356         POSTING_READ(reg);
4357         udelay(200);
4358
4359         /* Switch from Rawclk to PCDclk */
4360         temp = I915_READ(reg);
4361         I915_WRITE(reg, temp | FDI_PCDCLK);
4362
4363         POSTING_READ(reg);
4364         udelay(200);
4365
4366         /* Enable CPU FDI TX PLL, always on for Ironlake */
4367         reg = FDI_TX_CTL(pipe);
4368         temp = I915_READ(reg);
4369         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4370                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4371
4372                 POSTING_READ(reg);
4373                 udelay(100);
4374         }
4375 }
4376
4377 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4378 {
4379         struct drm_device *dev = intel_crtc->base.dev;
4380         struct drm_i915_private *dev_priv = to_i915(dev);
4381         int pipe = intel_crtc->pipe;
4382         i915_reg_t reg;
4383         u32 temp;
4384
4385         /* Switch from PCDclk to Rawclk */
4386         reg = FDI_RX_CTL(pipe);
4387         temp = I915_READ(reg);
4388         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4389
4390         /* Disable CPU FDI TX PLL */
4391         reg = FDI_TX_CTL(pipe);
4392         temp = I915_READ(reg);
4393         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4394
4395         POSTING_READ(reg);
4396         udelay(100);
4397
4398         reg = FDI_RX_CTL(pipe);
4399         temp = I915_READ(reg);
4400         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4401
4402         /* Wait for the clocks to turn off. */
4403         POSTING_READ(reg);
4404         udelay(100);
4405 }
4406
4407 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4408 {
4409         struct drm_device *dev = crtc->dev;
4410         struct drm_i915_private *dev_priv = to_i915(dev);
4411         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4412         int pipe = intel_crtc->pipe;
4413         i915_reg_t reg;
4414         u32 temp;
4415
4416         /* disable CPU FDI tx and PCH FDI rx */
4417         reg = FDI_TX_CTL(pipe);
4418         temp = I915_READ(reg);
4419         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4420         POSTING_READ(reg);
4421
4422         reg = FDI_RX_CTL(pipe);
4423         temp = I915_READ(reg);
4424         temp &= ~(0x7 << 16);
4425         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4426         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4427
4428         POSTING_READ(reg);
4429         udelay(100);
4430
4431         /* Ironlake workaround, disable clock pointer after downing FDI */
4432         if (HAS_PCH_IBX(dev_priv))
4433                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4434
4435         /* still set train pattern 1 */
4436         reg = FDI_TX_CTL(pipe);
4437         temp = I915_READ(reg);
4438         temp &= ~FDI_LINK_TRAIN_NONE;
4439         temp |= FDI_LINK_TRAIN_PATTERN_1;
4440         I915_WRITE(reg, temp);
4441
4442         reg = FDI_RX_CTL(pipe);
4443         temp = I915_READ(reg);
4444         if (HAS_PCH_CPT(dev_priv)) {
4445                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4446                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4447         } else {
4448                 temp &= ~FDI_LINK_TRAIN_NONE;
4449                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4450         }
4451         /* BPC in FDI rx is consistent with that in PIPECONF */
4452         temp &= ~(0x07 << 16);
4453         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4454         I915_WRITE(reg, temp);
4455
4456         POSTING_READ(reg);
4457         udelay(100);
4458 }
4459
4460 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4461 {
4462         struct drm_crtc *crtc;
4463         bool cleanup_done;
4464
4465         drm_for_each_crtc(crtc, &dev_priv->drm) {
4466                 struct drm_crtc_commit *commit;
4467                 spin_lock(&crtc->commit_lock);
4468                 commit = list_first_entry_or_null(&crtc->commit_list,
4469                                                   struct drm_crtc_commit, commit_entry);
4470                 cleanup_done = commit ?
4471                         try_wait_for_completion(&commit->cleanup_done) : true;
4472                 spin_unlock(&crtc->commit_lock);
4473
4474                 if (cleanup_done)
4475                         continue;
4476
4477                 drm_crtc_wait_one_vblank(crtc);
4478
4479                 return true;
4480         }
4481
4482         return false;
4483 }
4484
4485 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4486 {
4487         u32 temp;
4488
4489         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4490
4491         mutex_lock(&dev_priv->sb_lock);
4492
4493         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4494         temp |= SBI_SSCCTL_DISABLE;
4495         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4496
4497         mutex_unlock(&dev_priv->sb_lock);
4498 }
4499
4500 /* Program iCLKIP clock to the desired frequency */
4501 static void lpt_program_iclkip(const struct intel_crtc_state *crtc_state)
4502 {
4503         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4504         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4505         int clock = crtc_state->base.adjusted_mode.crtc_clock;
4506         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4507         u32 temp;
4508
4509         lpt_disable_iclkip(dev_priv);
4510
4511         /* The iCLK virtual clock root frequency is in MHz,
4512          * but the adjusted_mode->crtc_clock in in KHz. To get the
4513          * divisors, it is necessary to divide one by another, so we
4514          * convert the virtual clock precision to KHz here for higher
4515          * precision.
4516          */
4517         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4518                 u32 iclk_virtual_root_freq = 172800 * 1000;
4519                 u32 iclk_pi_range = 64;
4520                 u32 desired_divisor;
4521
4522                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4523                                                     clock << auxdiv);
4524                 divsel = (desired_divisor / iclk_pi_range) - 2;
4525                 phaseinc = desired_divisor % iclk_pi_range;
4526
4527                 /*
4528                  * Near 20MHz is a corner case which is
4529                  * out of range for the 7-bit divisor
4530                  */
4531                 if (divsel <= 0x7f)
4532                         break;
4533         }
4534
4535         /* This should not happen with any sane values */
4536         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4537                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4538         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4539                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4540
4541         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4542                         clock,
4543                         auxdiv,
4544                         divsel,
4545                         phasedir,
4546                         phaseinc);
4547
4548         mutex_lock(&dev_priv->sb_lock);
4549
4550         /* Program SSCDIVINTPHASE6 */
4551         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4552         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4553         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4554         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4555         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4556         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4557         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4558         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4559
4560         /* Program SSCAUXDIV */
4561         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4562         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4563         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4564         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4565
4566         /* Enable modulator and associated divider */
4567         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4568         temp &= ~SBI_SSCCTL_DISABLE;
4569         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4570
4571         mutex_unlock(&dev_priv->sb_lock);
4572
4573         /* Wait for initialization time */
4574         udelay(24);
4575
4576         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4577 }
4578
4579 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4580 {
4581         u32 divsel, phaseinc, auxdiv;
4582         u32 iclk_virtual_root_freq = 172800 * 1000;
4583         u32 iclk_pi_range = 64;
4584         u32 desired_divisor;
4585         u32 temp;
4586
4587         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4588                 return 0;
4589
4590         mutex_lock(&dev_priv->sb_lock);
4591
4592         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4593         if (temp & SBI_SSCCTL_DISABLE) {
4594                 mutex_unlock(&dev_priv->sb_lock);
4595                 return 0;
4596         }
4597
4598         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4599         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4600                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4601         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4602                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4603
4604         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4605         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4606                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4607
4608         mutex_unlock(&dev_priv->sb_lock);
4609
4610         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4611
4612         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4613                                  desired_divisor << auxdiv);
4614 }
4615
4616 static void ironlake_pch_transcoder_set_timings(const struct intel_crtc_state *crtc_state,
4617                                                 enum pipe pch_transcoder)
4618 {
4619         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4620         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4621         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4622
4623         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4624                    I915_READ(HTOTAL(cpu_transcoder)));
4625         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4626                    I915_READ(HBLANK(cpu_transcoder)));
4627         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4628                    I915_READ(HSYNC(cpu_transcoder)));
4629
4630         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4631                    I915_READ(VTOTAL(cpu_transcoder)));
4632         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4633                    I915_READ(VBLANK(cpu_transcoder)));
4634         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4635                    I915_READ(VSYNC(cpu_transcoder)));
4636         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4637                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4638 }
4639
4640 static void cpt_set_fdi_bc_bifurcation(struct drm_i915_private *dev_priv, bool enable)
4641 {
4642         u32 temp;
4643
4644         temp = I915_READ(SOUTH_CHICKEN1);
4645         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4646                 return;
4647
4648         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4649         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4650
4651         temp &= ~FDI_BC_BIFURCATION_SELECT;
4652         if (enable)
4653                 temp |= FDI_BC_BIFURCATION_SELECT;
4654
4655         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4656         I915_WRITE(SOUTH_CHICKEN1, temp);
4657         POSTING_READ(SOUTH_CHICKEN1);
4658 }
4659
4660 static void ivybridge_update_fdi_bc_bifurcation(const struct intel_crtc_state *crtc_state)
4661 {
4662         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4663         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4664
4665         switch (crtc->pipe) {
4666         case PIPE_A:
4667                 break;
4668         case PIPE_B:
4669                 if (crtc_state->fdi_lanes > 2)
4670                         cpt_set_fdi_bc_bifurcation(dev_priv, false);
4671                 else
4672                         cpt_set_fdi_bc_bifurcation(dev_priv, true);
4673
4674                 break;
4675         case PIPE_C:
4676                 cpt_set_fdi_bc_bifurcation(dev_priv, true);
4677
4678                 break;
4679         default:
4680                 BUG();
4681         }
4682 }
4683
4684 /*
4685  * Finds the encoder associated with the given CRTC. This can only be
4686  * used when we know that the CRTC isn't feeding multiple encoders!
4687  */
4688 static struct intel_encoder *
4689 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
4690                            const struct intel_crtc_state *crtc_state)
4691 {
4692         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4693         const struct drm_connector_state *connector_state;
4694         const struct drm_connector *connector;
4695         struct intel_encoder *encoder = NULL;
4696         int num_encoders = 0;
4697         int i;
4698
4699         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
4700                 if (connector_state->crtc != &crtc->base)
4701                         continue;
4702
4703                 encoder = to_intel_encoder(connector_state->best_encoder);
4704                 num_encoders++;
4705         }
4706
4707         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
4708              num_encoders, pipe_name(crtc->pipe));
4709
4710         return encoder;
4711 }
4712
4713 /*
4714  * Enable PCH resources required for PCH ports:
4715  *   - PCH PLLs
4716  *   - FDI training & RX/TX
4717  *   - update transcoder timings
4718  *   - DP transcoding bits
4719  *   - transcoder
4720  */
4721 static void ironlake_pch_enable(const struct intel_atomic_state *state,
4722                                 const struct intel_crtc_state *crtc_state)
4723 {
4724         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4725         struct drm_device *dev = crtc->base.dev;
4726         struct drm_i915_private *dev_priv = to_i915(dev);
4727         int pipe = crtc->pipe;
4728         u32 temp;
4729
4730         assert_pch_transcoder_disabled(dev_priv, pipe);
4731
4732         if (IS_IVYBRIDGE(dev_priv))
4733                 ivybridge_update_fdi_bc_bifurcation(crtc_state);
4734
4735         /* Write the TU size bits before fdi link training, so that error
4736          * detection works. */
4737         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4738                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4739
4740         /* For PCH output, training FDI link */
4741         dev_priv->display.fdi_link_train(crtc, crtc_state);
4742
4743         /* We need to program the right clock selection before writing the pixel
4744          * mutliplier into the DPLL. */
4745         if (HAS_PCH_CPT(dev_priv)) {
4746                 u32 sel;
4747
4748                 temp = I915_READ(PCH_DPLL_SEL);
4749                 temp |= TRANS_DPLL_ENABLE(pipe);
4750                 sel = TRANS_DPLLB_SEL(pipe);
4751                 if (crtc_state->shared_dpll ==
4752                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4753                         temp |= sel;
4754                 else
4755                         temp &= ~sel;
4756                 I915_WRITE(PCH_DPLL_SEL, temp);
4757         }
4758
4759         /* XXX: pch pll's can be enabled any time before we enable the PCH
4760          * transcoder, and we actually should do this to not upset any PCH
4761          * transcoder that already use the clock when we share it.
4762          *
4763          * Note that enable_shared_dpll tries to do the right thing, but
4764          * get_shared_dpll unconditionally resets the pll - we need that to have
4765          * the right LVDS enable sequence. */
4766         intel_enable_shared_dpll(crtc_state);
4767
4768         /* set transcoder timing, panel must allow it */
4769         assert_panel_unlocked(dev_priv, pipe);
4770         ironlake_pch_transcoder_set_timings(crtc_state, pipe);
4771
4772         intel_fdi_normal_train(crtc);
4773
4774         /* For PCH DP, enable TRANS_DP_CTL */
4775         if (HAS_PCH_CPT(dev_priv) &&
4776             intel_crtc_has_dp_encoder(crtc_state)) {
4777                 const struct drm_display_mode *adjusted_mode =
4778                         &crtc_state->base.adjusted_mode;
4779                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4780                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4781                 enum port port;
4782
4783                 temp = I915_READ(reg);
4784                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4785                           TRANS_DP_SYNC_MASK |
4786                           TRANS_DP_BPC_MASK);
4787                 temp |= TRANS_DP_OUTPUT_ENABLE;
4788                 temp |= bpc << 9; /* same format but at 11:9 */
4789
4790                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4791                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4792                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4793                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4794
4795                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
4796                 WARN_ON(port < PORT_B || port > PORT_D);
4797                 temp |= TRANS_DP_PORT_SEL(port);
4798
4799                 I915_WRITE(reg, temp);
4800         }
4801
4802         ironlake_enable_pch_transcoder(crtc_state);
4803 }
4804
4805 static void lpt_pch_enable(const struct intel_atomic_state *state,
4806                            const struct intel_crtc_state *crtc_state)
4807 {
4808         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4809         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4810         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4811
4812         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4813
4814         lpt_program_iclkip(crtc_state);
4815
4816         /* Set transcoder timing. */
4817         ironlake_pch_transcoder_set_timings(crtc_state, PIPE_A);
4818
4819         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4820 }
4821
4822 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4823 {
4824         struct drm_i915_private *dev_priv = to_i915(dev);
4825         i915_reg_t dslreg = PIPEDSL(pipe);
4826         u32 temp;
4827
4828         temp = I915_READ(dslreg);
4829         udelay(500);
4830         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4831                 if (wait_for(I915_READ(dslreg) != temp, 5))
4832                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4833         }
4834 }
4835
4836 /*
4837  * The hardware phase 0.0 refers to the center of the pixel.
4838  * We want to start from the top/left edge which is phase
4839  * -0.5. That matches how the hardware calculates the scaling
4840  * factors (from top-left of the first pixel to bottom-right
4841  * of the last pixel, as opposed to the pixel centers).
4842  *
4843  * For 4:2:0 subsampled chroma planes we obviously have to
4844  * adjust that so that the chroma sample position lands in
4845  * the right spot.
4846  *
4847  * Note that for packed YCbCr 4:2:2 formats there is no way to
4848  * control chroma siting. The hardware simply replicates the
4849  * chroma samples for both of the luma samples, and thus we don't
4850  * actually get the expected MPEG2 chroma siting convention :(
4851  * The same behaviour is observed on pre-SKL platforms as well.
4852  *
4853  * Theory behind the formula (note that we ignore sub-pixel
4854  * source coordinates):
4855  * s = source sample position
4856  * d = destination sample position
4857  *
4858  * Downscaling 4:1:
4859  * -0.5
4860  * | 0.0
4861  * | |     1.5 (initial phase)
4862  * | |     |
4863  * v v     v
4864  * | s | s | s | s |
4865  * |       d       |
4866  *
4867  * Upscaling 1:4:
4868  * -0.5
4869  * | -0.375 (initial phase)
4870  * | |     0.0
4871  * | |     |
4872  * v v     v
4873  * |       s       |
4874  * | d | d | d | d |
4875  */
4876 u16 skl_scaler_calc_phase(int sub, int scale, bool chroma_cosited)
4877 {
4878         int phase = -0x8000;
4879         u16 trip = 0;
4880
4881         if (chroma_cosited)
4882                 phase += (sub - 1) * 0x8000 / sub;
4883
4884         phase += scale / (2 * sub);
4885
4886         /*
4887          * Hardware initial phase limited to [-0.5:1.5].
4888          * Since the max hardware scale factor is 3.0, we
4889          * should never actually excdeed 1.0 here.
4890          */
4891         WARN_ON(phase < -0x8000 || phase > 0x18000);
4892
4893         if (phase < 0)
4894                 phase = 0x10000 + phase;
4895         else
4896                 trip = PS_PHASE_TRIP;
4897
4898         return ((phase >> 2) & PS_PHASE_MASK) | trip;
4899 }
4900
4901 static int
4902 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4903                   unsigned int scaler_user, int *scaler_id,
4904                   int src_w, int src_h, int dst_w, int dst_h,
4905                   const struct drm_format_info *format, bool need_scaler)
4906 {
4907         struct intel_crtc_scaler_state *scaler_state =
4908                 &crtc_state->scaler_state;
4909         struct intel_crtc *intel_crtc =
4910                 to_intel_crtc(crtc_state->base.crtc);
4911         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4912         const struct drm_display_mode *adjusted_mode =
4913                 &crtc_state->base.adjusted_mode;
4914
4915         /*
4916          * Src coordinates are already rotated by 270 degrees for
4917          * the 90/270 degree plane rotation cases (to match the
4918          * GTT mapping), hence no need to account for rotation here.
4919          */
4920         if (src_w != dst_w || src_h != dst_h)
4921                 need_scaler = true;
4922
4923         /*
4924          * Scaling/fitting not supported in IF-ID mode in GEN9+
4925          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4926          * Once NV12 is enabled, handle it here while allocating scaler
4927          * for NV12.
4928          */
4929         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4930             need_scaler && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4931                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4932                 return -EINVAL;
4933         }
4934
4935         /*
4936          * if plane is being disabled or scaler is no more required or force detach
4937          *  - free scaler binded to this plane/crtc
4938          *  - in order to do this, update crtc->scaler_usage
4939          *
4940          * Here scaler state in crtc_state is set free so that
4941          * scaler can be assigned to other user. Actual register
4942          * update to free the scaler is done in plane/panel-fit programming.
4943          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4944          */
4945         if (force_detach || !need_scaler) {
4946                 if (*scaler_id >= 0) {
4947                         scaler_state->scaler_users &= ~(1 << scaler_user);
4948                         scaler_state->scalers[*scaler_id].in_use = 0;
4949
4950                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4951                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4952                                 intel_crtc->pipe, scaler_user, *scaler_id,
4953                                 scaler_state->scaler_users);
4954                         *scaler_id = -1;
4955                 }
4956                 return 0;
4957         }
4958
4959         if (format && format->format == DRM_FORMAT_NV12 &&
4960             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
4961                 DRM_DEBUG_KMS("NV12: src dimensions not met\n");
4962                 return -EINVAL;
4963         }
4964
4965         /* range checks */
4966         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4967             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4968             (IS_GEN(dev_priv, 11) &&
4969              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
4970               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
4971             (!IS_GEN(dev_priv, 11) &&
4972              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4973               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
4974                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4975                         "size is out of scaler range\n",
4976                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4977                 return -EINVAL;
4978         }
4979
4980         /* mark this plane as a scaler user in crtc_state */
4981         scaler_state->scaler_users |= (1 << scaler_user);
4982         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4983                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4984                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4985                 scaler_state->scaler_users);
4986
4987         return 0;
4988 }
4989
4990 /**
4991  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4992  *
4993  * @state: crtc's scaler state
4994  *
4995  * Return
4996  *     0 - scaler_usage updated successfully
4997  *    error - requested scaling cannot be supported or other error condition
4998  */
4999 int skl_update_scaler_crtc(struct intel_crtc_state *state)
5000 {
5001         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
5002         bool need_scaler = false;
5003
5004         if (state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
5005                 need_scaler = true;
5006
5007         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
5008                                  &state->scaler_state.scaler_id,
5009                                  state->pipe_src_w, state->pipe_src_h,
5010                                  adjusted_mode->crtc_hdisplay,
5011                                  adjusted_mode->crtc_vdisplay, NULL, need_scaler);
5012 }
5013
5014 /**
5015  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
5016  * @crtc_state: crtc's scaler state
5017  * @plane_state: atomic plane state to update
5018  *
5019  * Return
5020  *     0 - scaler_usage updated successfully
5021  *    error - requested scaling cannot be supported or other error condition
5022  */
5023 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
5024                                    struct intel_plane_state *plane_state)
5025 {
5026         struct intel_plane *intel_plane =
5027                 to_intel_plane(plane_state->base.plane);
5028         struct drm_framebuffer *fb = plane_state->base.fb;
5029         int ret;
5030         bool force_detach = !fb || !plane_state->base.visible;
5031         bool need_scaler = false;
5032
5033         /* Pre-gen11 and SDR planes always need a scaler for planar formats. */
5034         if (!icl_is_hdr_plane(intel_plane) &&
5035             fb && fb->format->format == DRM_FORMAT_NV12)
5036                 need_scaler = true;
5037
5038         ret = skl_update_scaler(crtc_state, force_detach,
5039                                 drm_plane_index(&intel_plane->base),
5040                                 &plane_state->scaler_id,
5041                                 drm_rect_width(&plane_state->base.src) >> 16,
5042                                 drm_rect_height(&plane_state->base.src) >> 16,
5043                                 drm_rect_width(&plane_state->base.dst),
5044                                 drm_rect_height(&plane_state->base.dst),
5045                                 fb ? fb->format : NULL, need_scaler);
5046
5047         if (ret || plane_state->scaler_id < 0)
5048                 return ret;
5049
5050         /* check colorkey */
5051         if (plane_state->ckey.flags) {
5052                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
5053                               intel_plane->base.base.id,
5054                               intel_plane->base.name);
5055                 return -EINVAL;
5056         }
5057
5058         /* Check src format */
5059         switch (fb->format->format) {
5060         case DRM_FORMAT_RGB565:
5061         case DRM_FORMAT_XBGR8888:
5062         case DRM_FORMAT_XRGB8888:
5063         case DRM_FORMAT_ABGR8888:
5064         case DRM_FORMAT_ARGB8888:
5065         case DRM_FORMAT_XRGB2101010:
5066         case DRM_FORMAT_XBGR2101010:
5067         case DRM_FORMAT_YUYV:
5068         case DRM_FORMAT_YVYU:
5069         case DRM_FORMAT_UYVY:
5070         case DRM_FORMAT_VYUY:
5071         case DRM_FORMAT_NV12:
5072                 break;
5073         default:
5074                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
5075                               intel_plane->base.base.id, intel_plane->base.name,
5076                               fb->base.id, fb->format->format);
5077                 return -EINVAL;
5078         }
5079
5080         return 0;
5081 }
5082
5083 static void skylake_scaler_disable(struct intel_crtc *crtc)
5084 {
5085         int i;
5086
5087         for (i = 0; i < crtc->num_scalers; i++)
5088                 skl_detach_scaler(crtc, i);
5089 }
5090
5091 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state)
5092 {
5093         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5094         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5095         enum pipe pipe = crtc->pipe;
5096         const struct intel_crtc_scaler_state *scaler_state =
5097                 &crtc_state->scaler_state;
5098
5099         if (crtc_state->pch_pfit.enabled) {
5100                 u16 uv_rgb_hphase, uv_rgb_vphase;
5101                 int pfit_w, pfit_h, hscale, vscale;
5102                 int id;
5103
5104                 if (WARN_ON(crtc_state->scaler_state.scaler_id < 0))
5105                         return;
5106
5107                 pfit_w = (crtc_state->pch_pfit.size >> 16) & 0xFFFF;
5108                 pfit_h = crtc_state->pch_pfit.size & 0xFFFF;
5109
5110                 hscale = (crtc_state->pipe_src_w << 16) / pfit_w;
5111                 vscale = (crtc_state->pipe_src_h << 16) / pfit_h;
5112
5113                 uv_rgb_hphase = skl_scaler_calc_phase(1, hscale, false);
5114                 uv_rgb_vphase = skl_scaler_calc_phase(1, vscale, false);
5115
5116                 id = scaler_state->scaler_id;
5117                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5118                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5119                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5120                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5121                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5122                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5123                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc_state->pch_pfit.pos);
5124                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc_state->pch_pfit.size);
5125         }
5126 }
5127
5128 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state)
5129 {
5130         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5131         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5132         int pipe = crtc->pipe;
5133
5134         if (crtc_state->pch_pfit.enabled) {
5135                 /* Force use of hard-coded filter coefficients
5136                  * as some pre-programmed values are broken,
5137                  * e.g. x201.
5138                  */
5139                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5140                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5141                                                  PF_PIPE_SEL_IVB(pipe));
5142                 else
5143                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5144                 I915_WRITE(PF_WIN_POS(pipe), crtc_state->pch_pfit.pos);
5145                 I915_WRITE(PF_WIN_SZ(pipe), crtc_state->pch_pfit.size);
5146         }
5147 }
5148
5149 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5150 {
5151         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5152         struct drm_device *dev = crtc->base.dev;
5153         struct drm_i915_private *dev_priv = to_i915(dev);
5154
5155         if (!crtc_state->ips_enabled)
5156                 return;
5157
5158         /*
5159          * We can only enable IPS after we enable a plane and wait for a vblank
5160          * This function is called from post_plane_update, which is run after
5161          * a vblank wait.
5162          */
5163         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5164
5165         if (IS_BROADWELL(dev_priv)) {
5166                 mutex_lock(&dev_priv->pcu_lock);
5167                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5168                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5169                 mutex_unlock(&dev_priv->pcu_lock);
5170                 /* Quoting Art Runyan: "its not safe to expect any particular
5171                  * value in IPS_CTL bit 31 after enabling IPS through the
5172                  * mailbox." Moreover, the mailbox may return a bogus state,
5173                  * so we need to just enable it and continue on.
5174                  */
5175         } else {
5176                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5177                 /* The bit only becomes 1 in the next vblank, so this wait here
5178                  * is essentially intel_wait_for_vblank. If we don't have this
5179                  * and don't wait for vblanks until the end of crtc_enable, then
5180                  * the HW state readout code will complain that the expected
5181                  * IPS_CTL value is not the one we read. */
5182                 if (intel_wait_for_register(dev_priv,
5183                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5184                                             50))
5185                         DRM_ERROR("Timed out waiting for IPS enable\n");
5186         }
5187 }
5188
5189 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5190 {
5191         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5192         struct drm_device *dev = crtc->base.dev;
5193         struct drm_i915_private *dev_priv = to_i915(dev);
5194
5195         if (!crtc_state->ips_enabled)
5196                 return;
5197
5198         if (IS_BROADWELL(dev_priv)) {
5199                 mutex_lock(&dev_priv->pcu_lock);
5200                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5201                 mutex_unlock(&dev_priv->pcu_lock);
5202                 /*
5203                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5204                  * 42ms timeout value leads to occasional timeouts so use 100ms
5205                  * instead.
5206                  */
5207                 if (intel_wait_for_register(dev_priv,
5208                                             IPS_CTL, IPS_ENABLE, 0,
5209                                             100))
5210                         DRM_ERROR("Timed out waiting for IPS disable\n");
5211         } else {
5212                 I915_WRITE(IPS_CTL, 0);
5213                 POSTING_READ(IPS_CTL);
5214         }
5215
5216         /* We need to wait for a vblank before we can disable the plane. */
5217         intel_wait_for_vblank(dev_priv, crtc->pipe);
5218 }
5219
5220 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5221 {
5222         if (intel_crtc->overlay) {
5223                 struct drm_device *dev = intel_crtc->base.dev;
5224
5225                 mutex_lock(&dev->struct_mutex);
5226                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5227                 mutex_unlock(&dev->struct_mutex);
5228         }
5229
5230         /* Let userspace switch the overlay on again. In most cases userspace
5231          * has to recompute where to put it anyway.
5232          */
5233 }
5234
5235 /**
5236  * intel_post_enable_primary - Perform operations after enabling primary plane
5237  * @crtc: the CRTC whose primary plane was just enabled
5238  * @new_crtc_state: the enabling state
5239  *
5240  * Performs potentially sleeping operations that must be done after the primary
5241  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5242  * called due to an explicit primary plane update, or due to an implicit
5243  * re-enable that is caused when a sprite plane is updated to no longer
5244  * completely hide the primary plane.
5245  */
5246 static void
5247 intel_post_enable_primary(struct drm_crtc *crtc,
5248                           const struct intel_crtc_state *new_crtc_state)
5249 {
5250         struct drm_device *dev = crtc->dev;
5251         struct drm_i915_private *dev_priv = to_i915(dev);
5252         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5253         int pipe = intel_crtc->pipe;
5254
5255         /*
5256          * Gen2 reports pipe underruns whenever all planes are disabled.
5257          * So don't enable underrun reporting before at least some planes
5258          * are enabled.
5259          * FIXME: Need to fix the logic to work when we turn off all planes
5260          * but leave the pipe running.
5261          */
5262         if (IS_GEN(dev_priv, 2))
5263                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5264
5265         /* Underruns don't always raise interrupts, so check manually. */
5266         intel_check_cpu_fifo_underruns(dev_priv);
5267         intel_check_pch_fifo_underruns(dev_priv);
5268 }
5269
5270 /* FIXME get rid of this and use pre_plane_update */
5271 static void
5272 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5273 {
5274         struct drm_device *dev = crtc->dev;
5275         struct drm_i915_private *dev_priv = to_i915(dev);
5276         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5277         int pipe = intel_crtc->pipe;
5278
5279         /*
5280          * Gen2 reports pipe underruns whenever all planes are disabled.
5281          * So disable underrun reporting before all the planes get disabled.
5282          */
5283         if (IS_GEN(dev_priv, 2))
5284                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5285
5286         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5287
5288         /*
5289          * Vblank time updates from the shadow to live plane control register
5290          * are blocked if the memory self-refresh mode is active at that
5291          * moment. So to make sure the plane gets truly disabled, disable
5292          * first the self-refresh mode. The self-refresh enable bit in turn
5293          * will be checked/applied by the HW only at the next frame start
5294          * event which is after the vblank start event, so we need to have a
5295          * wait-for-vblank between disabling the plane and the pipe.
5296          */
5297         if (HAS_GMCH_DISPLAY(dev_priv) &&
5298             intel_set_memory_cxsr(dev_priv, false))
5299                 intel_wait_for_vblank(dev_priv, pipe);
5300 }
5301
5302 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5303                                        const struct intel_crtc_state *new_crtc_state)
5304 {
5305         if (!old_crtc_state->ips_enabled)
5306                 return false;
5307
5308         if (needs_modeset(&new_crtc_state->base))
5309                 return true;
5310
5311         return !new_crtc_state->ips_enabled;
5312 }
5313
5314 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5315                                        const struct intel_crtc_state *new_crtc_state)
5316 {
5317         if (!new_crtc_state->ips_enabled)
5318                 return false;
5319
5320         if (needs_modeset(&new_crtc_state->base))
5321                 return true;
5322
5323         /*
5324          * We can't read out IPS on broadwell, assume the worst and
5325          * forcibly enable IPS on the first fastset.
5326          */
5327         if (new_crtc_state->update_pipe &&
5328             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5329                 return true;
5330
5331         return !old_crtc_state->ips_enabled;
5332 }
5333
5334 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5335                           const struct intel_crtc_state *crtc_state)
5336 {
5337         if (!crtc_state->nv12_planes)
5338                 return false;
5339
5340         /* WA Display #0827: Gen9:all */
5341         if (IS_GEN(dev_priv, 9) && !IS_GEMINILAKE(dev_priv))
5342                 return true;
5343
5344         return false;
5345 }
5346
5347 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5348 {
5349         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5350         struct drm_device *dev = crtc->base.dev;
5351         struct drm_i915_private *dev_priv = to_i915(dev);
5352         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5353         struct intel_crtc_state *pipe_config =
5354                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5355                                                 crtc);
5356         struct drm_plane *primary = crtc->base.primary;
5357         struct drm_plane_state *old_primary_state =
5358                 drm_atomic_get_old_plane_state(old_state, primary);
5359
5360         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5361
5362         if (pipe_config->update_wm_post && pipe_config->base.active)
5363                 intel_update_watermarks(crtc);
5364
5365         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5366                 hsw_enable_ips(pipe_config);
5367
5368         if (old_primary_state) {
5369                 struct drm_plane_state *new_primary_state =
5370                         drm_atomic_get_new_plane_state(old_state, primary);
5371
5372                 intel_fbc_post_update(crtc);
5373
5374                 if (new_primary_state->visible &&
5375                     (needs_modeset(&pipe_config->base) ||
5376                      !old_primary_state->visible))
5377                         intel_post_enable_primary(&crtc->base, pipe_config);
5378         }
5379
5380         /* Display WA 827 */
5381         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5382             !needs_nv12_wa(dev_priv, pipe_config)) {
5383                 skl_wa_clkgate(dev_priv, crtc->pipe, false);
5384         }
5385 }
5386
5387 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5388                                    struct intel_crtc_state *pipe_config)
5389 {
5390         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5391         struct drm_device *dev = crtc->base.dev;
5392         struct drm_i915_private *dev_priv = to_i915(dev);
5393         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5394         struct drm_plane *primary = crtc->base.primary;
5395         struct drm_plane_state *old_primary_state =
5396                 drm_atomic_get_old_plane_state(old_state, primary);
5397         bool modeset = needs_modeset(&pipe_config->base);
5398         struct intel_atomic_state *old_intel_state =
5399                 to_intel_atomic_state(old_state);
5400
5401         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5402                 hsw_disable_ips(old_crtc_state);
5403
5404         if (old_primary_state) {
5405                 struct intel_plane_state *new_primary_state =
5406                         intel_atomic_get_new_plane_state(old_intel_state,
5407                                                          to_intel_plane(primary));
5408
5409                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5410                 /*
5411                  * Gen2 reports pipe underruns whenever all planes are disabled.
5412                  * So disable underrun reporting before all the planes get disabled.
5413                  */
5414                 if (IS_GEN(dev_priv, 2) && old_primary_state->visible &&
5415                     (modeset || !new_primary_state->base.visible))
5416                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5417         }
5418
5419         /* Display WA 827 */
5420         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5421             needs_nv12_wa(dev_priv, pipe_config)) {
5422                 skl_wa_clkgate(dev_priv, crtc->pipe, true);
5423         }
5424
5425         /*
5426          * Vblank time updates from the shadow to live plane control register
5427          * are blocked if the memory self-refresh mode is active at that
5428          * moment. So to make sure the plane gets truly disabled, disable
5429          * first the self-refresh mode. The self-refresh enable bit in turn
5430          * will be checked/applied by the HW only at the next frame start
5431          * event which is after the vblank start event, so we need to have a
5432          * wait-for-vblank between disabling the plane and the pipe.
5433          */
5434         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5435             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5436                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5437
5438         /*
5439          * IVB workaround: must disable low power watermarks for at least
5440          * one frame before enabling scaling.  LP watermarks can be re-enabled
5441          * when scaling is disabled.
5442          *
5443          * WaCxSRDisabledForSpriteScaling:ivb
5444          */
5445         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev) &&
5446             old_crtc_state->base.active)
5447                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5448
5449         /*
5450          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5451          * watermark programming here.
5452          */
5453         if (needs_modeset(&pipe_config->base))
5454                 return;
5455
5456         /*
5457          * For platforms that support atomic watermarks, program the
5458          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5459          * will be the intermediate values that are safe for both pre- and
5460          * post- vblank; when vblank happens, the 'active' values will be set
5461          * to the final 'target' values and we'll do this again to get the
5462          * optimal watermarks.  For gen9+ platforms, the values we program here
5463          * will be the final target values which will get automatically latched
5464          * at vblank time; no further programming will be necessary.
5465          *
5466          * If a platform hasn't been transitioned to atomic watermarks yet,
5467          * we'll continue to update watermarks the old way, if flags tell
5468          * us to.
5469          */
5470         if (dev_priv->display.initial_watermarks != NULL)
5471                 dev_priv->display.initial_watermarks(old_intel_state,
5472                                                      pipe_config);
5473         else if (pipe_config->update_wm_pre)
5474                 intel_update_watermarks(crtc);
5475 }
5476
5477 static void intel_crtc_disable_planes(struct intel_atomic_state *state,
5478                                       struct intel_crtc *crtc)
5479 {
5480         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5481         const struct intel_crtc_state *new_crtc_state =
5482                 intel_atomic_get_new_crtc_state(state, crtc);
5483         unsigned int update_mask = new_crtc_state->update_planes;
5484         const struct intel_plane_state *old_plane_state;
5485         struct intel_plane *plane;
5486         unsigned fb_bits = 0;
5487         int i;
5488
5489         intel_crtc_dpms_overlay_disable(crtc);
5490
5491         for_each_old_intel_plane_in_state(state, plane, old_plane_state, i) {
5492                 if (crtc->pipe != plane->pipe ||
5493                     !(update_mask & BIT(plane->id)))
5494                         continue;
5495
5496                 plane->disable_plane(plane, new_crtc_state);
5497
5498                 if (old_plane_state->base.visible)
5499                         fb_bits |= plane->frontbuffer_bit;
5500         }
5501
5502         intel_frontbuffer_flip(dev_priv, fb_bits);
5503 }
5504
5505 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5506                                           struct intel_crtc_state *crtc_state,
5507                                           struct drm_atomic_state *old_state)
5508 {
5509         struct drm_connector_state *conn_state;
5510         struct drm_connector *conn;
5511         int i;
5512
5513         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5514                 struct intel_encoder *encoder =
5515                         to_intel_encoder(conn_state->best_encoder);
5516
5517                 if (conn_state->crtc != crtc)
5518                         continue;
5519
5520                 if (encoder->pre_pll_enable)
5521                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5522         }
5523 }
5524
5525 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5526                                       struct intel_crtc_state *crtc_state,
5527                                       struct drm_atomic_state *old_state)
5528 {
5529         struct drm_connector_state *conn_state;
5530         struct drm_connector *conn;
5531         int i;
5532
5533         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5534                 struct intel_encoder *encoder =
5535                         to_intel_encoder(conn_state->best_encoder);
5536
5537                 if (conn_state->crtc != crtc)
5538                         continue;
5539
5540                 if (encoder->pre_enable)
5541                         encoder->pre_enable(encoder, crtc_state, conn_state);
5542         }
5543 }
5544
5545 static void intel_encoders_enable(struct drm_crtc *crtc,
5546                                   struct intel_crtc_state *crtc_state,
5547                                   struct drm_atomic_state *old_state)
5548 {
5549         struct drm_connector_state *conn_state;
5550         struct drm_connector *conn;
5551         int i;
5552
5553         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5554                 struct intel_encoder *encoder =
5555                         to_intel_encoder(conn_state->best_encoder);
5556
5557                 if (conn_state->crtc != crtc)
5558                         continue;
5559
5560                 if (encoder->enable)
5561                         encoder->enable(encoder, crtc_state, conn_state);
5562                 intel_opregion_notify_encoder(encoder, true);
5563         }
5564 }
5565
5566 static void intel_encoders_disable(struct drm_crtc *crtc,
5567                                    struct intel_crtc_state *old_crtc_state,
5568                                    struct drm_atomic_state *old_state)
5569 {
5570         struct drm_connector_state *old_conn_state;
5571         struct drm_connector *conn;
5572         int i;
5573
5574         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5575                 struct intel_encoder *encoder =
5576                         to_intel_encoder(old_conn_state->best_encoder);
5577
5578                 if (old_conn_state->crtc != crtc)
5579                         continue;
5580
5581                 intel_opregion_notify_encoder(encoder, false);
5582                 if (encoder->disable)
5583                         encoder->disable(encoder, old_crtc_state, old_conn_state);
5584         }
5585 }
5586
5587 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5588                                         struct intel_crtc_state *old_crtc_state,
5589                                         struct drm_atomic_state *old_state)
5590 {
5591         struct drm_connector_state *old_conn_state;
5592         struct drm_connector *conn;
5593         int i;
5594
5595         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5596                 struct intel_encoder *encoder =
5597                         to_intel_encoder(old_conn_state->best_encoder);
5598
5599                 if (old_conn_state->crtc != crtc)
5600                         continue;
5601
5602                 if (encoder->post_disable)
5603                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5604         }
5605 }
5606
5607 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5608                                             struct intel_crtc_state *old_crtc_state,
5609                                             struct drm_atomic_state *old_state)
5610 {
5611         struct drm_connector_state *old_conn_state;
5612         struct drm_connector *conn;
5613         int i;
5614
5615         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5616                 struct intel_encoder *encoder =
5617                         to_intel_encoder(old_conn_state->best_encoder);
5618
5619                 if (old_conn_state->crtc != crtc)
5620                         continue;
5621
5622                 if (encoder->post_pll_disable)
5623                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5624         }
5625 }
5626
5627 static void intel_encoders_update_pipe(struct drm_crtc *crtc,
5628                                        struct intel_crtc_state *crtc_state,
5629                                        struct drm_atomic_state *old_state)
5630 {
5631         struct drm_connector_state *conn_state;
5632         struct drm_connector *conn;
5633         int i;
5634
5635         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5636                 struct intel_encoder *encoder =
5637                         to_intel_encoder(conn_state->best_encoder);
5638
5639                 if (conn_state->crtc != crtc)
5640                         continue;
5641
5642                 if (encoder->update_pipe)
5643                         encoder->update_pipe(encoder, crtc_state, conn_state);
5644         }
5645 }
5646
5647 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5648                                  struct drm_atomic_state *old_state)
5649 {
5650         struct drm_crtc *crtc = pipe_config->base.crtc;
5651         struct drm_device *dev = crtc->dev;
5652         struct drm_i915_private *dev_priv = to_i915(dev);
5653         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5654         int pipe = intel_crtc->pipe;
5655         struct intel_atomic_state *old_intel_state =
5656                 to_intel_atomic_state(old_state);
5657
5658         if (WARN_ON(intel_crtc->active))
5659                 return;
5660
5661         /*
5662          * Sometimes spurious CPU pipe underruns happen during FDI
5663          * training, at least with VGA+HDMI cloning. Suppress them.
5664          *
5665          * On ILK we get an occasional spurious CPU pipe underruns
5666          * between eDP port A enable and vdd enable. Also PCH port
5667          * enable seems to result in the occasional CPU pipe underrun.
5668          *
5669          * Spurious PCH underruns also occur during PCH enabling.
5670          */
5671         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5672         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5673
5674         if (pipe_config->has_pch_encoder)
5675                 intel_prepare_shared_dpll(pipe_config);
5676
5677         if (intel_crtc_has_dp_encoder(pipe_config))
5678                 intel_dp_set_m_n(pipe_config, M1_N1);
5679
5680         intel_set_pipe_timings(pipe_config);
5681         intel_set_pipe_src_size(pipe_config);
5682
5683         if (pipe_config->has_pch_encoder) {
5684                 intel_cpu_transcoder_set_m_n(pipe_config,
5685                                              &pipe_config->fdi_m_n, NULL);
5686         }
5687
5688         ironlake_set_pipeconf(pipe_config);
5689
5690         intel_crtc->active = true;
5691
5692         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5693
5694         if (pipe_config->has_pch_encoder) {
5695                 /* Note: FDI PLL enabling _must_ be done before we enable the
5696                  * cpu pipes, hence this is separate from all the other fdi/pch
5697                  * enabling. */
5698                 ironlake_fdi_pll_enable(pipe_config);
5699         } else {
5700                 assert_fdi_tx_disabled(dev_priv, pipe);
5701                 assert_fdi_rx_disabled(dev_priv, pipe);
5702         }
5703
5704         ironlake_pfit_enable(pipe_config);
5705
5706         /*
5707          * On ILK+ LUT must be loaded before the pipe is running but with
5708          * clocks enabled
5709          */
5710         intel_color_load_luts(pipe_config);
5711
5712         if (dev_priv->display.initial_watermarks != NULL)
5713                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5714         intel_enable_pipe(pipe_config);
5715
5716         if (pipe_config->has_pch_encoder)
5717                 ironlake_pch_enable(old_intel_state, pipe_config);
5718
5719         assert_vblank_disabled(crtc);
5720         intel_crtc_vblank_on(pipe_config);
5721
5722         intel_encoders_enable(crtc, pipe_config, old_state);
5723
5724         if (HAS_PCH_CPT(dev_priv))
5725                 cpt_verify_modeset(dev, intel_crtc->pipe);
5726
5727         /*
5728          * Must wait for vblank to avoid spurious PCH FIFO underruns.
5729          * And a second vblank wait is needed at least on ILK with
5730          * some interlaced HDMI modes. Let's do the double wait always
5731          * in case there are more corner cases we don't know about.
5732          */
5733         if (pipe_config->has_pch_encoder) {
5734                 intel_wait_for_vblank(dev_priv, pipe);
5735                 intel_wait_for_vblank(dev_priv, pipe);
5736         }
5737         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5738         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5739 }
5740
5741 /* IPS only exists on ULT machines and is tied to pipe A. */
5742 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5743 {
5744         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5745 }
5746
5747 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5748                                             enum pipe pipe, bool apply)
5749 {
5750         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5751         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5752
5753         if (apply)
5754                 val |= mask;
5755         else
5756                 val &= ~mask;
5757
5758         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5759 }
5760
5761 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5762 {
5763         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5764         enum pipe pipe = crtc->pipe;
5765         u32 val;
5766
5767         val = MBUS_DBOX_A_CREDIT(2);
5768         val |= MBUS_DBOX_BW_CREDIT(1);
5769         val |= MBUS_DBOX_B_CREDIT(8);
5770
5771         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5772 }
5773
5774 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5775                                 struct drm_atomic_state *old_state)
5776 {
5777         struct drm_crtc *crtc = pipe_config->base.crtc;
5778         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5779         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5780         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5781         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
5782         struct intel_atomic_state *old_intel_state =
5783                 to_intel_atomic_state(old_state);
5784         bool psl_clkgate_wa;
5785         u32 pipe_chicken;
5786
5787         if (WARN_ON(intel_crtc->active))
5788                 return;
5789
5790         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5791
5792         if (pipe_config->shared_dpll)
5793                 intel_enable_shared_dpll(pipe_config);
5794
5795         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5796
5797         if (intel_crtc_has_dp_encoder(pipe_config))
5798                 intel_dp_set_m_n(pipe_config, M1_N1);
5799
5800         if (!transcoder_is_dsi(cpu_transcoder))
5801                 intel_set_pipe_timings(pipe_config);
5802
5803         intel_set_pipe_src_size(pipe_config);
5804
5805         if (cpu_transcoder != TRANSCODER_EDP &&
5806             !transcoder_is_dsi(cpu_transcoder)) {
5807                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5808                            pipe_config->pixel_multiplier - 1);
5809         }
5810
5811         if (pipe_config->has_pch_encoder) {
5812                 intel_cpu_transcoder_set_m_n(pipe_config,
5813                                              &pipe_config->fdi_m_n, NULL);
5814         }
5815
5816         if (!transcoder_is_dsi(cpu_transcoder))
5817                 haswell_set_pipeconf(pipe_config);
5818
5819         haswell_set_pipemisc(pipe_config);
5820
5821         intel_color_set_csc(pipe_config);
5822
5823         intel_crtc->active = true;
5824
5825         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5826         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5827                          pipe_config->pch_pfit.enabled;
5828         if (psl_clkgate_wa)
5829                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5830
5831         if (INTEL_GEN(dev_priv) >= 9)
5832                 skylake_pfit_enable(pipe_config);
5833         else
5834                 ironlake_pfit_enable(pipe_config);
5835
5836         /*
5837          * On ILK+ LUT must be loaded before the pipe is running but with
5838          * clocks enabled
5839          */
5840         intel_color_load_luts(pipe_config);
5841
5842         /*
5843          * Display WA #1153: enable hardware to bypass the alpha math
5844          * and rounding for per-pixel values 00 and 0xff
5845          */
5846         if (INTEL_GEN(dev_priv) >= 11) {
5847                 pipe_chicken = I915_READ(PIPE_CHICKEN(pipe));
5848                 if (!(pipe_chicken & PER_PIXEL_ALPHA_BYPASS_EN))
5849                         I915_WRITE_FW(PIPE_CHICKEN(pipe),
5850                                       pipe_chicken | PER_PIXEL_ALPHA_BYPASS_EN);
5851         }
5852
5853         intel_ddi_set_pipe_settings(pipe_config);
5854         if (!transcoder_is_dsi(cpu_transcoder))
5855                 intel_ddi_enable_transcoder_func(pipe_config);
5856
5857         if (dev_priv->display.initial_watermarks != NULL)
5858                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5859
5860         if (INTEL_GEN(dev_priv) >= 11)
5861                 icl_pipe_mbus_enable(intel_crtc);
5862
5863         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5864         if (!transcoder_is_dsi(cpu_transcoder))
5865                 intel_enable_pipe(pipe_config);
5866
5867         if (pipe_config->has_pch_encoder)
5868                 lpt_pch_enable(old_intel_state, pipe_config);
5869
5870         if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DP_MST))
5871                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5872
5873         assert_vblank_disabled(crtc);
5874         intel_crtc_vblank_on(pipe_config);
5875
5876         intel_encoders_enable(crtc, pipe_config, old_state);
5877
5878         if (psl_clkgate_wa) {
5879                 intel_wait_for_vblank(dev_priv, pipe);
5880                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5881         }
5882
5883         /* If we change the relative order between pipe/planes enabling, we need
5884          * to change the workaround. */
5885         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5886         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5887                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5888                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5889         }
5890 }
5891
5892 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state)
5893 {
5894         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5895         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5896         enum pipe pipe = crtc->pipe;
5897
5898         /* To avoid upsetting the power well on haswell only disable the pfit if
5899          * it's in use. The hw state code will make sure we get this right. */
5900         if (old_crtc_state->pch_pfit.enabled) {
5901                 I915_WRITE(PF_CTL(pipe), 0);
5902                 I915_WRITE(PF_WIN_POS(pipe), 0);
5903                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5904         }
5905 }
5906
5907 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5908                                   struct drm_atomic_state *old_state)
5909 {
5910         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5911         struct drm_device *dev = crtc->dev;
5912         struct drm_i915_private *dev_priv = to_i915(dev);
5913         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5914         int pipe = intel_crtc->pipe;
5915
5916         /*
5917          * Sometimes spurious CPU pipe underruns happen when the
5918          * pipe is already disabled, but FDI RX/TX is still enabled.
5919          * Happens at least with VGA+HDMI cloning. Suppress them.
5920          */
5921         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5922         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5923
5924         intel_encoders_disable(crtc, old_crtc_state, old_state);
5925
5926         drm_crtc_vblank_off(crtc);
5927         assert_vblank_disabled(crtc);
5928
5929         intel_disable_pipe(old_crtc_state);
5930
5931         ironlake_pfit_disable(old_crtc_state);
5932
5933         if (old_crtc_state->has_pch_encoder)
5934                 ironlake_fdi_disable(crtc);
5935
5936         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5937
5938         if (old_crtc_state->has_pch_encoder) {
5939                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5940
5941                 if (HAS_PCH_CPT(dev_priv)) {
5942                         i915_reg_t reg;
5943                         u32 temp;
5944
5945                         /* disable TRANS_DP_CTL */
5946                         reg = TRANS_DP_CTL(pipe);
5947                         temp = I915_READ(reg);
5948                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5949                                   TRANS_DP_PORT_SEL_MASK);
5950                         temp |= TRANS_DP_PORT_SEL_NONE;
5951                         I915_WRITE(reg, temp);
5952
5953                         /* disable DPLL_SEL */
5954                         temp = I915_READ(PCH_DPLL_SEL);
5955                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5956                         I915_WRITE(PCH_DPLL_SEL, temp);
5957                 }
5958
5959                 ironlake_fdi_pll_disable(intel_crtc);
5960         }
5961
5962         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5963         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5964 }
5965
5966 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5967                                  struct drm_atomic_state *old_state)
5968 {
5969         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5970         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5971         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5972         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
5973
5974         intel_encoders_disable(crtc, old_crtc_state, old_state);
5975
5976         drm_crtc_vblank_off(crtc);
5977         assert_vblank_disabled(crtc);
5978
5979         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5980         if (!transcoder_is_dsi(cpu_transcoder))
5981                 intel_disable_pipe(old_crtc_state);
5982
5983         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
5984                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
5985
5986         if (!transcoder_is_dsi(cpu_transcoder))
5987                 intel_ddi_disable_transcoder_func(old_crtc_state);
5988
5989         intel_dsc_disable(old_crtc_state);
5990
5991         if (INTEL_GEN(dev_priv) >= 9)
5992                 skylake_scaler_disable(intel_crtc);
5993         else
5994                 ironlake_pfit_disable(old_crtc_state);
5995
5996         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5997
5998         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
5999 }
6000
6001 static void i9xx_pfit_enable(const struct intel_crtc_state *crtc_state)
6002 {
6003         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6004         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6005
6006         if (!crtc_state->gmch_pfit.control)
6007                 return;
6008
6009         /*
6010          * The panel fitter should only be adjusted whilst the pipe is disabled,
6011          * according to register description and PRM.
6012          */
6013         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
6014         assert_pipe_disabled(dev_priv, crtc->pipe);
6015
6016         I915_WRITE(PFIT_PGM_RATIOS, crtc_state->gmch_pfit.pgm_ratios);
6017         I915_WRITE(PFIT_CONTROL, crtc_state->gmch_pfit.control);
6018
6019         /* Border color in case we don't scale up to the full screen. Black by
6020          * default, change to something else for debugging. */
6021         I915_WRITE(BCLRPAT(crtc->pipe), 0);
6022 }
6023
6024 bool intel_port_is_combophy(struct drm_i915_private *dev_priv, enum port port)
6025 {
6026         if (port == PORT_NONE)
6027                 return false;
6028
6029         if (IS_ICELAKE(dev_priv))
6030                 return port <= PORT_B;
6031
6032         return false;
6033 }
6034
6035 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
6036 {
6037         if (IS_ICELAKE(dev_priv))
6038                 return port >= PORT_C && port <= PORT_F;
6039
6040         return false;
6041 }
6042
6043 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
6044 {
6045         if (!intel_port_is_tc(dev_priv, port))
6046                 return PORT_TC_NONE;
6047
6048         return port - PORT_C;
6049 }
6050
6051 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
6052 {
6053         switch (port) {
6054         case PORT_A:
6055                 return POWER_DOMAIN_PORT_DDI_A_LANES;
6056         case PORT_B:
6057                 return POWER_DOMAIN_PORT_DDI_B_LANES;
6058         case PORT_C:
6059                 return POWER_DOMAIN_PORT_DDI_C_LANES;
6060         case PORT_D:
6061                 return POWER_DOMAIN_PORT_DDI_D_LANES;
6062         case PORT_E:
6063                 return POWER_DOMAIN_PORT_DDI_E_LANES;
6064         case PORT_F:
6065                 return POWER_DOMAIN_PORT_DDI_F_LANES;
6066         default:
6067                 MISSING_CASE(port);
6068                 return POWER_DOMAIN_PORT_OTHER;
6069         }
6070 }
6071
6072 enum intel_display_power_domain
6073 intel_aux_power_domain(struct intel_digital_port *dig_port)
6074 {
6075         switch (dig_port->aux_ch) {
6076         case AUX_CH_A:
6077                 return POWER_DOMAIN_AUX_A;
6078         case AUX_CH_B:
6079                 return POWER_DOMAIN_AUX_B;
6080         case AUX_CH_C:
6081                 return POWER_DOMAIN_AUX_C;
6082         case AUX_CH_D:
6083                 return POWER_DOMAIN_AUX_D;
6084         case AUX_CH_E:
6085                 return POWER_DOMAIN_AUX_E;
6086         case AUX_CH_F:
6087                 return POWER_DOMAIN_AUX_F;
6088         default:
6089                 MISSING_CASE(dig_port->aux_ch);
6090                 return POWER_DOMAIN_AUX_A;
6091         }
6092 }
6093
6094 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
6095                                   struct intel_crtc_state *crtc_state)
6096 {
6097         struct drm_device *dev = crtc->dev;
6098         struct drm_i915_private *dev_priv = to_i915(dev);
6099         struct drm_encoder *encoder;
6100         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6101         enum pipe pipe = intel_crtc->pipe;
6102         u64 mask;
6103         enum transcoder transcoder = crtc_state->cpu_transcoder;
6104
6105         if (!crtc_state->base.active)
6106                 return 0;
6107
6108         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
6109         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
6110         if (crtc_state->pch_pfit.enabled ||
6111             crtc_state->pch_pfit.force_thru)
6112                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
6113
6114         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
6115                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6116
6117                 mask |= BIT_ULL(intel_encoder->power_domain);
6118         }
6119
6120         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
6121                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
6122
6123         if (crtc_state->shared_dpll)
6124                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
6125
6126         return mask;
6127 }
6128
6129 static u64
6130 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
6131                                struct intel_crtc_state *crtc_state)
6132 {
6133         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6134         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6135         enum intel_display_power_domain domain;
6136         u64 domains, new_domains, old_domains;
6137
6138         old_domains = intel_crtc->enabled_power_domains;
6139         intel_crtc->enabled_power_domains = new_domains =
6140                 get_crtc_power_domains(crtc, crtc_state);
6141
6142         domains = new_domains & ~old_domains;
6143
6144         for_each_power_domain(domain, domains)
6145                 intel_display_power_get(dev_priv, domain);
6146
6147         return old_domains & ~new_domains;
6148 }
6149
6150 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
6151                                       u64 domains)
6152 {
6153         enum intel_display_power_domain domain;
6154
6155         for_each_power_domain(domain, domains)
6156                 intel_display_power_put_unchecked(dev_priv, domain);
6157 }
6158
6159 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6160                                    struct drm_atomic_state *old_state)
6161 {
6162         struct intel_atomic_state *old_intel_state =
6163                 to_intel_atomic_state(old_state);
6164         struct drm_crtc *crtc = pipe_config->base.crtc;
6165         struct drm_device *dev = crtc->dev;
6166         struct drm_i915_private *dev_priv = to_i915(dev);
6167         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6168         int pipe = intel_crtc->pipe;
6169
6170         if (WARN_ON(intel_crtc->active))
6171                 return;
6172
6173         if (intel_crtc_has_dp_encoder(pipe_config))
6174                 intel_dp_set_m_n(pipe_config, M1_N1);
6175
6176         intel_set_pipe_timings(pipe_config);
6177         intel_set_pipe_src_size(pipe_config);
6178
6179         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6180                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6181                 I915_WRITE(CHV_CANVAS(pipe), 0);
6182         }
6183
6184         i9xx_set_pipeconf(pipe_config);
6185
6186         intel_color_set_csc(pipe_config);
6187
6188         intel_crtc->active = true;
6189
6190         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6191
6192         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6193
6194         if (IS_CHERRYVIEW(dev_priv)) {
6195                 chv_prepare_pll(intel_crtc, pipe_config);
6196                 chv_enable_pll(intel_crtc, pipe_config);
6197         } else {
6198                 vlv_prepare_pll(intel_crtc, pipe_config);
6199                 vlv_enable_pll(intel_crtc, pipe_config);
6200         }
6201
6202         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6203
6204         i9xx_pfit_enable(pipe_config);
6205
6206         intel_color_load_luts(pipe_config);
6207
6208         dev_priv->display.initial_watermarks(old_intel_state,
6209                                              pipe_config);
6210         intel_enable_pipe(pipe_config);
6211
6212         assert_vblank_disabled(crtc);
6213         intel_crtc_vblank_on(pipe_config);
6214
6215         intel_encoders_enable(crtc, pipe_config, old_state);
6216 }
6217
6218 static void i9xx_set_pll_dividers(const struct intel_crtc_state *crtc_state)
6219 {
6220         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6221         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6222
6223         I915_WRITE(FP0(crtc->pipe), crtc_state->dpll_hw_state.fp0);
6224         I915_WRITE(FP1(crtc->pipe), crtc_state->dpll_hw_state.fp1);
6225 }
6226
6227 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6228                              struct drm_atomic_state *old_state)
6229 {
6230         struct intel_atomic_state *old_intel_state =
6231                 to_intel_atomic_state(old_state);
6232         struct drm_crtc *crtc = pipe_config->base.crtc;
6233         struct drm_device *dev = crtc->dev;
6234         struct drm_i915_private *dev_priv = to_i915(dev);
6235         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6236         enum pipe pipe = intel_crtc->pipe;
6237
6238         if (WARN_ON(intel_crtc->active))
6239                 return;
6240
6241         i9xx_set_pll_dividers(pipe_config);
6242
6243         if (intel_crtc_has_dp_encoder(pipe_config))
6244                 intel_dp_set_m_n(pipe_config, M1_N1);
6245
6246         intel_set_pipe_timings(pipe_config);
6247         intel_set_pipe_src_size(pipe_config);
6248
6249         i9xx_set_pipeconf(pipe_config);
6250
6251         intel_crtc->active = true;
6252
6253         if (!IS_GEN(dev_priv, 2))
6254                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6255
6256         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6257
6258         i9xx_enable_pll(intel_crtc, pipe_config);
6259
6260         i9xx_pfit_enable(pipe_config);
6261
6262         intel_color_load_luts(pipe_config);
6263
6264         if (dev_priv->display.initial_watermarks != NULL)
6265                 dev_priv->display.initial_watermarks(old_intel_state,
6266                                                      pipe_config);
6267         else
6268                 intel_update_watermarks(intel_crtc);
6269         intel_enable_pipe(pipe_config);
6270
6271         assert_vblank_disabled(crtc);
6272         intel_crtc_vblank_on(pipe_config);
6273
6274         intel_encoders_enable(crtc, pipe_config, old_state);
6275 }
6276
6277 static void i9xx_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6278 {
6279         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6280         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6281
6282         if (!old_crtc_state->gmch_pfit.control)
6283                 return;
6284
6285         assert_pipe_disabled(dev_priv, crtc->pipe);
6286
6287         DRM_DEBUG_KMS("disabling pfit, current: 0x%08x\n",
6288                       I915_READ(PFIT_CONTROL));
6289         I915_WRITE(PFIT_CONTROL, 0);
6290 }
6291
6292 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6293                               struct drm_atomic_state *old_state)
6294 {
6295         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6296         struct drm_device *dev = crtc->dev;
6297         struct drm_i915_private *dev_priv = to_i915(dev);
6298         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6299         int pipe = intel_crtc->pipe;
6300
6301         /*
6302          * On gen2 planes are double buffered but the pipe isn't, so we must
6303          * wait for planes to fully turn off before disabling the pipe.
6304          */
6305         if (IS_GEN(dev_priv, 2))
6306                 intel_wait_for_vblank(dev_priv, pipe);
6307
6308         intel_encoders_disable(crtc, old_crtc_state, old_state);
6309
6310         drm_crtc_vblank_off(crtc);
6311         assert_vblank_disabled(crtc);
6312
6313         intel_disable_pipe(old_crtc_state);
6314
6315         i9xx_pfit_disable(old_crtc_state);
6316
6317         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6318
6319         if (!intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DSI)) {
6320                 if (IS_CHERRYVIEW(dev_priv))
6321                         chv_disable_pll(dev_priv, pipe);
6322                 else if (IS_VALLEYVIEW(dev_priv))
6323                         vlv_disable_pll(dev_priv, pipe);
6324                 else
6325                         i9xx_disable_pll(old_crtc_state);
6326         }
6327
6328         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6329
6330         if (!IS_GEN(dev_priv, 2))
6331                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6332
6333         if (!dev_priv->display.initial_watermarks)
6334                 intel_update_watermarks(intel_crtc);
6335
6336         /* clock the pipe down to 640x480@60 to potentially save power */
6337         if (IS_I830(dev_priv))
6338                 i830_enable_pipe(dev_priv, pipe);
6339 }
6340
6341 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6342                                         struct drm_modeset_acquire_ctx *ctx)
6343 {
6344         struct intel_encoder *encoder;
6345         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6346         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6347         enum intel_display_power_domain domain;
6348         struct intel_plane *plane;
6349         u64 domains;
6350         struct drm_atomic_state *state;
6351         struct intel_crtc_state *crtc_state;
6352         int ret;
6353
6354         if (!intel_crtc->active)
6355                 return;
6356
6357         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6358                 const struct intel_plane_state *plane_state =
6359                         to_intel_plane_state(plane->base.state);
6360
6361                 if (plane_state->base.visible)
6362                         intel_plane_disable_noatomic(intel_crtc, plane);
6363         }
6364
6365         state = drm_atomic_state_alloc(crtc->dev);
6366         if (!state) {
6367                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6368                               crtc->base.id, crtc->name);
6369                 return;
6370         }
6371
6372         state->acquire_ctx = ctx;
6373
6374         /* Everything's already locked, -EDEADLK can't happen. */
6375         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6376         ret = drm_atomic_add_affected_connectors(state, crtc);
6377
6378         WARN_ON(IS_ERR(crtc_state) || ret);
6379
6380         dev_priv->display.crtc_disable(crtc_state, state);
6381
6382         drm_atomic_state_put(state);
6383
6384         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6385                       crtc->base.id, crtc->name);
6386
6387         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6388         crtc->state->active = false;
6389         intel_crtc->active = false;
6390         crtc->enabled = false;
6391         crtc->state->connector_mask = 0;
6392         crtc->state->encoder_mask = 0;
6393
6394         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6395                 encoder->base.crtc = NULL;
6396
6397         intel_fbc_disable(intel_crtc);
6398         intel_update_watermarks(intel_crtc);
6399         intel_disable_shared_dpll(to_intel_crtc_state(crtc->state));
6400
6401         domains = intel_crtc->enabled_power_domains;
6402         for_each_power_domain(domain, domains)
6403                 intel_display_power_put_unchecked(dev_priv, domain);
6404         intel_crtc->enabled_power_domains = 0;
6405
6406         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6407         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6408         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6409 }
6410
6411 /*
6412  * turn all crtc's off, but do not adjust state
6413  * This has to be paired with a call to intel_modeset_setup_hw_state.
6414  */
6415 int intel_display_suspend(struct drm_device *dev)
6416 {
6417         struct drm_i915_private *dev_priv = to_i915(dev);
6418         struct drm_atomic_state *state;
6419         int ret;
6420
6421         state = drm_atomic_helper_suspend(dev);
6422         ret = PTR_ERR_OR_ZERO(state);
6423         if (ret)
6424                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6425         else
6426                 dev_priv->modeset_restore_state = state;
6427         return ret;
6428 }
6429
6430 void intel_encoder_destroy(struct drm_encoder *encoder)
6431 {
6432         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6433
6434         drm_encoder_cleanup(encoder);
6435         kfree(intel_encoder);
6436 }
6437
6438 /* Cross check the actual hw state with our own modeset state tracking (and it's
6439  * internal consistency). */
6440 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6441                                          struct drm_connector_state *conn_state)
6442 {
6443         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6444
6445         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6446                       connector->base.base.id,
6447                       connector->base.name);
6448
6449         if (connector->get_hw_state(connector)) {
6450                 struct intel_encoder *encoder = connector->encoder;
6451
6452                 I915_STATE_WARN(!crtc_state,
6453                          "connector enabled without attached crtc\n");
6454
6455                 if (!crtc_state)
6456                         return;
6457
6458                 I915_STATE_WARN(!crtc_state->active,
6459                       "connector is active, but attached crtc isn't\n");
6460
6461                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6462                         return;
6463
6464                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6465                         "atomic encoder doesn't match attached encoder\n");
6466
6467                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6468                         "attached encoder crtc differs from connector crtc\n");
6469         } else {
6470                 I915_STATE_WARN(crtc_state && crtc_state->active,
6471                         "attached crtc is active, but connector isn't\n");
6472                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6473                         "best encoder set without crtc!\n");
6474         }
6475 }
6476
6477 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6478 {
6479         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6480                 return crtc_state->fdi_lanes;
6481
6482         return 0;
6483 }
6484
6485 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6486                                      struct intel_crtc_state *pipe_config)
6487 {
6488         struct drm_i915_private *dev_priv = to_i915(dev);
6489         struct drm_atomic_state *state = pipe_config->base.state;
6490         struct intel_crtc *other_crtc;
6491         struct intel_crtc_state *other_crtc_state;
6492
6493         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6494                       pipe_name(pipe), pipe_config->fdi_lanes);
6495         if (pipe_config->fdi_lanes > 4) {
6496                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6497                               pipe_name(pipe), pipe_config->fdi_lanes);
6498                 return -EINVAL;
6499         }
6500
6501         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6502                 if (pipe_config->fdi_lanes > 2) {
6503                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6504                                       pipe_config->fdi_lanes);
6505                         return -EINVAL;
6506                 } else {
6507                         return 0;
6508                 }
6509         }
6510
6511         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6512                 return 0;
6513
6514         /* Ivybridge 3 pipe is really complicated */
6515         switch (pipe) {
6516         case PIPE_A:
6517                 return 0;
6518         case PIPE_B:
6519                 if (pipe_config->fdi_lanes <= 2)
6520                         return 0;
6521
6522                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6523                 other_crtc_state =
6524                         intel_atomic_get_crtc_state(state, other_crtc);
6525                 if (IS_ERR(other_crtc_state))
6526                         return PTR_ERR(other_crtc_state);
6527
6528                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6529                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6530                                       pipe_name(pipe), pipe_config->fdi_lanes);
6531                         return -EINVAL;
6532                 }
6533                 return 0;
6534         case PIPE_C:
6535                 if (pipe_config->fdi_lanes > 2) {
6536                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6537                                       pipe_name(pipe), pipe_config->fdi_lanes);
6538                         return -EINVAL;
6539                 }
6540
6541                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6542                 other_crtc_state =
6543                         intel_atomic_get_crtc_state(state, other_crtc);
6544                 if (IS_ERR(other_crtc_state))
6545                         return PTR_ERR(other_crtc_state);
6546
6547                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6548                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6549                         return -EINVAL;
6550                 }
6551                 return 0;
6552         default:
6553                 BUG();
6554         }
6555 }
6556
6557 #define RETRY 1
6558 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6559                                        struct intel_crtc_state *pipe_config)
6560 {
6561         struct drm_device *dev = intel_crtc->base.dev;
6562         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6563         int lane, link_bw, fdi_dotclock, ret;
6564         bool needs_recompute = false;
6565
6566 retry:
6567         /* FDI is a binary signal running at ~2.7GHz, encoding
6568          * each output octet as 10 bits. The actual frequency
6569          * is stored as a divider into a 100MHz clock, and the
6570          * mode pixel clock is stored in units of 1KHz.
6571          * Hence the bw of each lane in terms of the mode signal
6572          * is:
6573          */
6574         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6575
6576         fdi_dotclock = adjusted_mode->crtc_clock;
6577
6578         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6579                                            pipe_config->pipe_bpp);
6580
6581         pipe_config->fdi_lanes = lane;
6582
6583         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6584                                link_bw, &pipe_config->fdi_m_n, false);
6585
6586         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6587         if (ret == -EDEADLK)
6588                 return ret;
6589
6590         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6591                 pipe_config->pipe_bpp -= 2*3;
6592                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6593                               pipe_config->pipe_bpp);
6594                 needs_recompute = true;
6595                 pipe_config->bw_constrained = true;
6596
6597                 goto retry;
6598         }
6599
6600         if (needs_recompute)
6601                 return RETRY;
6602
6603         return ret;
6604 }
6605
6606 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6607 {
6608         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6609         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6610
6611         /* IPS only exists on ULT machines and is tied to pipe A. */
6612         if (!hsw_crtc_supports_ips(crtc))
6613                 return false;
6614
6615         if (!i915_modparams.enable_ips)
6616                 return false;
6617
6618         if (crtc_state->pipe_bpp > 24)
6619                 return false;
6620
6621         /*
6622          * We compare against max which means we must take
6623          * the increased cdclk requirement into account when
6624          * calculating the new cdclk.
6625          *
6626          * Should measure whether using a lower cdclk w/o IPS
6627          */
6628         if (IS_BROADWELL(dev_priv) &&
6629             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6630                 return false;
6631
6632         return true;
6633 }
6634
6635 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6636 {
6637         struct drm_i915_private *dev_priv =
6638                 to_i915(crtc_state->base.crtc->dev);
6639         struct intel_atomic_state *intel_state =
6640                 to_intel_atomic_state(crtc_state->base.state);
6641
6642         if (!hsw_crtc_state_ips_capable(crtc_state))
6643                 return false;
6644
6645         if (crtc_state->ips_force_disable)
6646                 return false;
6647
6648         /* IPS should be fine as long as at least one plane is enabled. */
6649         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6650                 return false;
6651
6652         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6653         if (IS_BROADWELL(dev_priv) &&
6654             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6655                 return false;
6656
6657         return true;
6658 }
6659
6660 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6661 {
6662         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6663
6664         /* GDG double wide on either pipe, otherwise pipe A only */
6665         return INTEL_GEN(dev_priv) < 4 &&
6666                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6667 }
6668
6669 static u32 ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6670 {
6671         u32 pixel_rate;
6672
6673         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6674
6675         /*
6676          * We only use IF-ID interlacing. If we ever use
6677          * PF-ID we'll need to adjust the pixel_rate here.
6678          */
6679
6680         if (pipe_config->pch_pfit.enabled) {
6681                 u64 pipe_w, pipe_h, pfit_w, pfit_h;
6682                 u32 pfit_size = pipe_config->pch_pfit.size;
6683
6684                 pipe_w = pipe_config->pipe_src_w;
6685                 pipe_h = pipe_config->pipe_src_h;
6686
6687                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6688                 pfit_h = pfit_size & 0xFFFF;
6689                 if (pipe_w < pfit_w)
6690                         pipe_w = pfit_w;
6691                 if (pipe_h < pfit_h)
6692                         pipe_h = pfit_h;
6693
6694                 if (WARN_ON(!pfit_w || !pfit_h))
6695                         return pixel_rate;
6696
6697                 pixel_rate = div_u64((u64)pixel_rate * pipe_w * pipe_h,
6698                                      pfit_w * pfit_h);
6699         }
6700
6701         return pixel_rate;
6702 }
6703
6704 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6705 {
6706         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6707
6708         if (HAS_GMCH_DISPLAY(dev_priv))
6709                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6710                 crtc_state->pixel_rate =
6711                         crtc_state->base.adjusted_mode.crtc_clock;
6712         else
6713                 crtc_state->pixel_rate =
6714                         ilk_pipe_pixel_rate(crtc_state);
6715 }
6716
6717 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6718                                      struct intel_crtc_state *pipe_config)
6719 {
6720         struct drm_device *dev = crtc->base.dev;
6721         struct drm_i915_private *dev_priv = to_i915(dev);
6722         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6723         int clock_limit = dev_priv->max_dotclk_freq;
6724
6725         if (INTEL_GEN(dev_priv) < 4) {
6726                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6727
6728                 /*
6729                  * Enable double wide mode when the dot clock
6730                  * is > 90% of the (display) core speed.
6731                  */
6732                 if (intel_crtc_supports_double_wide(crtc) &&
6733                     adjusted_mode->crtc_clock > clock_limit) {
6734                         clock_limit = dev_priv->max_dotclk_freq;
6735                         pipe_config->double_wide = true;
6736                 }
6737         }
6738
6739         if (adjusted_mode->crtc_clock > clock_limit) {
6740                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6741                               adjusted_mode->crtc_clock, clock_limit,
6742                               yesno(pipe_config->double_wide));
6743                 return -EINVAL;
6744         }
6745
6746         if ((pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
6747              pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR444) &&
6748              pipe_config->base.ctm) {
6749                 /*
6750                  * There is only one pipe CSC unit per pipe, and we need that
6751                  * for output conversion from RGB->YCBCR. So if CTM is already
6752                  * applied we can't support YCBCR420 output.
6753                  */
6754                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6755                 return -EINVAL;
6756         }
6757
6758         /*
6759          * Pipe horizontal size must be even in:
6760          * - DVO ganged mode
6761          * - LVDS dual channel mode
6762          * - Double wide pipe
6763          */
6764         if (pipe_config->pipe_src_w & 1) {
6765                 if (pipe_config->double_wide) {
6766                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6767                         return -EINVAL;
6768                 }
6769
6770                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6771                     intel_is_dual_link_lvds(dev)) {
6772                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6773                         return -EINVAL;
6774                 }
6775         }
6776
6777         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6778          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6779          */
6780         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6781                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6782                 return -EINVAL;
6783
6784         intel_crtc_compute_pixel_rate(pipe_config);
6785
6786         if (pipe_config->has_pch_encoder)
6787                 return ironlake_fdi_compute_config(crtc, pipe_config);
6788
6789         return 0;
6790 }
6791
6792 static void
6793 intel_reduce_m_n_ratio(u32 *num, u32 *den)
6794 {
6795         while (*num > DATA_LINK_M_N_MASK ||
6796                *den > DATA_LINK_M_N_MASK) {
6797                 *num >>= 1;
6798                 *den >>= 1;
6799         }
6800 }
6801
6802 static void compute_m_n(unsigned int m, unsigned int n,
6803                         u32 *ret_m, u32 *ret_n,
6804                         bool constant_n)
6805 {
6806         /*
6807          * Several DP dongles in particular seem to be fussy about
6808          * too large link M/N values. Give N value as 0x8000 that
6809          * should be acceptable by specific devices. 0x8000 is the
6810          * specified fixed N value for asynchronous clock mode,
6811          * which the devices expect also in synchronous clock mode.
6812          */
6813         if (constant_n)
6814                 *ret_n = 0x8000;
6815         else
6816                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6817
6818         *ret_m = div_u64((u64)m * *ret_n, n);
6819         intel_reduce_m_n_ratio(ret_m, ret_n);
6820 }
6821
6822 void
6823 intel_link_compute_m_n(u16 bits_per_pixel, int nlanes,
6824                        int pixel_clock, int link_clock,
6825                        struct intel_link_m_n *m_n,
6826                        bool constant_n)
6827 {
6828         m_n->tu = 64;
6829
6830         compute_m_n(bits_per_pixel * pixel_clock,
6831                     link_clock * nlanes * 8,
6832                     &m_n->gmch_m, &m_n->gmch_n,
6833                     constant_n);
6834
6835         compute_m_n(pixel_clock, link_clock,
6836                     &m_n->link_m, &m_n->link_n,
6837                     constant_n);
6838 }
6839
6840 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6841 {
6842         if (i915_modparams.panel_use_ssc >= 0)
6843                 return i915_modparams.panel_use_ssc != 0;
6844         return dev_priv->vbt.lvds_use_ssc
6845                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6846 }
6847
6848 static u32 pnv_dpll_compute_fp(struct dpll *dpll)
6849 {
6850         return (1 << dpll->n) << 16 | dpll->m2;
6851 }
6852
6853 static u32 i9xx_dpll_compute_fp(struct dpll *dpll)
6854 {
6855         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6856 }
6857
6858 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6859                                      struct intel_crtc_state *crtc_state,
6860                                      struct dpll *reduced_clock)
6861 {
6862         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6863         u32 fp, fp2 = 0;
6864
6865         if (IS_PINEVIEW(dev_priv)) {
6866                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6867                 if (reduced_clock)
6868                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6869         } else {
6870                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6871                 if (reduced_clock)
6872                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6873         }
6874
6875         crtc_state->dpll_hw_state.fp0 = fp;
6876
6877         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6878             reduced_clock) {
6879                 crtc_state->dpll_hw_state.fp1 = fp2;
6880         } else {
6881                 crtc_state->dpll_hw_state.fp1 = fp;
6882         }
6883 }
6884
6885 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6886                 pipe)
6887 {
6888         u32 reg_val;
6889
6890         /*
6891          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6892          * and set it to a reasonable value instead.
6893          */
6894         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6895         reg_val &= 0xffffff00;
6896         reg_val |= 0x00000030;
6897         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6898
6899         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6900         reg_val &= 0x00ffffff;
6901         reg_val |= 0x8c000000;
6902         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6903
6904         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6905         reg_val &= 0xffffff00;
6906         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6907
6908         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6909         reg_val &= 0x00ffffff;
6910         reg_val |= 0xb0000000;
6911         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6912 }
6913
6914 static void intel_pch_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
6915                                          const struct intel_link_m_n *m_n)
6916 {
6917         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6918         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6919         enum pipe pipe = crtc->pipe;
6920
6921         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6922         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6923         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6924         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6925 }
6926
6927 static bool transcoder_has_m2_n2(struct drm_i915_private *dev_priv,
6928                                  enum transcoder transcoder)
6929 {
6930         if (IS_HASWELL(dev_priv))
6931                 return transcoder == TRANSCODER_EDP;
6932
6933         /*
6934          * Strictly speaking some registers are available before
6935          * gen7, but we only support DRRS on gen7+
6936          */
6937         return IS_GEN(dev_priv, 7) || IS_CHERRYVIEW(dev_priv);
6938 }
6939
6940 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
6941                                          const struct intel_link_m_n *m_n,
6942                                          const struct intel_link_m_n *m2_n2)
6943 {
6944         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6945         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6946         enum pipe pipe = crtc->pipe;
6947         enum transcoder transcoder = crtc_state->cpu_transcoder;
6948
6949         if (INTEL_GEN(dev_priv) >= 5) {
6950                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6951                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6952                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6953                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6954                 /*
6955                  *  M2_N2 registers are set only if DRRS is supported
6956                  * (to make sure the registers are not unnecessarily accessed).
6957                  */
6958                 if (m2_n2 && crtc_state->has_drrs &&
6959                     transcoder_has_m2_n2(dev_priv, transcoder)) {
6960                         I915_WRITE(PIPE_DATA_M2(transcoder),
6961                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6962                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6963                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6964                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6965                 }
6966         } else {
6967                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6968                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6969                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6970                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6971         }
6972 }
6973
6974 void intel_dp_set_m_n(const struct intel_crtc_state *crtc_state, enum link_m_n_set m_n)
6975 {
6976         const struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6977
6978         if (m_n == M1_N1) {
6979                 dp_m_n = &crtc_state->dp_m_n;
6980                 dp_m2_n2 = &crtc_state->dp_m2_n2;
6981         } else if (m_n == M2_N2) {
6982
6983                 /*
6984                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6985                  * needs to be programmed into M1_N1.
6986                  */
6987                 dp_m_n = &crtc_state->dp_m2_n2;
6988         } else {
6989                 DRM_ERROR("Unsupported divider value\n");
6990                 return;
6991         }
6992
6993         if (crtc_state->has_pch_encoder)
6994                 intel_pch_transcoder_set_m_n(crtc_state, &crtc_state->dp_m_n);
6995         else
6996                 intel_cpu_transcoder_set_m_n(crtc_state, dp_m_n, dp_m2_n2);
6997 }
6998
6999 static void vlv_compute_dpll(struct intel_crtc *crtc,
7000                              struct intel_crtc_state *pipe_config)
7001 {
7002         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
7003                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7004         if (crtc->pipe != PIPE_A)
7005                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7006
7007         /* DPLL not used with DSI, but still need the rest set up */
7008         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7009                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
7010                         DPLL_EXT_BUFFER_ENABLE_VLV;
7011
7012         pipe_config->dpll_hw_state.dpll_md =
7013                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7014 }
7015
7016 static void chv_compute_dpll(struct intel_crtc *crtc,
7017                              struct intel_crtc_state *pipe_config)
7018 {
7019         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
7020                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
7021         if (crtc->pipe != PIPE_A)
7022                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
7023
7024         /* DPLL not used with DSI, but still need the rest set up */
7025         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
7026                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
7027
7028         pipe_config->dpll_hw_state.dpll_md =
7029                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7030 }
7031
7032 static void vlv_prepare_pll(struct intel_crtc *crtc,
7033                             const struct intel_crtc_state *pipe_config)
7034 {
7035         struct drm_device *dev = crtc->base.dev;
7036         struct drm_i915_private *dev_priv = to_i915(dev);
7037         enum pipe pipe = crtc->pipe;
7038         u32 mdiv;
7039         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7040         u32 coreclk, reg_val;
7041
7042         /* Enable Refclk */
7043         I915_WRITE(DPLL(pipe),
7044                    pipe_config->dpll_hw_state.dpll &
7045                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7046
7047         /* No need to actually set up the DPLL with DSI */
7048         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7049                 return;
7050
7051         mutex_lock(&dev_priv->sb_lock);
7052
7053         bestn = pipe_config->dpll.n;
7054         bestm1 = pipe_config->dpll.m1;
7055         bestm2 = pipe_config->dpll.m2;
7056         bestp1 = pipe_config->dpll.p1;
7057         bestp2 = pipe_config->dpll.p2;
7058
7059         /* See eDP HDMI DPIO driver vbios notes doc */
7060
7061         /* PLL B needs special handling */
7062         if (pipe == PIPE_B)
7063                 vlv_pllb_recal_opamp(dev_priv, pipe);
7064
7065         /* Set up Tx target for periodic Rcomp update */
7066         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7067
7068         /* Disable target IRef on PLL */
7069         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7070         reg_val &= 0x00ffffff;
7071         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7072
7073         /* Disable fast lock */
7074         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7075
7076         /* Set idtafcrecal before PLL is enabled */
7077         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7078         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7079         mdiv |= ((bestn << DPIO_N_SHIFT));
7080         mdiv |= (1 << DPIO_K_SHIFT);
7081
7082         /*
7083          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7084          * but we don't support that).
7085          * Note: don't use the DAC post divider as it seems unstable.
7086          */
7087         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7088         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7089
7090         mdiv |= DPIO_ENABLE_CALIBRATION;
7091         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7092
7093         /* Set HBR and RBR LPF coefficients */
7094         if (pipe_config->port_clock == 162000 ||
7095             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_ANALOG) ||
7096             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_HDMI))
7097                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7098                                  0x009f0003);
7099         else
7100                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7101                                  0x00d0000f);
7102
7103         if (intel_crtc_has_dp_encoder(pipe_config)) {
7104                 /* Use SSC source */
7105                 if (pipe == PIPE_A)
7106                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7107                                          0x0df40000);
7108                 else
7109                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7110                                          0x0df70000);
7111         } else { /* HDMI or VGA */
7112                 /* Use bend source */
7113                 if (pipe == PIPE_A)
7114                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7115                                          0x0df70000);
7116                 else
7117                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7118                                          0x0df40000);
7119         }
7120
7121         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7122         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7123         if (intel_crtc_has_dp_encoder(pipe_config))
7124                 coreclk |= 0x01000000;
7125         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7126
7127         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7128         mutex_unlock(&dev_priv->sb_lock);
7129 }
7130
7131 static void chv_prepare_pll(struct intel_crtc *crtc,
7132                             const struct intel_crtc_state *pipe_config)
7133 {
7134         struct drm_device *dev = crtc->base.dev;
7135         struct drm_i915_private *dev_priv = to_i915(dev);
7136         enum pipe pipe = crtc->pipe;
7137         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7138         u32 loopfilter, tribuf_calcntr;
7139         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7140         u32 dpio_val;
7141         int vco;
7142
7143         /* Enable Refclk and SSC */
7144         I915_WRITE(DPLL(pipe),
7145                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7146
7147         /* No need to actually set up the DPLL with DSI */
7148         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7149                 return;
7150
7151         bestn = pipe_config->dpll.n;
7152         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7153         bestm1 = pipe_config->dpll.m1;
7154         bestm2 = pipe_config->dpll.m2 >> 22;
7155         bestp1 = pipe_config->dpll.p1;
7156         bestp2 = pipe_config->dpll.p2;
7157         vco = pipe_config->dpll.vco;
7158         dpio_val = 0;
7159         loopfilter = 0;
7160
7161         mutex_lock(&dev_priv->sb_lock);
7162
7163         /* p1 and p2 divider */
7164         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7165                         5 << DPIO_CHV_S1_DIV_SHIFT |
7166                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7167                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7168                         1 << DPIO_CHV_K_DIV_SHIFT);
7169
7170         /* Feedback post-divider - m2 */
7171         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7172
7173         /* Feedback refclk divider - n and m1 */
7174         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7175                         DPIO_CHV_M1_DIV_BY_2 |
7176                         1 << DPIO_CHV_N_DIV_SHIFT);
7177
7178         /* M2 fraction division */
7179         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7180
7181         /* M2 fraction division enable */
7182         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7183         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7184         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7185         if (bestm2_frac)
7186                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7187         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7188
7189         /* Program digital lock detect threshold */
7190         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7191         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7192                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7193         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7194         if (!bestm2_frac)
7195                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7196         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7197
7198         /* Loop filter */
7199         if (vco == 5400000) {
7200                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7201                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7202                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7203                 tribuf_calcntr = 0x9;
7204         } else if (vco <= 6200000) {
7205                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7206                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7207                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7208                 tribuf_calcntr = 0x9;
7209         } else if (vco <= 6480000) {
7210                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7211                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7212                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7213                 tribuf_calcntr = 0x8;
7214         } else {
7215                 /* Not supported. Apply the same limits as in the max case */
7216                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7217                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7218                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7219                 tribuf_calcntr = 0;
7220         }
7221         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7222
7223         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7224         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7225         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7226         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7227
7228         /* AFC Recal */
7229         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7230                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7231                         DPIO_AFC_RECAL);
7232
7233         mutex_unlock(&dev_priv->sb_lock);
7234 }
7235
7236 /**
7237  * vlv_force_pll_on - forcibly enable just the PLL
7238  * @dev_priv: i915 private structure
7239  * @pipe: pipe PLL to enable
7240  * @dpll: PLL configuration
7241  *
7242  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7243  * in cases where we need the PLL enabled even when @pipe is not going to
7244  * be enabled.
7245  */
7246 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7247                      const struct dpll *dpll)
7248 {
7249         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7250         struct intel_crtc_state *pipe_config;
7251
7252         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7253         if (!pipe_config)
7254                 return -ENOMEM;
7255
7256         pipe_config->base.crtc = &crtc->base;
7257         pipe_config->pixel_multiplier = 1;
7258         pipe_config->dpll = *dpll;
7259
7260         if (IS_CHERRYVIEW(dev_priv)) {
7261                 chv_compute_dpll(crtc, pipe_config);
7262                 chv_prepare_pll(crtc, pipe_config);
7263                 chv_enable_pll(crtc, pipe_config);
7264         } else {
7265                 vlv_compute_dpll(crtc, pipe_config);
7266                 vlv_prepare_pll(crtc, pipe_config);
7267                 vlv_enable_pll(crtc, pipe_config);
7268         }
7269
7270         kfree(pipe_config);
7271
7272         return 0;
7273 }
7274
7275 /**
7276  * vlv_force_pll_off - forcibly disable just the PLL
7277  * @dev_priv: i915 private structure
7278  * @pipe: pipe PLL to disable
7279  *
7280  * Disable the PLL for @pipe. To be used in cases where we need
7281  * the PLL enabled even when @pipe is not going to be enabled.
7282  */
7283 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7284 {
7285         if (IS_CHERRYVIEW(dev_priv))
7286                 chv_disable_pll(dev_priv, pipe);
7287         else
7288                 vlv_disable_pll(dev_priv, pipe);
7289 }
7290
7291 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7292                               struct intel_crtc_state *crtc_state,
7293                               struct dpll *reduced_clock)
7294 {
7295         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7296         u32 dpll;
7297         struct dpll *clock = &crtc_state->dpll;
7298
7299         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7300
7301         dpll = DPLL_VGA_MODE_DIS;
7302
7303         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7304                 dpll |= DPLLB_MODE_LVDS;
7305         else
7306                 dpll |= DPLLB_MODE_DAC_SERIAL;
7307
7308         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7309             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7310                 dpll |= (crtc_state->pixel_multiplier - 1)
7311                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7312         }
7313
7314         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7315             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7316                 dpll |= DPLL_SDVO_HIGH_SPEED;
7317
7318         if (intel_crtc_has_dp_encoder(crtc_state))
7319                 dpll |= DPLL_SDVO_HIGH_SPEED;
7320
7321         /* compute bitmask from p1 value */
7322         if (IS_PINEVIEW(dev_priv))
7323                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7324         else {
7325                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7326                 if (IS_G4X(dev_priv) && reduced_clock)
7327                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7328         }
7329         switch (clock->p2) {
7330         case 5:
7331                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7332                 break;
7333         case 7:
7334                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7335                 break;
7336         case 10:
7337                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7338                 break;
7339         case 14:
7340                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7341                 break;
7342         }
7343         if (INTEL_GEN(dev_priv) >= 4)
7344                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7345
7346         if (crtc_state->sdvo_tv_clock)
7347                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7348         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7349                  intel_panel_use_ssc(dev_priv))
7350                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7351         else
7352                 dpll |= PLL_REF_INPUT_DREFCLK;
7353
7354         dpll |= DPLL_VCO_ENABLE;
7355         crtc_state->dpll_hw_state.dpll = dpll;
7356
7357         if (INTEL_GEN(dev_priv) >= 4) {
7358                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7359                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7360                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7361         }
7362 }
7363
7364 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7365                               struct intel_crtc_state *crtc_state,
7366                               struct dpll *reduced_clock)
7367 {
7368         struct drm_device *dev = crtc->base.dev;
7369         struct drm_i915_private *dev_priv = to_i915(dev);
7370         u32 dpll;
7371         struct dpll *clock = &crtc_state->dpll;
7372
7373         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7374
7375         dpll = DPLL_VGA_MODE_DIS;
7376
7377         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7378                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7379         } else {
7380                 if (clock->p1 == 2)
7381                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7382                 else
7383                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7384                 if (clock->p2 == 4)
7385                         dpll |= PLL_P2_DIVIDE_BY_4;
7386         }
7387
7388         if (!IS_I830(dev_priv) &&
7389             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7390                 dpll |= DPLL_DVO_2X_MODE;
7391
7392         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7393             intel_panel_use_ssc(dev_priv))
7394                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7395         else
7396                 dpll |= PLL_REF_INPUT_DREFCLK;
7397
7398         dpll |= DPLL_VCO_ENABLE;
7399         crtc_state->dpll_hw_state.dpll = dpll;
7400 }
7401
7402 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state)
7403 {
7404         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7405         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7406         enum pipe pipe = crtc->pipe;
7407         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
7408         const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
7409         u32 crtc_vtotal, crtc_vblank_end;
7410         int vsyncshift = 0;
7411
7412         /* We need to be careful not to changed the adjusted mode, for otherwise
7413          * the hw state checker will get angry at the mismatch. */
7414         crtc_vtotal = adjusted_mode->crtc_vtotal;
7415         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7416
7417         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7418                 /* the chip adds 2 halflines automatically */
7419                 crtc_vtotal -= 1;
7420                 crtc_vblank_end -= 1;
7421
7422                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7423                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7424                 else
7425                         vsyncshift = adjusted_mode->crtc_hsync_start -
7426                                 adjusted_mode->crtc_htotal / 2;
7427                 if (vsyncshift < 0)
7428                         vsyncshift += adjusted_mode->crtc_htotal;
7429         }
7430
7431         if (INTEL_GEN(dev_priv) > 3)
7432                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7433
7434         I915_WRITE(HTOTAL(cpu_transcoder),
7435                    (adjusted_mode->crtc_hdisplay - 1) |
7436                    ((adjusted_mode->crtc_htotal - 1) << 16));
7437         I915_WRITE(HBLANK(cpu_transcoder),
7438                    (adjusted_mode->crtc_hblank_start - 1) |
7439                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7440         I915_WRITE(HSYNC(cpu_transcoder),
7441                    (adjusted_mode->crtc_hsync_start - 1) |
7442                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7443
7444         I915_WRITE(VTOTAL(cpu_transcoder),
7445                    (adjusted_mode->crtc_vdisplay - 1) |
7446                    ((crtc_vtotal - 1) << 16));
7447         I915_WRITE(VBLANK(cpu_transcoder),
7448                    (adjusted_mode->crtc_vblank_start - 1) |
7449                    ((crtc_vblank_end - 1) << 16));
7450         I915_WRITE(VSYNC(cpu_transcoder),
7451                    (adjusted_mode->crtc_vsync_start - 1) |
7452                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7453
7454         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7455          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7456          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7457          * bits. */
7458         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7459             (pipe == PIPE_B || pipe == PIPE_C))
7460                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7461
7462 }
7463
7464 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state)
7465 {
7466         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7467         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7468         enum pipe pipe = crtc->pipe;
7469
7470         /* pipesrc controls the size that is scaled from, which should
7471          * always be the user's requested size.
7472          */
7473         I915_WRITE(PIPESRC(pipe),
7474                    ((crtc_state->pipe_src_w - 1) << 16) |
7475                    (crtc_state->pipe_src_h - 1));
7476 }
7477
7478 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7479                                    struct intel_crtc_state *pipe_config)
7480 {
7481         struct drm_device *dev = crtc->base.dev;
7482         struct drm_i915_private *dev_priv = to_i915(dev);
7483         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7484         u32 tmp;
7485
7486         tmp = I915_READ(HTOTAL(cpu_transcoder));
7487         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7488         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7489         tmp = I915_READ(HBLANK(cpu_transcoder));
7490         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7491         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7492         tmp = I915_READ(HSYNC(cpu_transcoder));
7493         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7494         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7495
7496         tmp = I915_READ(VTOTAL(cpu_transcoder));
7497         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7498         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7499         tmp = I915_READ(VBLANK(cpu_transcoder));
7500         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7501         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7502         tmp = I915_READ(VSYNC(cpu_transcoder));
7503         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7504         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7505
7506         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7507                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7508                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7509                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7510         }
7511 }
7512
7513 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7514                                     struct intel_crtc_state *pipe_config)
7515 {
7516         struct drm_device *dev = crtc->base.dev;
7517         struct drm_i915_private *dev_priv = to_i915(dev);
7518         u32 tmp;
7519
7520         tmp = I915_READ(PIPESRC(crtc->pipe));
7521         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7522         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7523
7524         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7525         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7526 }
7527
7528 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7529                                  struct intel_crtc_state *pipe_config)
7530 {
7531         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7532         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7533         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7534         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7535
7536         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7537         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7538         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7539         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7540
7541         mode->flags = pipe_config->base.adjusted_mode.flags;
7542         mode->type = DRM_MODE_TYPE_DRIVER;
7543
7544         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7545
7546         mode->hsync = drm_mode_hsync(mode);
7547         mode->vrefresh = drm_mode_vrefresh(mode);
7548         drm_mode_set_name(mode);
7549 }
7550
7551 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state)
7552 {
7553         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7554         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7555         u32 pipeconf;
7556
7557         pipeconf = 0;
7558
7559         /* we keep both pipes enabled on 830 */
7560         if (IS_I830(dev_priv))
7561                 pipeconf |= I915_READ(PIPECONF(crtc->pipe)) & PIPECONF_ENABLE;
7562
7563         if (crtc_state->double_wide)
7564                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7565
7566         /* only g4x and later have fancy bpc/dither controls */
7567         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7568             IS_CHERRYVIEW(dev_priv)) {
7569                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7570                 if (crtc_state->dither && crtc_state->pipe_bpp != 30)
7571                         pipeconf |= PIPECONF_DITHER_EN |
7572                                     PIPECONF_DITHER_TYPE_SP;
7573
7574                 switch (crtc_state->pipe_bpp) {
7575                 case 18:
7576                         pipeconf |= PIPECONF_6BPC;
7577                         break;
7578                 case 24:
7579                         pipeconf |= PIPECONF_8BPC;
7580                         break;
7581                 case 30:
7582                         pipeconf |= PIPECONF_10BPC;
7583                         break;
7584                 default:
7585                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7586                         BUG();
7587                 }
7588         }
7589
7590         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7591                 if (INTEL_GEN(dev_priv) < 4 ||
7592                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7593                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7594                 else
7595                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7596         } else
7597                 pipeconf |= PIPECONF_PROGRESSIVE;
7598
7599         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7600              crtc_state->limited_color_range)
7601                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7602
7603         I915_WRITE(PIPECONF(crtc->pipe), pipeconf);
7604         POSTING_READ(PIPECONF(crtc->pipe));
7605 }
7606
7607 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7608                                    struct intel_crtc_state *crtc_state)
7609 {
7610         struct drm_device *dev = crtc->base.dev;
7611         struct drm_i915_private *dev_priv = to_i915(dev);
7612         const struct intel_limit *limit;
7613         int refclk = 48000;
7614
7615         memset(&crtc_state->dpll_hw_state, 0,
7616                sizeof(crtc_state->dpll_hw_state));
7617
7618         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7619                 if (intel_panel_use_ssc(dev_priv)) {
7620                         refclk = dev_priv->vbt.lvds_ssc_freq;
7621                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7622                 }
7623
7624                 limit = &intel_limits_i8xx_lvds;
7625         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7626                 limit = &intel_limits_i8xx_dvo;
7627         } else {
7628                 limit = &intel_limits_i8xx_dac;
7629         }
7630
7631         if (!crtc_state->clock_set &&
7632             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7633                                  refclk, NULL, &crtc_state->dpll)) {
7634                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7635                 return -EINVAL;
7636         }
7637
7638         i8xx_compute_dpll(crtc, crtc_state, NULL);
7639
7640         return 0;
7641 }
7642
7643 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7644                                   struct intel_crtc_state *crtc_state)
7645 {
7646         struct drm_device *dev = crtc->base.dev;
7647         struct drm_i915_private *dev_priv = to_i915(dev);
7648         const struct intel_limit *limit;
7649         int refclk = 96000;
7650
7651         memset(&crtc_state->dpll_hw_state, 0,
7652                sizeof(crtc_state->dpll_hw_state));
7653
7654         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7655                 if (intel_panel_use_ssc(dev_priv)) {
7656                         refclk = dev_priv->vbt.lvds_ssc_freq;
7657                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7658                 }
7659
7660                 if (intel_is_dual_link_lvds(dev))
7661                         limit = &intel_limits_g4x_dual_channel_lvds;
7662                 else
7663                         limit = &intel_limits_g4x_single_channel_lvds;
7664         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7665                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7666                 limit = &intel_limits_g4x_hdmi;
7667         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7668                 limit = &intel_limits_g4x_sdvo;
7669         } else {
7670                 /* The option is for other outputs */
7671                 limit = &intel_limits_i9xx_sdvo;
7672         }
7673
7674         if (!crtc_state->clock_set &&
7675             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7676                                 refclk, NULL, &crtc_state->dpll)) {
7677                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7678                 return -EINVAL;
7679         }
7680
7681         i9xx_compute_dpll(crtc, crtc_state, NULL);
7682
7683         return 0;
7684 }
7685
7686 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7687                                   struct intel_crtc_state *crtc_state)
7688 {
7689         struct drm_device *dev = crtc->base.dev;
7690         struct drm_i915_private *dev_priv = to_i915(dev);
7691         const struct intel_limit *limit;
7692         int refclk = 96000;
7693
7694         memset(&crtc_state->dpll_hw_state, 0,
7695                sizeof(crtc_state->dpll_hw_state));
7696
7697         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7698                 if (intel_panel_use_ssc(dev_priv)) {
7699                         refclk = dev_priv->vbt.lvds_ssc_freq;
7700                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7701                 }
7702
7703                 limit = &intel_limits_pineview_lvds;
7704         } else {
7705                 limit = &intel_limits_pineview_sdvo;
7706         }
7707
7708         if (!crtc_state->clock_set &&
7709             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7710                                 refclk, NULL, &crtc_state->dpll)) {
7711                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7712                 return -EINVAL;
7713         }
7714
7715         i9xx_compute_dpll(crtc, crtc_state, NULL);
7716
7717         return 0;
7718 }
7719
7720 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7721                                    struct intel_crtc_state *crtc_state)
7722 {
7723         struct drm_device *dev = crtc->base.dev;
7724         struct drm_i915_private *dev_priv = to_i915(dev);
7725         const struct intel_limit *limit;
7726         int refclk = 96000;
7727
7728         memset(&crtc_state->dpll_hw_state, 0,
7729                sizeof(crtc_state->dpll_hw_state));
7730
7731         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7732                 if (intel_panel_use_ssc(dev_priv)) {
7733                         refclk = dev_priv->vbt.lvds_ssc_freq;
7734                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7735                 }
7736
7737                 limit = &intel_limits_i9xx_lvds;
7738         } else {
7739                 limit = &intel_limits_i9xx_sdvo;
7740         }
7741
7742         if (!crtc_state->clock_set &&
7743             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7744                                  refclk, NULL, &crtc_state->dpll)) {
7745                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7746                 return -EINVAL;
7747         }
7748
7749         i9xx_compute_dpll(crtc, crtc_state, NULL);
7750
7751         return 0;
7752 }
7753
7754 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7755                                   struct intel_crtc_state *crtc_state)
7756 {
7757         int refclk = 100000;
7758         const struct intel_limit *limit = &intel_limits_chv;
7759
7760         memset(&crtc_state->dpll_hw_state, 0,
7761                sizeof(crtc_state->dpll_hw_state));
7762
7763         if (!crtc_state->clock_set &&
7764             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7765                                 refclk, NULL, &crtc_state->dpll)) {
7766                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7767                 return -EINVAL;
7768         }
7769
7770         chv_compute_dpll(crtc, crtc_state);
7771
7772         return 0;
7773 }
7774
7775 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7776                                   struct intel_crtc_state *crtc_state)
7777 {
7778         int refclk = 100000;
7779         const struct intel_limit *limit = &intel_limits_vlv;
7780
7781         memset(&crtc_state->dpll_hw_state, 0,
7782                sizeof(crtc_state->dpll_hw_state));
7783
7784         if (!crtc_state->clock_set &&
7785             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7786                                 refclk, NULL, &crtc_state->dpll)) {
7787                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7788                 return -EINVAL;
7789         }
7790
7791         vlv_compute_dpll(crtc, crtc_state);
7792
7793         return 0;
7794 }
7795
7796 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7797                                  struct intel_crtc_state *pipe_config)
7798 {
7799         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7800         u32 tmp;
7801
7802         if (INTEL_GEN(dev_priv) <= 3 &&
7803             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7804                 return;
7805
7806         tmp = I915_READ(PFIT_CONTROL);
7807         if (!(tmp & PFIT_ENABLE))
7808                 return;
7809
7810         /* Check whether the pfit is attached to our pipe. */
7811         if (INTEL_GEN(dev_priv) < 4) {
7812                 if (crtc->pipe != PIPE_B)
7813                         return;
7814         } else {
7815                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7816                         return;
7817         }
7818
7819         pipe_config->gmch_pfit.control = tmp;
7820         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7821 }
7822
7823 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7824                                struct intel_crtc_state *pipe_config)
7825 {
7826         struct drm_device *dev = crtc->base.dev;
7827         struct drm_i915_private *dev_priv = to_i915(dev);
7828         int pipe = pipe_config->cpu_transcoder;
7829         struct dpll clock;
7830         u32 mdiv;
7831         int refclk = 100000;
7832
7833         /* In case of DSI, DPLL will not be used */
7834         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7835                 return;
7836
7837         mutex_lock(&dev_priv->sb_lock);
7838         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7839         mutex_unlock(&dev_priv->sb_lock);
7840
7841         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7842         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7843         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7844         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7845         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7846
7847         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7848 }
7849
7850 static void
7851 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7852                               struct intel_initial_plane_config *plane_config)
7853 {
7854         struct drm_device *dev = crtc->base.dev;
7855         struct drm_i915_private *dev_priv = to_i915(dev);
7856         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7857         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7858         enum pipe pipe;
7859         u32 val, base, offset;
7860         int fourcc, pixel_format;
7861         unsigned int aligned_height;
7862         struct drm_framebuffer *fb;
7863         struct intel_framebuffer *intel_fb;
7864
7865         if (!plane->get_hw_state(plane, &pipe))
7866                 return;
7867
7868         WARN_ON(pipe != crtc->pipe);
7869
7870         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7871         if (!intel_fb) {
7872                 DRM_DEBUG_KMS("failed to alloc fb\n");
7873                 return;
7874         }
7875
7876         fb = &intel_fb->base;
7877
7878         fb->dev = dev;
7879
7880         val = I915_READ(DSPCNTR(i9xx_plane));
7881
7882         if (INTEL_GEN(dev_priv) >= 4) {
7883                 if (val & DISPPLANE_TILED) {
7884                         plane_config->tiling = I915_TILING_X;
7885                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7886                 }
7887
7888                 if (val & DISPPLANE_ROTATE_180)
7889                         plane_config->rotation = DRM_MODE_ROTATE_180;
7890         }
7891
7892         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B &&
7893             val & DISPPLANE_MIRROR)
7894                 plane_config->rotation |= DRM_MODE_REFLECT_X;
7895
7896         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7897         fourcc = i9xx_format_to_fourcc(pixel_format);
7898         fb->format = drm_format_info(fourcc);
7899
7900         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7901                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7902                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7903         } else if (INTEL_GEN(dev_priv) >= 4) {
7904                 if (plane_config->tiling)
7905                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7906                 else
7907                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7908                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7909         } else {
7910                 base = I915_READ(DSPADDR(i9xx_plane));
7911         }
7912         plane_config->base = base;
7913
7914         val = I915_READ(PIPESRC(pipe));
7915         fb->width = ((val >> 16) & 0xfff) + 1;
7916         fb->height = ((val >> 0) & 0xfff) + 1;
7917
7918         val = I915_READ(DSPSTRIDE(i9xx_plane));
7919         fb->pitches[0] = val & 0xffffffc0;
7920
7921         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7922
7923         plane_config->size = fb->pitches[0] * aligned_height;
7924
7925         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7926                       crtc->base.name, plane->base.name, fb->width, fb->height,
7927                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7928                       plane_config->size);
7929
7930         plane_config->fb = intel_fb;
7931 }
7932
7933 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7934                                struct intel_crtc_state *pipe_config)
7935 {
7936         struct drm_device *dev = crtc->base.dev;
7937         struct drm_i915_private *dev_priv = to_i915(dev);
7938         int pipe = pipe_config->cpu_transcoder;
7939         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7940         struct dpll clock;
7941         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7942         int refclk = 100000;
7943
7944         /* In case of DSI, DPLL will not be used */
7945         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7946                 return;
7947
7948         mutex_lock(&dev_priv->sb_lock);
7949         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7950         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7951         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7952         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7953         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7954         mutex_unlock(&dev_priv->sb_lock);
7955
7956         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7957         clock.m2 = (pll_dw0 & 0xff) << 22;
7958         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7959                 clock.m2 |= pll_dw2 & 0x3fffff;
7960         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7961         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7962         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7963
7964         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7965 }
7966
7967 static void intel_get_crtc_ycbcr_config(struct intel_crtc *crtc,
7968                                         struct intel_crtc_state *pipe_config)
7969 {
7970         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7971         enum intel_output_format output = INTEL_OUTPUT_FORMAT_RGB;
7972
7973         pipe_config->lspcon_downsampling = false;
7974
7975         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
7976                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
7977
7978                 if (tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV) {
7979                         bool ycbcr420_enabled = tmp & PIPEMISC_YUV420_ENABLE;
7980                         bool blend = tmp & PIPEMISC_YUV420_MODE_FULL_BLEND;
7981
7982                         if (ycbcr420_enabled) {
7983                                 /* We support 4:2:0 in full blend mode only */
7984                                 if (!blend)
7985                                         output = INTEL_OUTPUT_FORMAT_INVALID;
7986                                 else if (!(IS_GEMINILAKE(dev_priv) ||
7987                                            INTEL_GEN(dev_priv) >= 10))
7988                                         output = INTEL_OUTPUT_FORMAT_INVALID;
7989                                 else
7990                                         output = INTEL_OUTPUT_FORMAT_YCBCR420;
7991                         } else {
7992                                 /*
7993                                  * Currently there is no interface defined to
7994                                  * check user preference between RGB/YCBCR444
7995                                  * or YCBCR420. So the only possible case for
7996                                  * YCBCR444 usage is driving YCBCR420 output
7997                                  * with LSPCON, when pipe is configured for
7998                                  * YCBCR444 output and LSPCON takes care of
7999                                  * downsampling it.
8000                                  */
8001                                 pipe_config->lspcon_downsampling = true;
8002                                 output = INTEL_OUTPUT_FORMAT_YCBCR444;
8003                         }
8004                 }
8005         }
8006
8007         pipe_config->output_format = output;
8008 }
8009
8010 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
8011                                  struct intel_crtc_state *pipe_config)
8012 {
8013         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8014         enum intel_display_power_domain power_domain;
8015         intel_wakeref_t wakeref;
8016         u32 tmp;
8017         bool ret;
8018
8019         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8020         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
8021         if (!wakeref)
8022                 return false;
8023
8024         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
8025         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8026         pipe_config->shared_dpll = NULL;
8027
8028         ret = false;
8029
8030         tmp = I915_READ(PIPECONF(crtc->pipe));
8031         if (!(tmp & PIPECONF_ENABLE))
8032                 goto out;
8033
8034         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
8035             IS_CHERRYVIEW(dev_priv)) {
8036                 switch (tmp & PIPECONF_BPC_MASK) {
8037                 case PIPECONF_6BPC:
8038                         pipe_config->pipe_bpp = 18;
8039                         break;
8040                 case PIPECONF_8BPC:
8041                         pipe_config->pipe_bpp = 24;
8042                         break;
8043                 case PIPECONF_10BPC:
8044                         pipe_config->pipe_bpp = 30;
8045                         break;
8046                 default:
8047                         break;
8048                 }
8049         }
8050
8051         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
8052             (tmp & PIPECONF_COLOR_RANGE_SELECT))
8053                 pipe_config->limited_color_range = true;
8054
8055         if (INTEL_GEN(dev_priv) < 4)
8056                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
8057
8058         intel_get_pipe_timings(crtc, pipe_config);
8059         intel_get_pipe_src_size(crtc, pipe_config);
8060
8061         i9xx_get_pfit_config(crtc, pipe_config);
8062
8063         if (INTEL_GEN(dev_priv) >= 4) {
8064                 /* No way to read it out on pipes B and C */
8065                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
8066                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
8067                 else
8068                         tmp = I915_READ(DPLL_MD(crtc->pipe));
8069                 pipe_config->pixel_multiplier =
8070                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
8071                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
8072                 pipe_config->dpll_hw_state.dpll_md = tmp;
8073         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
8074                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
8075                 tmp = I915_READ(DPLL(crtc->pipe));
8076                 pipe_config->pixel_multiplier =
8077                         ((tmp & SDVO_MULTIPLIER_MASK)
8078                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
8079         } else {
8080                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
8081                  * port and will be fixed up in the encoder->get_config
8082                  * function. */
8083                 pipe_config->pixel_multiplier = 1;
8084         }
8085         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
8086         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
8087                 /*
8088                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
8089                  * on 830. Filter it out here so that we don't
8090                  * report errors due to that.
8091                  */
8092                 if (IS_I830(dev_priv))
8093                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8094
8095                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8096                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8097         } else {
8098                 /* Mask out read-only status bits. */
8099                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8100                                                      DPLL_PORTC_READY_MASK |
8101                                                      DPLL_PORTB_READY_MASK);
8102         }
8103
8104         if (IS_CHERRYVIEW(dev_priv))
8105                 chv_crtc_clock_get(crtc, pipe_config);
8106         else if (IS_VALLEYVIEW(dev_priv))
8107                 vlv_crtc_clock_get(crtc, pipe_config);
8108         else
8109                 i9xx_crtc_clock_get(crtc, pipe_config);
8110
8111         /*
8112          * Normally the dotclock is filled in by the encoder .get_config()
8113          * but in case the pipe is enabled w/o any ports we need a sane
8114          * default.
8115          */
8116         pipe_config->base.adjusted_mode.crtc_clock =
8117                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8118
8119         ret = true;
8120
8121 out:
8122         intel_display_power_put(dev_priv, power_domain, wakeref);
8123
8124         return ret;
8125 }
8126
8127 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
8128 {
8129         struct intel_encoder *encoder;
8130         int i;
8131         u32 val, final;
8132         bool has_lvds = false;
8133         bool has_cpu_edp = false;
8134         bool has_panel = false;
8135         bool has_ck505 = false;
8136         bool can_ssc = false;
8137         bool using_ssc_source = false;
8138
8139         /* We need to take the global config into account */
8140         for_each_intel_encoder(&dev_priv->drm, encoder) {
8141                 switch (encoder->type) {
8142                 case INTEL_OUTPUT_LVDS:
8143                         has_panel = true;
8144                         has_lvds = true;
8145                         break;
8146                 case INTEL_OUTPUT_EDP:
8147                         has_panel = true;
8148                         if (encoder->port == PORT_A)
8149                                 has_cpu_edp = true;
8150                         break;
8151                 default:
8152                         break;
8153                 }
8154         }
8155
8156         if (HAS_PCH_IBX(dev_priv)) {
8157                 has_ck505 = dev_priv->vbt.display_clock_mode;
8158                 can_ssc = has_ck505;
8159         } else {
8160                 has_ck505 = false;
8161                 can_ssc = true;
8162         }
8163
8164         /* Check if any DPLLs are using the SSC source */
8165         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8166                 u32 temp = I915_READ(PCH_DPLL(i));
8167
8168                 if (!(temp & DPLL_VCO_ENABLE))
8169                         continue;
8170
8171                 if ((temp & PLL_REF_INPUT_MASK) ==
8172                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8173                         using_ssc_source = true;
8174                         break;
8175                 }
8176         }
8177
8178         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8179                       has_panel, has_lvds, has_ck505, using_ssc_source);
8180
8181         /* Ironlake: try to setup display ref clock before DPLL
8182          * enabling. This is only under driver's control after
8183          * PCH B stepping, previous chipset stepping should be
8184          * ignoring this setting.
8185          */
8186         val = I915_READ(PCH_DREF_CONTROL);
8187
8188         /* As we must carefully and slowly disable/enable each source in turn,
8189          * compute the final state we want first and check if we need to
8190          * make any changes at all.
8191          */
8192         final = val;
8193         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8194         if (has_ck505)
8195                 final |= DREF_NONSPREAD_CK505_ENABLE;
8196         else
8197                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8198
8199         final &= ~DREF_SSC_SOURCE_MASK;
8200         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8201         final &= ~DREF_SSC1_ENABLE;
8202
8203         if (has_panel) {
8204                 final |= DREF_SSC_SOURCE_ENABLE;
8205
8206                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8207                         final |= DREF_SSC1_ENABLE;
8208
8209                 if (has_cpu_edp) {
8210                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8211                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8212                         else
8213                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8214                 } else
8215                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8216         } else if (using_ssc_source) {
8217                 final |= DREF_SSC_SOURCE_ENABLE;
8218                 final |= DREF_SSC1_ENABLE;
8219         }
8220
8221         if (final == val)
8222                 return;
8223
8224         /* Always enable nonspread source */
8225         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8226
8227         if (has_ck505)
8228                 val |= DREF_NONSPREAD_CK505_ENABLE;
8229         else
8230                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8231
8232         if (has_panel) {
8233                 val &= ~DREF_SSC_SOURCE_MASK;
8234                 val |= DREF_SSC_SOURCE_ENABLE;
8235
8236                 /* SSC must be turned on before enabling the CPU output  */
8237                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8238                         DRM_DEBUG_KMS("Using SSC on panel\n");
8239                         val |= DREF_SSC1_ENABLE;
8240                 } else
8241                         val &= ~DREF_SSC1_ENABLE;
8242
8243                 /* Get SSC going before enabling the outputs */
8244                 I915_WRITE(PCH_DREF_CONTROL, val);
8245                 POSTING_READ(PCH_DREF_CONTROL);
8246                 udelay(200);
8247
8248                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8249
8250                 /* Enable CPU source on CPU attached eDP */
8251                 if (has_cpu_edp) {
8252                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8253                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8254                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8255                         } else
8256                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8257                 } else
8258                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8259
8260                 I915_WRITE(PCH_DREF_CONTROL, val);
8261                 POSTING_READ(PCH_DREF_CONTROL);
8262                 udelay(200);
8263         } else {
8264                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8265
8266                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8267
8268                 /* Turn off CPU output */
8269                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8270
8271                 I915_WRITE(PCH_DREF_CONTROL, val);
8272                 POSTING_READ(PCH_DREF_CONTROL);
8273                 udelay(200);
8274
8275                 if (!using_ssc_source) {
8276                         DRM_DEBUG_KMS("Disabling SSC source\n");
8277
8278                         /* Turn off the SSC source */
8279                         val &= ~DREF_SSC_SOURCE_MASK;
8280                         val |= DREF_SSC_SOURCE_DISABLE;
8281
8282                         /* Turn off SSC1 */
8283                         val &= ~DREF_SSC1_ENABLE;
8284
8285                         I915_WRITE(PCH_DREF_CONTROL, val);
8286                         POSTING_READ(PCH_DREF_CONTROL);
8287                         udelay(200);
8288                 }
8289         }
8290
8291         BUG_ON(val != final);
8292 }
8293
8294 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8295 {
8296         u32 tmp;
8297
8298         tmp = I915_READ(SOUTH_CHICKEN2);
8299         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8300         I915_WRITE(SOUTH_CHICKEN2, tmp);
8301
8302         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8303                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8304                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8305
8306         tmp = I915_READ(SOUTH_CHICKEN2);
8307         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8308         I915_WRITE(SOUTH_CHICKEN2, tmp);
8309
8310         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8311                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8312                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8313 }
8314
8315 /* WaMPhyProgramming:hsw */
8316 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8317 {
8318         u32 tmp;
8319
8320         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8321         tmp &= ~(0xFF << 24);
8322         tmp |= (0x12 << 24);
8323         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8324
8325         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8326         tmp |= (1 << 11);
8327         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8328
8329         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8330         tmp |= (1 << 11);
8331         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8332
8333         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8334         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8335         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8336
8337         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8338         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8339         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8340
8341         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8342         tmp &= ~(7 << 13);
8343         tmp |= (5 << 13);
8344         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8345
8346         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8347         tmp &= ~(7 << 13);
8348         tmp |= (5 << 13);
8349         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8350
8351         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8352         tmp &= ~0xFF;
8353         tmp |= 0x1C;
8354         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8355
8356         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8357         tmp &= ~0xFF;
8358         tmp |= 0x1C;
8359         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8360
8361         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8362         tmp &= ~(0xFF << 16);
8363         tmp |= (0x1C << 16);
8364         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8365
8366         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8367         tmp &= ~(0xFF << 16);
8368         tmp |= (0x1C << 16);
8369         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8370
8371         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8372         tmp |= (1 << 27);
8373         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8374
8375         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8376         tmp |= (1 << 27);
8377         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8378
8379         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8380         tmp &= ~(0xF << 28);
8381         tmp |= (4 << 28);
8382         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8383
8384         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8385         tmp &= ~(0xF << 28);
8386         tmp |= (4 << 28);
8387         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8388 }
8389
8390 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8391  * Programming" based on the parameters passed:
8392  * - Sequence to enable CLKOUT_DP
8393  * - Sequence to enable CLKOUT_DP without spread
8394  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8395  */
8396 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8397                                  bool with_spread, bool with_fdi)
8398 {
8399         u32 reg, tmp;
8400
8401         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8402                 with_spread = true;
8403         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8404             with_fdi, "LP PCH doesn't have FDI\n"))
8405                 with_fdi = false;
8406
8407         mutex_lock(&dev_priv->sb_lock);
8408
8409         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8410         tmp &= ~SBI_SSCCTL_DISABLE;
8411         tmp |= SBI_SSCCTL_PATHALT;
8412         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8413
8414         udelay(24);
8415
8416         if (with_spread) {
8417                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8418                 tmp &= ~SBI_SSCCTL_PATHALT;
8419                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8420
8421                 if (with_fdi) {
8422                         lpt_reset_fdi_mphy(dev_priv);
8423                         lpt_program_fdi_mphy(dev_priv);
8424                 }
8425         }
8426
8427         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8428         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8429         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8430         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8431
8432         mutex_unlock(&dev_priv->sb_lock);
8433 }
8434
8435 /* Sequence to disable CLKOUT_DP */
8436 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8437 {
8438         u32 reg, tmp;
8439
8440         mutex_lock(&dev_priv->sb_lock);
8441
8442         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8443         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8444         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8445         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8446
8447         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8448         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8449                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8450                         tmp |= SBI_SSCCTL_PATHALT;
8451                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8452                         udelay(32);
8453                 }
8454                 tmp |= SBI_SSCCTL_DISABLE;
8455                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8456         }
8457
8458         mutex_unlock(&dev_priv->sb_lock);
8459 }
8460
8461 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8462
8463 static const u16 sscdivintphase[] = {
8464         [BEND_IDX( 50)] = 0x3B23,
8465         [BEND_IDX( 45)] = 0x3B23,
8466         [BEND_IDX( 40)] = 0x3C23,
8467         [BEND_IDX( 35)] = 0x3C23,
8468         [BEND_IDX( 30)] = 0x3D23,
8469         [BEND_IDX( 25)] = 0x3D23,
8470         [BEND_IDX( 20)] = 0x3E23,
8471         [BEND_IDX( 15)] = 0x3E23,
8472         [BEND_IDX( 10)] = 0x3F23,
8473         [BEND_IDX(  5)] = 0x3F23,
8474         [BEND_IDX(  0)] = 0x0025,
8475         [BEND_IDX( -5)] = 0x0025,
8476         [BEND_IDX(-10)] = 0x0125,
8477         [BEND_IDX(-15)] = 0x0125,
8478         [BEND_IDX(-20)] = 0x0225,
8479         [BEND_IDX(-25)] = 0x0225,
8480         [BEND_IDX(-30)] = 0x0325,
8481         [BEND_IDX(-35)] = 0x0325,
8482         [BEND_IDX(-40)] = 0x0425,
8483         [BEND_IDX(-45)] = 0x0425,
8484         [BEND_IDX(-50)] = 0x0525,
8485 };
8486
8487 /*
8488  * Bend CLKOUT_DP
8489  * steps -50 to 50 inclusive, in steps of 5
8490  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8491  * change in clock period = -(steps / 10) * 5.787 ps
8492  */
8493 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8494 {
8495         u32 tmp;
8496         int idx = BEND_IDX(steps);
8497
8498         if (WARN_ON(steps % 5 != 0))
8499                 return;
8500
8501         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8502                 return;
8503
8504         mutex_lock(&dev_priv->sb_lock);
8505
8506         if (steps % 10 != 0)
8507                 tmp = 0xAAAAAAAB;
8508         else
8509                 tmp = 0x00000000;
8510         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8511
8512         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8513         tmp &= 0xffff0000;
8514         tmp |= sscdivintphase[idx];
8515         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8516
8517         mutex_unlock(&dev_priv->sb_lock);
8518 }
8519
8520 #undef BEND_IDX
8521
8522 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8523 {
8524         struct intel_encoder *encoder;
8525         bool has_vga = false;
8526
8527         for_each_intel_encoder(&dev_priv->drm, encoder) {
8528                 switch (encoder->type) {
8529                 case INTEL_OUTPUT_ANALOG:
8530                         has_vga = true;
8531                         break;
8532                 default:
8533                         break;
8534                 }
8535         }
8536
8537         if (has_vga) {
8538                 lpt_bend_clkout_dp(dev_priv, 0);
8539                 lpt_enable_clkout_dp(dev_priv, true, true);
8540         } else {
8541                 lpt_disable_clkout_dp(dev_priv);
8542         }
8543 }
8544
8545 /*
8546  * Initialize reference clocks when the driver loads
8547  */
8548 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8549 {
8550         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8551                 ironlake_init_pch_refclk(dev_priv);
8552         else if (HAS_PCH_LPT(dev_priv))
8553                 lpt_init_pch_refclk(dev_priv);
8554 }
8555
8556 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state)
8557 {
8558         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8559         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8560         enum pipe pipe = crtc->pipe;
8561         u32 val;
8562
8563         val = 0;
8564
8565         switch (crtc_state->pipe_bpp) {
8566         case 18:
8567                 val |= PIPECONF_6BPC;
8568                 break;
8569         case 24:
8570                 val |= PIPECONF_8BPC;
8571                 break;
8572         case 30:
8573                 val |= PIPECONF_10BPC;
8574                 break;
8575         case 36:
8576                 val |= PIPECONF_12BPC;
8577                 break;
8578         default:
8579                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8580                 BUG();
8581         }
8582
8583         if (crtc_state->dither)
8584                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8585
8586         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8587                 val |= PIPECONF_INTERLACED_ILK;
8588         else
8589                 val |= PIPECONF_PROGRESSIVE;
8590
8591         if (crtc_state->limited_color_range)
8592                 val |= PIPECONF_COLOR_RANGE_SELECT;
8593
8594         I915_WRITE(PIPECONF(pipe), val);
8595         POSTING_READ(PIPECONF(pipe));
8596 }
8597
8598 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state)
8599 {
8600         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8601         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8602         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
8603         u32 val = 0;
8604
8605         if (IS_HASWELL(dev_priv) && crtc_state->dither)
8606                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8607
8608         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8609                 val |= PIPECONF_INTERLACED_ILK;
8610         else
8611                 val |= PIPECONF_PROGRESSIVE;
8612
8613         I915_WRITE(PIPECONF(cpu_transcoder), val);
8614         POSTING_READ(PIPECONF(cpu_transcoder));
8615 }
8616
8617 static void haswell_set_pipemisc(const struct intel_crtc_state *crtc_state)
8618 {
8619         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
8620         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
8621
8622         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8623                 u32 val = 0;
8624
8625                 switch (crtc_state->pipe_bpp) {
8626                 case 18:
8627                         val |= PIPEMISC_DITHER_6_BPC;
8628                         break;
8629                 case 24:
8630                         val |= PIPEMISC_DITHER_8_BPC;
8631                         break;
8632                 case 30:
8633                         val |= PIPEMISC_DITHER_10_BPC;
8634                         break;
8635                 case 36:
8636                         val |= PIPEMISC_DITHER_12_BPC;
8637                         break;
8638                 default:
8639                         /* Case prevented by pipe_config_set_bpp. */
8640                         BUG();
8641                 }
8642
8643                 if (crtc_state->dither)
8644                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8645
8646                 if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
8647                     crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR444)
8648                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV;
8649
8650                 if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
8651                         val |= PIPEMISC_YUV420_ENABLE |
8652                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8653
8654                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8655         }
8656 }
8657
8658 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8659 {
8660         /*
8661          * Account for spread spectrum to avoid
8662          * oversubscribing the link. Max center spread
8663          * is 2.5%; use 5% for safety's sake.
8664          */
8665         u32 bps = target_clock * bpp * 21 / 20;
8666         return DIV_ROUND_UP(bps, link_bw * 8);
8667 }
8668
8669 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8670 {
8671         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8672 }
8673
8674 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8675                                   struct intel_crtc_state *crtc_state,
8676                                   struct dpll *reduced_clock)
8677 {
8678         struct drm_crtc *crtc = &intel_crtc->base;
8679         struct drm_device *dev = crtc->dev;
8680         struct drm_i915_private *dev_priv = to_i915(dev);
8681         u32 dpll, fp, fp2;
8682         int factor;
8683
8684         /* Enable autotuning of the PLL clock (if permissible) */
8685         factor = 21;
8686         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8687                 if ((intel_panel_use_ssc(dev_priv) &&
8688                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8689                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8690                         factor = 25;
8691         } else if (crtc_state->sdvo_tv_clock)
8692                 factor = 20;
8693
8694         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8695
8696         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8697                 fp |= FP_CB_TUNE;
8698
8699         if (reduced_clock) {
8700                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8701
8702                 if (reduced_clock->m < factor * reduced_clock->n)
8703                         fp2 |= FP_CB_TUNE;
8704         } else {
8705                 fp2 = fp;
8706         }
8707
8708         dpll = 0;
8709
8710         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8711                 dpll |= DPLLB_MODE_LVDS;
8712         else
8713                 dpll |= DPLLB_MODE_DAC_SERIAL;
8714
8715         dpll |= (crtc_state->pixel_multiplier - 1)
8716                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8717
8718         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8719             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8720                 dpll |= DPLL_SDVO_HIGH_SPEED;
8721
8722         if (intel_crtc_has_dp_encoder(crtc_state))
8723                 dpll |= DPLL_SDVO_HIGH_SPEED;
8724
8725         /*
8726          * The high speed IO clock is only really required for
8727          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8728          * possible to share the DPLL between CRT and HDMI. Enabling
8729          * the clock needlessly does no real harm, except use up a
8730          * bit of power potentially.
8731          *
8732          * We'll limit this to IVB with 3 pipes, since it has only two
8733          * DPLLs and so DPLL sharing is the only way to get three pipes
8734          * driving PCH ports at the same time. On SNB we could do this,
8735          * and potentially avoid enabling the second DPLL, but it's not
8736          * clear if it''s a win or loss power wise. No point in doing
8737          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8738          */
8739         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8740             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8741                 dpll |= DPLL_SDVO_HIGH_SPEED;
8742
8743         /* compute bitmask from p1 value */
8744         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8745         /* also FPA1 */
8746         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8747
8748         switch (crtc_state->dpll.p2) {
8749         case 5:
8750                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8751                 break;
8752         case 7:
8753                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8754                 break;
8755         case 10:
8756                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8757                 break;
8758         case 14:
8759                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8760                 break;
8761         }
8762
8763         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8764             intel_panel_use_ssc(dev_priv))
8765                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8766         else
8767                 dpll |= PLL_REF_INPUT_DREFCLK;
8768
8769         dpll |= DPLL_VCO_ENABLE;
8770
8771         crtc_state->dpll_hw_state.dpll = dpll;
8772         crtc_state->dpll_hw_state.fp0 = fp;
8773         crtc_state->dpll_hw_state.fp1 = fp2;
8774 }
8775
8776 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8777                                        struct intel_crtc_state *crtc_state)
8778 {
8779         struct drm_device *dev = crtc->base.dev;
8780         struct drm_i915_private *dev_priv = to_i915(dev);
8781         const struct intel_limit *limit;
8782         int refclk = 120000;
8783
8784         memset(&crtc_state->dpll_hw_state, 0,
8785                sizeof(crtc_state->dpll_hw_state));
8786
8787         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8788         if (!crtc_state->has_pch_encoder)
8789                 return 0;
8790
8791         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8792                 if (intel_panel_use_ssc(dev_priv)) {
8793                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8794                                       dev_priv->vbt.lvds_ssc_freq);
8795                         refclk = dev_priv->vbt.lvds_ssc_freq;
8796                 }
8797
8798                 if (intel_is_dual_link_lvds(dev)) {
8799                         if (refclk == 100000)
8800                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8801                         else
8802                                 limit = &intel_limits_ironlake_dual_lvds;
8803                 } else {
8804                         if (refclk == 100000)
8805                                 limit = &intel_limits_ironlake_single_lvds_100m;
8806                         else
8807                                 limit = &intel_limits_ironlake_single_lvds;
8808                 }
8809         } else {
8810                 limit = &intel_limits_ironlake_dac;
8811         }
8812
8813         if (!crtc_state->clock_set &&
8814             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8815                                 refclk, NULL, &crtc_state->dpll)) {
8816                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8817                 return -EINVAL;
8818         }
8819
8820         ironlake_compute_dpll(crtc, crtc_state, NULL);
8821
8822         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8823                 DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
8824                               pipe_name(crtc->pipe));
8825                 return -EINVAL;
8826         }
8827
8828         return 0;
8829 }
8830
8831 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8832                                          struct intel_link_m_n *m_n)
8833 {
8834         struct drm_device *dev = crtc->base.dev;
8835         struct drm_i915_private *dev_priv = to_i915(dev);
8836         enum pipe pipe = crtc->pipe;
8837
8838         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8839         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8840         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8841                 & ~TU_SIZE_MASK;
8842         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8843         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8844                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8845 }
8846
8847 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8848                                          enum transcoder transcoder,
8849                                          struct intel_link_m_n *m_n,
8850                                          struct intel_link_m_n *m2_n2)
8851 {
8852         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8853         enum pipe pipe = crtc->pipe;
8854
8855         if (INTEL_GEN(dev_priv) >= 5) {
8856                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8857                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8858                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8859                         & ~TU_SIZE_MASK;
8860                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8861                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8862                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8863
8864                 if (m2_n2 && transcoder_has_m2_n2(dev_priv, transcoder)) {
8865                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8866                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8867                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8868                                         & ~TU_SIZE_MASK;
8869                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8870                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8871                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8872                 }
8873         } else {
8874                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8875                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8876                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8877                         & ~TU_SIZE_MASK;
8878                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8879                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8880                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8881         }
8882 }
8883
8884 void intel_dp_get_m_n(struct intel_crtc *crtc,
8885                       struct intel_crtc_state *pipe_config)
8886 {
8887         if (pipe_config->has_pch_encoder)
8888                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8889         else
8890                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8891                                              &pipe_config->dp_m_n,
8892                                              &pipe_config->dp_m2_n2);
8893 }
8894
8895 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8896                                         struct intel_crtc_state *pipe_config)
8897 {
8898         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8899                                      &pipe_config->fdi_m_n, NULL);
8900 }
8901
8902 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8903                                     struct intel_crtc_state *pipe_config)
8904 {
8905         struct drm_device *dev = crtc->base.dev;
8906         struct drm_i915_private *dev_priv = to_i915(dev);
8907         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8908         u32 ps_ctrl = 0;
8909         int id = -1;
8910         int i;
8911
8912         /* find scaler attached to this pipe */
8913         for (i = 0; i < crtc->num_scalers; i++) {
8914                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8915                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8916                         id = i;
8917                         pipe_config->pch_pfit.enabled = true;
8918                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8919                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8920                         scaler_state->scalers[i].in_use = true;
8921                         break;
8922                 }
8923         }
8924
8925         scaler_state->scaler_id = id;
8926         if (id >= 0) {
8927                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8928         } else {
8929                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8930         }
8931 }
8932
8933 static void
8934 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8935                                  struct intel_initial_plane_config *plane_config)
8936 {
8937         struct drm_device *dev = crtc->base.dev;
8938         struct drm_i915_private *dev_priv = to_i915(dev);
8939         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8940         enum plane_id plane_id = plane->id;
8941         enum pipe pipe;
8942         u32 val, base, offset, stride_mult, tiling, alpha;
8943         int fourcc, pixel_format;
8944         unsigned int aligned_height;
8945         struct drm_framebuffer *fb;
8946         struct intel_framebuffer *intel_fb;
8947
8948         if (!plane->get_hw_state(plane, &pipe))
8949                 return;
8950
8951         WARN_ON(pipe != crtc->pipe);
8952
8953         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8954         if (!intel_fb) {
8955                 DRM_DEBUG_KMS("failed to alloc fb\n");
8956                 return;
8957         }
8958
8959         fb = &intel_fb->base;
8960
8961         fb->dev = dev;
8962
8963         val = I915_READ(PLANE_CTL(pipe, plane_id));
8964
8965         if (INTEL_GEN(dev_priv) >= 11)
8966                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8967         else
8968                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8969
8970         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8971                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8972                 alpha &= PLANE_COLOR_ALPHA_MASK;
8973         } else {
8974                 alpha = val & PLANE_CTL_ALPHA_MASK;
8975         }
8976
8977         fourcc = skl_format_to_fourcc(pixel_format,
8978                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8979         fb->format = drm_format_info(fourcc);
8980
8981         tiling = val & PLANE_CTL_TILED_MASK;
8982         switch (tiling) {
8983         case PLANE_CTL_TILED_LINEAR:
8984                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8985                 break;
8986         case PLANE_CTL_TILED_X:
8987                 plane_config->tiling = I915_TILING_X;
8988                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8989                 break;
8990         case PLANE_CTL_TILED_Y:
8991                 plane_config->tiling = I915_TILING_Y;
8992                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8993                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8994                 else
8995                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8996                 break;
8997         case PLANE_CTL_TILED_YF:
8998                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8999                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
9000                 else
9001                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
9002                 break;
9003         default:
9004                 MISSING_CASE(tiling);
9005                 goto error;
9006         }
9007
9008         /*
9009          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
9010          * while i915 HW rotation is clockwise, thats why this swapping.
9011          */
9012         switch (val & PLANE_CTL_ROTATE_MASK) {
9013         case PLANE_CTL_ROTATE_0:
9014                 plane_config->rotation = DRM_MODE_ROTATE_0;
9015                 break;
9016         case PLANE_CTL_ROTATE_90:
9017                 plane_config->rotation = DRM_MODE_ROTATE_270;
9018                 break;
9019         case PLANE_CTL_ROTATE_180:
9020                 plane_config->rotation = DRM_MODE_ROTATE_180;
9021                 break;
9022         case PLANE_CTL_ROTATE_270:
9023                 plane_config->rotation = DRM_MODE_ROTATE_90;
9024                 break;
9025         }
9026
9027         if (INTEL_GEN(dev_priv) >= 10 &&
9028             val & PLANE_CTL_FLIP_HORIZONTAL)
9029                 plane_config->rotation |= DRM_MODE_REFLECT_X;
9030
9031         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
9032         plane_config->base = base;
9033
9034         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
9035
9036         val = I915_READ(PLANE_SIZE(pipe, plane_id));
9037         fb->height = ((val >> 16) & 0xfff) + 1;
9038         fb->width = ((val >> 0) & 0x1fff) + 1;
9039
9040         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
9041         stride_mult = skl_plane_stride_mult(fb, 0, DRM_MODE_ROTATE_0);
9042         fb->pitches[0] = (val & 0x3ff) * stride_mult;
9043
9044         aligned_height = intel_fb_align_height(fb, 0, fb->height);
9045
9046         plane_config->size = fb->pitches[0] * aligned_height;
9047
9048         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
9049                       crtc->base.name, plane->base.name, fb->width, fb->height,
9050                       fb->format->cpp[0] * 8, base, fb->pitches[0],
9051                       plane_config->size);
9052
9053         plane_config->fb = intel_fb;
9054         return;
9055
9056 error:
9057         kfree(intel_fb);
9058 }
9059
9060 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
9061                                      struct intel_crtc_state *pipe_config)
9062 {
9063         struct drm_device *dev = crtc->base.dev;
9064         struct drm_i915_private *dev_priv = to_i915(dev);
9065         u32 tmp;
9066
9067         tmp = I915_READ(PF_CTL(crtc->pipe));
9068
9069         if (tmp & PF_ENABLE) {
9070                 pipe_config->pch_pfit.enabled = true;
9071                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
9072                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
9073
9074                 /* We currently do not free assignements of panel fitters on
9075                  * ivb/hsw (since we don't use the higher upscaling modes which
9076                  * differentiates them) so just WARN about this case for now. */
9077                 if (IS_GEN(dev_priv, 7)) {
9078                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
9079                                 PF_PIPE_SEL_IVB(crtc->pipe));
9080                 }
9081         }
9082 }
9083
9084 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
9085                                      struct intel_crtc_state *pipe_config)
9086 {
9087         struct drm_device *dev = crtc->base.dev;
9088         struct drm_i915_private *dev_priv = to_i915(dev);
9089         enum intel_display_power_domain power_domain;
9090         intel_wakeref_t wakeref;
9091         u32 tmp;
9092         bool ret;
9093
9094         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9095         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
9096         if (!wakeref)
9097                 return false;
9098
9099         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
9100         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9101         pipe_config->shared_dpll = NULL;
9102
9103         ret = false;
9104         tmp = I915_READ(PIPECONF(crtc->pipe));
9105         if (!(tmp & PIPECONF_ENABLE))
9106                 goto out;
9107
9108         switch (tmp & PIPECONF_BPC_MASK) {
9109         case PIPECONF_6BPC:
9110                 pipe_config->pipe_bpp = 18;
9111                 break;
9112         case PIPECONF_8BPC:
9113                 pipe_config->pipe_bpp = 24;
9114                 break;
9115         case PIPECONF_10BPC:
9116                 pipe_config->pipe_bpp = 30;
9117                 break;
9118         case PIPECONF_12BPC:
9119                 pipe_config->pipe_bpp = 36;
9120                 break;
9121         default:
9122                 break;
9123         }
9124
9125         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9126                 pipe_config->limited_color_range = true;
9127
9128         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9129                 struct intel_shared_dpll *pll;
9130                 enum intel_dpll_id pll_id;
9131
9132                 pipe_config->has_pch_encoder = true;
9133
9134                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9135                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9136                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9137
9138                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9139
9140                 if (HAS_PCH_IBX(dev_priv)) {
9141                         /*
9142                          * The pipe->pch transcoder and pch transcoder->pll
9143                          * mapping is fixed.
9144                          */
9145                         pll_id = (enum intel_dpll_id) crtc->pipe;
9146                 } else {
9147                         tmp = I915_READ(PCH_DPLL_SEL);
9148                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9149                                 pll_id = DPLL_ID_PCH_PLL_B;
9150                         else
9151                                 pll_id= DPLL_ID_PCH_PLL_A;
9152                 }
9153
9154                 pipe_config->shared_dpll =
9155                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9156                 pll = pipe_config->shared_dpll;
9157
9158                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9159                                                 &pipe_config->dpll_hw_state));
9160
9161                 tmp = pipe_config->dpll_hw_state.dpll;
9162                 pipe_config->pixel_multiplier =
9163                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9164                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9165
9166                 ironlake_pch_clock_get(crtc, pipe_config);
9167         } else {
9168                 pipe_config->pixel_multiplier = 1;
9169         }
9170
9171         intel_get_pipe_timings(crtc, pipe_config);
9172         intel_get_pipe_src_size(crtc, pipe_config);
9173
9174         ironlake_get_pfit_config(crtc, pipe_config);
9175
9176         ret = true;
9177
9178 out:
9179         intel_display_power_put(dev_priv, power_domain, wakeref);
9180
9181         return ret;
9182 }
9183
9184 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9185 {
9186         struct drm_device *dev = &dev_priv->drm;
9187         struct intel_crtc *crtc;
9188
9189         for_each_intel_crtc(dev, crtc)
9190                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9191                      pipe_name(crtc->pipe));
9192
9193         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL2),
9194                         "Display power well on\n");
9195         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9196         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9197         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9198         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
9199         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9200              "CPU PWM1 enabled\n");
9201         if (IS_HASWELL(dev_priv))
9202                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9203                      "CPU PWM2 enabled\n");
9204         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9205              "PCH PWM1 enabled\n");
9206         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9207              "Utility pin enabled\n");
9208         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9209
9210         /*
9211          * In theory we can still leave IRQs enabled, as long as only the HPD
9212          * interrupts remain enabled. We used to check for that, but since it's
9213          * gen-specific and since we only disable LCPLL after we fully disable
9214          * the interrupts, the check below should be enough.
9215          */
9216         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9217 }
9218
9219 static u32 hsw_read_dcomp(struct drm_i915_private *dev_priv)
9220 {
9221         if (IS_HASWELL(dev_priv))
9222                 return I915_READ(D_COMP_HSW);
9223         else
9224                 return I915_READ(D_COMP_BDW);
9225 }
9226
9227 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, u32 val)
9228 {
9229         if (IS_HASWELL(dev_priv)) {
9230                 mutex_lock(&dev_priv->pcu_lock);
9231                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9232                                             val))
9233                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
9234                 mutex_unlock(&dev_priv->pcu_lock);
9235         } else {
9236                 I915_WRITE(D_COMP_BDW, val);
9237                 POSTING_READ(D_COMP_BDW);
9238         }
9239 }
9240
9241 /*
9242  * This function implements pieces of two sequences from BSpec:
9243  * - Sequence for display software to disable LCPLL
9244  * - Sequence for display software to allow package C8+
9245  * The steps implemented here are just the steps that actually touch the LCPLL
9246  * register. Callers should take care of disabling all the display engine
9247  * functions, doing the mode unset, fixing interrupts, etc.
9248  */
9249 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9250                               bool switch_to_fclk, bool allow_power_down)
9251 {
9252         u32 val;
9253
9254         assert_can_disable_lcpll(dev_priv);
9255
9256         val = I915_READ(LCPLL_CTL);
9257
9258         if (switch_to_fclk) {
9259                 val |= LCPLL_CD_SOURCE_FCLK;
9260                 I915_WRITE(LCPLL_CTL, val);
9261
9262                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9263                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9264                         DRM_ERROR("Switching to FCLK failed\n");
9265
9266                 val = I915_READ(LCPLL_CTL);
9267         }
9268
9269         val |= LCPLL_PLL_DISABLE;
9270         I915_WRITE(LCPLL_CTL, val);
9271         POSTING_READ(LCPLL_CTL);
9272
9273         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9274                 DRM_ERROR("LCPLL still locked\n");
9275
9276         val = hsw_read_dcomp(dev_priv);
9277         val |= D_COMP_COMP_DISABLE;
9278         hsw_write_dcomp(dev_priv, val);
9279         ndelay(100);
9280
9281         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9282                      1))
9283                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9284
9285         if (allow_power_down) {
9286                 val = I915_READ(LCPLL_CTL);
9287                 val |= LCPLL_POWER_DOWN_ALLOW;
9288                 I915_WRITE(LCPLL_CTL, val);
9289                 POSTING_READ(LCPLL_CTL);
9290         }
9291 }
9292
9293 /*
9294  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9295  * source.
9296  */
9297 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9298 {
9299         u32 val;
9300
9301         val = I915_READ(LCPLL_CTL);
9302
9303         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9304                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9305                 return;
9306
9307         /*
9308          * Make sure we're not on PC8 state before disabling PC8, otherwise
9309          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9310          */
9311         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9312
9313         if (val & LCPLL_POWER_DOWN_ALLOW) {
9314                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9315                 I915_WRITE(LCPLL_CTL, val);
9316                 POSTING_READ(LCPLL_CTL);
9317         }
9318
9319         val = hsw_read_dcomp(dev_priv);
9320         val |= D_COMP_COMP_FORCE;
9321         val &= ~D_COMP_COMP_DISABLE;
9322         hsw_write_dcomp(dev_priv, val);
9323
9324         val = I915_READ(LCPLL_CTL);
9325         val &= ~LCPLL_PLL_DISABLE;
9326         I915_WRITE(LCPLL_CTL, val);
9327
9328         if (intel_wait_for_register(dev_priv,
9329                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9330                                     5))
9331                 DRM_ERROR("LCPLL not locked yet\n");
9332
9333         if (val & LCPLL_CD_SOURCE_FCLK) {
9334                 val = I915_READ(LCPLL_CTL);
9335                 val &= ~LCPLL_CD_SOURCE_FCLK;
9336                 I915_WRITE(LCPLL_CTL, val);
9337
9338                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9339                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9340                         DRM_ERROR("Switching back to LCPLL failed\n");
9341         }
9342
9343         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9344
9345         intel_update_cdclk(dev_priv);
9346         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
9347 }
9348
9349 /*
9350  * Package states C8 and deeper are really deep PC states that can only be
9351  * reached when all the devices on the system allow it, so even if the graphics
9352  * device allows PC8+, it doesn't mean the system will actually get to these
9353  * states. Our driver only allows PC8+ when going into runtime PM.
9354  *
9355  * The requirements for PC8+ are that all the outputs are disabled, the power
9356  * well is disabled and most interrupts are disabled, and these are also
9357  * requirements for runtime PM. When these conditions are met, we manually do
9358  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9359  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9360  * hang the machine.
9361  *
9362  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9363  * the state of some registers, so when we come back from PC8+ we need to
9364  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9365  * need to take care of the registers kept by RC6. Notice that this happens even
9366  * if we don't put the device in PCI D3 state (which is what currently happens
9367  * because of the runtime PM support).
9368  *
9369  * For more, read "Display Sequences for Package C8" on the hardware
9370  * documentation.
9371  */
9372 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9373 {
9374         u32 val;
9375
9376         DRM_DEBUG_KMS("Enabling package C8+\n");
9377
9378         if (HAS_PCH_LPT_LP(dev_priv)) {
9379                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9380                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9381                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9382         }
9383
9384         lpt_disable_clkout_dp(dev_priv);
9385         hsw_disable_lcpll(dev_priv, true, true);
9386 }
9387
9388 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9389 {
9390         u32 val;
9391
9392         DRM_DEBUG_KMS("Disabling package C8+\n");
9393
9394         hsw_restore_lcpll(dev_priv);
9395         lpt_init_pch_refclk(dev_priv);
9396
9397         if (HAS_PCH_LPT_LP(dev_priv)) {
9398                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9399                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9400                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9401         }
9402 }
9403
9404 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9405                                       struct intel_crtc_state *crtc_state)
9406 {
9407         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9408         struct intel_atomic_state *state =
9409                 to_intel_atomic_state(crtc_state->base.state);
9410
9411         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI) ||
9412             IS_ICELAKE(dev_priv)) {
9413                 struct intel_encoder *encoder =
9414                         intel_get_crtc_new_encoder(state, crtc_state);
9415
9416                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9417                         DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9418                                       pipe_name(crtc->pipe));
9419                         return -EINVAL;
9420                 }
9421         }
9422
9423         return 0;
9424 }
9425
9426 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9427                                    enum port port,
9428                                    struct intel_crtc_state *pipe_config)
9429 {
9430         enum intel_dpll_id id;
9431         u32 temp;
9432
9433         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9434         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9435
9436         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9437                 return;
9438
9439         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9440 }
9441
9442 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9443                                 enum port port,
9444                                 struct intel_crtc_state *pipe_config)
9445 {
9446         enum intel_dpll_id id;
9447         u32 temp;
9448
9449         /* TODO: TBT pll not implemented. */
9450         if (intel_port_is_combophy(dev_priv, port)) {
9451                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9452                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9453                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9454
9455                 if (WARN_ON(!intel_dpll_is_combophy(id)))
9456                         return;
9457         } else if (intel_port_is_tc(dev_priv, port)) {
9458                 id = icl_tc_port_to_pll_id(intel_port_to_tc(dev_priv, port));
9459         } else {
9460                 WARN(1, "Invalid port %x\n", port);
9461                 return;
9462         }
9463
9464         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9465 }
9466
9467 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9468                                 enum port port,
9469                                 struct intel_crtc_state *pipe_config)
9470 {
9471         enum intel_dpll_id id;
9472
9473         switch (port) {
9474         case PORT_A:
9475                 id = DPLL_ID_SKL_DPLL0;
9476                 break;
9477         case PORT_B:
9478                 id = DPLL_ID_SKL_DPLL1;
9479                 break;
9480         case PORT_C:
9481                 id = DPLL_ID_SKL_DPLL2;
9482                 break;
9483         default:
9484                 DRM_ERROR("Incorrect port type\n");
9485                 return;
9486         }
9487
9488         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9489 }
9490
9491 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9492                                 enum port port,
9493                                 struct intel_crtc_state *pipe_config)
9494 {
9495         enum intel_dpll_id id;
9496         u32 temp;
9497
9498         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9499         id = temp >> (port * 3 + 1);
9500
9501         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9502                 return;
9503
9504         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9505 }
9506
9507 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9508                                 enum port port,
9509                                 struct intel_crtc_state *pipe_config)
9510 {
9511         enum intel_dpll_id id;
9512         u32 ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9513
9514         switch (ddi_pll_sel) {
9515         case PORT_CLK_SEL_WRPLL1:
9516                 id = DPLL_ID_WRPLL1;
9517                 break;
9518         case PORT_CLK_SEL_WRPLL2:
9519                 id = DPLL_ID_WRPLL2;
9520                 break;
9521         case PORT_CLK_SEL_SPLL:
9522                 id = DPLL_ID_SPLL;
9523                 break;
9524         case PORT_CLK_SEL_LCPLL_810:
9525                 id = DPLL_ID_LCPLL_810;
9526                 break;
9527         case PORT_CLK_SEL_LCPLL_1350:
9528                 id = DPLL_ID_LCPLL_1350;
9529                 break;
9530         case PORT_CLK_SEL_LCPLL_2700:
9531                 id = DPLL_ID_LCPLL_2700;
9532                 break;
9533         default:
9534                 MISSING_CASE(ddi_pll_sel);
9535                 /* fall through */
9536         case PORT_CLK_SEL_NONE:
9537                 return;
9538         }
9539
9540         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9541 }
9542
9543 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9544                                      struct intel_crtc_state *pipe_config,
9545                                      u64 *power_domain_mask)
9546 {
9547         struct drm_device *dev = crtc->base.dev;
9548         struct drm_i915_private *dev_priv = to_i915(dev);
9549         enum intel_display_power_domain power_domain;
9550         unsigned long panel_transcoder_mask = BIT(TRANSCODER_EDP);
9551         unsigned long enabled_panel_transcoders = 0;
9552         enum transcoder panel_transcoder;
9553         u32 tmp;
9554
9555         if (IS_ICELAKE(dev_priv))
9556                 panel_transcoder_mask |=
9557                         BIT(TRANSCODER_DSI_0) | BIT(TRANSCODER_DSI_1);
9558
9559         /*
9560          * The pipe->transcoder mapping is fixed with the exception of the eDP
9561          * and DSI transcoders handled below.
9562          */
9563         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9564
9565         /*
9566          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9567          * consistency and less surprising code; it's in always on power).
9568          */
9569         for_each_set_bit(panel_transcoder,
9570                          &panel_transcoder_mask,
9571                          ARRAY_SIZE(INTEL_INFO(dev_priv)->trans_offsets)) {
9572                 enum pipe trans_pipe;
9573
9574                 tmp = I915_READ(TRANS_DDI_FUNC_CTL(panel_transcoder));
9575                 if (!(tmp & TRANS_DDI_FUNC_ENABLE))
9576                         continue;
9577
9578                 /*
9579                  * Log all enabled ones, only use the first one.
9580                  *
9581                  * FIXME: This won't work for two separate DSI displays.
9582                  */
9583                 enabled_panel_transcoders |= BIT(panel_transcoder);
9584                 if (enabled_panel_transcoders != BIT(panel_transcoder))
9585                         continue;
9586
9587                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9588                 default:
9589                         WARN(1, "unknown pipe linked to transcoder %s\n",
9590                              transcoder_name(panel_transcoder));
9591                         /* fall through */
9592                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9593                 case TRANS_DDI_EDP_INPUT_A_ON:
9594                         trans_pipe = PIPE_A;
9595                         break;
9596                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9597                         trans_pipe = PIPE_B;
9598                         break;
9599                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9600                         trans_pipe = PIPE_C;
9601                         break;
9602                 }
9603
9604                 if (trans_pipe == crtc->pipe)
9605                         pipe_config->cpu_transcoder = panel_transcoder;
9606         }
9607
9608         /*
9609          * Valid combos: none, eDP, DSI0, DSI1, DSI0+DSI1
9610          */
9611         WARN_ON((enabled_panel_transcoders & BIT(TRANSCODER_EDP)) &&
9612                 enabled_panel_transcoders != BIT(TRANSCODER_EDP));
9613
9614         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9615         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9616                 return false;
9617
9618         WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
9619         *power_domain_mask |= BIT_ULL(power_domain);
9620
9621         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9622
9623         return tmp & PIPECONF_ENABLE;
9624 }
9625
9626 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9627                                          struct intel_crtc_state *pipe_config,
9628                                          u64 *power_domain_mask)
9629 {
9630         struct drm_device *dev = crtc->base.dev;
9631         struct drm_i915_private *dev_priv = to_i915(dev);
9632         enum intel_display_power_domain power_domain;
9633         enum port port;
9634         enum transcoder cpu_transcoder;
9635         u32 tmp;
9636
9637         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9638                 if (port == PORT_A)
9639                         cpu_transcoder = TRANSCODER_DSI_A;
9640                 else
9641                         cpu_transcoder = TRANSCODER_DSI_C;
9642
9643                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9644                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9645                         continue;
9646
9647                 WARN_ON(*power_domain_mask & BIT_ULL(power_domain));
9648                 *power_domain_mask |= BIT_ULL(power_domain);
9649
9650                 /*
9651                  * The PLL needs to be enabled with a valid divider
9652                  * configuration, otherwise accessing DSI registers will hang
9653                  * the machine. See BSpec North Display Engine
9654                  * registers/MIPI[BXT]. We can break out here early, since we
9655                  * need the same DSI PLL to be enabled for both DSI ports.
9656                  */
9657                 if (!bxt_dsi_pll_is_enabled(dev_priv))
9658                         break;
9659
9660                 /* XXX: this works for video mode only */
9661                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9662                 if (!(tmp & DPI_ENABLE))
9663                         continue;
9664
9665                 tmp = I915_READ(MIPI_CTRL(port));
9666                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9667                         continue;
9668
9669                 pipe_config->cpu_transcoder = cpu_transcoder;
9670                 break;
9671         }
9672
9673         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9674 }
9675
9676 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9677                                        struct intel_crtc_state *pipe_config)
9678 {
9679         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9680         struct intel_shared_dpll *pll;
9681         enum port port;
9682         u32 tmp;
9683
9684         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9685
9686         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9687
9688         if (IS_ICELAKE(dev_priv))
9689                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
9690         else if (IS_CANNONLAKE(dev_priv))
9691                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9692         else if (IS_GEN9_BC(dev_priv))
9693                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9694         else if (IS_GEN9_LP(dev_priv))
9695                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9696         else
9697                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9698
9699         pll = pipe_config->shared_dpll;
9700         if (pll) {
9701                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9702                                                 &pipe_config->dpll_hw_state));
9703         }
9704
9705         /*
9706          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9707          * DDI E. So just check whether this pipe is wired to DDI E and whether
9708          * the PCH transcoder is on.
9709          */
9710         if (INTEL_GEN(dev_priv) < 9 &&
9711             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9712                 pipe_config->has_pch_encoder = true;
9713
9714                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9715                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9716                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9717
9718                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9719         }
9720 }
9721
9722 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9723                                     struct intel_crtc_state *pipe_config)
9724 {
9725         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9726         enum intel_display_power_domain power_domain;
9727         u64 power_domain_mask;
9728         bool active;
9729
9730         intel_crtc_init_scalers(crtc, pipe_config);
9731
9732         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9733         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9734                 return false;
9735         power_domain_mask = BIT_ULL(power_domain);
9736
9737         pipe_config->shared_dpll = NULL;
9738
9739         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9740
9741         if (IS_GEN9_LP(dev_priv) &&
9742             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9743                 WARN_ON(active);
9744                 active = true;
9745         }
9746
9747         if (!active)
9748                 goto out;
9749
9750         if (!transcoder_is_dsi(pipe_config->cpu_transcoder) ||
9751             IS_ICELAKE(dev_priv)) {
9752                 haswell_get_ddi_port_state(crtc, pipe_config);
9753                 intel_get_pipe_timings(crtc, pipe_config);
9754         }
9755
9756         intel_get_pipe_src_size(crtc, pipe_config);
9757         intel_get_crtc_ycbcr_config(crtc, pipe_config);
9758
9759         pipe_config->gamma_mode =
9760                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9761
9762         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9763         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9764                 WARN_ON(power_domain_mask & BIT_ULL(power_domain));
9765                 power_domain_mask |= BIT_ULL(power_domain);
9766
9767                 if (INTEL_GEN(dev_priv) >= 9)
9768                         skylake_get_pfit_config(crtc, pipe_config);
9769                 else
9770                         ironlake_get_pfit_config(crtc, pipe_config);
9771         }
9772
9773         if (hsw_crtc_supports_ips(crtc)) {
9774                 if (IS_HASWELL(dev_priv))
9775                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9776                 else {
9777                         /*
9778                          * We cannot readout IPS state on broadwell, set to
9779                          * true so we can set it to a defined state on first
9780                          * commit.
9781                          */
9782                         pipe_config->ips_enabled = true;
9783                 }
9784         }
9785
9786         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9787             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9788                 pipe_config->pixel_multiplier =
9789                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9790         } else {
9791                 pipe_config->pixel_multiplier = 1;
9792         }
9793
9794 out:
9795         for_each_power_domain(power_domain, power_domain_mask)
9796                 intel_display_power_put_unchecked(dev_priv, power_domain);
9797
9798         return active;
9799 }
9800
9801 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9802 {
9803         struct drm_i915_private *dev_priv =
9804                 to_i915(plane_state->base.plane->dev);
9805         const struct drm_framebuffer *fb = plane_state->base.fb;
9806         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9807         u32 base;
9808
9809         if (INTEL_INFO(dev_priv)->display.cursor_needs_physical)
9810                 base = obj->phys_handle->busaddr;
9811         else
9812                 base = intel_plane_ggtt_offset(plane_state);
9813
9814         base += plane_state->color_plane[0].offset;
9815
9816         /* ILK+ do this automagically */
9817         if (HAS_GMCH_DISPLAY(dev_priv) &&
9818             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9819                 base += (plane_state->base.crtc_h *
9820                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9821
9822         return base;
9823 }
9824
9825 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9826 {
9827         int x = plane_state->base.crtc_x;
9828         int y = plane_state->base.crtc_y;
9829         u32 pos = 0;
9830
9831         if (x < 0) {
9832                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9833                 x = -x;
9834         }
9835         pos |= x << CURSOR_X_SHIFT;
9836
9837         if (y < 0) {
9838                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9839                 y = -y;
9840         }
9841         pos |= y << CURSOR_Y_SHIFT;
9842
9843         return pos;
9844 }
9845
9846 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9847 {
9848         const struct drm_mode_config *config =
9849                 &plane_state->base.plane->dev->mode_config;
9850         int width = plane_state->base.crtc_w;
9851         int height = plane_state->base.crtc_h;
9852
9853         return width > 0 && width <= config->cursor_width &&
9854                 height > 0 && height <= config->cursor_height;
9855 }
9856
9857 static int intel_cursor_check_surface(struct intel_plane_state *plane_state)
9858 {
9859         const struct drm_framebuffer *fb = plane_state->base.fb;
9860         unsigned int rotation = plane_state->base.rotation;
9861         int src_x, src_y;
9862         u32 offset;
9863         int ret;
9864
9865         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
9866         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
9867
9868         ret = intel_plane_check_stride(plane_state);
9869         if (ret)
9870                 return ret;
9871
9872         src_x = plane_state->base.src_x >> 16;
9873         src_y = plane_state->base.src_y >> 16;
9874
9875         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9876         offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
9877                                                     plane_state, 0);
9878
9879         if (src_x != 0 || src_y != 0) {
9880                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9881                 return -EINVAL;
9882         }
9883
9884         plane_state->color_plane[0].offset = offset;
9885
9886         return 0;
9887 }
9888
9889 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9890                               struct intel_plane_state *plane_state)
9891 {
9892         const struct drm_framebuffer *fb = plane_state->base.fb;
9893         int ret;
9894
9895         if (fb && fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9896                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9897                 return -EINVAL;
9898         }
9899
9900         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9901                                                   &crtc_state->base,
9902                                                   DRM_PLANE_HELPER_NO_SCALING,
9903                                                   DRM_PLANE_HELPER_NO_SCALING,
9904                                                   true, true);
9905         if (ret)
9906                 return ret;
9907
9908         if (!plane_state->base.visible)
9909                 return 0;
9910
9911         ret = intel_plane_check_src_coordinates(plane_state);
9912         if (ret)
9913                 return ret;
9914
9915         ret = intel_cursor_check_surface(plane_state);
9916         if (ret)
9917                 return ret;
9918
9919         return 0;
9920 }
9921
9922 static unsigned int
9923 i845_cursor_max_stride(struct intel_plane *plane,
9924                        u32 pixel_format, u64 modifier,
9925                        unsigned int rotation)
9926 {
9927         return 2048;
9928 }
9929
9930 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9931                            const struct intel_plane_state *plane_state)
9932 {
9933         return CURSOR_ENABLE |
9934                 CURSOR_GAMMA_ENABLE |
9935                 CURSOR_FORMAT_ARGB |
9936                 CURSOR_STRIDE(plane_state->color_plane[0].stride);
9937 }
9938
9939 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9940 {
9941         int width = plane_state->base.crtc_w;
9942
9943         /*
9944          * 845g/865g are only limited by the width of their cursors,
9945          * the height is arbitrary up to the precision of the register.
9946          */
9947         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9948 }
9949
9950 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
9951                              struct intel_plane_state *plane_state)
9952 {
9953         const struct drm_framebuffer *fb = plane_state->base.fb;
9954         int ret;
9955
9956         ret = intel_check_cursor(crtc_state, plane_state);
9957         if (ret)
9958                 return ret;
9959
9960         /* if we want to turn off the cursor ignore width and height */
9961         if (!fb)
9962                 return 0;
9963
9964         /* Check for which cursor types we support */
9965         if (!i845_cursor_size_ok(plane_state)) {
9966                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9967                           plane_state->base.crtc_w,
9968                           plane_state->base.crtc_h);
9969                 return -EINVAL;
9970         }
9971
9972         WARN_ON(plane_state->base.visible &&
9973                 plane_state->color_plane[0].stride != fb->pitches[0]);
9974
9975         switch (fb->pitches[0]) {
9976         case 256:
9977         case 512:
9978         case 1024:
9979         case 2048:
9980                 break;
9981         default:
9982                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9983                               fb->pitches[0]);
9984                 return -EINVAL;
9985         }
9986
9987         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9988
9989         return 0;
9990 }
9991
9992 static void i845_update_cursor(struct intel_plane *plane,
9993                                const struct intel_crtc_state *crtc_state,
9994                                const struct intel_plane_state *plane_state)
9995 {
9996         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9997         u32 cntl = 0, base = 0, pos = 0, size = 0;
9998         unsigned long irqflags;
9999
10000         if (plane_state && plane_state->base.visible) {
10001                 unsigned int width = plane_state->base.crtc_w;
10002                 unsigned int height = plane_state->base.crtc_h;
10003
10004                 cntl = plane_state->ctl;
10005                 size = (height << 12) | width;
10006
10007                 base = intel_cursor_base(plane_state);
10008                 pos = intel_cursor_position(plane_state);
10009         }
10010
10011         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10012
10013         /* On these chipsets we can only modify the base/size/stride
10014          * whilst the cursor is disabled.
10015          */
10016         if (plane->cursor.base != base ||
10017             plane->cursor.size != size ||
10018             plane->cursor.cntl != cntl) {
10019                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
10020                 I915_WRITE_FW(CURBASE(PIPE_A), base);
10021                 I915_WRITE_FW(CURSIZE, size);
10022                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
10023                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
10024
10025                 plane->cursor.base = base;
10026                 plane->cursor.size = size;
10027                 plane->cursor.cntl = cntl;
10028         } else {
10029                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
10030         }
10031
10032         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10033 }
10034
10035 static void i845_disable_cursor(struct intel_plane *plane,
10036                                 const struct intel_crtc_state *crtc_state)
10037 {
10038         i845_update_cursor(plane, crtc_state, NULL);
10039 }
10040
10041 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
10042                                      enum pipe *pipe)
10043 {
10044         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10045         enum intel_display_power_domain power_domain;
10046         intel_wakeref_t wakeref;
10047         bool ret;
10048
10049         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
10050         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10051         if (!wakeref)
10052                 return false;
10053
10054         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
10055
10056         *pipe = PIPE_A;
10057
10058         intel_display_power_put(dev_priv, power_domain, wakeref);
10059
10060         return ret;
10061 }
10062
10063 static unsigned int
10064 i9xx_cursor_max_stride(struct intel_plane *plane,
10065                        u32 pixel_format, u64 modifier,
10066                        unsigned int rotation)
10067 {
10068         return plane->base.dev->mode_config.cursor_width * 4;
10069 }
10070
10071 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
10072                            const struct intel_plane_state *plane_state)
10073 {
10074         struct drm_i915_private *dev_priv =
10075                 to_i915(plane_state->base.plane->dev);
10076         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
10077         u32 cntl = 0;
10078
10079         if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
10080                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
10081
10082         if (INTEL_GEN(dev_priv) <= 10) {
10083                 cntl |= MCURSOR_GAMMA_ENABLE;
10084
10085                 if (HAS_DDI(dev_priv))
10086                         cntl |= MCURSOR_PIPE_CSC_ENABLE;
10087         }
10088
10089         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10090                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
10091
10092         switch (plane_state->base.crtc_w) {
10093         case 64:
10094                 cntl |= MCURSOR_MODE_64_ARGB_AX;
10095                 break;
10096         case 128:
10097                 cntl |= MCURSOR_MODE_128_ARGB_AX;
10098                 break;
10099         case 256:
10100                 cntl |= MCURSOR_MODE_256_ARGB_AX;
10101                 break;
10102         default:
10103                 MISSING_CASE(plane_state->base.crtc_w);
10104                 return 0;
10105         }
10106
10107         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
10108                 cntl |= MCURSOR_ROTATE_180;
10109
10110         return cntl;
10111 }
10112
10113 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
10114 {
10115         struct drm_i915_private *dev_priv =
10116                 to_i915(plane_state->base.plane->dev);
10117         int width = plane_state->base.crtc_w;
10118         int height = plane_state->base.crtc_h;
10119
10120         if (!intel_cursor_size_ok(plane_state))
10121                 return false;
10122
10123         /* Cursor width is limited to a few power-of-two sizes */
10124         switch (width) {
10125         case 256:
10126         case 128:
10127         case 64:
10128                 break;
10129         default:
10130                 return false;
10131         }
10132
10133         /*
10134          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
10135          * height from 8 lines up to the cursor width, when the
10136          * cursor is not rotated. Everything else requires square
10137          * cursors.
10138          */
10139         if (HAS_CUR_FBC(dev_priv) &&
10140             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
10141                 if (height < 8 || height > width)
10142                         return false;
10143         } else {
10144                 if (height != width)
10145                         return false;
10146         }
10147
10148         return true;
10149 }
10150
10151 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
10152                              struct intel_plane_state *plane_state)
10153 {
10154         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
10155         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10156         const struct drm_framebuffer *fb = plane_state->base.fb;
10157         enum pipe pipe = plane->pipe;
10158         int ret;
10159
10160         ret = intel_check_cursor(crtc_state, plane_state);
10161         if (ret)
10162                 return ret;
10163
10164         /* if we want to turn off the cursor ignore width and height */
10165         if (!fb)
10166                 return 0;
10167
10168         /* Check for which cursor types we support */
10169         if (!i9xx_cursor_size_ok(plane_state)) {
10170                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10171                           plane_state->base.crtc_w,
10172                           plane_state->base.crtc_h);
10173                 return -EINVAL;
10174         }
10175
10176         WARN_ON(plane_state->base.visible &&
10177                 plane_state->color_plane[0].stride != fb->pitches[0]);
10178
10179         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
10180                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
10181                               fb->pitches[0], plane_state->base.crtc_w);
10182                 return -EINVAL;
10183         }
10184
10185         /*
10186          * There's something wrong with the cursor on CHV pipe C.
10187          * If it straddles the left edge of the screen then
10188          * moving it away from the edge or disabling it often
10189          * results in a pipe underrun, and often that can lead to
10190          * dead pipe (constant underrun reported, and it scans
10191          * out just a solid color). To recover from that, the
10192          * display power well must be turned off and on again.
10193          * Refuse the put the cursor into that compromised position.
10194          */
10195         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
10196             plane_state->base.visible && plane_state->base.crtc_x < 0) {
10197                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
10198                 return -EINVAL;
10199         }
10200
10201         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
10202
10203         return 0;
10204 }
10205
10206 static void i9xx_update_cursor(struct intel_plane *plane,
10207                                const struct intel_crtc_state *crtc_state,
10208                                const struct intel_plane_state *plane_state)
10209 {
10210         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10211         enum pipe pipe = plane->pipe;
10212         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
10213         unsigned long irqflags;
10214
10215         if (plane_state && plane_state->base.visible) {
10216                 cntl = plane_state->ctl;
10217
10218                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
10219                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
10220
10221                 base = intel_cursor_base(plane_state);
10222                 pos = intel_cursor_position(plane_state);
10223         }
10224
10225         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10226
10227         /*
10228          * On some platforms writing CURCNTR first will also
10229          * cause CURPOS to be armed by the CURBASE write.
10230          * Without the CURCNTR write the CURPOS write would
10231          * arm itself. Thus we always update CURCNTR before
10232          * CURPOS.
10233          *
10234          * On other platforms CURPOS always requires the
10235          * CURBASE write to arm the update. Additonally
10236          * a write to any of the cursor register will cancel
10237          * an already armed cursor update. Thus leaving out
10238          * the CURBASE write after CURPOS could lead to a
10239          * cursor that doesn't appear to move, or even change
10240          * shape. Thus we always write CURBASE.
10241          *
10242          * The other registers are armed by by the CURBASE write
10243          * except when the plane is getting enabled at which time
10244          * the CURCNTR write arms the update.
10245          */
10246
10247         if (INTEL_GEN(dev_priv) >= 9)
10248                 skl_write_cursor_wm(plane, crtc_state);
10249
10250         if (plane->cursor.base != base ||
10251             plane->cursor.size != fbc_ctl ||
10252             plane->cursor.cntl != cntl) {
10253                 if (HAS_CUR_FBC(dev_priv))
10254                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
10255                 I915_WRITE_FW(CURCNTR(pipe), cntl);
10256                 I915_WRITE_FW(CURPOS(pipe), pos);
10257                 I915_WRITE_FW(CURBASE(pipe), base);
10258
10259                 plane->cursor.base = base;
10260                 plane->cursor.size = fbc_ctl;
10261                 plane->cursor.cntl = cntl;
10262         } else {
10263                 I915_WRITE_FW(CURPOS(pipe), pos);
10264                 I915_WRITE_FW(CURBASE(pipe), base);
10265         }
10266
10267         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10268 }
10269
10270 static void i9xx_disable_cursor(struct intel_plane *plane,
10271                                 const struct intel_crtc_state *crtc_state)
10272 {
10273         i9xx_update_cursor(plane, crtc_state, NULL);
10274 }
10275
10276 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10277                                      enum pipe *pipe)
10278 {
10279         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10280         enum intel_display_power_domain power_domain;
10281         intel_wakeref_t wakeref;
10282         bool ret;
10283         u32 val;
10284
10285         /*
10286          * Not 100% correct for planes that can move between pipes,
10287          * but that's only the case for gen2-3 which don't have any
10288          * display power wells.
10289          */
10290         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10291         wakeref = intel_display_power_get_if_enabled(dev_priv, power_domain);
10292         if (!wakeref)
10293                 return false;
10294
10295         val = I915_READ(CURCNTR(plane->pipe));
10296
10297         ret = val & MCURSOR_MODE;
10298
10299         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10300                 *pipe = plane->pipe;
10301         else
10302                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10303                         MCURSOR_PIPE_SELECT_SHIFT;
10304
10305         intel_display_power_put(dev_priv, power_domain, wakeref);
10306
10307         return ret;
10308 }
10309
10310 /* VESA 640x480x72Hz mode to set on the pipe */
10311 static const struct drm_display_mode load_detect_mode = {
10312         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10313                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10314 };
10315
10316 struct drm_framebuffer *
10317 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10318                          struct drm_mode_fb_cmd2 *mode_cmd)
10319 {
10320         struct intel_framebuffer *intel_fb;
10321         int ret;
10322
10323         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10324         if (!intel_fb)
10325                 return ERR_PTR(-ENOMEM);
10326
10327         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10328         if (ret)
10329                 goto err;
10330
10331         return &intel_fb->base;
10332
10333 err:
10334         kfree(intel_fb);
10335         return ERR_PTR(ret);
10336 }
10337
10338 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10339                                         struct drm_crtc *crtc)
10340 {
10341         struct drm_plane *plane;
10342         struct drm_plane_state *plane_state;
10343         int ret, i;
10344
10345         ret = drm_atomic_add_affected_planes(state, crtc);
10346         if (ret)
10347                 return ret;
10348
10349         for_each_new_plane_in_state(state, plane, plane_state, i) {
10350                 if (plane_state->crtc != crtc)
10351                         continue;
10352
10353                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10354                 if (ret)
10355                         return ret;
10356
10357                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10358         }
10359
10360         return 0;
10361 }
10362
10363 int intel_get_load_detect_pipe(struct drm_connector *connector,
10364                                const struct drm_display_mode *mode,
10365                                struct intel_load_detect_pipe *old,
10366                                struct drm_modeset_acquire_ctx *ctx)
10367 {
10368         struct intel_crtc *intel_crtc;
10369         struct intel_encoder *intel_encoder =
10370                 intel_attached_encoder(connector);
10371         struct drm_crtc *possible_crtc;
10372         struct drm_encoder *encoder = &intel_encoder->base;
10373         struct drm_crtc *crtc = NULL;
10374         struct drm_device *dev = encoder->dev;
10375         struct drm_i915_private *dev_priv = to_i915(dev);
10376         struct drm_mode_config *config = &dev->mode_config;
10377         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10378         struct drm_connector_state *connector_state;
10379         struct intel_crtc_state *crtc_state;
10380         int ret, i = -1;
10381
10382         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10383                       connector->base.id, connector->name,
10384                       encoder->base.id, encoder->name);
10385
10386         old->restore_state = NULL;
10387
10388         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10389
10390         /*
10391          * Algorithm gets a little messy:
10392          *
10393          *   - if the connector already has an assigned crtc, use it (but make
10394          *     sure it's on first)
10395          *
10396          *   - try to find the first unused crtc that can drive this connector,
10397          *     and use that if we find one
10398          */
10399
10400         /* See if we already have a CRTC for this connector */
10401         if (connector->state->crtc) {
10402                 crtc = connector->state->crtc;
10403
10404                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10405                 if (ret)
10406                         goto fail;
10407
10408                 /* Make sure the crtc and connector are running */
10409                 goto found;
10410         }
10411
10412         /* Find an unused one (if possible) */
10413         for_each_crtc(dev, possible_crtc) {
10414                 i++;
10415                 if (!(encoder->possible_crtcs & (1 << i)))
10416                         continue;
10417
10418                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10419                 if (ret)
10420                         goto fail;
10421
10422                 if (possible_crtc->state->enable) {
10423                         drm_modeset_unlock(&possible_crtc->mutex);
10424                         continue;
10425                 }
10426
10427                 crtc = possible_crtc;
10428                 break;
10429         }
10430
10431         /*
10432          * If we didn't find an unused CRTC, don't use any.
10433          */
10434         if (!crtc) {
10435                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10436                 ret = -ENODEV;
10437                 goto fail;
10438         }
10439
10440 found:
10441         intel_crtc = to_intel_crtc(crtc);
10442
10443         state = drm_atomic_state_alloc(dev);
10444         restore_state = drm_atomic_state_alloc(dev);
10445         if (!state || !restore_state) {
10446                 ret = -ENOMEM;
10447                 goto fail;
10448         }
10449
10450         state->acquire_ctx = ctx;
10451         restore_state->acquire_ctx = ctx;
10452
10453         connector_state = drm_atomic_get_connector_state(state, connector);
10454         if (IS_ERR(connector_state)) {
10455                 ret = PTR_ERR(connector_state);
10456                 goto fail;
10457         }
10458
10459         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10460         if (ret)
10461                 goto fail;
10462
10463         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10464         if (IS_ERR(crtc_state)) {
10465                 ret = PTR_ERR(crtc_state);
10466                 goto fail;
10467         }
10468
10469         crtc_state->base.active = crtc_state->base.enable = true;
10470
10471         if (!mode)
10472                 mode = &load_detect_mode;
10473
10474         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10475         if (ret)
10476                 goto fail;
10477
10478         ret = intel_modeset_disable_planes(state, crtc);
10479         if (ret)
10480                 goto fail;
10481
10482         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10483         if (!ret)
10484                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10485         if (!ret)
10486                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10487         if (ret) {
10488                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10489                 goto fail;
10490         }
10491
10492         ret = drm_atomic_commit(state);
10493         if (ret) {
10494                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10495                 goto fail;
10496         }
10497
10498         old->restore_state = restore_state;
10499         drm_atomic_state_put(state);
10500
10501         /* let the connector get through one full cycle before testing */
10502         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10503         return true;
10504
10505 fail:
10506         if (state) {
10507                 drm_atomic_state_put(state);
10508                 state = NULL;
10509         }
10510         if (restore_state) {
10511                 drm_atomic_state_put(restore_state);
10512                 restore_state = NULL;
10513         }
10514
10515         if (ret == -EDEADLK)
10516                 return ret;
10517
10518         return false;
10519 }
10520
10521 void intel_release_load_detect_pipe(struct drm_connector *connector,
10522                                     struct intel_load_detect_pipe *old,
10523                                     struct drm_modeset_acquire_ctx *ctx)
10524 {
10525         struct intel_encoder *intel_encoder =
10526                 intel_attached_encoder(connector);
10527         struct drm_encoder *encoder = &intel_encoder->base;
10528         struct drm_atomic_state *state = old->restore_state;
10529         int ret;
10530
10531         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10532                       connector->base.id, connector->name,
10533                       encoder->base.id, encoder->name);
10534
10535         if (!state)
10536                 return;
10537
10538         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10539         if (ret)
10540                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10541         drm_atomic_state_put(state);
10542 }
10543
10544 static int i9xx_pll_refclk(struct drm_device *dev,
10545                            const struct intel_crtc_state *pipe_config)
10546 {
10547         struct drm_i915_private *dev_priv = to_i915(dev);
10548         u32 dpll = pipe_config->dpll_hw_state.dpll;
10549
10550         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10551                 return dev_priv->vbt.lvds_ssc_freq;
10552         else if (HAS_PCH_SPLIT(dev_priv))
10553                 return 120000;
10554         else if (!IS_GEN(dev_priv, 2))
10555                 return 96000;
10556         else
10557                 return 48000;
10558 }
10559
10560 /* Returns the clock of the currently programmed mode of the given pipe. */
10561 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10562                                 struct intel_crtc_state *pipe_config)
10563 {
10564         struct drm_device *dev = crtc->base.dev;
10565         struct drm_i915_private *dev_priv = to_i915(dev);
10566         int pipe = pipe_config->cpu_transcoder;
10567         u32 dpll = pipe_config->dpll_hw_state.dpll;
10568         u32 fp;
10569         struct dpll clock;
10570         int port_clock;
10571         int refclk = i9xx_pll_refclk(dev, pipe_config);
10572
10573         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10574                 fp = pipe_config->dpll_hw_state.fp0;
10575         else
10576                 fp = pipe_config->dpll_hw_state.fp1;
10577
10578         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10579         if (IS_PINEVIEW(dev_priv)) {
10580                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10581                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10582         } else {
10583                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10584                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10585         }
10586
10587         if (!IS_GEN(dev_priv, 2)) {
10588                 if (IS_PINEVIEW(dev_priv))
10589                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10590                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10591                 else
10592                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10593                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10594
10595                 switch (dpll & DPLL_MODE_MASK) {
10596                 case DPLLB_MODE_DAC_SERIAL:
10597                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10598                                 5 : 10;
10599                         break;
10600                 case DPLLB_MODE_LVDS:
10601                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10602                                 7 : 14;
10603                         break;
10604                 default:
10605                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10606                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10607                         return;
10608                 }
10609
10610                 if (IS_PINEVIEW(dev_priv))
10611                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10612                 else
10613                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10614         } else {
10615                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10616                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10617
10618                 if (is_lvds) {
10619                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10620                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10621
10622                         if (lvds & LVDS_CLKB_POWER_UP)
10623                                 clock.p2 = 7;
10624                         else
10625                                 clock.p2 = 14;
10626                 } else {
10627                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10628                                 clock.p1 = 2;
10629                         else {
10630                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10631                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10632                         }
10633                         if (dpll & PLL_P2_DIVIDE_BY_4)
10634                                 clock.p2 = 4;
10635                         else
10636                                 clock.p2 = 2;
10637                 }
10638
10639                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10640         }
10641
10642         /*
10643          * This value includes pixel_multiplier. We will use
10644          * port_clock to compute adjusted_mode.crtc_clock in the
10645          * encoder's get_config() function.
10646          */
10647         pipe_config->port_clock = port_clock;
10648 }
10649
10650 int intel_dotclock_calculate(int link_freq,
10651                              const struct intel_link_m_n *m_n)
10652 {
10653         /*
10654          * The calculation for the data clock is:
10655          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10656          * But we want to avoid losing precison if possible, so:
10657          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10658          *
10659          * and the link clock is simpler:
10660          * link_clock = (m * link_clock) / n
10661          */
10662
10663         if (!m_n->link_n)
10664                 return 0;
10665
10666         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10667 }
10668
10669 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10670                                    struct intel_crtc_state *pipe_config)
10671 {
10672         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10673
10674         /* read out port_clock from the DPLL */
10675         i9xx_crtc_clock_get(crtc, pipe_config);
10676
10677         /*
10678          * In case there is an active pipe without active ports,
10679          * we may need some idea for the dotclock anyway.
10680          * Calculate one based on the FDI configuration.
10681          */
10682         pipe_config->base.adjusted_mode.crtc_clock =
10683                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10684                                          &pipe_config->fdi_m_n);
10685 }
10686
10687 /* Returns the currently programmed mode of the given encoder. */
10688 struct drm_display_mode *
10689 intel_encoder_current_mode(struct intel_encoder *encoder)
10690 {
10691         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10692         struct intel_crtc_state *crtc_state;
10693         struct drm_display_mode *mode;
10694         struct intel_crtc *crtc;
10695         enum pipe pipe;
10696
10697         if (!encoder->get_hw_state(encoder, &pipe))
10698                 return NULL;
10699
10700         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10701
10702         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10703         if (!mode)
10704                 return NULL;
10705
10706         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10707         if (!crtc_state) {
10708                 kfree(mode);
10709                 return NULL;
10710         }
10711
10712         crtc_state->base.crtc = &crtc->base;
10713
10714         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10715                 kfree(crtc_state);
10716                 kfree(mode);
10717                 return NULL;
10718         }
10719
10720         encoder->get_config(encoder, crtc_state);
10721
10722         intel_mode_from_pipe_config(mode, crtc_state);
10723
10724         kfree(crtc_state);
10725
10726         return mode;
10727 }
10728
10729 static void intel_crtc_destroy(struct drm_crtc *crtc)
10730 {
10731         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10732
10733         drm_crtc_cleanup(crtc);
10734         kfree(intel_crtc);
10735 }
10736
10737 /**
10738  * intel_wm_need_update - Check whether watermarks need updating
10739  * @cur: current plane state
10740  * @new: new plane state
10741  *
10742  * Check current plane state versus the new one to determine whether
10743  * watermarks need to be recalculated.
10744  *
10745  * Returns true or false.
10746  */
10747 static bool intel_wm_need_update(struct intel_plane_state *cur,
10748                                  struct intel_plane_state *new)
10749 {
10750         /* Update watermarks on tiling or size changes. */
10751         if (new->base.visible != cur->base.visible)
10752                 return true;
10753
10754         if (!cur->base.fb || !new->base.fb)
10755                 return false;
10756
10757         if (cur->base.fb->modifier != new->base.fb->modifier ||
10758             cur->base.rotation != new->base.rotation ||
10759             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10760             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10761             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10762             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10763                 return true;
10764
10765         return false;
10766 }
10767
10768 static bool needs_scaling(const struct intel_plane_state *state)
10769 {
10770         int src_w = drm_rect_width(&state->base.src) >> 16;
10771         int src_h = drm_rect_height(&state->base.src) >> 16;
10772         int dst_w = drm_rect_width(&state->base.dst);
10773         int dst_h = drm_rect_height(&state->base.dst);
10774
10775         return (src_w != dst_w || src_h != dst_h);
10776 }
10777
10778 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10779                                     struct drm_crtc_state *crtc_state,
10780                                     const struct intel_plane_state *old_plane_state,
10781                                     struct drm_plane_state *plane_state)
10782 {
10783         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10784         struct drm_crtc *crtc = crtc_state->crtc;
10785         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10786         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10787         struct drm_device *dev = crtc->dev;
10788         struct drm_i915_private *dev_priv = to_i915(dev);
10789         bool mode_changed = needs_modeset(crtc_state);
10790         bool was_crtc_enabled = old_crtc_state->base.active;
10791         bool is_crtc_enabled = crtc_state->active;
10792         bool turn_off, turn_on, visible, was_visible;
10793         struct drm_framebuffer *fb = plane_state->fb;
10794         int ret;
10795
10796         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10797                 ret = skl_update_scaler_plane(
10798                         to_intel_crtc_state(crtc_state),
10799                         to_intel_plane_state(plane_state));
10800                 if (ret)
10801                         return ret;
10802         }
10803
10804         was_visible = old_plane_state->base.visible;
10805         visible = plane_state->visible;
10806
10807         if (!was_crtc_enabled && WARN_ON(was_visible))
10808                 was_visible = false;
10809
10810         /*
10811          * Visibility is calculated as if the crtc was on, but
10812          * after scaler setup everything depends on it being off
10813          * when the crtc isn't active.
10814          *
10815          * FIXME this is wrong for watermarks. Watermarks should also
10816          * be computed as if the pipe would be active. Perhaps move
10817          * per-plane wm computation to the .check_plane() hook, and
10818          * only combine the results from all planes in the current place?
10819          */
10820         if (!is_crtc_enabled) {
10821                 plane_state->visible = visible = false;
10822                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10823         }
10824
10825         if (!was_visible && !visible)
10826                 return 0;
10827
10828         if (fb != old_plane_state->base.fb)
10829                 pipe_config->fb_changed = true;
10830
10831         turn_off = was_visible && (!visible || mode_changed);
10832         turn_on = visible && (!was_visible || mode_changed);
10833
10834         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10835                          intel_crtc->base.base.id, intel_crtc->base.name,
10836                          plane->base.base.id, plane->base.name,
10837                          fb ? fb->base.id : -1);
10838
10839         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10840                          plane->base.base.id, plane->base.name,
10841                          was_visible, visible,
10842                          turn_off, turn_on, mode_changed);
10843
10844         if (turn_on) {
10845                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10846                         pipe_config->update_wm_pre = true;
10847
10848                 /* must disable cxsr around plane enable/disable */
10849                 if (plane->id != PLANE_CURSOR)
10850                         pipe_config->disable_cxsr = true;
10851         } else if (turn_off) {
10852                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10853                         pipe_config->update_wm_post = true;
10854
10855                 /* must disable cxsr around plane enable/disable */
10856                 if (plane->id != PLANE_CURSOR)
10857                         pipe_config->disable_cxsr = true;
10858         } else if (intel_wm_need_update(to_intel_plane_state(plane->base.state),
10859                                         to_intel_plane_state(plane_state))) {
10860                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10861                         /* FIXME bollocks */
10862                         pipe_config->update_wm_pre = true;
10863                         pipe_config->update_wm_post = true;
10864                 }
10865         }
10866
10867         if (visible || was_visible)
10868                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10869
10870         /*
10871          * ILK/SNB DVSACNTR/Sprite Enable
10872          * IVB SPR_CTL/Sprite Enable
10873          * "When in Self Refresh Big FIFO mode, a write to enable the
10874          *  plane will be internally buffered and delayed while Big FIFO
10875          *  mode is exiting."
10876          *
10877          * Which means that enabling the sprite can take an extra frame
10878          * when we start in big FIFO mode (LP1+). Thus we need to drop
10879          * down to LP0 and wait for vblank in order to make sure the
10880          * sprite gets enabled on the next vblank after the register write.
10881          * Doing otherwise would risk enabling the sprite one frame after
10882          * we've already signalled flip completion. We can resume LP1+
10883          * once the sprite has been enabled.
10884          *
10885          *
10886          * WaCxSRDisabledForSpriteScaling:ivb
10887          * IVB SPR_SCALE/Scaling Enable
10888          * "Low Power watermarks must be disabled for at least one
10889          *  frame before enabling sprite scaling, and kept disabled
10890          *  until sprite scaling is disabled."
10891          *
10892          * ILK/SNB DVSASCALE/Scaling Enable
10893          * "When in Self Refresh Big FIFO mode, scaling enable will be
10894          *  masked off while Big FIFO mode is exiting."
10895          *
10896          * Despite the w/a only being listed for IVB we assume that
10897          * the ILK/SNB note has similar ramifications, hence we apply
10898          * the w/a on all three platforms.
10899          *
10900          * With experimental results seems this is needed also for primary
10901          * plane, not only sprite plane.
10902          */
10903         if (plane->id != PLANE_CURSOR &&
10904             (IS_GEN_RANGE(dev_priv, 5, 6) ||
10905              IS_IVYBRIDGE(dev_priv)) &&
10906             (turn_on || (!needs_scaling(old_plane_state) &&
10907                          needs_scaling(to_intel_plane_state(plane_state)))))
10908                 pipe_config->disable_lp_wm = true;
10909
10910         return 0;
10911 }
10912
10913 static bool encoders_cloneable(const struct intel_encoder *a,
10914                                const struct intel_encoder *b)
10915 {
10916         /* masks could be asymmetric, so check both ways */
10917         return a == b || (a->cloneable & (1 << b->type) &&
10918                           b->cloneable & (1 << a->type));
10919 }
10920
10921 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10922                                          struct intel_crtc *crtc,
10923                                          struct intel_encoder *encoder)
10924 {
10925         struct intel_encoder *source_encoder;
10926         struct drm_connector *connector;
10927         struct drm_connector_state *connector_state;
10928         int i;
10929
10930         for_each_new_connector_in_state(state, connector, connector_state, i) {
10931                 if (connector_state->crtc != &crtc->base)
10932                         continue;
10933
10934                 source_encoder =
10935                         to_intel_encoder(connector_state->best_encoder);
10936                 if (!encoders_cloneable(encoder, source_encoder))
10937                         return false;
10938         }
10939
10940         return true;
10941 }
10942
10943 static int icl_add_linked_planes(struct intel_atomic_state *state)
10944 {
10945         struct intel_plane *plane, *linked;
10946         struct intel_plane_state *plane_state, *linked_plane_state;
10947         int i;
10948
10949         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
10950                 linked = plane_state->linked_plane;
10951
10952                 if (!linked)
10953                         continue;
10954
10955                 linked_plane_state = intel_atomic_get_plane_state(state, linked);
10956                 if (IS_ERR(linked_plane_state))
10957                         return PTR_ERR(linked_plane_state);
10958
10959                 WARN_ON(linked_plane_state->linked_plane != plane);
10960                 WARN_ON(linked_plane_state->slave == plane_state->slave);
10961         }
10962
10963         return 0;
10964 }
10965
10966 static int icl_check_nv12_planes(struct intel_crtc_state *crtc_state)
10967 {
10968         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
10969         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10970         struct intel_atomic_state *state = to_intel_atomic_state(crtc_state->base.state);
10971         struct intel_plane *plane, *linked;
10972         struct intel_plane_state *plane_state;
10973         int i;
10974
10975         if (INTEL_GEN(dev_priv) < 11)
10976                 return 0;
10977
10978         /*
10979          * Destroy all old plane links and make the slave plane invisible
10980          * in the crtc_state->active_planes mask.
10981          */
10982         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
10983                 if (plane->pipe != crtc->pipe || !plane_state->linked_plane)
10984                         continue;
10985
10986                 plane_state->linked_plane = NULL;
10987                 if (plane_state->slave && !plane_state->base.visible) {
10988                         crtc_state->active_planes &= ~BIT(plane->id);
10989                         crtc_state->update_planes |= BIT(plane->id);
10990                 }
10991
10992                 plane_state->slave = false;
10993         }
10994
10995         if (!crtc_state->nv12_planes)
10996                 return 0;
10997
10998         for_each_new_intel_plane_in_state(state, plane, plane_state, i) {
10999                 struct intel_plane_state *linked_state = NULL;
11000
11001                 if (plane->pipe != crtc->pipe ||
11002                     !(crtc_state->nv12_planes & BIT(plane->id)))
11003                         continue;
11004
11005                 for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, linked) {
11006                         if (!icl_is_nv12_y_plane(linked->id))
11007                                 continue;
11008
11009                         if (crtc_state->active_planes & BIT(linked->id))
11010                                 continue;
11011
11012                         linked_state = intel_atomic_get_plane_state(state, linked);
11013                         if (IS_ERR(linked_state))
11014                                 return PTR_ERR(linked_state);
11015
11016                         break;
11017                 }
11018
11019                 if (!linked_state) {
11020                         DRM_DEBUG_KMS("Need %d free Y planes for NV12\n",
11021                                       hweight8(crtc_state->nv12_planes));
11022
11023                         return -EINVAL;
11024                 }
11025
11026                 plane_state->linked_plane = linked;
11027
11028                 linked_state->slave = true;
11029                 linked_state->linked_plane = plane;
11030                 crtc_state->active_planes |= BIT(linked->id);
11031                 crtc_state->update_planes |= BIT(linked->id);
11032                 DRM_DEBUG_KMS("Using %s as Y plane for %s\n", linked->base.name, plane->base.name);
11033         }
11034
11035         return 0;
11036 }
11037
11038 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
11039                                    struct drm_crtc_state *crtc_state)
11040 {
11041         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11042         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11043         struct intel_crtc_state *pipe_config =
11044                 to_intel_crtc_state(crtc_state);
11045         int ret;
11046         bool mode_changed = needs_modeset(crtc_state);
11047
11048         if (mode_changed && !crtc_state->active)
11049                 pipe_config->update_wm_post = true;
11050
11051         if (mode_changed && crtc_state->enable &&
11052             dev_priv->display.crtc_compute_clock &&
11053             !WARN_ON(pipe_config->shared_dpll)) {
11054                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
11055                                                            pipe_config);
11056                 if (ret)
11057                         return ret;
11058         }
11059
11060         if (crtc_state->color_mgmt_changed) {
11061                 ret = intel_color_check(pipe_config);
11062                 if (ret)
11063                         return ret;
11064
11065                 /*
11066                  * Changing color management on Intel hardware is
11067                  * handled as part of planes update.
11068                  */
11069                 crtc_state->planes_changed = true;
11070         }
11071
11072         ret = 0;
11073         if (dev_priv->display.compute_pipe_wm) {
11074                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
11075                 if (ret) {
11076                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
11077                         return ret;
11078                 }
11079         }
11080
11081         if (dev_priv->display.compute_intermediate_wm) {
11082                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
11083                         return 0;
11084
11085                 /*
11086                  * Calculate 'intermediate' watermarks that satisfy both the
11087                  * old state and the new state.  We can program these
11088                  * immediately.
11089                  */
11090                 ret = dev_priv->display.compute_intermediate_wm(pipe_config);
11091                 if (ret) {
11092                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
11093                         return ret;
11094                 }
11095         }
11096
11097         if (INTEL_GEN(dev_priv) >= 9) {
11098                 if (mode_changed || pipe_config->update_pipe)
11099                         ret = skl_update_scaler_crtc(pipe_config);
11100
11101                 if (!ret)
11102                         ret = icl_check_nv12_planes(pipe_config);
11103                 if (!ret)
11104                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
11105                                                             pipe_config);
11106                 if (!ret)
11107                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
11108                                                          pipe_config);
11109         }
11110
11111         if (HAS_IPS(dev_priv))
11112                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
11113
11114         return ret;
11115 }
11116
11117 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
11118         .atomic_check = intel_crtc_atomic_check,
11119 };
11120
11121 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
11122 {
11123         struct intel_connector *connector;
11124         struct drm_connector_list_iter conn_iter;
11125
11126         drm_connector_list_iter_begin(dev, &conn_iter);
11127         for_each_intel_connector_iter(connector, &conn_iter) {
11128                 if (connector->base.state->crtc)
11129                         drm_connector_put(&connector->base);
11130
11131                 if (connector->base.encoder) {
11132                         connector->base.state->best_encoder =
11133                                 connector->base.encoder;
11134                         connector->base.state->crtc =
11135                                 connector->base.encoder->crtc;
11136
11137                         drm_connector_get(&connector->base);
11138                 } else {
11139                         connector->base.state->best_encoder = NULL;
11140                         connector->base.state->crtc = NULL;
11141                 }
11142         }
11143         drm_connector_list_iter_end(&conn_iter);
11144 }
11145
11146 static int
11147 compute_sink_pipe_bpp(const struct drm_connector_state *conn_state,
11148                       struct intel_crtc_state *pipe_config)
11149 {
11150         struct drm_connector *connector = conn_state->connector;
11151         const struct drm_display_info *info = &connector->display_info;
11152         int bpp;
11153
11154         switch (conn_state->max_bpc) {
11155         case 6 ... 7:
11156                 bpp = 6 * 3;
11157                 break;
11158         case 8 ... 9:
11159                 bpp = 8 * 3;
11160                 break;
11161         case 10 ... 11:
11162                 bpp = 10 * 3;
11163                 break;
11164         case 12:
11165                 bpp = 12 * 3;
11166                 break;
11167         default:
11168                 return -EINVAL;
11169         }
11170
11171         if (bpp < pipe_config->pipe_bpp) {
11172                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] Limiting display bpp to %d instead of "
11173                               "EDID bpp %d, requested bpp %d, max platform bpp %d\n",
11174                               connector->base.id, connector->name,
11175                               bpp, 3 * info->bpc, 3 * conn_state->max_requested_bpc,
11176                               pipe_config->pipe_bpp);
11177
11178                 pipe_config->pipe_bpp = bpp;
11179         }
11180
11181         return 0;
11182 }
11183
11184 static int
11185 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
11186                           struct intel_crtc_state *pipe_config)
11187 {
11188         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11189         struct drm_atomic_state *state = pipe_config->base.state;
11190         struct drm_connector *connector;
11191         struct drm_connector_state *connector_state;
11192         int bpp, i;
11193
11194         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
11195             IS_CHERRYVIEW(dev_priv)))
11196                 bpp = 10*3;
11197         else if (INTEL_GEN(dev_priv) >= 5)
11198                 bpp = 12*3;
11199         else
11200                 bpp = 8*3;
11201
11202         pipe_config->pipe_bpp = bpp;
11203
11204         /* Clamp display bpp to connector max bpp */
11205         for_each_new_connector_in_state(state, connector, connector_state, i) {
11206                 int ret;
11207
11208                 if (connector_state->crtc != &crtc->base)
11209                         continue;
11210
11211                 ret = compute_sink_pipe_bpp(connector_state, pipe_config);
11212                 if (ret)
11213                         return ret;
11214         }
11215
11216         return 0;
11217 }
11218
11219 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
11220 {
11221         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
11222                         "type: 0x%x flags: 0x%x\n",
11223                 mode->crtc_clock,
11224                 mode->crtc_hdisplay, mode->crtc_hsync_start,
11225                 mode->crtc_hsync_end, mode->crtc_htotal,
11226                 mode->crtc_vdisplay, mode->crtc_vsync_start,
11227                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
11228 }
11229
11230 static inline void
11231 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
11232                       unsigned int lane_count, struct intel_link_m_n *m_n)
11233 {
11234         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
11235                       id, lane_count,
11236                       m_n->gmch_m, m_n->gmch_n,
11237                       m_n->link_m, m_n->link_n, m_n->tu);
11238 }
11239
11240 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
11241
11242 static const char * const output_type_str[] = {
11243         OUTPUT_TYPE(UNUSED),
11244         OUTPUT_TYPE(ANALOG),
11245         OUTPUT_TYPE(DVO),
11246         OUTPUT_TYPE(SDVO),
11247         OUTPUT_TYPE(LVDS),
11248         OUTPUT_TYPE(TVOUT),
11249         OUTPUT_TYPE(HDMI),
11250         OUTPUT_TYPE(DP),
11251         OUTPUT_TYPE(EDP),
11252         OUTPUT_TYPE(DSI),
11253         OUTPUT_TYPE(DDI),
11254         OUTPUT_TYPE(DP_MST),
11255 };
11256
11257 #undef OUTPUT_TYPE
11258
11259 static void snprintf_output_types(char *buf, size_t len,
11260                                   unsigned int output_types)
11261 {
11262         char *str = buf;
11263         int i;
11264
11265         str[0] = '\0';
11266
11267         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
11268                 int r;
11269
11270                 if ((output_types & BIT(i)) == 0)
11271                         continue;
11272
11273                 r = snprintf(str, len, "%s%s",
11274                              str != buf ? "," : "", output_type_str[i]);
11275                 if (r >= len)
11276                         break;
11277                 str += r;
11278                 len -= r;
11279
11280                 output_types &= ~BIT(i);
11281         }
11282
11283         WARN_ON_ONCE(output_types != 0);
11284 }
11285
11286 static const char * const output_format_str[] = {
11287         [INTEL_OUTPUT_FORMAT_INVALID] = "Invalid",
11288         [INTEL_OUTPUT_FORMAT_RGB] = "RGB",
11289         [INTEL_OUTPUT_FORMAT_YCBCR420] = "YCBCR4:2:0",
11290         [INTEL_OUTPUT_FORMAT_YCBCR444] = "YCBCR4:4:4",
11291 };
11292
11293 static const char *output_formats(enum intel_output_format format)
11294 {
11295         if (format >= ARRAY_SIZE(output_format_str))
11296                 format = INTEL_OUTPUT_FORMAT_INVALID;
11297         return output_format_str[format];
11298 }
11299
11300 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11301                                    struct intel_crtc_state *pipe_config,
11302                                    const char *context)
11303 {
11304         struct drm_device *dev = crtc->base.dev;
11305         struct drm_i915_private *dev_priv = to_i915(dev);
11306         struct drm_plane *plane;
11307         struct intel_plane *intel_plane;
11308         struct intel_plane_state *state;
11309         struct drm_framebuffer *fb;
11310         char buf[64];
11311
11312         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
11313                       crtc->base.base.id, crtc->base.name, context);
11314
11315         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
11316         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
11317                       buf, pipe_config->output_types);
11318
11319         DRM_DEBUG_KMS("output format: %s\n",
11320                       output_formats(pipe_config->output_format));
11321
11322         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
11323                       transcoder_name(pipe_config->cpu_transcoder),
11324                       pipe_config->pipe_bpp, pipe_config->dither);
11325
11326         if (pipe_config->has_pch_encoder)
11327                 intel_dump_m_n_config(pipe_config, "fdi",
11328                                       pipe_config->fdi_lanes,
11329                                       &pipe_config->fdi_m_n);
11330
11331         if (intel_crtc_has_dp_encoder(pipe_config)) {
11332                 intel_dump_m_n_config(pipe_config, "dp m_n",
11333                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11334                 if (pipe_config->has_drrs)
11335                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11336                                               pipe_config->lane_count,
11337                                               &pipe_config->dp_m2_n2);
11338         }
11339
11340         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11341                       pipe_config->has_audio, pipe_config->has_infoframe);
11342
11343         DRM_DEBUG_KMS("requested mode:\n");
11344         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11345         DRM_DEBUG_KMS("adjusted mode:\n");
11346         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11347         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11348         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11349                       pipe_config->port_clock,
11350                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11351                       pipe_config->pixel_rate);
11352
11353         if (INTEL_GEN(dev_priv) >= 9)
11354                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11355                               crtc->num_scalers,
11356                               pipe_config->scaler_state.scaler_users,
11357                               pipe_config->scaler_state.scaler_id);
11358
11359         if (HAS_GMCH_DISPLAY(dev_priv))
11360                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11361                               pipe_config->gmch_pfit.control,
11362                               pipe_config->gmch_pfit.pgm_ratios,
11363                               pipe_config->gmch_pfit.lvds_border_bits);
11364         else
11365                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11366                               pipe_config->pch_pfit.pos,
11367                               pipe_config->pch_pfit.size,
11368                               enableddisabled(pipe_config->pch_pfit.enabled));
11369
11370         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11371                       pipe_config->ips_enabled, pipe_config->double_wide);
11372
11373         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11374
11375         DRM_DEBUG_KMS("planes on this crtc\n");
11376         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11377                 struct drm_format_name_buf format_name;
11378                 intel_plane = to_intel_plane(plane);
11379                 if (intel_plane->pipe != crtc->pipe)
11380                         continue;
11381
11382                 state = to_intel_plane_state(plane->state);
11383                 fb = state->base.fb;
11384                 if (!fb) {
11385                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11386                                       plane->base.id, plane->name, state->scaler_id);
11387                         continue;
11388                 }
11389
11390                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11391                               plane->base.id, plane->name,
11392                               fb->base.id, fb->width, fb->height,
11393                               drm_get_format_name(fb->format->format, &format_name));
11394                 if (INTEL_GEN(dev_priv) >= 9)
11395                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11396                                       state->scaler_id,
11397                                       state->base.src.x1 >> 16,
11398                                       state->base.src.y1 >> 16,
11399                                       drm_rect_width(&state->base.src) >> 16,
11400                                       drm_rect_height(&state->base.src) >> 16,
11401                                       state->base.dst.x1, state->base.dst.y1,
11402                                       drm_rect_width(&state->base.dst),
11403                                       drm_rect_height(&state->base.dst));
11404         }
11405 }
11406
11407 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11408 {
11409         struct drm_device *dev = state->dev;
11410         struct drm_connector *connector;
11411         struct drm_connector_list_iter conn_iter;
11412         unsigned int used_ports = 0;
11413         unsigned int used_mst_ports = 0;
11414         bool ret = true;
11415
11416         /*
11417          * Walk the connector list instead of the encoder
11418          * list to detect the problem on ddi platforms
11419          * where there's just one encoder per digital port.
11420          */
11421         drm_connector_list_iter_begin(dev, &conn_iter);
11422         drm_for_each_connector_iter(connector, &conn_iter) {
11423                 struct drm_connector_state *connector_state;
11424                 struct intel_encoder *encoder;
11425
11426                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11427                 if (!connector_state)
11428                         connector_state = connector->state;
11429
11430                 if (!connector_state->best_encoder)
11431                         continue;
11432
11433                 encoder = to_intel_encoder(connector_state->best_encoder);
11434
11435                 WARN_ON(!connector_state->crtc);
11436
11437                 switch (encoder->type) {
11438                         unsigned int port_mask;
11439                 case INTEL_OUTPUT_DDI:
11440                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11441                                 break;
11442                         /* else: fall through */
11443                 case INTEL_OUTPUT_DP:
11444                 case INTEL_OUTPUT_HDMI:
11445                 case INTEL_OUTPUT_EDP:
11446                         port_mask = 1 << encoder->port;
11447
11448                         /* the same port mustn't appear more than once */
11449                         if (used_ports & port_mask)
11450                                 ret = false;
11451
11452                         used_ports |= port_mask;
11453                         break;
11454                 case INTEL_OUTPUT_DP_MST:
11455                         used_mst_ports |=
11456                                 1 << encoder->port;
11457                         break;
11458                 default:
11459                         break;
11460                 }
11461         }
11462         drm_connector_list_iter_end(&conn_iter);
11463
11464         /* can't mix MST and SST/HDMI on the same port */
11465         if (used_ports & used_mst_ports)
11466                 return false;
11467
11468         return ret;
11469 }
11470
11471 static void
11472 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11473 {
11474         struct drm_i915_private *dev_priv =
11475                 to_i915(crtc_state->base.crtc->dev);
11476         struct intel_crtc_scaler_state scaler_state;
11477         struct intel_dpll_hw_state dpll_hw_state;
11478         struct intel_shared_dpll *shared_dpll;
11479         struct intel_crtc_wm_state wm_state;
11480         bool force_thru, ips_force_disable;
11481
11482         /* FIXME: before the switch to atomic started, a new pipe_config was
11483          * kzalloc'd. Code that depends on any field being zero should be
11484          * fixed, so that the crtc_state can be safely duplicated. For now,
11485          * only fields that are know to not cause problems are preserved. */
11486
11487         scaler_state = crtc_state->scaler_state;
11488         shared_dpll = crtc_state->shared_dpll;
11489         dpll_hw_state = crtc_state->dpll_hw_state;
11490         force_thru = crtc_state->pch_pfit.force_thru;
11491         ips_force_disable = crtc_state->ips_force_disable;
11492         if (IS_G4X(dev_priv) ||
11493             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11494                 wm_state = crtc_state->wm;
11495
11496         /* Keep base drm_crtc_state intact, only clear our extended struct */
11497         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11498         memset(&crtc_state->base + 1, 0,
11499                sizeof(*crtc_state) - sizeof(crtc_state->base));
11500
11501         crtc_state->scaler_state = scaler_state;
11502         crtc_state->shared_dpll = shared_dpll;
11503         crtc_state->dpll_hw_state = dpll_hw_state;
11504         crtc_state->pch_pfit.force_thru = force_thru;
11505         crtc_state->ips_force_disable = ips_force_disable;
11506         if (IS_G4X(dev_priv) ||
11507             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11508                 crtc_state->wm = wm_state;
11509 }
11510
11511 static int
11512 intel_modeset_pipe_config(struct drm_crtc *crtc,
11513                           struct intel_crtc_state *pipe_config)
11514 {
11515         struct drm_atomic_state *state = pipe_config->base.state;
11516         struct intel_encoder *encoder;
11517         struct drm_connector *connector;
11518         struct drm_connector_state *connector_state;
11519         int base_bpp, ret;
11520         int i;
11521         bool retry = true;
11522
11523         clear_intel_crtc_state(pipe_config);
11524
11525         pipe_config->cpu_transcoder =
11526                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11527
11528         /*
11529          * Sanitize sync polarity flags based on requested ones. If neither
11530          * positive or negative polarity is requested, treat this as meaning
11531          * negative polarity.
11532          */
11533         if (!(pipe_config->base.adjusted_mode.flags &
11534               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11535                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11536
11537         if (!(pipe_config->base.adjusted_mode.flags &
11538               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11539                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11540
11541         ret = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11542                                         pipe_config);
11543         if (ret)
11544                 return ret;
11545
11546         base_bpp = pipe_config->pipe_bpp;
11547
11548         /*
11549          * Determine the real pipe dimensions. Note that stereo modes can
11550          * increase the actual pipe size due to the frame doubling and
11551          * insertion of additional space for blanks between the frame. This
11552          * is stored in the crtc timings. We use the requested mode to do this
11553          * computation to clearly distinguish it from the adjusted mode, which
11554          * can be changed by the connectors in the below retry loop.
11555          */
11556         drm_mode_get_hv_timing(&pipe_config->base.mode,
11557                                &pipe_config->pipe_src_w,
11558                                &pipe_config->pipe_src_h);
11559
11560         for_each_new_connector_in_state(state, connector, connector_state, i) {
11561                 if (connector_state->crtc != crtc)
11562                         continue;
11563
11564                 encoder = to_intel_encoder(connector_state->best_encoder);
11565
11566                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11567                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11568                         return -EINVAL;
11569                 }
11570
11571                 /*
11572                  * Determine output_types before calling the .compute_config()
11573                  * hooks so that the hooks can use this information safely.
11574                  */
11575                 if (encoder->compute_output_type)
11576                         pipe_config->output_types |=
11577                                 BIT(encoder->compute_output_type(encoder, pipe_config,
11578                                                                  connector_state));
11579                 else
11580                         pipe_config->output_types |= BIT(encoder->type);
11581         }
11582
11583 encoder_retry:
11584         /* Ensure the port clock defaults are reset when retrying. */
11585         pipe_config->port_clock = 0;
11586         pipe_config->pixel_multiplier = 1;
11587
11588         /* Fill in default crtc timings, allow encoders to overwrite them. */
11589         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11590                               CRTC_STEREO_DOUBLE);
11591
11592         /* Pass our mode to the connectors and the CRTC to give them a chance to
11593          * adjust it according to limitations or connector properties, and also
11594          * a chance to reject the mode entirely.
11595          */
11596         for_each_new_connector_in_state(state, connector, connector_state, i) {
11597                 if (connector_state->crtc != crtc)
11598                         continue;
11599
11600                 encoder = to_intel_encoder(connector_state->best_encoder);
11601                 ret = encoder->compute_config(encoder, pipe_config,
11602                                               connector_state);
11603                 if (ret < 0) {
11604                         if (ret != -EDEADLK)
11605                                 DRM_DEBUG_KMS("Encoder config failure: %d\n",
11606                                               ret);
11607                         return ret;
11608                 }
11609         }
11610
11611         /* Set default port clock if not overwritten by the encoder. Needs to be
11612          * done afterwards in case the encoder adjusts the mode. */
11613         if (!pipe_config->port_clock)
11614                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11615                         * pipe_config->pixel_multiplier;
11616
11617         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11618         if (ret == -EDEADLK)
11619                 return ret;
11620         if (ret < 0) {
11621                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11622                 return ret;
11623         }
11624
11625         if (ret == RETRY) {
11626                 if (WARN(!retry, "loop in pipe configuration computation\n"))
11627                         return -EINVAL;
11628
11629                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11630                 retry = false;
11631                 goto encoder_retry;
11632         }
11633
11634         /* Dithering seems to not pass-through bits correctly when it should, so
11635          * only enable it on 6bpc panels and when its not a compliance
11636          * test requesting 6bpc video pattern.
11637          */
11638         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11639                 !pipe_config->dither_force_disable;
11640         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11641                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11642
11643         return 0;
11644 }
11645
11646 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11647 {
11648         int diff;
11649
11650         if (clock1 == clock2)
11651                 return true;
11652
11653         if (!clock1 || !clock2)
11654                 return false;
11655
11656         diff = abs(clock1 - clock2);
11657
11658         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11659                 return true;
11660
11661         return false;
11662 }
11663
11664 static bool
11665 intel_compare_m_n(unsigned int m, unsigned int n,
11666                   unsigned int m2, unsigned int n2,
11667                   bool exact)
11668 {
11669         if (m == m2 && n == n2)
11670                 return true;
11671
11672         if (exact || !m || !n || !m2 || !n2)
11673                 return false;
11674
11675         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11676
11677         if (n > n2) {
11678                 while (n > n2) {
11679                         m2 <<= 1;
11680                         n2 <<= 1;
11681                 }
11682         } else if (n < n2) {
11683                 while (n < n2) {
11684                         m <<= 1;
11685                         n <<= 1;
11686                 }
11687         }
11688
11689         if (n != n2)
11690                 return false;
11691
11692         return intel_fuzzy_clock_check(m, m2);
11693 }
11694
11695 static bool
11696 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11697                        struct intel_link_m_n *m2_n2,
11698                        bool adjust)
11699 {
11700         if (m_n->tu == m2_n2->tu &&
11701             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11702                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11703             intel_compare_m_n(m_n->link_m, m_n->link_n,
11704                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11705                 if (adjust)
11706                         *m2_n2 = *m_n;
11707
11708                 return true;
11709         }
11710
11711         return false;
11712 }
11713
11714 static void __printf(3, 4)
11715 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11716 {
11717         struct va_format vaf;
11718         va_list args;
11719
11720         va_start(args, format);
11721         vaf.fmt = format;
11722         vaf.va = &args;
11723
11724         if (adjust)
11725                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11726         else
11727                 drm_err("mismatch in %s %pV", name, &vaf);
11728
11729         va_end(args);
11730 }
11731
11732 static bool fastboot_enabled(struct drm_i915_private *dev_priv)
11733 {
11734         if (i915_modparams.fastboot != -1)
11735                 return i915_modparams.fastboot;
11736
11737         /* Enable fastboot by default on Skylake and newer */
11738         return INTEL_GEN(dev_priv) >= 9;
11739 }
11740
11741 static bool
11742 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11743                           struct intel_crtc_state *current_config,
11744                           struct intel_crtc_state *pipe_config,
11745                           bool adjust)
11746 {
11747         bool ret = true;
11748         bool fixup_inherited = adjust &&
11749                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11750                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11751
11752         if (fixup_inherited && !fastboot_enabled(dev_priv)) {
11753                 DRM_DEBUG_KMS("initial modeset and fastboot not set\n");
11754                 ret = false;
11755         }
11756
11757 #define PIPE_CONF_CHECK_X(name) do { \
11758         if (current_config->name != pipe_config->name) { \
11759                 pipe_config_err(adjust, __stringify(name), \
11760                           "(expected 0x%08x, found 0x%08x)\n", \
11761                           current_config->name, \
11762                           pipe_config->name); \
11763                 ret = false; \
11764         } \
11765 } while (0)
11766
11767 #define PIPE_CONF_CHECK_I(name) do { \
11768         if (current_config->name != pipe_config->name) { \
11769                 pipe_config_err(adjust, __stringify(name), \
11770                           "(expected %i, found %i)\n", \
11771                           current_config->name, \
11772                           pipe_config->name); \
11773                 ret = false; \
11774         } \
11775 } while (0)
11776
11777 #define PIPE_CONF_CHECK_BOOL(name) do { \
11778         if (current_config->name != pipe_config->name) { \
11779                 pipe_config_err(adjust, __stringify(name), \
11780                           "(expected %s, found %s)\n", \
11781                           yesno(current_config->name), \
11782                           yesno(pipe_config->name)); \
11783                 ret = false; \
11784         } \
11785 } while (0)
11786
11787 /*
11788  * Checks state where we only read out the enabling, but not the entire
11789  * state itself (like full infoframes or ELD for audio). These states
11790  * require a full modeset on bootup to fix up.
11791  */
11792 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
11793         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11794                 PIPE_CONF_CHECK_BOOL(name); \
11795         } else { \
11796                 pipe_config_err(adjust, __stringify(name), \
11797                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11798                           yesno(current_config->name), \
11799                           yesno(pipe_config->name)); \
11800                 ret = false; \
11801         } \
11802 } while (0)
11803
11804 #define PIPE_CONF_CHECK_P(name) do { \
11805         if (current_config->name != pipe_config->name) { \
11806                 pipe_config_err(adjust, __stringify(name), \
11807                           "(expected %p, found %p)\n", \
11808                           current_config->name, \
11809                           pipe_config->name); \
11810                 ret = false; \
11811         } \
11812 } while (0)
11813
11814 #define PIPE_CONF_CHECK_M_N(name) do { \
11815         if (!intel_compare_link_m_n(&current_config->name, \
11816                                     &pipe_config->name,\
11817                                     adjust)) { \
11818                 pipe_config_err(adjust, __stringify(name), \
11819                           "(expected tu %i gmch %i/%i link %i/%i, " \
11820                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11821                           current_config->name.tu, \
11822                           current_config->name.gmch_m, \
11823                           current_config->name.gmch_n, \
11824                           current_config->name.link_m, \
11825                           current_config->name.link_n, \
11826                           pipe_config->name.tu, \
11827                           pipe_config->name.gmch_m, \
11828                           pipe_config->name.gmch_n, \
11829                           pipe_config->name.link_m, \
11830                           pipe_config->name.link_n); \
11831                 ret = false; \
11832         } \
11833 } while (0)
11834
11835 /* This is required for BDW+ where there is only one set of registers for
11836  * switching between high and low RR.
11837  * This macro can be used whenever a comparison has to be made between one
11838  * hw state and multiple sw state variables.
11839  */
11840 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
11841         if (!intel_compare_link_m_n(&current_config->name, \
11842                                     &pipe_config->name, adjust) && \
11843             !intel_compare_link_m_n(&current_config->alt_name, \
11844                                     &pipe_config->name, adjust)) { \
11845                 pipe_config_err(adjust, __stringify(name), \
11846                           "(expected tu %i gmch %i/%i link %i/%i, " \
11847                           "or tu %i gmch %i/%i link %i/%i, " \
11848                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11849                           current_config->name.tu, \
11850                           current_config->name.gmch_m, \
11851                           current_config->name.gmch_n, \
11852                           current_config->name.link_m, \
11853                           current_config->name.link_n, \
11854                           current_config->alt_name.tu, \
11855                           current_config->alt_name.gmch_m, \
11856                           current_config->alt_name.gmch_n, \
11857                           current_config->alt_name.link_m, \
11858                           current_config->alt_name.link_n, \
11859                           pipe_config->name.tu, \
11860                           pipe_config->name.gmch_m, \
11861                           pipe_config->name.gmch_n, \
11862                           pipe_config->name.link_m, \
11863                           pipe_config->name.link_n); \
11864                 ret = false; \
11865         } \
11866 } while (0)
11867
11868 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
11869         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11870                 pipe_config_err(adjust, __stringify(name), \
11871                           "(%x) (expected %i, found %i)\n", \
11872                           (mask), \
11873                           current_config->name & (mask), \
11874                           pipe_config->name & (mask)); \
11875                 ret = false; \
11876         } \
11877 } while (0)
11878
11879 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
11880         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11881                 pipe_config_err(adjust, __stringify(name), \
11882                           "(expected %i, found %i)\n", \
11883                           current_config->name, \
11884                           pipe_config->name); \
11885                 ret = false; \
11886         } \
11887 } while (0)
11888
11889 #define PIPE_CONF_QUIRK(quirk)  \
11890         ((current_config->quirks | pipe_config->quirks) & (quirk))
11891
11892         PIPE_CONF_CHECK_I(cpu_transcoder);
11893
11894         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11895         PIPE_CONF_CHECK_I(fdi_lanes);
11896         PIPE_CONF_CHECK_M_N(fdi_m_n);
11897
11898         PIPE_CONF_CHECK_I(lane_count);
11899         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11900
11901         if (INTEL_GEN(dev_priv) < 8) {
11902                 PIPE_CONF_CHECK_M_N(dp_m_n);
11903
11904                 if (current_config->has_drrs)
11905                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11906         } else
11907                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11908
11909         PIPE_CONF_CHECK_X(output_types);
11910
11911         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11912         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11913         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11914         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11915         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11916         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11917
11918         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11919         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11920         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11921         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11922         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11923         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11924
11925         PIPE_CONF_CHECK_I(pixel_multiplier);
11926         PIPE_CONF_CHECK_I(output_format);
11927         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11928         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11929             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11930                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11931
11932         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11933         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11934         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11935
11936         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11937
11938         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11939                               DRM_MODE_FLAG_INTERLACE);
11940
11941         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11942                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11943                                       DRM_MODE_FLAG_PHSYNC);
11944                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11945                                       DRM_MODE_FLAG_NHSYNC);
11946                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11947                                       DRM_MODE_FLAG_PVSYNC);
11948                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11949                                       DRM_MODE_FLAG_NVSYNC);
11950         }
11951
11952         PIPE_CONF_CHECK_X(gmch_pfit.control);
11953         /* pfit ratios are autocomputed by the hw on gen4+ */
11954         if (INTEL_GEN(dev_priv) < 4)
11955                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11956         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11957
11958         if (!adjust) {
11959                 PIPE_CONF_CHECK_I(pipe_src_w);
11960                 PIPE_CONF_CHECK_I(pipe_src_h);
11961
11962                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11963                 if (current_config->pch_pfit.enabled) {
11964                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11965                         PIPE_CONF_CHECK_X(pch_pfit.size);
11966                 }
11967
11968                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11969                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11970         }
11971
11972         PIPE_CONF_CHECK_BOOL(double_wide);
11973
11974         PIPE_CONF_CHECK_P(shared_dpll);
11975         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11976         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11977         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11978         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11979         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11980         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11981         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11982         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11983         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11984         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11985         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11986         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11987         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11988         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11989         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11990         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11991         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11992         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11993         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11994         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11995         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11996         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
11997         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
11998         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
11999         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
12000         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
12001         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
12002         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
12003         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
12004         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
12005         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
12006
12007         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
12008         PIPE_CONF_CHECK_X(dsi_pll.div);
12009
12010         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
12011                 PIPE_CONF_CHECK_I(pipe_bpp);
12012
12013         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
12014         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
12015
12016         PIPE_CONF_CHECK_I(min_voltage_level);
12017
12018 #undef PIPE_CONF_CHECK_X
12019 #undef PIPE_CONF_CHECK_I
12020 #undef PIPE_CONF_CHECK_BOOL
12021 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
12022 #undef PIPE_CONF_CHECK_P
12023 #undef PIPE_CONF_CHECK_FLAGS
12024 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
12025 #undef PIPE_CONF_QUIRK
12026
12027         return ret;
12028 }
12029
12030 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
12031                                            const struct intel_crtc_state *pipe_config)
12032 {
12033         if (pipe_config->has_pch_encoder) {
12034                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
12035                                                             &pipe_config->fdi_m_n);
12036                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
12037
12038                 /*
12039                  * FDI already provided one idea for the dotclock.
12040                  * Yell if the encoder disagrees.
12041                  */
12042                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
12043                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
12044                      fdi_dotclock, dotclock);
12045         }
12046 }
12047
12048 static void verify_wm_state(struct drm_crtc *crtc,
12049                             struct drm_crtc_state *new_state)
12050 {
12051         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12052         struct skl_ddb_allocation hw_ddb, *sw_ddb;
12053         struct skl_pipe_wm hw_wm, *sw_wm;
12054         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
12055         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
12056         struct skl_ddb_entry hw_ddb_y[I915_MAX_PLANES];
12057         struct skl_ddb_entry hw_ddb_uv[I915_MAX_PLANES];
12058         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12059         const enum pipe pipe = intel_crtc->pipe;
12060         int plane, level, max_level = ilk_wm_max_level(dev_priv);
12061
12062         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
12063                 return;
12064
12065         skl_pipe_wm_get_hw_state(intel_crtc, &hw_wm);
12066         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
12067
12068         skl_pipe_ddb_get_hw_state(intel_crtc, hw_ddb_y, hw_ddb_uv);
12069
12070         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
12071         sw_ddb = &dev_priv->wm.skl_hw.ddb;
12072
12073         if (INTEL_GEN(dev_priv) >= 11)
12074                 if (hw_ddb.enabled_slices != sw_ddb->enabled_slices)
12075                         DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
12076                                   sw_ddb->enabled_slices,
12077                                   hw_ddb.enabled_slices);
12078         /* planes */
12079         for_each_universal_plane(dev_priv, pipe, plane) {
12080                 hw_plane_wm = &hw_wm.planes[plane];
12081                 sw_plane_wm = &sw_wm->planes[plane];
12082
12083                 /* Watermarks */
12084                 for (level = 0; level <= max_level; level++) {
12085                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12086                                                 &sw_plane_wm->wm[level]))
12087                                 continue;
12088
12089                         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",
12090                                   pipe_name(pipe), plane + 1, level,
12091                                   sw_plane_wm->wm[level].plane_en,
12092                                   sw_plane_wm->wm[level].plane_res_b,
12093                                   sw_plane_wm->wm[level].plane_res_l,
12094                                   hw_plane_wm->wm[level].plane_en,
12095                                   hw_plane_wm->wm[level].plane_res_b,
12096                                   hw_plane_wm->wm[level].plane_res_l);
12097                 }
12098
12099                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12100                                          &sw_plane_wm->trans_wm)) {
12101                         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",
12102                                   pipe_name(pipe), plane + 1,
12103                                   sw_plane_wm->trans_wm.plane_en,
12104                                   sw_plane_wm->trans_wm.plane_res_b,
12105                                   sw_plane_wm->trans_wm.plane_res_l,
12106                                   hw_plane_wm->trans_wm.plane_en,
12107                                   hw_plane_wm->trans_wm.plane_res_b,
12108                                   hw_plane_wm->trans_wm.plane_res_l);
12109                 }
12110
12111                 /* DDB */
12112                 hw_ddb_entry = &hw_ddb_y[plane];
12113                 sw_ddb_entry = &to_intel_crtc_state(new_state)->wm.skl.plane_ddb_y[plane];
12114
12115                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12116                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
12117                                   pipe_name(pipe), plane + 1,
12118                                   sw_ddb_entry->start, sw_ddb_entry->end,
12119                                   hw_ddb_entry->start, hw_ddb_entry->end);
12120                 }
12121         }
12122
12123         /*
12124          * cursor
12125          * If the cursor plane isn't active, we may not have updated it's ddb
12126          * allocation. In that case since the ddb allocation will be updated
12127          * once the plane becomes visible, we can skip this check
12128          */
12129         if (1) {
12130                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
12131                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
12132
12133                 /* Watermarks */
12134                 for (level = 0; level <= max_level; level++) {
12135                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
12136                                                 &sw_plane_wm->wm[level]))
12137                                 continue;
12138
12139                         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",
12140                                   pipe_name(pipe), level,
12141                                   sw_plane_wm->wm[level].plane_en,
12142                                   sw_plane_wm->wm[level].plane_res_b,
12143                                   sw_plane_wm->wm[level].plane_res_l,
12144                                   hw_plane_wm->wm[level].plane_en,
12145                                   hw_plane_wm->wm[level].plane_res_b,
12146                                   hw_plane_wm->wm[level].plane_res_l);
12147                 }
12148
12149                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
12150                                          &sw_plane_wm->trans_wm)) {
12151                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
12152                                   pipe_name(pipe),
12153                                   sw_plane_wm->trans_wm.plane_en,
12154                                   sw_plane_wm->trans_wm.plane_res_b,
12155                                   sw_plane_wm->trans_wm.plane_res_l,
12156                                   hw_plane_wm->trans_wm.plane_en,
12157                                   hw_plane_wm->trans_wm.plane_res_b,
12158                                   hw_plane_wm->trans_wm.plane_res_l);
12159                 }
12160
12161                 /* DDB */
12162                 hw_ddb_entry = &hw_ddb_y[PLANE_CURSOR];
12163                 sw_ddb_entry = &to_intel_crtc_state(new_state)->wm.skl.plane_ddb_y[PLANE_CURSOR];
12164
12165                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
12166                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
12167                                   pipe_name(pipe),
12168                                   sw_ddb_entry->start, sw_ddb_entry->end,
12169                                   hw_ddb_entry->start, hw_ddb_entry->end);
12170                 }
12171         }
12172 }
12173
12174 static void
12175 verify_connector_state(struct drm_device *dev,
12176                        struct drm_atomic_state *state,
12177                        struct drm_crtc *crtc)
12178 {
12179         struct drm_connector *connector;
12180         struct drm_connector_state *new_conn_state;
12181         int i;
12182
12183         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
12184                 struct drm_encoder *encoder = connector->encoder;
12185                 struct drm_crtc_state *crtc_state = NULL;
12186
12187                 if (new_conn_state->crtc != crtc)
12188                         continue;
12189
12190                 if (crtc)
12191                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
12192
12193                 intel_connector_verify_state(crtc_state, new_conn_state);
12194
12195                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
12196                      "connector's atomic encoder doesn't match legacy encoder\n");
12197         }
12198 }
12199
12200 static void
12201 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
12202 {
12203         struct intel_encoder *encoder;
12204         struct drm_connector *connector;
12205         struct drm_connector_state *old_conn_state, *new_conn_state;
12206         int i;
12207
12208         for_each_intel_encoder(dev, encoder) {
12209                 bool enabled = false, found = false;
12210                 enum pipe pipe;
12211
12212                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
12213                               encoder->base.base.id,
12214                               encoder->base.name);
12215
12216                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
12217                                                    new_conn_state, i) {
12218                         if (old_conn_state->best_encoder == &encoder->base)
12219                                 found = true;
12220
12221                         if (new_conn_state->best_encoder != &encoder->base)
12222                                 continue;
12223                         found = enabled = true;
12224
12225                         I915_STATE_WARN(new_conn_state->crtc !=
12226                                         encoder->base.crtc,
12227                              "connector's crtc doesn't match encoder crtc\n");
12228                 }
12229
12230                 if (!found)
12231                         continue;
12232
12233                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
12234                      "encoder's enabled state mismatch "
12235                      "(expected %i, found %i)\n",
12236                      !!encoder->base.crtc, enabled);
12237
12238                 if (!encoder->base.crtc) {
12239                         bool active;
12240
12241                         active = encoder->get_hw_state(encoder, &pipe);
12242                         I915_STATE_WARN(active,
12243                              "encoder detached but still enabled on pipe %c.\n",
12244                              pipe_name(pipe));
12245                 }
12246         }
12247 }
12248
12249 static void
12250 verify_crtc_state(struct drm_crtc *crtc,
12251                   struct drm_crtc_state *old_crtc_state,
12252                   struct drm_crtc_state *new_crtc_state)
12253 {
12254         struct drm_device *dev = crtc->dev;
12255         struct drm_i915_private *dev_priv = to_i915(dev);
12256         struct intel_encoder *encoder;
12257         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12258         struct intel_crtc_state *pipe_config, *sw_config;
12259         struct drm_atomic_state *old_state;
12260         bool active;
12261
12262         old_state = old_crtc_state->state;
12263         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
12264         pipe_config = to_intel_crtc_state(old_crtc_state);
12265         memset(pipe_config, 0, sizeof(*pipe_config));
12266         pipe_config->base.crtc = crtc;
12267         pipe_config->base.state = old_state;
12268
12269         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
12270
12271         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
12272
12273         /* we keep both pipes enabled on 830 */
12274         if (IS_I830(dev_priv))
12275                 active = new_crtc_state->active;
12276
12277         I915_STATE_WARN(new_crtc_state->active != active,
12278              "crtc active state doesn't match with hw state "
12279              "(expected %i, found %i)\n", new_crtc_state->active, active);
12280
12281         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
12282              "transitional active state does not match atomic hw state "
12283              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
12284
12285         for_each_encoder_on_crtc(dev, crtc, encoder) {
12286                 enum pipe pipe;
12287
12288                 active = encoder->get_hw_state(encoder, &pipe);
12289                 I915_STATE_WARN(active != new_crtc_state->active,
12290                         "[ENCODER:%i] active %i with crtc active %i\n",
12291                         encoder->base.base.id, active, new_crtc_state->active);
12292
12293                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12294                                 "Encoder connected to wrong pipe %c\n",
12295                                 pipe_name(pipe));
12296
12297                 if (active)
12298                         encoder->get_config(encoder, pipe_config);
12299         }
12300
12301         intel_crtc_compute_pixel_rate(pipe_config);
12302
12303         if (!new_crtc_state->active)
12304                 return;
12305
12306         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12307
12308         sw_config = to_intel_crtc_state(new_crtc_state);
12309         if (!intel_pipe_config_compare(dev_priv, sw_config,
12310                                        pipe_config, false)) {
12311                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12312                 intel_dump_pipe_config(intel_crtc, pipe_config,
12313                                        "[hw state]");
12314                 intel_dump_pipe_config(intel_crtc, sw_config,
12315                                        "[sw state]");
12316         }
12317 }
12318
12319 static void
12320 intel_verify_planes(struct intel_atomic_state *state)
12321 {
12322         struct intel_plane *plane;
12323         const struct intel_plane_state *plane_state;
12324         int i;
12325
12326         for_each_new_intel_plane_in_state(state, plane,
12327                                           plane_state, i)
12328                 assert_plane(plane, plane_state->base.visible);
12329 }
12330
12331 static void
12332 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12333                          struct intel_shared_dpll *pll,
12334                          struct drm_crtc *crtc,
12335                          struct drm_crtc_state *new_state)
12336 {
12337         struct intel_dpll_hw_state dpll_hw_state;
12338         unsigned int crtc_mask;
12339         bool active;
12340
12341         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12342
12343         DRM_DEBUG_KMS("%s\n", pll->info->name);
12344
12345         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
12346
12347         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
12348                 I915_STATE_WARN(!pll->on && pll->active_mask,
12349                      "pll in active use but not on in sw tracking\n");
12350                 I915_STATE_WARN(pll->on && !pll->active_mask,
12351                      "pll is on but not used by any active crtc\n");
12352                 I915_STATE_WARN(pll->on != active,
12353                      "pll on state mismatch (expected %i, found %i)\n",
12354                      pll->on, active);
12355         }
12356
12357         if (!crtc) {
12358                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12359                                 "more active pll users than references: %x vs %x\n",
12360                                 pll->active_mask, pll->state.crtc_mask);
12361
12362                 return;
12363         }
12364
12365         crtc_mask = drm_crtc_mask(crtc);
12366
12367         if (new_state->active)
12368                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12369                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12370                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12371         else
12372                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12373                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12374                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12375
12376         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12377                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12378                         crtc_mask, pll->state.crtc_mask);
12379
12380         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12381                                           &dpll_hw_state,
12382                                           sizeof(dpll_hw_state)),
12383                         "pll hw state mismatch\n");
12384 }
12385
12386 static void
12387 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12388                          struct drm_crtc_state *old_crtc_state,
12389                          struct drm_crtc_state *new_crtc_state)
12390 {
12391         struct drm_i915_private *dev_priv = to_i915(dev);
12392         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12393         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12394
12395         if (new_state->shared_dpll)
12396                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12397
12398         if (old_state->shared_dpll &&
12399             old_state->shared_dpll != new_state->shared_dpll) {
12400                 unsigned int crtc_mask = drm_crtc_mask(crtc);
12401                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12402
12403                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12404                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12405                                 pipe_name(drm_crtc_index(crtc)));
12406                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12407                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12408                                 pipe_name(drm_crtc_index(crtc)));
12409         }
12410 }
12411
12412 static void
12413 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12414                           struct drm_atomic_state *state,
12415                           struct drm_crtc_state *old_state,
12416                           struct drm_crtc_state *new_state)
12417 {
12418         if (!needs_modeset(new_state) &&
12419             !to_intel_crtc_state(new_state)->update_pipe)
12420                 return;
12421
12422         verify_wm_state(crtc, new_state);
12423         verify_connector_state(crtc->dev, state, crtc);
12424         verify_crtc_state(crtc, old_state, new_state);
12425         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12426 }
12427
12428 static void
12429 verify_disabled_dpll_state(struct drm_device *dev)
12430 {
12431         struct drm_i915_private *dev_priv = to_i915(dev);
12432         int i;
12433
12434         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12435                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12436 }
12437
12438 static void
12439 intel_modeset_verify_disabled(struct drm_device *dev,
12440                               struct drm_atomic_state *state)
12441 {
12442         verify_encoder_state(dev, state);
12443         verify_connector_state(dev, state, NULL);
12444         verify_disabled_dpll_state(dev);
12445 }
12446
12447 static void update_scanline_offset(const struct intel_crtc_state *crtc_state)
12448 {
12449         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
12450         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12451
12452         /*
12453          * The scanline counter increments at the leading edge of hsync.
12454          *
12455          * On most platforms it starts counting from vtotal-1 on the
12456          * first active line. That means the scanline counter value is
12457          * always one less than what we would expect. Ie. just after
12458          * start of vblank, which also occurs at start of hsync (on the
12459          * last active line), the scanline counter will read vblank_start-1.
12460          *
12461          * On gen2 the scanline counter starts counting from 1 instead
12462          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12463          * to keep the value positive), instead of adding one.
12464          *
12465          * On HSW+ the behaviour of the scanline counter depends on the output
12466          * type. For DP ports it behaves like most other platforms, but on HDMI
12467          * there's an extra 1 line difference. So we need to add two instead of
12468          * one to the value.
12469          *
12470          * On VLV/CHV DSI the scanline counter would appear to increment
12471          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12472          * that means we can't tell whether we're in vblank or not while
12473          * we're on that particular line. We must still set scanline_offset
12474          * to 1 so that the vblank timestamps come out correct when we query
12475          * the scanline counter from within the vblank interrupt handler.
12476          * However if queried just before the start of vblank we'll get an
12477          * answer that's slightly in the future.
12478          */
12479         if (IS_GEN(dev_priv, 2)) {
12480                 const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
12481                 int vtotal;
12482
12483                 vtotal = adjusted_mode->crtc_vtotal;
12484                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12485                         vtotal /= 2;
12486
12487                 crtc->scanline_offset = vtotal - 1;
12488         } else if (HAS_DDI(dev_priv) &&
12489                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI)) {
12490                 crtc->scanline_offset = 2;
12491         } else
12492                 crtc->scanline_offset = 1;
12493 }
12494
12495 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12496 {
12497         struct drm_device *dev = state->dev;
12498         struct drm_i915_private *dev_priv = to_i915(dev);
12499         struct drm_crtc *crtc;
12500         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12501         int i;
12502
12503         if (!dev_priv->display.crtc_compute_clock)
12504                 return;
12505
12506         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12507                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12508                 struct intel_shared_dpll *old_dpll =
12509                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12510
12511                 if (!needs_modeset(new_crtc_state))
12512                         continue;
12513
12514                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12515
12516                 if (!old_dpll)
12517                         continue;
12518
12519                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12520         }
12521 }
12522
12523 /*
12524  * This implements the workaround described in the "notes" section of the mode
12525  * set sequence documentation. When going from no pipes or single pipe to
12526  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12527  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12528  */
12529 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12530 {
12531         struct drm_crtc_state *crtc_state;
12532         struct intel_crtc *intel_crtc;
12533         struct drm_crtc *crtc;
12534         struct intel_crtc_state *first_crtc_state = NULL;
12535         struct intel_crtc_state *other_crtc_state = NULL;
12536         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12537         int i;
12538
12539         /* look at all crtc's that are going to be enabled in during modeset */
12540         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12541                 intel_crtc = to_intel_crtc(crtc);
12542
12543                 if (!crtc_state->active || !needs_modeset(crtc_state))
12544                         continue;
12545
12546                 if (first_crtc_state) {
12547                         other_crtc_state = to_intel_crtc_state(crtc_state);
12548                         break;
12549                 } else {
12550                         first_crtc_state = to_intel_crtc_state(crtc_state);
12551                         first_pipe = intel_crtc->pipe;
12552                 }
12553         }
12554
12555         /* No workaround needed? */
12556         if (!first_crtc_state)
12557                 return 0;
12558
12559         /* w/a possibly needed, check how many crtc's are already enabled. */
12560         for_each_intel_crtc(state->dev, intel_crtc) {
12561                 struct intel_crtc_state *pipe_config;
12562
12563                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12564                 if (IS_ERR(pipe_config))
12565                         return PTR_ERR(pipe_config);
12566
12567                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12568
12569                 if (!pipe_config->base.active ||
12570                     needs_modeset(&pipe_config->base))
12571                         continue;
12572
12573                 /* 2 or more enabled crtcs means no need for w/a */
12574                 if (enabled_pipe != INVALID_PIPE)
12575                         return 0;
12576
12577                 enabled_pipe = intel_crtc->pipe;
12578         }
12579
12580         if (enabled_pipe != INVALID_PIPE)
12581                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12582         else if (other_crtc_state)
12583                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12584
12585         return 0;
12586 }
12587
12588 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12589 {
12590         struct drm_crtc *crtc;
12591
12592         /* Add all pipes to the state */
12593         for_each_crtc(state->dev, crtc) {
12594                 struct drm_crtc_state *crtc_state;
12595
12596                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12597                 if (IS_ERR(crtc_state))
12598                         return PTR_ERR(crtc_state);
12599         }
12600
12601         return 0;
12602 }
12603
12604 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12605 {
12606         struct drm_crtc *crtc;
12607
12608         /*
12609          * Add all pipes to the state, and force
12610          * a modeset on all the active ones.
12611          */
12612         for_each_crtc(state->dev, crtc) {
12613                 struct drm_crtc_state *crtc_state;
12614                 int ret;
12615
12616                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12617                 if (IS_ERR(crtc_state))
12618                         return PTR_ERR(crtc_state);
12619
12620                 if (!crtc_state->active || needs_modeset(crtc_state))
12621                         continue;
12622
12623                 crtc_state->mode_changed = true;
12624
12625                 ret = drm_atomic_add_affected_connectors(state, crtc);
12626                 if (ret)
12627                         return ret;
12628
12629                 ret = drm_atomic_add_affected_planes(state, crtc);
12630                 if (ret)
12631                         return ret;
12632         }
12633
12634         return 0;
12635 }
12636
12637 static int intel_modeset_checks(struct drm_atomic_state *state)
12638 {
12639         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12640         struct drm_i915_private *dev_priv = to_i915(state->dev);
12641         struct drm_crtc *crtc;
12642         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12643         int ret = 0, i;
12644
12645         if (!check_digital_port_conflicts(state)) {
12646                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12647                 return -EINVAL;
12648         }
12649
12650         intel_state->modeset = true;
12651         intel_state->active_crtcs = dev_priv->active_crtcs;
12652         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12653         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12654
12655         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12656                 if (new_crtc_state->active)
12657                         intel_state->active_crtcs |= 1 << i;
12658                 else
12659                         intel_state->active_crtcs &= ~(1 << i);
12660
12661                 if (old_crtc_state->active != new_crtc_state->active)
12662                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12663         }
12664
12665         /*
12666          * See if the config requires any additional preparation, e.g.
12667          * to adjust global state with pipes off.  We need to do this
12668          * here so we can get the modeset_pipe updated config for the new
12669          * mode set on this crtc.  For other crtcs we need to use the
12670          * adjusted_mode bits in the crtc directly.
12671          */
12672         if (dev_priv->display.modeset_calc_cdclk) {
12673                 ret = dev_priv->display.modeset_calc_cdclk(state);
12674                 if (ret < 0)
12675                         return ret;
12676
12677                 /*
12678                  * Writes to dev_priv->cdclk.logical must protected by
12679                  * holding all the crtc locks, even if we don't end up
12680                  * touching the hardware
12681                  */
12682                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12683                                         &intel_state->cdclk.logical)) {
12684                         ret = intel_lock_all_pipes(state);
12685                         if (ret < 0)
12686                                 return ret;
12687                 }
12688
12689                 /* All pipes must be switched off while we change the cdclk. */
12690                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12691                                               &intel_state->cdclk.actual)) {
12692                         ret = intel_modeset_all_pipes(state);
12693                         if (ret < 0)
12694                                 return ret;
12695                 }
12696
12697                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12698                               intel_state->cdclk.logical.cdclk,
12699                               intel_state->cdclk.actual.cdclk);
12700                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12701                               intel_state->cdclk.logical.voltage_level,
12702                               intel_state->cdclk.actual.voltage_level);
12703         } else {
12704                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12705         }
12706
12707         intel_modeset_clear_plls(state);
12708
12709         if (IS_HASWELL(dev_priv))
12710                 return haswell_mode_set_planes_workaround(state);
12711
12712         return 0;
12713 }
12714
12715 /*
12716  * Handle calculation of various watermark data at the end of the atomic check
12717  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12718  * handlers to ensure that all derived state has been updated.
12719  */
12720 static int calc_watermark_data(struct intel_atomic_state *state)
12721 {
12722         struct drm_device *dev = state->base.dev;
12723         struct drm_i915_private *dev_priv = to_i915(dev);
12724
12725         /* Is there platform-specific watermark information to calculate? */
12726         if (dev_priv->display.compute_global_watermarks)
12727                 return dev_priv->display.compute_global_watermarks(state);
12728
12729         return 0;
12730 }
12731
12732 /**
12733  * intel_atomic_check - validate state object
12734  * @dev: drm device
12735  * @state: state to validate
12736  */
12737 static int intel_atomic_check(struct drm_device *dev,
12738                               struct drm_atomic_state *state)
12739 {
12740         struct drm_i915_private *dev_priv = to_i915(dev);
12741         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12742         struct drm_crtc *crtc;
12743         struct drm_crtc_state *old_crtc_state, *crtc_state;
12744         int ret, i;
12745         bool any_ms = false;
12746
12747         /* Catch I915_MODE_FLAG_INHERITED */
12748         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12749                                       crtc_state, i) {
12750                 if (crtc_state->mode.private_flags !=
12751                     old_crtc_state->mode.private_flags)
12752                         crtc_state->mode_changed = true;
12753         }
12754
12755         ret = drm_atomic_helper_check_modeset(dev, state);
12756         if (ret)
12757                 return ret;
12758
12759         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12760                 struct intel_crtc_state *pipe_config =
12761                         to_intel_crtc_state(crtc_state);
12762
12763                 if (!needs_modeset(crtc_state))
12764                         continue;
12765
12766                 if (!crtc_state->enable) {
12767                         any_ms = true;
12768                         continue;
12769                 }
12770
12771                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12772                 if (ret == -EDEADLK)
12773                         return ret;
12774                 if (ret) {
12775                         intel_dump_pipe_config(to_intel_crtc(crtc),
12776                                                pipe_config, "[failed]");
12777                         return ret;
12778                 }
12779
12780                 if (intel_pipe_config_compare(dev_priv,
12781                                         to_intel_crtc_state(old_crtc_state),
12782                                         pipe_config, true)) {
12783                         crtc_state->mode_changed = false;
12784                         pipe_config->update_pipe = true;
12785                 }
12786
12787                 if (needs_modeset(crtc_state))
12788                         any_ms = true;
12789
12790                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12791                                        needs_modeset(crtc_state) ?
12792                                        "[modeset]" : "[fastset]");
12793         }
12794
12795         ret = drm_dp_mst_atomic_check(state);
12796         if (ret)
12797                 return ret;
12798
12799         if (any_ms) {
12800                 ret = intel_modeset_checks(state);
12801
12802                 if (ret)
12803                         return ret;
12804         } else {
12805                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12806         }
12807
12808         ret = icl_add_linked_planes(intel_state);
12809         if (ret)
12810                 return ret;
12811
12812         ret = drm_atomic_helper_check_planes(dev, state);
12813         if (ret)
12814                 return ret;
12815
12816         intel_fbc_choose_crtc(dev_priv, intel_state);
12817         return calc_watermark_data(intel_state);
12818 }
12819
12820 static int intel_atomic_prepare_commit(struct drm_device *dev,
12821                                        struct drm_atomic_state *state)
12822 {
12823         return drm_atomic_helper_prepare_planes(dev, state);
12824 }
12825
12826 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12827 {
12828         struct drm_device *dev = crtc->base.dev;
12829         struct drm_vblank_crtc *vblank = &dev->vblank[drm_crtc_index(&crtc->base)];
12830
12831         if (!vblank->max_vblank_count)
12832                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12833
12834         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12835 }
12836
12837 static void intel_update_crtc(struct drm_crtc *crtc,
12838                               struct drm_atomic_state *state,
12839                               struct drm_crtc_state *old_crtc_state,
12840                               struct drm_crtc_state *new_crtc_state)
12841 {
12842         struct drm_device *dev = crtc->dev;
12843         struct drm_i915_private *dev_priv = to_i915(dev);
12844         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12845         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12846         bool modeset = needs_modeset(new_crtc_state);
12847         struct intel_plane_state *new_plane_state =
12848                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
12849                                                  to_intel_plane(crtc->primary));
12850
12851         if (modeset) {
12852                 update_scanline_offset(pipe_config);
12853                 dev_priv->display.crtc_enable(pipe_config, state);
12854
12855                 /* vblanks work again, re-enable pipe CRC. */
12856                 intel_crtc_enable_pipe_crc(intel_crtc);
12857         } else {
12858                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12859                                        pipe_config);
12860
12861                 if (pipe_config->update_pipe)
12862                         intel_encoders_update_pipe(crtc, pipe_config, state);
12863         }
12864
12865         if (pipe_config->update_pipe && !pipe_config->enable_fbc)
12866                 intel_fbc_disable(intel_crtc);
12867         else if (new_plane_state)
12868                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
12869
12870         intel_begin_crtc_commit(crtc, old_crtc_state);
12871
12872         if (INTEL_GEN(dev_priv) >= 9)
12873                 skl_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc);
12874         else
12875                 i9xx_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc);
12876
12877         intel_finish_crtc_commit(crtc, old_crtc_state);
12878 }
12879
12880 static void intel_update_crtcs(struct drm_atomic_state *state)
12881 {
12882         struct drm_crtc *crtc;
12883         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12884         int i;
12885
12886         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12887                 if (!new_crtc_state->active)
12888                         continue;
12889
12890                 intel_update_crtc(crtc, state, old_crtc_state,
12891                                   new_crtc_state);
12892         }
12893 }
12894
12895 static void skl_update_crtcs(struct drm_atomic_state *state)
12896 {
12897         struct drm_i915_private *dev_priv = to_i915(state->dev);
12898         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12899         struct drm_crtc *crtc;
12900         struct intel_crtc *intel_crtc;
12901         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12902         struct intel_crtc_state *cstate;
12903         unsigned int updated = 0;
12904         bool progress;
12905         enum pipe pipe;
12906         int i;
12907         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
12908         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
12909         struct skl_ddb_entry entries[I915_MAX_PIPES] = {};
12910
12911         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12912                 /* ignore allocations for crtc's that have been turned off. */
12913                 if (new_crtc_state->active)
12914                         entries[i] = to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12915
12916         /* If 2nd DBuf slice required, enable it here */
12917         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
12918                 icl_dbuf_slices_update(dev_priv, required_slices);
12919
12920         /*
12921          * Whenever the number of active pipes changes, we need to make sure we
12922          * update the pipes in the right order so that their ddb allocations
12923          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12924          * cause pipe underruns and other bad stuff.
12925          */
12926         do {
12927                 progress = false;
12928
12929                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12930                         bool vbl_wait = false;
12931                         unsigned int cmask = drm_crtc_mask(crtc);
12932
12933                         intel_crtc = to_intel_crtc(crtc);
12934                         cstate = to_intel_crtc_state(new_crtc_state);
12935                         pipe = intel_crtc->pipe;
12936
12937                         if (updated & cmask || !cstate->base.active)
12938                                 continue;
12939
12940                         if (skl_ddb_allocation_overlaps(&cstate->wm.skl.ddb,
12941                                                         entries,
12942                                                         INTEL_INFO(dev_priv)->num_pipes, i))
12943                                 continue;
12944
12945                         updated |= cmask;
12946                         entries[i] = cstate->wm.skl.ddb;
12947
12948                         /*
12949                          * If this is an already active pipe, it's DDB changed,
12950                          * and this isn't the last pipe that needs updating
12951                          * then we need to wait for a vblank to pass for the
12952                          * new ddb allocation to take effect.
12953                          */
12954                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12955                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12956                             !new_crtc_state->active_changed &&
12957                             intel_state->wm_results.dirty_pipes != updated)
12958                                 vbl_wait = true;
12959
12960                         intel_update_crtc(crtc, state, old_crtc_state,
12961                                           new_crtc_state);
12962
12963                         if (vbl_wait)
12964                                 intel_wait_for_vblank(dev_priv, pipe);
12965
12966                         progress = true;
12967                 }
12968         } while (progress);
12969
12970         /* If 2nd DBuf slice is no more required disable it */
12971         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
12972                 icl_dbuf_slices_update(dev_priv, required_slices);
12973 }
12974
12975 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12976 {
12977         struct intel_atomic_state *state, *next;
12978         struct llist_node *freed;
12979
12980         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12981         llist_for_each_entry_safe(state, next, freed, freed)
12982                 drm_atomic_state_put(&state->base);
12983 }
12984
12985 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12986 {
12987         struct drm_i915_private *dev_priv =
12988                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12989
12990         intel_atomic_helper_free_state(dev_priv);
12991 }
12992
12993 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12994 {
12995         struct wait_queue_entry wait_fence, wait_reset;
12996         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12997
12998         init_wait_entry(&wait_fence, 0);
12999         init_wait_entry(&wait_reset, 0);
13000         for (;;) {
13001                 prepare_to_wait(&intel_state->commit_ready.wait,
13002                                 &wait_fence, TASK_UNINTERRUPTIBLE);
13003                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
13004                                 &wait_reset, TASK_UNINTERRUPTIBLE);
13005
13006
13007                 if (i915_sw_fence_done(&intel_state->commit_ready)
13008                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
13009                         break;
13010
13011                 schedule();
13012         }
13013         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
13014         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
13015 }
13016
13017 static void intel_atomic_cleanup_work(struct work_struct *work)
13018 {
13019         struct drm_atomic_state *state =
13020                 container_of(work, struct drm_atomic_state, commit_work);
13021         struct drm_i915_private *i915 = to_i915(state->dev);
13022
13023         drm_atomic_helper_cleanup_planes(&i915->drm, state);
13024         drm_atomic_helper_commit_cleanup_done(state);
13025         drm_atomic_state_put(state);
13026
13027         intel_atomic_helper_free_state(i915);
13028 }
13029
13030 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
13031 {
13032         struct drm_device *dev = state->dev;
13033         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13034         struct drm_i915_private *dev_priv = to_i915(dev);
13035         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13036         struct intel_crtc_state *new_intel_crtc_state, *old_intel_crtc_state;
13037         struct drm_crtc *crtc;
13038         struct intel_crtc *intel_crtc;
13039         u64 put_domains[I915_MAX_PIPES] = {};
13040         intel_wakeref_t wakeref = 0;
13041         int i;
13042
13043         intel_atomic_commit_fence_wait(intel_state);
13044
13045         drm_atomic_helper_wait_for_dependencies(state);
13046
13047         if (intel_state->modeset)
13048                 wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
13049
13050         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13051                 old_intel_crtc_state = to_intel_crtc_state(old_crtc_state);
13052                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13053                 intel_crtc = to_intel_crtc(crtc);
13054
13055                 if (needs_modeset(new_crtc_state) ||
13056                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
13057
13058                         put_domains[intel_crtc->pipe] =
13059                                 modeset_get_crtc_power_domains(crtc,
13060                                         new_intel_crtc_state);
13061                 }
13062
13063                 if (!needs_modeset(new_crtc_state))
13064                         continue;
13065
13066                 intel_pre_plane_update(old_intel_crtc_state, new_intel_crtc_state);
13067
13068                 if (old_crtc_state->active) {
13069                         intel_crtc_disable_planes(intel_state, intel_crtc);
13070
13071                         /*
13072                          * We need to disable pipe CRC before disabling the pipe,
13073                          * or we race against vblank off.
13074                          */
13075                         intel_crtc_disable_pipe_crc(intel_crtc);
13076
13077                         dev_priv->display.crtc_disable(old_intel_crtc_state, state);
13078                         intel_crtc->active = false;
13079                         intel_fbc_disable(intel_crtc);
13080                         intel_disable_shared_dpll(old_intel_crtc_state);
13081
13082                         /*
13083                          * Underruns don't always raise
13084                          * interrupts, so check manually.
13085                          */
13086                         intel_check_cpu_fifo_underruns(dev_priv);
13087                         intel_check_pch_fifo_underruns(dev_priv);
13088
13089                         /* FIXME unify this for all platforms */
13090                         if (!new_crtc_state->active &&
13091                             !HAS_GMCH_DISPLAY(dev_priv) &&
13092                             dev_priv->display.initial_watermarks)
13093                                 dev_priv->display.initial_watermarks(intel_state,
13094                                                                      new_intel_crtc_state);
13095                 }
13096         }
13097
13098         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
13099         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
13100                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
13101
13102         if (intel_state->modeset) {
13103                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
13104
13105                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
13106
13107                 /*
13108                  * SKL workaround: bspec recommends we disable the SAGV when we
13109                  * have more then one pipe enabled
13110                  */
13111                 if (!intel_can_enable_sagv(state))
13112                         intel_disable_sagv(dev_priv);
13113
13114                 intel_modeset_verify_disabled(dev, state);
13115         }
13116
13117         /* Complete the events for pipes that have now been disabled */
13118         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13119                 bool modeset = needs_modeset(new_crtc_state);
13120
13121                 /* Complete events for now disable pipes here. */
13122                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
13123                         spin_lock_irq(&dev->event_lock);
13124                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
13125                         spin_unlock_irq(&dev->event_lock);
13126
13127                         new_crtc_state->event = NULL;
13128                 }
13129         }
13130
13131         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
13132         dev_priv->display.update_crtcs(state);
13133
13134         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
13135          * already, but still need the state for the delayed optimization. To
13136          * fix this:
13137          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
13138          * - schedule that vblank worker _before_ calling hw_done
13139          * - at the start of commit_tail, cancel it _synchrously
13140          * - switch over to the vblank wait helper in the core after that since
13141          *   we don't need out special handling any more.
13142          */
13143         drm_atomic_helper_wait_for_flip_done(dev, state);
13144
13145         /*
13146          * Now that the vblank has passed, we can go ahead and program the
13147          * optimal watermarks on platforms that need two-step watermark
13148          * programming.
13149          *
13150          * TODO: Move this (and other cleanup) to an async worker eventually.
13151          */
13152         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13153                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
13154
13155                 if (dev_priv->display.optimize_watermarks)
13156                         dev_priv->display.optimize_watermarks(intel_state,
13157                                                               new_intel_crtc_state);
13158         }
13159
13160         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13161                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
13162
13163                 if (put_domains[i])
13164                         modeset_put_power_domains(dev_priv, put_domains[i]);
13165
13166                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
13167         }
13168
13169         if (intel_state->modeset)
13170                 intel_verify_planes(intel_state);
13171
13172         if (intel_state->modeset && intel_can_enable_sagv(state))
13173                 intel_enable_sagv(dev_priv);
13174
13175         drm_atomic_helper_commit_hw_done(state);
13176
13177         if (intel_state->modeset) {
13178                 /* As one of the primary mmio accessors, KMS has a high
13179                  * likelihood of triggering bugs in unclaimed access. After we
13180                  * finish modesetting, see if an error has been flagged, and if
13181                  * so enable debugging for the next modeset - and hope we catch
13182                  * the culprit.
13183                  */
13184                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
13185                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET, wakeref);
13186         }
13187
13188         /*
13189          * Defer the cleanup of the old state to a separate worker to not
13190          * impede the current task (userspace for blocking modesets) that
13191          * are executed inline. For out-of-line asynchronous modesets/flips,
13192          * deferring to a new worker seems overkill, but we would place a
13193          * schedule point (cond_resched()) here anyway to keep latencies
13194          * down.
13195          */
13196         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
13197         queue_work(system_highpri_wq, &state->commit_work);
13198 }
13199
13200 static void intel_atomic_commit_work(struct work_struct *work)
13201 {
13202         struct drm_atomic_state *state =
13203                 container_of(work, struct drm_atomic_state, commit_work);
13204
13205         intel_atomic_commit_tail(state);
13206 }
13207
13208 static int __i915_sw_fence_call
13209 intel_atomic_commit_ready(struct i915_sw_fence *fence,
13210                           enum i915_sw_fence_notify notify)
13211 {
13212         struct intel_atomic_state *state =
13213                 container_of(fence, struct intel_atomic_state, commit_ready);
13214
13215         switch (notify) {
13216         case FENCE_COMPLETE:
13217                 /* we do blocking waits in the worker, nothing to do here */
13218                 break;
13219         case FENCE_FREE:
13220                 {
13221                         struct intel_atomic_helper *helper =
13222                                 &to_i915(state->base.dev)->atomic_helper;
13223
13224                         if (llist_add(&state->freed, &helper->free_list))
13225                                 schedule_work(&helper->free_work);
13226                         break;
13227                 }
13228         }
13229
13230         return NOTIFY_DONE;
13231 }
13232
13233 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
13234 {
13235         struct drm_plane_state *old_plane_state, *new_plane_state;
13236         struct drm_plane *plane;
13237         int i;
13238
13239         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
13240                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
13241                                   intel_fb_obj(new_plane_state->fb),
13242                                   to_intel_plane(plane)->frontbuffer_bit);
13243 }
13244
13245 /**
13246  * intel_atomic_commit - commit validated state object
13247  * @dev: DRM device
13248  * @state: the top-level driver state object
13249  * @nonblock: nonblocking commit
13250  *
13251  * This function commits a top-level state object that has been validated
13252  * with drm_atomic_helper_check().
13253  *
13254  * RETURNS
13255  * Zero for success or -errno.
13256  */
13257 static int intel_atomic_commit(struct drm_device *dev,
13258                                struct drm_atomic_state *state,
13259                                bool nonblock)
13260 {
13261         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
13262         struct drm_i915_private *dev_priv = to_i915(dev);
13263         int ret = 0;
13264
13265         drm_atomic_state_get(state);
13266         i915_sw_fence_init(&intel_state->commit_ready,
13267                            intel_atomic_commit_ready);
13268
13269         /*
13270          * The intel_legacy_cursor_update() fast path takes care
13271          * of avoiding the vblank waits for simple cursor
13272          * movement and flips. For cursor on/off and size changes,
13273          * we want to perform the vblank waits so that watermark
13274          * updates happen during the correct frames. Gen9+ have
13275          * double buffered watermarks and so shouldn't need this.
13276          *
13277          * Unset state->legacy_cursor_update before the call to
13278          * drm_atomic_helper_setup_commit() because otherwise
13279          * drm_atomic_helper_wait_for_flip_done() is a noop and
13280          * we get FIFO underruns because we didn't wait
13281          * for vblank.
13282          *
13283          * FIXME doing watermarks and fb cleanup from a vblank worker
13284          * (assuming we had any) would solve these problems.
13285          */
13286         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
13287                 struct intel_crtc_state *new_crtc_state;
13288                 struct intel_crtc *crtc;
13289                 int i;
13290
13291                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
13292                         if (new_crtc_state->wm.need_postvbl_update ||
13293                             new_crtc_state->update_wm_post)
13294                                 state->legacy_cursor_update = false;
13295         }
13296
13297         ret = intel_atomic_prepare_commit(dev, state);
13298         if (ret) {
13299                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
13300                 i915_sw_fence_commit(&intel_state->commit_ready);
13301                 return ret;
13302         }
13303
13304         ret = drm_atomic_helper_setup_commit(state, nonblock);
13305         if (!ret)
13306                 ret = drm_atomic_helper_swap_state(state, true);
13307
13308         if (ret) {
13309                 i915_sw_fence_commit(&intel_state->commit_ready);
13310
13311                 drm_atomic_helper_cleanup_planes(dev, state);
13312                 return ret;
13313         }
13314         dev_priv->wm.distrust_bios_wm = false;
13315         intel_shared_dpll_swap_state(state);
13316         intel_atomic_track_fbs(state);
13317
13318         if (intel_state->modeset) {
13319                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
13320                        sizeof(intel_state->min_cdclk));
13321                 memcpy(dev_priv->min_voltage_level,
13322                        intel_state->min_voltage_level,
13323                        sizeof(intel_state->min_voltage_level));
13324                 dev_priv->active_crtcs = intel_state->active_crtcs;
13325                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
13326                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
13327         }
13328
13329         drm_atomic_state_get(state);
13330         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
13331
13332         i915_sw_fence_commit(&intel_state->commit_ready);
13333         if (nonblock && intel_state->modeset) {
13334                 queue_work(dev_priv->modeset_wq, &state->commit_work);
13335         } else if (nonblock) {
13336                 queue_work(system_unbound_wq, &state->commit_work);
13337         } else {
13338                 if (intel_state->modeset)
13339                         flush_workqueue(dev_priv->modeset_wq);
13340                 intel_atomic_commit_tail(state);
13341         }
13342
13343         return 0;
13344 }
13345
13346 static const struct drm_crtc_funcs intel_crtc_funcs = {
13347         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13348         .set_config = drm_atomic_helper_set_config,
13349         .destroy = intel_crtc_destroy,
13350         .page_flip = drm_atomic_helper_page_flip,
13351         .atomic_duplicate_state = intel_crtc_duplicate_state,
13352         .atomic_destroy_state = intel_crtc_destroy_state,
13353         .set_crc_source = intel_crtc_set_crc_source,
13354         .verify_crc_source = intel_crtc_verify_crc_source,
13355         .get_crc_sources = intel_crtc_get_crc_sources,
13356 };
13357
13358 struct wait_rps_boost {
13359         struct wait_queue_entry wait;
13360
13361         struct drm_crtc *crtc;
13362         struct i915_request *request;
13363 };
13364
13365 static int do_rps_boost(struct wait_queue_entry *_wait,
13366                         unsigned mode, int sync, void *key)
13367 {
13368         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
13369         struct i915_request *rq = wait->request;
13370
13371         /*
13372          * If we missed the vblank, but the request is already running it
13373          * is reasonable to assume that it will complete before the next
13374          * vblank without our intervention, so leave RPS alone.
13375          */
13376         if (!i915_request_started(rq))
13377                 gen6_rps_boost(rq, NULL);
13378         i915_request_put(rq);
13379
13380         drm_crtc_vblank_put(wait->crtc);
13381
13382         list_del(&wait->wait.entry);
13383         kfree(wait);
13384         return 1;
13385 }
13386
13387 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
13388                                        struct dma_fence *fence)
13389 {
13390         struct wait_rps_boost *wait;
13391
13392         if (!dma_fence_is_i915(fence))
13393                 return;
13394
13395         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
13396                 return;
13397
13398         if (drm_crtc_vblank_get(crtc))
13399                 return;
13400
13401         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
13402         if (!wait) {
13403                 drm_crtc_vblank_put(crtc);
13404                 return;
13405         }
13406
13407         wait->request = to_request(dma_fence_get(fence));
13408         wait->crtc = crtc;
13409
13410         wait->wait.func = do_rps_boost;
13411         wait->wait.flags = 0;
13412
13413         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
13414 }
13415
13416 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
13417 {
13418         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
13419         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13420         struct drm_framebuffer *fb = plane_state->base.fb;
13421         struct i915_vma *vma;
13422
13423         if (plane->id == PLANE_CURSOR &&
13424             INTEL_INFO(dev_priv)->display.cursor_needs_physical) {
13425                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13426                 const int align = intel_cursor_alignment(dev_priv);
13427                 int err;
13428
13429                 err = i915_gem_object_attach_phys(obj, align);
13430                 if (err)
13431                         return err;
13432         }
13433
13434         vma = intel_pin_and_fence_fb_obj(fb,
13435                                          &plane_state->view,
13436                                          intel_plane_uses_fence(plane_state),
13437                                          &plane_state->flags);
13438         if (IS_ERR(vma))
13439                 return PTR_ERR(vma);
13440
13441         plane_state->vma = vma;
13442
13443         return 0;
13444 }
13445
13446 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
13447 {
13448         struct i915_vma *vma;
13449
13450         vma = fetch_and_zero(&old_plane_state->vma);
13451         if (vma)
13452                 intel_unpin_fb_vma(vma, old_plane_state->flags);
13453 }
13454
13455 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
13456 {
13457         struct i915_sched_attr attr = {
13458                 .priority = I915_PRIORITY_DISPLAY,
13459         };
13460
13461         i915_gem_object_wait_priority(obj, 0, &attr);
13462 }
13463
13464 /**
13465  * intel_prepare_plane_fb - Prepare fb for usage on plane
13466  * @plane: drm plane to prepare for
13467  * @new_state: the plane state being prepared
13468  *
13469  * Prepares a framebuffer for usage on a display plane.  Generally this
13470  * involves pinning the underlying object and updating the frontbuffer tracking
13471  * bits.  Some older platforms need special physical address handling for
13472  * cursor planes.
13473  *
13474  * Must be called with struct_mutex held.
13475  *
13476  * Returns 0 on success, negative error code on failure.
13477  */
13478 int
13479 intel_prepare_plane_fb(struct drm_plane *plane,
13480                        struct drm_plane_state *new_state)
13481 {
13482         struct intel_atomic_state *intel_state =
13483                 to_intel_atomic_state(new_state->state);
13484         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13485         struct drm_framebuffer *fb = new_state->fb;
13486         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13487         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13488         int ret;
13489
13490         if (old_obj) {
13491                 struct drm_crtc_state *crtc_state =
13492                         drm_atomic_get_new_crtc_state(new_state->state,
13493                                                       plane->state->crtc);
13494
13495                 /* Big Hammer, we also need to ensure that any pending
13496                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13497                  * current scanout is retired before unpinning the old
13498                  * framebuffer. Note that we rely on userspace rendering
13499                  * into the buffer attached to the pipe they are waiting
13500                  * on. If not, userspace generates a GPU hang with IPEHR
13501                  * point to the MI_WAIT_FOR_EVENT.
13502                  *
13503                  * This should only fail upon a hung GPU, in which case we
13504                  * can safely continue.
13505                  */
13506                 if (needs_modeset(crtc_state)) {
13507                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13508                                                               old_obj->resv, NULL,
13509                                                               false, 0,
13510                                                               GFP_KERNEL);
13511                         if (ret < 0)
13512                                 return ret;
13513                 }
13514         }
13515
13516         if (new_state->fence) { /* explicit fencing */
13517                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13518                                                     new_state->fence,
13519                                                     I915_FENCE_TIMEOUT,
13520                                                     GFP_KERNEL);
13521                 if (ret < 0)
13522                         return ret;
13523         }
13524
13525         if (!obj)
13526                 return 0;
13527
13528         ret = i915_gem_object_pin_pages(obj);
13529         if (ret)
13530                 return ret;
13531
13532         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13533         if (ret) {
13534                 i915_gem_object_unpin_pages(obj);
13535                 return ret;
13536         }
13537
13538         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
13539
13540         mutex_unlock(&dev_priv->drm.struct_mutex);
13541         i915_gem_object_unpin_pages(obj);
13542         if (ret)
13543                 return ret;
13544
13545         fb_obj_bump_render_priority(obj);
13546         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13547
13548         if (!new_state->fence) { /* implicit fencing */
13549                 struct dma_fence *fence;
13550
13551                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13552                                                       obj->resv, NULL,
13553                                                       false, I915_FENCE_TIMEOUT,
13554                                                       GFP_KERNEL);
13555                 if (ret < 0)
13556                         return ret;
13557
13558                 fence = reservation_object_get_excl_rcu(obj->resv);
13559                 if (fence) {
13560                         add_rps_boost_after_vblank(new_state->crtc, fence);
13561                         dma_fence_put(fence);
13562                 }
13563         } else {
13564                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
13565         }
13566
13567         /*
13568          * We declare pageflips to be interactive and so merit a small bias
13569          * towards upclocking to deliver the frame on time. By only changing
13570          * the RPS thresholds to sample more regularly and aim for higher
13571          * clocks we can hopefully deliver low power workloads (like kodi)
13572          * that are not quite steady state without resorting to forcing
13573          * maximum clocks following a vblank miss (see do_rps_boost()).
13574          */
13575         if (!intel_state->rps_interactive) {
13576                 intel_rps_mark_interactive(dev_priv, true);
13577                 intel_state->rps_interactive = true;
13578         }
13579
13580         return 0;
13581 }
13582
13583 /**
13584  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13585  * @plane: drm plane to clean up for
13586  * @old_state: the state from the previous modeset
13587  *
13588  * Cleans up a framebuffer that has just been removed from a plane.
13589  *
13590  * Must be called with struct_mutex held.
13591  */
13592 void
13593 intel_cleanup_plane_fb(struct drm_plane *plane,
13594                        struct drm_plane_state *old_state)
13595 {
13596         struct intel_atomic_state *intel_state =
13597                 to_intel_atomic_state(old_state->state);
13598         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13599
13600         if (intel_state->rps_interactive) {
13601                 intel_rps_mark_interactive(dev_priv, false);
13602                 intel_state->rps_interactive = false;
13603         }
13604
13605         /* Should only be called after a successful intel_prepare_plane_fb()! */
13606         mutex_lock(&dev_priv->drm.struct_mutex);
13607         intel_plane_unpin_fb(to_intel_plane_state(old_state));
13608         mutex_unlock(&dev_priv->drm.struct_mutex);
13609 }
13610
13611 int
13612 skl_max_scale(const struct intel_crtc_state *crtc_state,
13613               u32 pixel_format)
13614 {
13615         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
13616         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13617         int max_scale, mult;
13618         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
13619
13620         if (!crtc_state->base.enable)
13621                 return DRM_PLANE_HELPER_NO_SCALING;
13622
13623         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13624         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13625
13626         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
13627                 max_dotclk *= 2;
13628
13629         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13630                 return DRM_PLANE_HELPER_NO_SCALING;
13631
13632         /*
13633          * skl max scale is lower of:
13634          *    close to 3 but not 3, -1 is for that purpose
13635          *            or
13636          *    cdclk/crtc_clock
13637          */
13638         mult = pixel_format == DRM_FORMAT_NV12 ? 2 : 3;
13639         tmpclk1 = (1 << 16) * mult - 1;
13640         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
13641         max_scale = min(tmpclk1, tmpclk2);
13642
13643         return max_scale;
13644 }
13645
13646 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13647                                     struct drm_crtc_state *old_crtc_state)
13648 {
13649         struct drm_device *dev = crtc->dev;
13650         struct drm_i915_private *dev_priv = to_i915(dev);
13651         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13652         struct intel_crtc_state *old_intel_cstate =
13653                 to_intel_crtc_state(old_crtc_state);
13654         struct intel_atomic_state *old_intel_state =
13655                 to_intel_atomic_state(old_crtc_state->state);
13656         struct intel_crtc_state *intel_cstate =
13657                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13658         bool modeset = needs_modeset(&intel_cstate->base);
13659
13660         if (!modeset &&
13661             (intel_cstate->base.color_mgmt_changed ||
13662              intel_cstate->update_pipe)) {
13663                 intel_color_set_csc(intel_cstate);
13664                 intel_color_load_luts(intel_cstate);
13665         }
13666
13667         /* Perform vblank evasion around commit operation */
13668         intel_pipe_update_start(intel_cstate);
13669
13670         if (modeset)
13671                 goto out;
13672
13673         if (intel_cstate->update_pipe)
13674                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
13675         else if (INTEL_GEN(dev_priv) >= 9)
13676                 skl_detach_scalers(intel_cstate);
13677
13678 out:
13679         if (dev_priv->display.atomic_update_watermarks)
13680                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13681                                                            intel_cstate);
13682 }
13683
13684 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
13685                                   struct intel_crtc_state *crtc_state)
13686 {
13687         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13688
13689         if (!IS_GEN(dev_priv, 2))
13690                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
13691
13692         if (crtc_state->has_pch_encoder) {
13693                 enum pipe pch_transcoder =
13694                         intel_crtc_pch_transcoder(crtc);
13695
13696                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13697         }
13698 }
13699
13700 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13701                                      struct drm_crtc_state *old_crtc_state)
13702 {
13703         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13704         struct intel_atomic_state *old_intel_state =
13705                 to_intel_atomic_state(old_crtc_state->state);
13706         struct intel_crtc_state *new_crtc_state =
13707                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13708
13709         intel_pipe_update_end(new_crtc_state);
13710
13711         if (new_crtc_state->update_pipe &&
13712             !needs_modeset(&new_crtc_state->base) &&
13713             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED)
13714                 intel_crtc_arm_fifo_underrun(intel_crtc, new_crtc_state);
13715 }
13716
13717 /**
13718  * intel_plane_destroy - destroy a plane
13719  * @plane: plane to destroy
13720  *
13721  * Common destruction function for all types of planes (primary, cursor,
13722  * sprite).
13723  */
13724 void intel_plane_destroy(struct drm_plane *plane)
13725 {
13726         drm_plane_cleanup(plane);
13727         kfree(to_intel_plane(plane));
13728 }
13729
13730 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
13731                                             u32 format, u64 modifier)
13732 {
13733         switch (modifier) {
13734         case DRM_FORMAT_MOD_LINEAR:
13735         case I915_FORMAT_MOD_X_TILED:
13736                 break;
13737         default:
13738                 return false;
13739         }
13740
13741         switch (format) {
13742         case DRM_FORMAT_C8:
13743         case DRM_FORMAT_RGB565:
13744         case DRM_FORMAT_XRGB1555:
13745         case DRM_FORMAT_XRGB8888:
13746                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13747                         modifier == I915_FORMAT_MOD_X_TILED;
13748         default:
13749                 return false;
13750         }
13751 }
13752
13753 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
13754                                             u32 format, u64 modifier)
13755 {
13756         switch (modifier) {
13757         case DRM_FORMAT_MOD_LINEAR:
13758         case I915_FORMAT_MOD_X_TILED:
13759                 break;
13760         default:
13761                 return false;
13762         }
13763
13764         switch (format) {
13765         case DRM_FORMAT_C8:
13766         case DRM_FORMAT_RGB565:
13767         case DRM_FORMAT_XRGB8888:
13768         case DRM_FORMAT_XBGR8888:
13769         case DRM_FORMAT_XRGB2101010:
13770         case DRM_FORMAT_XBGR2101010:
13771                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13772                         modifier == I915_FORMAT_MOD_X_TILED;
13773         default:
13774                 return false;
13775         }
13776 }
13777
13778 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
13779                                               u32 format, u64 modifier)
13780 {
13781         return modifier == DRM_FORMAT_MOD_LINEAR &&
13782                 format == DRM_FORMAT_ARGB8888;
13783 }
13784
13785 static const struct drm_plane_funcs i965_plane_funcs = {
13786         .update_plane = drm_atomic_helper_update_plane,
13787         .disable_plane = drm_atomic_helper_disable_plane,
13788         .destroy = intel_plane_destroy,
13789         .atomic_get_property = intel_plane_atomic_get_property,
13790         .atomic_set_property = intel_plane_atomic_set_property,
13791         .atomic_duplicate_state = intel_plane_duplicate_state,
13792         .atomic_destroy_state = intel_plane_destroy_state,
13793         .format_mod_supported = i965_plane_format_mod_supported,
13794 };
13795
13796 static const struct drm_plane_funcs i8xx_plane_funcs = {
13797         .update_plane = drm_atomic_helper_update_plane,
13798         .disable_plane = drm_atomic_helper_disable_plane,
13799         .destroy = intel_plane_destroy,
13800         .atomic_get_property = intel_plane_atomic_get_property,
13801         .atomic_set_property = intel_plane_atomic_set_property,
13802         .atomic_duplicate_state = intel_plane_duplicate_state,
13803         .atomic_destroy_state = intel_plane_destroy_state,
13804         .format_mod_supported = i8xx_plane_format_mod_supported,
13805 };
13806
13807 static int
13808 intel_legacy_cursor_update(struct drm_plane *plane,
13809                            struct drm_crtc *crtc,
13810                            struct drm_framebuffer *fb,
13811                            int crtc_x, int crtc_y,
13812                            unsigned int crtc_w, unsigned int crtc_h,
13813                            u32 src_x, u32 src_y,
13814                            u32 src_w, u32 src_h,
13815                            struct drm_modeset_acquire_ctx *ctx)
13816 {
13817         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13818         int ret;
13819         struct drm_plane_state *old_plane_state, *new_plane_state;
13820         struct intel_plane *intel_plane = to_intel_plane(plane);
13821         struct drm_framebuffer *old_fb;
13822         struct intel_crtc_state *crtc_state =
13823                 to_intel_crtc_state(crtc->state);
13824         struct intel_crtc_state *new_crtc_state;
13825
13826         /*
13827          * When crtc is inactive or there is a modeset pending,
13828          * wait for it to complete in the slowpath
13829          */
13830         if (!crtc_state->base.active || needs_modeset(&crtc_state->base) ||
13831             crtc_state->update_pipe)
13832                 goto slow;
13833
13834         old_plane_state = plane->state;
13835         /*
13836          * Don't do an async update if there is an outstanding commit modifying
13837          * the plane.  This prevents our async update's changes from getting
13838          * overridden by a previous synchronous update's state.
13839          */
13840         if (old_plane_state->commit &&
13841             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13842                 goto slow;
13843
13844         /*
13845          * If any parameters change that may affect watermarks,
13846          * take the slowpath. Only changing fb or position should be
13847          * in the fastpath.
13848          */
13849         if (old_plane_state->crtc != crtc ||
13850             old_plane_state->src_w != src_w ||
13851             old_plane_state->src_h != src_h ||
13852             old_plane_state->crtc_w != crtc_w ||
13853             old_plane_state->crtc_h != crtc_h ||
13854             !old_plane_state->fb != !fb)
13855                 goto slow;
13856
13857         new_plane_state = intel_plane_duplicate_state(plane);
13858         if (!new_plane_state)
13859                 return -ENOMEM;
13860
13861         new_crtc_state = to_intel_crtc_state(intel_crtc_duplicate_state(crtc));
13862         if (!new_crtc_state) {
13863                 ret = -ENOMEM;
13864                 goto out_free;
13865         }
13866
13867         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13868
13869         new_plane_state->src_x = src_x;
13870         new_plane_state->src_y = src_y;
13871         new_plane_state->src_w = src_w;
13872         new_plane_state->src_h = src_h;
13873         new_plane_state->crtc_x = crtc_x;
13874         new_plane_state->crtc_y = crtc_y;
13875         new_plane_state->crtc_w = crtc_w;
13876         new_plane_state->crtc_h = crtc_h;
13877
13878         ret = intel_plane_atomic_check_with_state(crtc_state, new_crtc_state,
13879                                                   to_intel_plane_state(old_plane_state),
13880                                                   to_intel_plane_state(new_plane_state));
13881         if (ret)
13882                 goto out_free;
13883
13884         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13885         if (ret)
13886                 goto out_free;
13887
13888         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13889         if (ret)
13890                 goto out_unlock;
13891
13892         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13893
13894         old_fb = old_plane_state->fb;
13895         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13896                           intel_plane->frontbuffer_bit);
13897
13898         /* Swap plane state */
13899         plane->state = new_plane_state;
13900
13901         /*
13902          * We cannot swap crtc_state as it may be in use by an atomic commit or
13903          * page flip that's running simultaneously. If we swap crtc_state and
13904          * destroy the old state, we will cause a use-after-free there.
13905          *
13906          * Only update active_planes, which is needed for our internal
13907          * bookkeeping. Either value will do the right thing when updating
13908          * planes atomically. If the cursor was part of the atomic update then
13909          * we would have taken the slowpath.
13910          */
13911         crtc_state->active_planes = new_crtc_state->active_planes;
13912
13913         if (plane->state->visible) {
13914                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13915                 intel_plane->update_plane(intel_plane, crtc_state,
13916                                           to_intel_plane_state(plane->state));
13917         } else {
13918                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13919                 intel_plane->disable_plane(intel_plane, crtc_state);
13920         }
13921
13922         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13923
13924 out_unlock:
13925         mutex_unlock(&dev_priv->drm.struct_mutex);
13926 out_free:
13927         if (new_crtc_state)
13928                 intel_crtc_destroy_state(crtc, &new_crtc_state->base);
13929         if (ret)
13930                 intel_plane_destroy_state(plane, new_plane_state);
13931         else
13932                 intel_plane_destroy_state(plane, old_plane_state);
13933         return ret;
13934
13935 slow:
13936         return drm_atomic_helper_update_plane(plane, crtc, fb,
13937                                               crtc_x, crtc_y, crtc_w, crtc_h,
13938                                               src_x, src_y, src_w, src_h, ctx);
13939 }
13940
13941 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13942         .update_plane = intel_legacy_cursor_update,
13943         .disable_plane = drm_atomic_helper_disable_plane,
13944         .destroy = intel_plane_destroy,
13945         .atomic_get_property = intel_plane_atomic_get_property,
13946         .atomic_set_property = intel_plane_atomic_set_property,
13947         .atomic_duplicate_state = intel_plane_duplicate_state,
13948         .atomic_destroy_state = intel_plane_destroy_state,
13949         .format_mod_supported = intel_cursor_format_mod_supported,
13950 };
13951
13952 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13953                                enum i9xx_plane_id i9xx_plane)
13954 {
13955         if (!HAS_FBC(dev_priv))
13956                 return false;
13957
13958         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13959                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13960         else if (IS_IVYBRIDGE(dev_priv))
13961                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13962                         i9xx_plane == PLANE_C;
13963         else if (INTEL_GEN(dev_priv) >= 4)
13964                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13965         else
13966                 return i9xx_plane == PLANE_A;
13967 }
13968
13969 static struct intel_plane *
13970 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13971 {
13972         struct intel_plane *plane;
13973         const struct drm_plane_funcs *plane_funcs;
13974         unsigned int supported_rotations;
13975         unsigned int possible_crtcs;
13976         const u64 *modifiers;
13977         const u32 *formats;
13978         int num_formats;
13979         int ret;
13980
13981         if (INTEL_GEN(dev_priv) >= 9)
13982                 return skl_universal_plane_create(dev_priv, pipe,
13983                                                   PLANE_PRIMARY);
13984
13985         plane = intel_plane_alloc();
13986         if (IS_ERR(plane))
13987                 return plane;
13988
13989         plane->pipe = pipe;
13990         /*
13991          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13992          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13993          */
13994         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13995                 plane->i9xx_plane = (enum i9xx_plane_id) !pipe;
13996         else
13997                 plane->i9xx_plane = (enum i9xx_plane_id) pipe;
13998         plane->id = PLANE_PRIMARY;
13999         plane->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, plane->id);
14000
14001         plane->has_fbc = i9xx_plane_has_fbc(dev_priv, plane->i9xx_plane);
14002         if (plane->has_fbc) {
14003                 struct intel_fbc *fbc = &dev_priv->fbc;
14004
14005                 fbc->possible_framebuffer_bits |= plane->frontbuffer_bit;
14006         }
14007
14008         if (INTEL_GEN(dev_priv) >= 4) {
14009                 formats = i965_primary_formats;
14010                 num_formats = ARRAY_SIZE(i965_primary_formats);
14011                 modifiers = i9xx_format_modifiers;
14012
14013                 plane->max_stride = i9xx_plane_max_stride;
14014                 plane->update_plane = i9xx_update_plane;
14015                 plane->disable_plane = i9xx_disable_plane;
14016                 plane->get_hw_state = i9xx_plane_get_hw_state;
14017                 plane->check_plane = i9xx_plane_check;
14018
14019                 plane_funcs = &i965_plane_funcs;
14020         } else {
14021                 formats = i8xx_primary_formats;
14022                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
14023                 modifiers = i9xx_format_modifiers;
14024
14025                 plane->max_stride = i9xx_plane_max_stride;
14026                 plane->update_plane = i9xx_update_plane;
14027                 plane->disable_plane = i9xx_disable_plane;
14028                 plane->get_hw_state = i9xx_plane_get_hw_state;
14029                 plane->check_plane = i9xx_plane_check;
14030
14031                 plane_funcs = &i8xx_plane_funcs;
14032         }
14033
14034         possible_crtcs = BIT(pipe);
14035
14036         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
14037                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
14038                                                possible_crtcs, plane_funcs,
14039                                                formats, num_formats, modifiers,
14040                                                DRM_PLANE_TYPE_PRIMARY,
14041                                                "primary %c", pipe_name(pipe));
14042         else
14043                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
14044                                                possible_crtcs, plane_funcs,
14045                                                formats, num_formats, modifiers,
14046                                                DRM_PLANE_TYPE_PRIMARY,
14047                                                "plane %c",
14048                                                plane_name(plane->i9xx_plane));
14049         if (ret)
14050                 goto fail;
14051
14052         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
14053                 supported_rotations =
14054                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
14055                         DRM_MODE_REFLECT_X;
14056         } else if (INTEL_GEN(dev_priv) >= 4) {
14057                 supported_rotations =
14058                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
14059         } else {
14060                 supported_rotations = DRM_MODE_ROTATE_0;
14061         }
14062
14063         if (INTEL_GEN(dev_priv) >= 4)
14064                 drm_plane_create_rotation_property(&plane->base,
14065                                                    DRM_MODE_ROTATE_0,
14066                                                    supported_rotations);
14067
14068         drm_plane_helper_add(&plane->base, &intel_plane_helper_funcs);
14069
14070         return plane;
14071
14072 fail:
14073         intel_plane_free(plane);
14074
14075         return ERR_PTR(ret);
14076 }
14077
14078 static struct intel_plane *
14079 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
14080                           enum pipe pipe)
14081 {
14082         unsigned int possible_crtcs;
14083         struct intel_plane *cursor;
14084         int ret;
14085
14086         cursor = intel_plane_alloc();
14087         if (IS_ERR(cursor))
14088                 return cursor;
14089
14090         cursor->pipe = pipe;
14091         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
14092         cursor->id = PLANE_CURSOR;
14093         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
14094
14095         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14096                 cursor->max_stride = i845_cursor_max_stride;
14097                 cursor->update_plane = i845_update_cursor;
14098                 cursor->disable_plane = i845_disable_cursor;
14099                 cursor->get_hw_state = i845_cursor_get_hw_state;
14100                 cursor->check_plane = i845_check_cursor;
14101         } else {
14102                 cursor->max_stride = i9xx_cursor_max_stride;
14103                 cursor->update_plane = i9xx_update_cursor;
14104                 cursor->disable_plane = i9xx_disable_cursor;
14105                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
14106                 cursor->check_plane = i9xx_check_cursor;
14107         }
14108
14109         cursor->cursor.base = ~0;
14110         cursor->cursor.cntl = ~0;
14111
14112         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
14113                 cursor->cursor.size = ~0;
14114
14115         possible_crtcs = BIT(pipe);
14116
14117         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
14118                                        possible_crtcs, &intel_cursor_plane_funcs,
14119                                        intel_cursor_formats,
14120                                        ARRAY_SIZE(intel_cursor_formats),
14121                                        cursor_format_modifiers,
14122                                        DRM_PLANE_TYPE_CURSOR,
14123                                        "cursor %c", pipe_name(pipe));
14124         if (ret)
14125                 goto fail;
14126
14127         if (INTEL_GEN(dev_priv) >= 4)
14128                 drm_plane_create_rotation_property(&cursor->base,
14129                                                    DRM_MODE_ROTATE_0,
14130                                                    DRM_MODE_ROTATE_0 |
14131                                                    DRM_MODE_ROTATE_180);
14132
14133         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
14134
14135         return cursor;
14136
14137 fail:
14138         intel_plane_free(cursor);
14139
14140         return ERR_PTR(ret);
14141 }
14142
14143 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
14144                                     struct intel_crtc_state *crtc_state)
14145 {
14146         struct intel_crtc_scaler_state *scaler_state =
14147                 &crtc_state->scaler_state;
14148         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14149         int i;
14150
14151         crtc->num_scalers = RUNTIME_INFO(dev_priv)->num_scalers[crtc->pipe];
14152         if (!crtc->num_scalers)
14153                 return;
14154
14155         for (i = 0; i < crtc->num_scalers; i++) {
14156                 struct intel_scaler *scaler = &scaler_state->scalers[i];
14157
14158                 scaler->in_use = 0;
14159                 scaler->mode = 0;
14160         }
14161
14162         scaler_state->scaler_id = -1;
14163 }
14164
14165 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
14166 {
14167         struct intel_crtc *intel_crtc;
14168         struct intel_crtc_state *crtc_state = NULL;
14169         struct intel_plane *primary = NULL;
14170         struct intel_plane *cursor = NULL;
14171         int sprite, ret;
14172
14173         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14174         if (!intel_crtc)
14175                 return -ENOMEM;
14176
14177         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14178         if (!crtc_state) {
14179                 ret = -ENOMEM;
14180                 goto fail;
14181         }
14182         intel_crtc->config = crtc_state;
14183         intel_crtc->base.state = &crtc_state->base;
14184         crtc_state->base.crtc = &intel_crtc->base;
14185
14186         primary = intel_primary_plane_create(dev_priv, pipe);
14187         if (IS_ERR(primary)) {
14188                 ret = PTR_ERR(primary);
14189                 goto fail;
14190         }
14191         intel_crtc->plane_ids_mask |= BIT(primary->id);
14192
14193         for_each_sprite(dev_priv, pipe, sprite) {
14194                 struct intel_plane *plane;
14195
14196                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
14197                 if (IS_ERR(plane)) {
14198                         ret = PTR_ERR(plane);
14199                         goto fail;
14200                 }
14201                 intel_crtc->plane_ids_mask |= BIT(plane->id);
14202         }
14203
14204         cursor = intel_cursor_plane_create(dev_priv, pipe);
14205         if (IS_ERR(cursor)) {
14206                 ret = PTR_ERR(cursor);
14207                 goto fail;
14208         }
14209         intel_crtc->plane_ids_mask |= BIT(cursor->id);
14210
14211         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
14212                                         &primary->base, &cursor->base,
14213                                         &intel_crtc_funcs,
14214                                         "pipe %c", pipe_name(pipe));
14215         if (ret)
14216                 goto fail;
14217
14218         intel_crtc->pipe = pipe;
14219
14220         /* initialize shared scalers */
14221         intel_crtc_init_scalers(intel_crtc, crtc_state);
14222
14223         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
14224                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
14225         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
14226
14227         if (INTEL_GEN(dev_priv) < 9) {
14228                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
14229
14230                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14231                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
14232                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
14233         }
14234
14235         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14236
14237         intel_color_init(intel_crtc);
14238
14239         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14240
14241         return 0;
14242
14243 fail:
14244         /*
14245          * drm_mode_config_cleanup() will free up any
14246          * crtcs/planes already initialized.
14247          */
14248         kfree(crtc_state);
14249         kfree(intel_crtc);
14250
14251         return ret;
14252 }
14253
14254 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
14255                                       struct drm_file *file)
14256 {
14257         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14258         struct drm_crtc *drmmode_crtc;
14259         struct intel_crtc *crtc;
14260
14261         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
14262         if (!drmmode_crtc)
14263                 return -ENOENT;
14264
14265         crtc = to_intel_crtc(drmmode_crtc);
14266         pipe_from_crtc_id->pipe = crtc->pipe;
14267
14268         return 0;
14269 }
14270
14271 static int intel_encoder_clones(struct intel_encoder *encoder)
14272 {
14273         struct drm_device *dev = encoder->base.dev;
14274         struct intel_encoder *source_encoder;
14275         int index_mask = 0;
14276         int entry = 0;
14277
14278         for_each_intel_encoder(dev, source_encoder) {
14279                 if (encoders_cloneable(encoder, source_encoder))
14280                         index_mask |= (1 << entry);
14281
14282                 entry++;
14283         }
14284
14285         return index_mask;
14286 }
14287
14288 static bool ilk_has_edp_a(struct drm_i915_private *dev_priv)
14289 {
14290         if (!IS_MOBILE(dev_priv))
14291                 return false;
14292
14293         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14294                 return false;
14295
14296         if (IS_GEN(dev_priv, 5) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14297                 return false;
14298
14299         return true;
14300 }
14301
14302 static bool intel_ddi_crt_present(struct drm_i915_private *dev_priv)
14303 {
14304         if (INTEL_GEN(dev_priv) >= 9)
14305                 return false;
14306
14307         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14308                 return false;
14309
14310         if (HAS_PCH_LPT_H(dev_priv) &&
14311             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14312                 return false;
14313
14314         /* DDI E can't be used if DDI A requires 4 lanes */
14315         if (I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14316                 return false;
14317
14318         if (!dev_priv->vbt.int_crt_support)
14319                 return false;
14320
14321         return true;
14322 }
14323
14324 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14325 {
14326         int pps_num;
14327         int pps_idx;
14328
14329         if (HAS_DDI(dev_priv))
14330                 return;
14331         /*
14332          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14333          * everywhere where registers can be write protected.
14334          */
14335         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14336                 pps_num = 2;
14337         else
14338                 pps_num = 1;
14339
14340         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14341                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14342
14343                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14344                 I915_WRITE(PP_CONTROL(pps_idx), val);
14345         }
14346 }
14347
14348 static void intel_pps_init(struct drm_i915_private *dev_priv)
14349 {
14350         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14351                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14352         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14353                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14354         else
14355                 dev_priv->pps_mmio_base = PPS_BASE;
14356
14357         intel_pps_unlock_regs_wa(dev_priv);
14358 }
14359
14360 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14361 {
14362         struct intel_encoder *encoder;
14363         bool dpd_is_edp = false;
14364
14365         intel_pps_init(dev_priv);
14366
14367         if (!HAS_DISPLAY(dev_priv))
14368                 return;
14369
14370         if (IS_ICELAKE(dev_priv)) {
14371                 intel_ddi_init(dev_priv, PORT_A);
14372                 intel_ddi_init(dev_priv, PORT_B);
14373                 intel_ddi_init(dev_priv, PORT_C);
14374                 intel_ddi_init(dev_priv, PORT_D);
14375                 intel_ddi_init(dev_priv, PORT_E);
14376                 /*
14377                  * On some ICL SKUs port F is not present. No strap bits for
14378                  * this, so rely on VBT.
14379                  */
14380                 if (intel_bios_is_port_present(dev_priv, PORT_F))
14381                         intel_ddi_init(dev_priv, PORT_F);
14382
14383                 icl_dsi_init(dev_priv);
14384         } else if (IS_GEN9_LP(dev_priv)) {
14385                 /*
14386                  * FIXME: Broxton doesn't support port detection via the
14387                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14388                  * detect the ports.
14389                  */
14390                 intel_ddi_init(dev_priv, PORT_A);
14391                 intel_ddi_init(dev_priv, PORT_B);
14392                 intel_ddi_init(dev_priv, PORT_C);
14393
14394                 vlv_dsi_init(dev_priv);
14395         } else if (HAS_DDI(dev_priv)) {
14396                 int found;
14397
14398                 if (intel_ddi_crt_present(dev_priv))
14399                         intel_crt_init(dev_priv);
14400
14401                 /*
14402                  * Haswell uses DDI functions to detect digital outputs.
14403                  * On SKL pre-D0 the strap isn't connected, so we assume
14404                  * it's there.
14405                  */
14406                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14407                 /* WaIgnoreDDIAStrap: skl */
14408                 if (found || IS_GEN9_BC(dev_priv))
14409                         intel_ddi_init(dev_priv, PORT_A);
14410
14411                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
14412                  * register */
14413                 found = I915_READ(SFUSE_STRAP);
14414
14415                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14416                         intel_ddi_init(dev_priv, PORT_B);
14417                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14418                         intel_ddi_init(dev_priv, PORT_C);
14419                 if (found & SFUSE_STRAP_DDID_DETECTED)
14420                         intel_ddi_init(dev_priv, PORT_D);
14421                 if (found & SFUSE_STRAP_DDIF_DETECTED)
14422                         intel_ddi_init(dev_priv, PORT_F);
14423                 /*
14424                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14425                  */
14426                 if (IS_GEN9_BC(dev_priv) &&
14427                     intel_bios_is_port_present(dev_priv, PORT_E))
14428                         intel_ddi_init(dev_priv, PORT_E);
14429
14430         } else if (HAS_PCH_SPLIT(dev_priv)) {
14431                 int found;
14432
14433                 /*
14434                  * intel_edp_init_connector() depends on this completing first,
14435                  * to prevent the registration of both eDP and LVDS and the
14436                  * incorrect sharing of the PPS.
14437                  */
14438                 intel_lvds_init(dev_priv);
14439                 intel_crt_init(dev_priv);
14440
14441                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14442
14443                 if (ilk_has_edp_a(dev_priv))
14444                         intel_dp_init(dev_priv, DP_A, PORT_A);
14445
14446                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14447                         /* PCH SDVOB multiplex with HDMIB */
14448                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14449                         if (!found)
14450                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14451                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14452                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14453                 }
14454
14455                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14456                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14457
14458                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14459                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14460
14461                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14462                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14463
14464                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14465                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14466         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14467                 bool has_edp, has_port;
14468
14469                 if (IS_VALLEYVIEW(dev_priv) && dev_priv->vbt.int_crt_support)
14470                         intel_crt_init(dev_priv);
14471
14472                 /*
14473                  * The DP_DETECTED bit is the latched state of the DDC
14474                  * SDA pin at boot. However since eDP doesn't require DDC
14475                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14476                  * eDP ports may have been muxed to an alternate function.
14477                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14478                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14479                  * detect eDP ports.
14480                  *
14481                  * Sadly the straps seem to be missing sometimes even for HDMI
14482                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14483                  * and VBT for the presence of the port. Additionally we can't
14484                  * trust the port type the VBT declares as we've seen at least
14485                  * HDMI ports that the VBT claim are DP or eDP.
14486                  */
14487                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14488                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14489                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14490                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14491                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14492                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14493
14494                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14495                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14496                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14497                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14498                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14499                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14500
14501                 if (IS_CHERRYVIEW(dev_priv)) {
14502                         /*
14503                          * eDP not supported on port D,
14504                          * so no need to worry about it
14505                          */
14506                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14507                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14508                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14509                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14510                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14511                 }
14512
14513                 vlv_dsi_init(dev_priv);
14514         } else if (IS_PINEVIEW(dev_priv)) {
14515                 intel_lvds_init(dev_priv);
14516                 intel_crt_init(dev_priv);
14517         } else if (IS_GEN_RANGE(dev_priv, 3, 4)) {
14518                 bool found = false;
14519
14520                 if (IS_MOBILE(dev_priv))
14521                         intel_lvds_init(dev_priv);
14522
14523                 intel_crt_init(dev_priv);
14524
14525                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14526                         DRM_DEBUG_KMS("probing SDVOB\n");
14527                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14528                         if (!found && IS_G4X(dev_priv)) {
14529                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14530                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14531                         }
14532
14533                         if (!found && IS_G4X(dev_priv))
14534                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14535                 }
14536
14537                 /* Before G4X SDVOC doesn't have its own detect register */
14538
14539                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14540                         DRM_DEBUG_KMS("probing SDVOC\n");
14541                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14542                 }
14543
14544                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14545
14546                         if (IS_G4X(dev_priv)) {
14547                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14548                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14549                         }
14550                         if (IS_G4X(dev_priv))
14551                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14552                 }
14553
14554                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14555                         intel_dp_init(dev_priv, DP_D, PORT_D);
14556
14557                 if (SUPPORTS_TV(dev_priv))
14558                         intel_tv_init(dev_priv);
14559         } else if (IS_GEN(dev_priv, 2)) {
14560                 if (IS_I85X(dev_priv))
14561                         intel_lvds_init(dev_priv);
14562
14563                 intel_crt_init(dev_priv);
14564                 intel_dvo_init(dev_priv);
14565         }
14566
14567         intel_psr_init(dev_priv);
14568
14569         for_each_intel_encoder(&dev_priv->drm, encoder) {
14570                 encoder->base.possible_crtcs = encoder->crtc_mask;
14571                 encoder->base.possible_clones =
14572                         intel_encoder_clones(encoder);
14573         }
14574
14575         intel_init_pch_refclk(dev_priv);
14576
14577         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14578 }
14579
14580 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14581 {
14582         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14583         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14584
14585         drm_framebuffer_cleanup(fb);
14586
14587         i915_gem_object_lock(obj);
14588         WARN_ON(!obj->framebuffer_references--);
14589         i915_gem_object_unlock(obj);
14590
14591         i915_gem_object_put(obj);
14592
14593         kfree(intel_fb);
14594 }
14595
14596 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14597                                                 struct drm_file *file,
14598                                                 unsigned int *handle)
14599 {
14600         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14601
14602         if (obj->userptr.mm) {
14603                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14604                 return -EINVAL;
14605         }
14606
14607         return drm_gem_handle_create(file, &obj->base, handle);
14608 }
14609
14610 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14611                                         struct drm_file *file,
14612                                         unsigned flags, unsigned color,
14613                                         struct drm_clip_rect *clips,
14614                                         unsigned num_clips)
14615 {
14616         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14617
14618         i915_gem_object_flush_if_display(obj);
14619         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14620
14621         return 0;
14622 }
14623
14624 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14625         .destroy = intel_user_framebuffer_destroy,
14626         .create_handle = intel_user_framebuffer_create_handle,
14627         .dirty = intel_user_framebuffer_dirty,
14628 };
14629
14630 static
14631 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14632                          u32 pixel_format, u64 fb_modifier)
14633 {
14634         struct intel_crtc *crtc;
14635         struct intel_plane *plane;
14636
14637         /*
14638          * We assume the primary plane for pipe A has
14639          * the highest stride limits of them all.
14640          */
14641         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
14642         plane = to_intel_plane(crtc->base.primary);
14643
14644         return plane->max_stride(plane, pixel_format, fb_modifier,
14645                                  DRM_MODE_ROTATE_0);
14646 }
14647
14648 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14649                                   struct drm_i915_gem_object *obj,
14650                                   struct drm_mode_fb_cmd2 *mode_cmd)
14651 {
14652         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14653         struct drm_framebuffer *fb = &intel_fb->base;
14654         u32 pitch_limit;
14655         unsigned int tiling, stride;
14656         int ret = -EINVAL;
14657         int i;
14658
14659         i915_gem_object_lock(obj);
14660         obj->framebuffer_references++;
14661         tiling = i915_gem_object_get_tiling(obj);
14662         stride = i915_gem_object_get_stride(obj);
14663         i915_gem_object_unlock(obj);
14664
14665         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14666                 /*
14667                  * If there's a fence, enforce that
14668                  * the fb modifier and tiling mode match.
14669                  */
14670                 if (tiling != I915_TILING_NONE &&
14671                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14672                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14673                         goto err;
14674                 }
14675         } else {
14676                 if (tiling == I915_TILING_X) {
14677                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14678                 } else if (tiling == I915_TILING_Y) {
14679                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14680                         goto err;
14681                 }
14682         }
14683
14684         if (!drm_any_plane_has_format(&dev_priv->drm,
14685                                       mode_cmd->pixel_format,
14686                                       mode_cmd->modifier[0])) {
14687                 struct drm_format_name_buf format_name;
14688
14689                 DRM_DEBUG_KMS("unsupported pixel format %s / modifier 0x%llx\n",
14690                               drm_get_format_name(mode_cmd->pixel_format,
14691                                                   &format_name),
14692                               mode_cmd->modifier[0]);
14693                 goto err;
14694         }
14695
14696         /*
14697          * gen2/3 display engine uses the fence if present,
14698          * so the tiling mode must match the fb modifier exactly.
14699          */
14700         if (INTEL_GEN(dev_priv) < 4 &&
14701             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14702                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14703                 goto err;
14704         }
14705
14706         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->pixel_format,
14707                                            mode_cmd->modifier[0]);
14708         if (mode_cmd->pitches[0] > pitch_limit) {
14709                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14710                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14711                               "tiled" : "linear",
14712                               mode_cmd->pitches[0], pitch_limit);
14713                 goto err;
14714         }
14715
14716         /*
14717          * If there's a fence, enforce that
14718          * the fb pitch and fence stride match.
14719          */
14720         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14721                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14722                               mode_cmd->pitches[0], stride);
14723                 goto err;
14724         }
14725
14726         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14727         if (mode_cmd->offsets[0] != 0)
14728                 goto err;
14729
14730         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14731
14732         for (i = 0; i < fb->format->num_planes; i++) {
14733                 u32 stride_alignment;
14734
14735                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14736                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14737                         goto err;
14738                 }
14739
14740                 stride_alignment = intel_fb_stride_alignment(fb, i);
14741
14742                 /*
14743                  * Display WA #0531: skl,bxt,kbl,glk
14744                  *
14745                  * Render decompression and plane width > 3840
14746                  * combined with horizontal panning requires the
14747                  * plane stride to be a multiple of 4. We'll just
14748                  * require the entire fb to accommodate that to avoid
14749                  * potential runtime errors at plane configuration time.
14750                  */
14751                 if (IS_GEN(dev_priv, 9) && i == 0 && fb->width > 3840 &&
14752                     is_ccs_modifier(fb->modifier))
14753                         stride_alignment *= 4;
14754
14755                 if (fb->pitches[i] & (stride_alignment - 1)) {
14756                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14757                                       i, fb->pitches[i], stride_alignment);
14758                         goto err;
14759                 }
14760
14761                 fb->obj[i] = &obj->base;
14762         }
14763
14764         ret = intel_fill_fb_info(dev_priv, fb);
14765         if (ret)
14766                 goto err;
14767
14768         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14769         if (ret) {
14770                 DRM_ERROR("framebuffer init failed %d\n", ret);
14771                 goto err;
14772         }
14773
14774         return 0;
14775
14776 err:
14777         i915_gem_object_lock(obj);
14778         obj->framebuffer_references--;
14779         i915_gem_object_unlock(obj);
14780         return ret;
14781 }
14782
14783 static struct drm_framebuffer *
14784 intel_user_framebuffer_create(struct drm_device *dev,
14785                               struct drm_file *filp,
14786                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14787 {
14788         struct drm_framebuffer *fb;
14789         struct drm_i915_gem_object *obj;
14790         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14791
14792         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14793         if (!obj)
14794                 return ERR_PTR(-ENOENT);
14795
14796         fb = intel_framebuffer_create(obj, &mode_cmd);
14797         if (IS_ERR(fb))
14798                 i915_gem_object_put(obj);
14799
14800         return fb;
14801 }
14802
14803 static void intel_atomic_state_free(struct drm_atomic_state *state)
14804 {
14805         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14806
14807         drm_atomic_state_default_release(state);
14808
14809         i915_sw_fence_fini(&intel_state->commit_ready);
14810
14811         kfree(state);
14812 }
14813
14814 static enum drm_mode_status
14815 intel_mode_valid(struct drm_device *dev,
14816                  const struct drm_display_mode *mode)
14817 {
14818         struct drm_i915_private *dev_priv = to_i915(dev);
14819         int hdisplay_max, htotal_max;
14820         int vdisplay_max, vtotal_max;
14821
14822         /*
14823          * Can't reject DBLSCAN here because Xorg ddxen can add piles
14824          * of DBLSCAN modes to the output's mode list when they detect
14825          * the scaling mode property on the connector. And they don't
14826          * ask the kernel to validate those modes in any way until
14827          * modeset time at which point the client gets a protocol error.
14828          * So in order to not upset those clients we silently ignore the
14829          * DBLSCAN flag on such connectors. For other connectors we will
14830          * reject modes with the DBLSCAN flag in encoder->compute_config().
14831          * And we always reject DBLSCAN modes in connector->mode_valid()
14832          * as we never want such modes on the connector's mode list.
14833          */
14834
14835         if (mode->vscan > 1)
14836                 return MODE_NO_VSCAN;
14837
14838         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14839                 return MODE_H_ILLEGAL;
14840
14841         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14842                            DRM_MODE_FLAG_NCSYNC |
14843                            DRM_MODE_FLAG_PCSYNC))
14844                 return MODE_HSYNC;
14845
14846         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14847                            DRM_MODE_FLAG_PIXMUX |
14848                            DRM_MODE_FLAG_CLKDIV2))
14849                 return MODE_BAD;
14850
14851         if (INTEL_GEN(dev_priv) >= 9 ||
14852             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
14853                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
14854                 vdisplay_max = 4096;
14855                 htotal_max = 8192;
14856                 vtotal_max = 8192;
14857         } else if (INTEL_GEN(dev_priv) >= 3) {
14858                 hdisplay_max = 4096;
14859                 vdisplay_max = 4096;
14860                 htotal_max = 8192;
14861                 vtotal_max = 8192;
14862         } else {
14863                 hdisplay_max = 2048;
14864                 vdisplay_max = 2048;
14865                 htotal_max = 4096;
14866                 vtotal_max = 4096;
14867         }
14868
14869         if (mode->hdisplay > hdisplay_max ||
14870             mode->hsync_start > htotal_max ||
14871             mode->hsync_end > htotal_max ||
14872             mode->htotal > htotal_max)
14873                 return MODE_H_ILLEGAL;
14874
14875         if (mode->vdisplay > vdisplay_max ||
14876             mode->vsync_start > vtotal_max ||
14877             mode->vsync_end > vtotal_max ||
14878             mode->vtotal > vtotal_max)
14879                 return MODE_V_ILLEGAL;
14880
14881         return MODE_OK;
14882 }
14883
14884 static const struct drm_mode_config_funcs intel_mode_funcs = {
14885         .fb_create = intel_user_framebuffer_create,
14886         .get_format_info = intel_get_format_info,
14887         .output_poll_changed = intel_fbdev_output_poll_changed,
14888         .mode_valid = intel_mode_valid,
14889         .atomic_check = intel_atomic_check,
14890         .atomic_commit = intel_atomic_commit,
14891         .atomic_state_alloc = intel_atomic_state_alloc,
14892         .atomic_state_clear = intel_atomic_state_clear,
14893         .atomic_state_free = intel_atomic_state_free,
14894 };
14895
14896 /**
14897  * intel_init_display_hooks - initialize the display modesetting hooks
14898  * @dev_priv: device private
14899  */
14900 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14901 {
14902         intel_init_cdclk_hooks(dev_priv);
14903
14904         if (INTEL_GEN(dev_priv) >= 9) {
14905                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14906                 dev_priv->display.get_initial_plane_config =
14907                         skylake_get_initial_plane_config;
14908                 dev_priv->display.crtc_compute_clock =
14909                         haswell_crtc_compute_clock;
14910                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14911                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14912         } else if (HAS_DDI(dev_priv)) {
14913                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14914                 dev_priv->display.get_initial_plane_config =
14915                         i9xx_get_initial_plane_config;
14916                 dev_priv->display.crtc_compute_clock =
14917                         haswell_crtc_compute_clock;
14918                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14919                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14920         } else if (HAS_PCH_SPLIT(dev_priv)) {
14921                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14922                 dev_priv->display.get_initial_plane_config =
14923                         i9xx_get_initial_plane_config;
14924                 dev_priv->display.crtc_compute_clock =
14925                         ironlake_crtc_compute_clock;
14926                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14927                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14928         } else if (IS_CHERRYVIEW(dev_priv)) {
14929                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14930                 dev_priv->display.get_initial_plane_config =
14931                         i9xx_get_initial_plane_config;
14932                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14933                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14934                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14935         } else if (IS_VALLEYVIEW(dev_priv)) {
14936                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14937                 dev_priv->display.get_initial_plane_config =
14938                         i9xx_get_initial_plane_config;
14939                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14940                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14941                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14942         } else if (IS_G4X(dev_priv)) {
14943                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14944                 dev_priv->display.get_initial_plane_config =
14945                         i9xx_get_initial_plane_config;
14946                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14947                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14948                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14949         } else if (IS_PINEVIEW(dev_priv)) {
14950                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14951                 dev_priv->display.get_initial_plane_config =
14952                         i9xx_get_initial_plane_config;
14953                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14954                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14955                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14956         } else if (!IS_GEN(dev_priv, 2)) {
14957                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14958                 dev_priv->display.get_initial_plane_config =
14959                         i9xx_get_initial_plane_config;
14960                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14961                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14962                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14963         } else {
14964                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14965                 dev_priv->display.get_initial_plane_config =
14966                         i9xx_get_initial_plane_config;
14967                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14968                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14969                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14970         }
14971
14972         if (IS_GEN(dev_priv, 5)) {
14973                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14974         } else if (IS_GEN(dev_priv, 6)) {
14975                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14976         } else if (IS_IVYBRIDGE(dev_priv)) {
14977                 /* FIXME: detect B0+ stepping and use auto training */
14978                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14979         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14980                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14981         }
14982
14983         if (INTEL_GEN(dev_priv) >= 9)
14984                 dev_priv->display.update_crtcs = skl_update_crtcs;
14985         else
14986                 dev_priv->display.update_crtcs = intel_update_crtcs;
14987 }
14988
14989 /* Disable the VGA plane that we never use */
14990 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14991 {
14992         struct pci_dev *pdev = dev_priv->drm.pdev;
14993         u8 sr1;
14994         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14995
14996         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14997         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14998         outb(SR01, VGA_SR_INDEX);
14999         sr1 = inb(VGA_SR_DATA);
15000         outb(sr1 | 1<<5, VGA_SR_DATA);
15001         vga_put(pdev, VGA_RSRC_LEGACY_IO);
15002         udelay(300);
15003
15004         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15005         POSTING_READ(vga_reg);
15006 }
15007
15008 void intel_modeset_init_hw(struct drm_device *dev)
15009 {
15010         struct drm_i915_private *dev_priv = to_i915(dev);
15011
15012         intel_update_cdclk(dev_priv);
15013         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
15014         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
15015 }
15016
15017 /*
15018  * Calculate what we think the watermarks should be for the state we've read
15019  * out of the hardware and then immediately program those watermarks so that
15020  * we ensure the hardware settings match our internal state.
15021  *
15022  * We can calculate what we think WM's should be by creating a duplicate of the
15023  * current state (which was constructed during hardware readout) and running it
15024  * through the atomic check code to calculate new watermark values in the
15025  * state object.
15026  */
15027 static void sanitize_watermarks(struct drm_device *dev)
15028 {
15029         struct drm_i915_private *dev_priv = to_i915(dev);
15030         struct drm_atomic_state *state;
15031         struct intel_atomic_state *intel_state;
15032         struct drm_crtc *crtc;
15033         struct drm_crtc_state *cstate;
15034         struct drm_modeset_acquire_ctx ctx;
15035         int ret;
15036         int i;
15037
15038         /* Only supported on platforms that use atomic watermark design */
15039         if (!dev_priv->display.optimize_watermarks)
15040                 return;
15041
15042         /*
15043          * We need to hold connection_mutex before calling duplicate_state so
15044          * that the connector loop is protected.
15045          */
15046         drm_modeset_acquire_init(&ctx, 0);
15047 retry:
15048         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15049         if (ret == -EDEADLK) {
15050                 drm_modeset_backoff(&ctx);
15051                 goto retry;
15052         } else if (WARN_ON(ret)) {
15053                 goto fail;
15054         }
15055
15056         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15057         if (WARN_ON(IS_ERR(state)))
15058                 goto fail;
15059
15060         intel_state = to_intel_atomic_state(state);
15061
15062         /*
15063          * Hardware readout is the only time we don't want to calculate
15064          * intermediate watermarks (since we don't trust the current
15065          * watermarks).
15066          */
15067         if (!HAS_GMCH_DISPLAY(dev_priv))
15068                 intel_state->skip_intermediate_wm = true;
15069
15070         ret = intel_atomic_check(dev, state);
15071         if (ret) {
15072                 /*
15073                  * If we fail here, it means that the hardware appears to be
15074                  * programmed in a way that shouldn't be possible, given our
15075                  * understanding of watermark requirements.  This might mean a
15076                  * mistake in the hardware readout code or a mistake in the
15077                  * watermark calculations for a given platform.  Raise a WARN
15078                  * so that this is noticeable.
15079                  *
15080                  * If this actually happens, we'll have to just leave the
15081                  * BIOS-programmed watermarks untouched and hope for the best.
15082                  */
15083                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15084                 goto put_state;
15085         }
15086
15087         /* Write calculated watermark values back */
15088         for_each_new_crtc_in_state(state, crtc, cstate, i) {
15089                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15090
15091                 cs->wm.need_postvbl_update = true;
15092                 dev_priv->display.optimize_watermarks(intel_state, cs);
15093
15094                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
15095         }
15096
15097 put_state:
15098         drm_atomic_state_put(state);
15099 fail:
15100         drm_modeset_drop_locks(&ctx);
15101         drm_modeset_acquire_fini(&ctx);
15102 }
15103
15104 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
15105 {
15106         if (IS_GEN(dev_priv, 5)) {
15107                 u32 fdi_pll_clk =
15108                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
15109
15110                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
15111         } else if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv)) {
15112                 dev_priv->fdi_pll_freq = 270000;
15113         } else {
15114                 return;
15115         }
15116
15117         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
15118 }
15119
15120 static int intel_initial_commit(struct drm_device *dev)
15121 {
15122         struct drm_atomic_state *state = NULL;
15123         struct drm_modeset_acquire_ctx ctx;
15124         struct drm_crtc *crtc;
15125         struct drm_crtc_state *crtc_state;
15126         int ret = 0;
15127
15128         state = drm_atomic_state_alloc(dev);
15129         if (!state)
15130                 return -ENOMEM;
15131
15132         drm_modeset_acquire_init(&ctx, 0);
15133
15134 retry:
15135         state->acquire_ctx = &ctx;
15136
15137         drm_for_each_crtc(crtc, dev) {
15138                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
15139                 if (IS_ERR(crtc_state)) {
15140                         ret = PTR_ERR(crtc_state);
15141                         goto out;
15142                 }
15143
15144                 if (crtc_state->active) {
15145                         ret = drm_atomic_add_affected_planes(state, crtc);
15146                         if (ret)
15147                                 goto out;
15148
15149                         /*
15150                          * FIXME hack to force a LUT update to avoid the
15151                          * plane update forcing the pipe gamma on without
15152                          * having a proper LUT loaded. Remove once we
15153                          * have readout for pipe gamma enable.
15154                          */
15155                         crtc_state->color_mgmt_changed = true;
15156                 }
15157         }
15158
15159         ret = drm_atomic_commit(state);
15160
15161 out:
15162         if (ret == -EDEADLK) {
15163                 drm_atomic_state_clear(state);
15164                 drm_modeset_backoff(&ctx);
15165                 goto retry;
15166         }
15167
15168         drm_atomic_state_put(state);
15169
15170         drm_modeset_drop_locks(&ctx);
15171         drm_modeset_acquire_fini(&ctx);
15172
15173         return ret;
15174 }
15175
15176 int intel_modeset_init(struct drm_device *dev)
15177 {
15178         struct drm_i915_private *dev_priv = to_i915(dev);
15179         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15180         enum pipe pipe;
15181         struct intel_crtc *crtc;
15182         int ret;
15183
15184         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15185
15186         drm_mode_config_init(dev);
15187
15188         dev->mode_config.min_width = 0;
15189         dev->mode_config.min_height = 0;
15190
15191         dev->mode_config.preferred_depth = 24;
15192         dev->mode_config.prefer_shadow = 1;
15193
15194         dev->mode_config.allow_fb_modifiers = true;
15195
15196         dev->mode_config.funcs = &intel_mode_funcs;
15197
15198         init_llist_head(&dev_priv->atomic_helper.free_list);
15199         INIT_WORK(&dev_priv->atomic_helper.free_work,
15200                   intel_atomic_helper_free_state_worker);
15201
15202         intel_init_quirks(dev_priv);
15203
15204         intel_fbc_init(dev_priv);
15205
15206         intel_init_pm(dev_priv);
15207
15208         /*
15209          * There may be no VBT; and if the BIOS enabled SSC we can
15210          * just keep using it to avoid unnecessary flicker.  Whereas if the
15211          * BIOS isn't using it, don't assume it will work even if the VBT
15212          * indicates as much.
15213          */
15214         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15215                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15216                                             DREF_SSC1_ENABLE);
15217
15218                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15219                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15220                                      bios_lvds_use_ssc ? "en" : "dis",
15221                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15222                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15223                 }
15224         }
15225
15226         /* maximum framebuffer dimensions */
15227         if (IS_GEN(dev_priv, 2)) {
15228                 dev->mode_config.max_width = 2048;
15229                 dev->mode_config.max_height = 2048;
15230         } else if (IS_GEN(dev_priv, 3)) {
15231                 dev->mode_config.max_width = 4096;
15232                 dev->mode_config.max_height = 4096;
15233         } else {
15234                 dev->mode_config.max_width = 8192;
15235                 dev->mode_config.max_height = 8192;
15236         }
15237
15238         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15239                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15240                 dev->mode_config.cursor_height = 1023;
15241         } else if (IS_GEN(dev_priv, 2)) {
15242                 dev->mode_config.cursor_width = 64;
15243                 dev->mode_config.cursor_height = 64;
15244         } else {
15245                 dev->mode_config.cursor_width = 256;
15246                 dev->mode_config.cursor_height = 256;
15247         }
15248
15249         dev->mode_config.fb_base = ggtt->gmadr.start;
15250
15251         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15252                       INTEL_INFO(dev_priv)->num_pipes,
15253                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15254
15255         for_each_pipe(dev_priv, pipe) {
15256                 ret = intel_crtc_init(dev_priv, pipe);
15257                 if (ret) {
15258                         drm_mode_config_cleanup(dev);
15259                         return ret;
15260                 }
15261         }
15262
15263         intel_shared_dpll_init(dev);
15264         intel_update_fdi_pll_freq(dev_priv);
15265
15266         intel_update_czclk(dev_priv);
15267         intel_modeset_init_hw(dev);
15268
15269         if (dev_priv->max_cdclk_freq == 0)
15270                 intel_update_max_cdclk(dev_priv);
15271
15272         /* Just disable it once at startup */
15273         i915_disable_vga(dev_priv);
15274         intel_setup_outputs(dev_priv);
15275
15276         drm_modeset_lock_all(dev);
15277         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15278         drm_modeset_unlock_all(dev);
15279
15280         for_each_intel_crtc(dev, crtc) {
15281                 struct intel_initial_plane_config plane_config = {};
15282
15283                 if (!crtc->active)
15284                         continue;
15285
15286                 /*
15287                  * Note that reserving the BIOS fb up front prevents us
15288                  * from stuffing other stolen allocations like the ring
15289                  * on top.  This prevents some ugliness at boot time, and
15290                  * can even allow for smooth boot transitions if the BIOS
15291                  * fb is large enough for the active pipe configuration.
15292                  */
15293                 dev_priv->display.get_initial_plane_config(crtc,
15294                                                            &plane_config);
15295
15296                 /*
15297                  * If the fb is shared between multiple heads, we'll
15298                  * just get the first one.
15299                  */
15300                 intel_find_initial_plane_obj(crtc, &plane_config);
15301         }
15302
15303         /*
15304          * Make sure hardware watermarks really match the state we read out.
15305          * Note that we need to do this after reconstructing the BIOS fb's
15306          * since the watermark calculation done here will use pstate->fb.
15307          */
15308         if (!HAS_GMCH_DISPLAY(dev_priv))
15309                 sanitize_watermarks(dev);
15310
15311         /*
15312          * Force all active planes to recompute their states. So that on
15313          * mode_setcrtc after probe, all the intel_plane_state variables
15314          * are already calculated and there is no assert_plane warnings
15315          * during bootup.
15316          */
15317         ret = intel_initial_commit(dev);
15318         if (ret)
15319                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15320
15321         return 0;
15322 }
15323
15324 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15325 {
15326         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15327         /* 640x480@60Hz, ~25175 kHz */
15328         struct dpll clock = {
15329                 .m1 = 18,
15330                 .m2 = 7,
15331                 .p1 = 13,
15332                 .p2 = 4,
15333                 .n = 2,
15334         };
15335         u32 dpll, fp;
15336         int i;
15337
15338         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15339
15340         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15341                       pipe_name(pipe), clock.vco, clock.dot);
15342
15343         fp = i9xx_dpll_compute_fp(&clock);
15344         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
15345                 DPLL_VGA_MODE_DIS |
15346                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15347                 PLL_P2_DIVIDE_BY_4 |
15348                 PLL_REF_INPUT_DREFCLK |
15349                 DPLL_VCO_ENABLE;
15350
15351         I915_WRITE(FP0(pipe), fp);
15352         I915_WRITE(FP1(pipe), fp);
15353
15354         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15355         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15356         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15357         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15358         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15359         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15360         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15361
15362         /*
15363          * Apparently we need to have VGA mode enabled prior to changing
15364          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15365          * dividers, even though the register value does change.
15366          */
15367         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15368         I915_WRITE(DPLL(pipe), dpll);
15369
15370         /* Wait for the clocks to stabilize. */
15371         POSTING_READ(DPLL(pipe));
15372         udelay(150);
15373
15374         /* The pixel multiplier can only be updated once the
15375          * DPLL is enabled and the clocks are stable.
15376          *
15377          * So write it again.
15378          */
15379         I915_WRITE(DPLL(pipe), dpll);
15380
15381         /* We do this three times for luck */
15382         for (i = 0; i < 3 ; i++) {
15383                 I915_WRITE(DPLL(pipe), dpll);
15384                 POSTING_READ(DPLL(pipe));
15385                 udelay(150); /* wait for warmup */
15386         }
15387
15388         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15389         POSTING_READ(PIPECONF(pipe));
15390
15391         intel_wait_for_pipe_scanline_moving(crtc);
15392 }
15393
15394 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15395 {
15396         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15397
15398         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15399                       pipe_name(pipe));
15400
15401         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15402         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15403         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15404         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15405         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
15406
15407         I915_WRITE(PIPECONF(pipe), 0);
15408         POSTING_READ(PIPECONF(pipe));
15409
15410         intel_wait_for_pipe_scanline_stopped(crtc);
15411
15412         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15413         POSTING_READ(DPLL(pipe));
15414 }
15415
15416 static void
15417 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15418 {
15419         struct intel_crtc *crtc;
15420
15421         if (INTEL_GEN(dev_priv) >= 4)
15422                 return;
15423
15424         for_each_intel_crtc(&dev_priv->drm, crtc) {
15425                 struct intel_plane *plane =
15426                         to_intel_plane(crtc->base.primary);
15427                 struct intel_crtc *plane_crtc;
15428                 enum pipe pipe;
15429
15430                 if (!plane->get_hw_state(plane, &pipe))
15431                         continue;
15432
15433                 if (pipe == crtc->pipe)
15434                         continue;
15435
15436                 DRM_DEBUG_KMS("[PLANE:%d:%s] attached to the wrong pipe, disabling plane\n",
15437                               plane->base.base.id, plane->base.name);
15438
15439                 plane_crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15440                 intel_plane_disable_noatomic(plane_crtc, plane);
15441         }
15442 }
15443
15444 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15445 {
15446         struct drm_device *dev = crtc->base.dev;
15447         struct intel_encoder *encoder;
15448
15449         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15450                 return true;
15451
15452         return false;
15453 }
15454
15455 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15456 {
15457         struct drm_device *dev = encoder->base.dev;
15458         struct intel_connector *connector;
15459
15460         for_each_connector_on_encoder(dev, &encoder->base, connector)
15461                 return connector;
15462
15463         return NULL;
15464 }
15465
15466 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15467                               enum pipe pch_transcoder)
15468 {
15469         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15470                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15471 }
15472
15473 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15474                                 struct drm_modeset_acquire_ctx *ctx)
15475 {
15476         struct drm_device *dev = crtc->base.dev;
15477         struct drm_i915_private *dev_priv = to_i915(dev);
15478         struct intel_crtc_state *crtc_state = to_intel_crtc_state(crtc->base.state);
15479         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
15480
15481         /* Clear any frame start delays used for debugging left by the BIOS */
15482         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15483                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15484
15485                 I915_WRITE(reg,
15486                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15487         }
15488
15489         if (crtc_state->base.active) {
15490                 struct intel_plane *plane;
15491
15492                 /* Disable everything but the primary plane */
15493                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15494                         const struct intel_plane_state *plane_state =
15495                                 to_intel_plane_state(plane->base.state);
15496
15497                         if (plane_state->base.visible &&
15498                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15499                                 intel_plane_disable_noatomic(crtc, plane);
15500                 }
15501
15502                 /*
15503                  * Disable any background color set by the BIOS, but enable the
15504                  * gamma and CSC to match how we program our planes.
15505                  */
15506                 if (INTEL_GEN(dev_priv) >= 9)
15507                         I915_WRITE(SKL_BOTTOM_COLOR(crtc->pipe),
15508                                    SKL_BOTTOM_COLOR_GAMMA_ENABLE |
15509                                    SKL_BOTTOM_COLOR_CSC_ENABLE);
15510         }
15511
15512         /* Adjust the state of the output pipe according to whether we
15513          * have active connectors/encoders. */
15514         if (crtc_state->base.active && !intel_crtc_has_encoders(crtc))
15515                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15516
15517         if (crtc_state->base.active || HAS_GMCH_DISPLAY(dev_priv)) {
15518                 /*
15519                  * We start out with underrun reporting disabled to avoid races.
15520                  * For correct bookkeeping mark this on active crtcs.
15521                  *
15522                  * Also on gmch platforms we dont have any hardware bits to
15523                  * disable the underrun reporting. Which means we need to start
15524                  * out with underrun reporting disabled also on inactive pipes,
15525                  * since otherwise we'll complain about the garbage we read when
15526                  * e.g. coming up after runtime pm.
15527                  *
15528                  * No protection against concurrent access is required - at
15529                  * worst a fifo underrun happens which also sets this to false.
15530                  */
15531                 crtc->cpu_fifo_underrun_disabled = true;
15532                 /*
15533                  * We track the PCH trancoder underrun reporting state
15534                  * within the crtc. With crtc for pipe A housing the underrun
15535                  * reporting state for PCH transcoder A, crtc for pipe B housing
15536                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15537                  * and marking underrun reporting as disabled for the non-existing
15538                  * PCH transcoders B and C would prevent enabling the south
15539                  * error interrupt (see cpt_can_enable_serr_int()).
15540                  */
15541                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15542                         crtc->pch_fifo_underrun_disabled = true;
15543         }
15544 }
15545
15546 static bool has_bogus_dpll_config(const struct intel_crtc_state *crtc_state)
15547 {
15548         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
15549
15550         /*
15551          * Some SNB BIOSen (eg. ASUS K53SV) are known to misprogram
15552          * the hardware when a high res displays plugged in. DPLL P
15553          * divider is zero, and the pipe timings are bonkers. We'll
15554          * try to disable everything in that case.
15555          *
15556          * FIXME would be nice to be able to sanitize this state
15557          * without several WARNs, but for now let's take the easy
15558          * road.
15559          */
15560         return IS_GEN(dev_priv, 6) &&
15561                 crtc_state->base.active &&
15562                 crtc_state->shared_dpll &&
15563                 crtc_state->port_clock == 0;
15564 }
15565
15566 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15567 {
15568         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
15569         struct intel_connector *connector;
15570         struct intel_crtc *crtc = to_intel_crtc(encoder->base.crtc);
15571         struct intel_crtc_state *crtc_state = crtc ?
15572                 to_intel_crtc_state(crtc->base.state) : NULL;
15573
15574         /* We need to check both for a crtc link (meaning that the
15575          * encoder is active and trying to read from a pipe) and the
15576          * pipe itself being active. */
15577         bool has_active_crtc = crtc_state &&
15578                 crtc_state->base.active;
15579
15580         if (crtc_state && has_bogus_dpll_config(crtc_state)) {
15581                 DRM_DEBUG_KMS("BIOS has misprogrammed the hardware. Disabling pipe %c\n",
15582                               pipe_name(crtc->pipe));
15583                 has_active_crtc = false;
15584         }
15585
15586         connector = intel_encoder_find_connector(encoder);
15587         if (connector && !has_active_crtc) {
15588                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15589                               encoder->base.base.id,
15590                               encoder->base.name);
15591
15592                 /* Connector is active, but has no active pipe. This is
15593                  * fallout from our resume register restoring. Disable
15594                  * the encoder manually again. */
15595                 if (crtc_state) {
15596                         struct drm_encoder *best_encoder;
15597
15598                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15599                                       encoder->base.base.id,
15600                                       encoder->base.name);
15601
15602                         /* avoid oopsing in case the hooks consult best_encoder */
15603                         best_encoder = connector->base.state->best_encoder;
15604                         connector->base.state->best_encoder = &encoder->base;
15605
15606                         if (encoder->disable)
15607                                 encoder->disable(encoder, crtc_state,
15608                                                  connector->base.state);
15609                         if (encoder->post_disable)
15610                                 encoder->post_disable(encoder, crtc_state,
15611                                                       connector->base.state);
15612
15613                         connector->base.state->best_encoder = best_encoder;
15614                 }
15615                 encoder->base.crtc = NULL;
15616
15617                 /* Inconsistent output/port/pipe state happens presumably due to
15618                  * a bug in one of the get_hw_state functions. Or someplace else
15619                  * in our code, like the register restore mess on resume. Clamp
15620                  * things to off as a safer default. */
15621
15622                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15623                 connector->base.encoder = NULL;
15624         }
15625
15626         /* notify opregion of the sanitized encoder state */
15627         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
15628
15629         if (INTEL_GEN(dev_priv) >= 11)
15630                 icl_sanitize_encoder_pll_mapping(encoder);
15631 }
15632
15633 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15634 {
15635         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15636
15637         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15638                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15639                 i915_disable_vga(dev_priv);
15640         }
15641 }
15642
15643 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15644 {
15645         intel_wakeref_t wakeref;
15646
15647         /*
15648          * This function can be called both from intel_modeset_setup_hw_state or
15649          * at a very early point in our resume sequence, where the power well
15650          * structures are not yet restored. Since this function is at a very
15651          * paranoid "someone might have enabled VGA while we were not looking"
15652          * level, just check if the power well is enabled instead of trying to
15653          * follow the "don't touch the power well if we don't need it" policy
15654          * the rest of the driver uses.
15655          */
15656         wakeref = intel_display_power_get_if_enabled(dev_priv,
15657                                                      POWER_DOMAIN_VGA);
15658         if (!wakeref)
15659                 return;
15660
15661         i915_redisable_vga_power_on(dev_priv);
15662
15663         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA, wakeref);
15664 }
15665
15666 /* FIXME read out full plane state for all planes */
15667 static void readout_plane_state(struct drm_i915_private *dev_priv)
15668 {
15669         struct intel_plane *plane;
15670         struct intel_crtc *crtc;
15671
15672         for_each_intel_plane(&dev_priv->drm, plane) {
15673                 struct intel_plane_state *plane_state =
15674                         to_intel_plane_state(plane->base.state);
15675                 struct intel_crtc_state *crtc_state;
15676                 enum pipe pipe = PIPE_A;
15677                 bool visible;
15678
15679                 visible = plane->get_hw_state(plane, &pipe);
15680
15681                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15682                 crtc_state = to_intel_crtc_state(crtc->base.state);
15683
15684                 intel_set_plane_visible(crtc_state, plane_state, visible);
15685
15686                 DRM_DEBUG_KMS("[PLANE:%d:%s] hw state readout: %s, pipe %c\n",
15687                               plane->base.base.id, plane->base.name,
15688                               enableddisabled(visible), pipe_name(pipe));
15689         }
15690
15691         for_each_intel_crtc(&dev_priv->drm, crtc) {
15692                 struct intel_crtc_state *crtc_state =
15693                         to_intel_crtc_state(crtc->base.state);
15694
15695                 fixup_active_planes(crtc_state);
15696         }
15697 }
15698
15699 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15700 {
15701         struct drm_i915_private *dev_priv = to_i915(dev);
15702         enum pipe pipe;
15703         struct intel_crtc *crtc;
15704         struct intel_encoder *encoder;
15705         struct intel_connector *connector;
15706         struct drm_connector_list_iter conn_iter;
15707         int i;
15708
15709         dev_priv->active_crtcs = 0;
15710
15711         for_each_intel_crtc(dev, crtc) {
15712                 struct intel_crtc_state *crtc_state =
15713                         to_intel_crtc_state(crtc->base.state);
15714
15715                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15716                 memset(crtc_state, 0, sizeof(*crtc_state));
15717                 crtc_state->base.crtc = &crtc->base;
15718
15719                 crtc_state->base.active = crtc_state->base.enable =
15720                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15721
15722                 crtc->base.enabled = crtc_state->base.enable;
15723                 crtc->active = crtc_state->base.active;
15724
15725                 if (crtc_state->base.active)
15726                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15727
15728                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15729                               crtc->base.base.id, crtc->base.name,
15730                               enableddisabled(crtc_state->base.active));
15731         }
15732
15733         readout_plane_state(dev_priv);
15734
15735         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15736                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15737
15738                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15739                                                         &pll->state.hw_state);
15740                 pll->state.crtc_mask = 0;
15741                 for_each_intel_crtc(dev, crtc) {
15742                         struct intel_crtc_state *crtc_state =
15743                                 to_intel_crtc_state(crtc->base.state);
15744
15745                         if (crtc_state->base.active &&
15746                             crtc_state->shared_dpll == pll)
15747                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15748                 }
15749                 pll->active_mask = pll->state.crtc_mask;
15750
15751                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15752                               pll->info->name, pll->state.crtc_mask, pll->on);
15753         }
15754
15755         for_each_intel_encoder(dev, encoder) {
15756                 pipe = 0;
15757
15758                 if (encoder->get_hw_state(encoder, &pipe)) {
15759                         struct intel_crtc_state *crtc_state;
15760
15761                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15762                         crtc_state = to_intel_crtc_state(crtc->base.state);
15763
15764                         encoder->base.crtc = &crtc->base;
15765                         encoder->get_config(encoder, crtc_state);
15766                 } else {
15767                         encoder->base.crtc = NULL;
15768                 }
15769
15770                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15771                               encoder->base.base.id, encoder->base.name,
15772                               enableddisabled(encoder->base.crtc),
15773                               pipe_name(pipe));
15774         }
15775
15776         drm_connector_list_iter_begin(dev, &conn_iter);
15777         for_each_intel_connector_iter(connector, &conn_iter) {
15778                 if (connector->get_hw_state(connector)) {
15779                         connector->base.dpms = DRM_MODE_DPMS_ON;
15780
15781                         encoder = connector->encoder;
15782                         connector->base.encoder = &encoder->base;
15783
15784                         if (encoder->base.crtc &&
15785                             encoder->base.crtc->state->active) {
15786                                 /*
15787                                  * This has to be done during hardware readout
15788                                  * because anything calling .crtc_disable may
15789                                  * rely on the connector_mask being accurate.
15790                                  */
15791                                 encoder->base.crtc->state->connector_mask |=
15792                                         drm_connector_mask(&connector->base);
15793                                 encoder->base.crtc->state->encoder_mask |=
15794                                         drm_encoder_mask(&encoder->base);
15795                         }
15796
15797                 } else {
15798                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15799                         connector->base.encoder = NULL;
15800                 }
15801                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15802                               connector->base.base.id, connector->base.name,
15803                               enableddisabled(connector->base.encoder));
15804         }
15805         drm_connector_list_iter_end(&conn_iter);
15806
15807         for_each_intel_crtc(dev, crtc) {
15808                 struct intel_crtc_state *crtc_state =
15809                         to_intel_crtc_state(crtc->base.state);
15810                 int min_cdclk = 0;
15811
15812                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15813                 if (crtc_state->base.active) {
15814                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15815                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
15816                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
15817                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15818                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15819
15820                         /*
15821                          * The initial mode needs to be set in order to keep
15822                          * the atomic core happy. It wants a valid mode if the
15823                          * crtc's enabled, so we do the above call.
15824                          *
15825                          * But we don't set all the derived state fully, hence
15826                          * set a flag to indicate that a full recalculation is
15827                          * needed on the next commit.
15828                          */
15829                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15830
15831                         intel_crtc_compute_pixel_rate(crtc_state);
15832
15833                         if (dev_priv->display.modeset_calc_cdclk) {
15834                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15835                                 if (WARN_ON(min_cdclk < 0))
15836                                         min_cdclk = 0;
15837                         }
15838
15839                         drm_calc_timestamping_constants(&crtc->base,
15840                                                         &crtc_state->base.adjusted_mode);
15841                         update_scanline_offset(crtc_state);
15842                 }
15843
15844                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15845                 dev_priv->min_voltage_level[crtc->pipe] =
15846                         crtc_state->min_voltage_level;
15847
15848                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15849         }
15850 }
15851
15852 static void
15853 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15854 {
15855         struct intel_encoder *encoder;
15856
15857         for_each_intel_encoder(&dev_priv->drm, encoder) {
15858                 u64 get_domains;
15859                 enum intel_display_power_domain domain;
15860                 struct intel_crtc_state *crtc_state;
15861
15862                 if (!encoder->get_power_domains)
15863                         continue;
15864
15865                 /*
15866                  * MST-primary and inactive encoders don't have a crtc state
15867                  * and neither of these require any power domain references.
15868                  */
15869                 if (!encoder->base.crtc)
15870                         continue;
15871
15872                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
15873                 get_domains = encoder->get_power_domains(encoder, crtc_state);
15874                 for_each_power_domain(domain, get_domains)
15875                         intel_display_power_get(dev_priv, domain);
15876         }
15877 }
15878
15879 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15880 {
15881         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15882         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15883                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15884                            DARBF_GATING_DIS);
15885
15886         if (IS_HASWELL(dev_priv)) {
15887                 /*
15888                  * WaRsPkgCStateDisplayPMReq:hsw
15889                  * System hang if this isn't done before disabling all planes!
15890                  */
15891                 I915_WRITE(CHICKEN_PAR1_1,
15892                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15893         }
15894 }
15895
15896 static void ibx_sanitize_pch_hdmi_port(struct drm_i915_private *dev_priv,
15897                                        enum port port, i915_reg_t hdmi_reg)
15898 {
15899         u32 val = I915_READ(hdmi_reg);
15900
15901         if (val & SDVO_ENABLE ||
15902             (val & SDVO_PIPE_SEL_MASK) == SDVO_PIPE_SEL(PIPE_A))
15903                 return;
15904
15905         DRM_DEBUG_KMS("Sanitizing transcoder select for HDMI %c\n",
15906                       port_name(port));
15907
15908         val &= ~SDVO_PIPE_SEL_MASK;
15909         val |= SDVO_PIPE_SEL(PIPE_A);
15910
15911         I915_WRITE(hdmi_reg, val);
15912 }
15913
15914 static void ibx_sanitize_pch_dp_port(struct drm_i915_private *dev_priv,
15915                                      enum port port, i915_reg_t dp_reg)
15916 {
15917         u32 val = I915_READ(dp_reg);
15918
15919         if (val & DP_PORT_EN ||
15920             (val & DP_PIPE_SEL_MASK) == DP_PIPE_SEL(PIPE_A))
15921                 return;
15922
15923         DRM_DEBUG_KMS("Sanitizing transcoder select for DP %c\n",
15924                       port_name(port));
15925
15926         val &= ~DP_PIPE_SEL_MASK;
15927         val |= DP_PIPE_SEL(PIPE_A);
15928
15929         I915_WRITE(dp_reg, val);
15930 }
15931
15932 static void ibx_sanitize_pch_ports(struct drm_i915_private *dev_priv)
15933 {
15934         /*
15935          * The BIOS may select transcoder B on some of the PCH
15936          * ports even it doesn't enable the port. This would trip
15937          * assert_pch_dp_disabled() and assert_pch_hdmi_disabled().
15938          * Sanitize the transcoder select bits to prevent that. We
15939          * assume that the BIOS never actually enabled the port,
15940          * because if it did we'd actually have to toggle the port
15941          * on and back off to make the transcoder A select stick
15942          * (see. intel_dp_link_down(), intel_disable_hdmi(),
15943          * intel_disable_sdvo()).
15944          */
15945         ibx_sanitize_pch_dp_port(dev_priv, PORT_B, PCH_DP_B);
15946         ibx_sanitize_pch_dp_port(dev_priv, PORT_C, PCH_DP_C);
15947         ibx_sanitize_pch_dp_port(dev_priv, PORT_D, PCH_DP_D);
15948
15949         /* PCH SDVOB multiplex with HDMIB */
15950         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_B, PCH_HDMIB);
15951         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_C, PCH_HDMIC);
15952         ibx_sanitize_pch_hdmi_port(dev_priv, PORT_D, PCH_HDMID);
15953 }
15954
15955 /* Scan out the current hw modeset state,
15956  * and sanitizes it to the current state
15957  */
15958 static void
15959 intel_modeset_setup_hw_state(struct drm_device *dev,
15960                              struct drm_modeset_acquire_ctx *ctx)
15961 {
15962         struct drm_i915_private *dev_priv = to_i915(dev);
15963         struct intel_crtc_state *crtc_state;
15964         struct intel_encoder *encoder;
15965         struct intel_crtc *crtc;
15966         intel_wakeref_t wakeref;
15967         int i;
15968
15969         wakeref = intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
15970
15971         intel_early_display_was(dev_priv);
15972         intel_modeset_readout_hw_state(dev);
15973
15974         /* HW state is read out, now we need to sanitize this mess. */
15975         get_encoder_power_domains(dev_priv);
15976
15977         if (HAS_PCH_IBX(dev_priv))
15978                 ibx_sanitize_pch_ports(dev_priv);
15979
15980         /*
15981          * intel_sanitize_plane_mapping() may need to do vblank
15982          * waits, so we need vblank interrupts restored beforehand.
15983          */
15984         for_each_intel_crtc(&dev_priv->drm, crtc) {
15985                 crtc_state = to_intel_crtc_state(crtc->base.state);
15986
15987                 drm_crtc_vblank_reset(&crtc->base);
15988
15989                 if (crtc_state->base.active)
15990                         intel_crtc_vblank_on(crtc_state);
15991         }
15992
15993         intel_sanitize_plane_mapping(dev_priv);
15994
15995         for_each_intel_encoder(dev, encoder)
15996                 intel_sanitize_encoder(encoder);
15997
15998         for_each_intel_crtc(&dev_priv->drm, crtc) {
15999                 crtc_state = to_intel_crtc_state(crtc->base.state);
16000                 intel_sanitize_crtc(crtc, ctx);
16001                 intel_dump_pipe_config(crtc, crtc_state,
16002                                        "[setup_hw_state]");
16003         }
16004
16005         intel_modeset_update_connector_atomic_state(dev);
16006
16007         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
16008                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
16009
16010                 if (!pll->on || pll->active_mask)
16011                         continue;
16012
16013                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
16014                               pll->info->name);
16015
16016                 pll->info->funcs->disable(dev_priv, pll);
16017                 pll->on = false;
16018         }
16019
16020         if (IS_G4X(dev_priv)) {
16021                 g4x_wm_get_hw_state(dev_priv);
16022                 g4x_wm_sanitize(dev_priv);
16023         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
16024                 vlv_wm_get_hw_state(dev_priv);
16025                 vlv_wm_sanitize(dev_priv);
16026         } else if (INTEL_GEN(dev_priv) >= 9) {
16027                 skl_wm_get_hw_state(dev_priv);
16028         } else if (HAS_PCH_SPLIT(dev_priv)) {
16029                 ilk_wm_get_hw_state(dev_priv);
16030         }
16031
16032         for_each_intel_crtc(dev, crtc) {
16033                 u64 put_domains;
16034
16035                 crtc_state = to_intel_crtc_state(crtc->base.state);
16036                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc_state);
16037                 if (WARN_ON(put_domains))
16038                         modeset_put_power_domains(dev_priv, put_domains);
16039         }
16040
16041         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT, wakeref);
16042
16043         intel_fbc_init_pipe_state(dev_priv);
16044 }
16045
16046 void intel_display_resume(struct drm_device *dev)
16047 {
16048         struct drm_i915_private *dev_priv = to_i915(dev);
16049         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
16050         struct drm_modeset_acquire_ctx ctx;
16051         int ret;
16052
16053         dev_priv->modeset_restore_state = NULL;
16054         if (state)
16055                 state->acquire_ctx = &ctx;
16056
16057         drm_modeset_acquire_init(&ctx, 0);
16058
16059         while (1) {
16060                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
16061                 if (ret != -EDEADLK)
16062                         break;
16063
16064                 drm_modeset_backoff(&ctx);
16065         }
16066
16067         if (!ret)
16068                 ret = __intel_display_resume(dev, state, &ctx);
16069
16070         intel_enable_ipc(dev_priv);
16071         drm_modeset_drop_locks(&ctx);
16072         drm_modeset_acquire_fini(&ctx);
16073
16074         if (ret)
16075                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16076         if (state)
16077                 drm_atomic_state_put(state);
16078 }
16079
16080 static void intel_hpd_poll_fini(struct drm_device *dev)
16081 {
16082         struct intel_connector *connector;
16083         struct drm_connector_list_iter conn_iter;
16084
16085         /* Kill all the work that may have been queued by hpd. */
16086         drm_connector_list_iter_begin(dev, &conn_iter);
16087         for_each_intel_connector_iter(connector, &conn_iter) {
16088                 if (connector->modeset_retry_work.func)
16089                         cancel_work_sync(&connector->modeset_retry_work);
16090                 if (connector->hdcp.shim) {
16091                         cancel_delayed_work_sync(&connector->hdcp.check_work);
16092                         cancel_work_sync(&connector->hdcp.prop_work);
16093                 }
16094         }
16095         drm_connector_list_iter_end(&conn_iter);
16096 }
16097
16098 void intel_modeset_cleanup(struct drm_device *dev)
16099 {
16100         struct drm_i915_private *dev_priv = to_i915(dev);
16101
16102         flush_workqueue(dev_priv->modeset_wq);
16103
16104         flush_work(&dev_priv->atomic_helper.free_work);
16105         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
16106
16107         /*
16108          * Interrupts and polling as the first thing to avoid creating havoc.
16109          * Too much stuff here (turning of connectors, ...) would
16110          * experience fancy races otherwise.
16111          */
16112         intel_irq_uninstall(dev_priv);
16113
16114         /*
16115          * Due to the hpd irq storm handling the hotplug work can re-arm the
16116          * poll handlers. Hence disable polling after hpd handling is shut down.
16117          */
16118         intel_hpd_poll_fini(dev);
16119
16120         /* poll work can call into fbdev, hence clean that up afterwards */
16121         intel_fbdev_fini(dev_priv);
16122
16123         intel_unregister_dsm_handler();
16124
16125         intel_fbc_global_disable(dev_priv);
16126
16127         /* flush any delayed tasks or pending work */
16128         flush_scheduled_work();
16129
16130         drm_mode_config_cleanup(dev);
16131
16132         intel_overlay_cleanup(dev_priv);
16133
16134         intel_teardown_gmbus(dev_priv);
16135
16136         destroy_workqueue(dev_priv->modeset_wq);
16137
16138         intel_fbc_cleanup_cfb(dev_priv);
16139 }
16140
16141 /*
16142  * set vga decode state - true == enable VGA decode
16143  */
16144 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
16145 {
16146         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16147         u16 gmch_ctrl;
16148
16149         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16150                 DRM_ERROR("failed to read control word\n");
16151                 return -EIO;
16152         }
16153
16154         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16155                 return 0;
16156
16157         if (state)
16158                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16159         else
16160                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16161
16162         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16163                 DRM_ERROR("failed to write control word\n");
16164                 return -EIO;
16165         }
16166
16167         return 0;
16168 }
16169
16170 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
16171
16172 struct intel_display_error_state {
16173
16174         u32 power_well_driver;
16175
16176         int num_transcoders;
16177
16178         struct intel_cursor_error_state {
16179                 u32 control;
16180                 u32 position;
16181                 u32 base;
16182                 u32 size;
16183         } cursor[I915_MAX_PIPES];
16184
16185         struct intel_pipe_error_state {
16186                 bool power_domain_on;
16187                 u32 source;
16188                 u32 stat;
16189         } pipe[I915_MAX_PIPES];
16190
16191         struct intel_plane_error_state {
16192                 u32 control;
16193                 u32 stride;
16194                 u32 size;
16195                 u32 pos;
16196                 u32 addr;
16197                 u32 surface;
16198                 u32 tile_offset;
16199         } plane[I915_MAX_PIPES];
16200
16201         struct intel_transcoder_error_state {
16202                 bool power_domain_on;
16203                 enum transcoder cpu_transcoder;
16204
16205                 u32 conf;
16206
16207                 u32 htotal;
16208                 u32 hblank;
16209                 u32 hsync;
16210                 u32 vtotal;
16211                 u32 vblank;
16212                 u32 vsync;
16213         } transcoder[4];
16214 };
16215
16216 struct intel_display_error_state *
16217 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16218 {
16219         struct intel_display_error_state *error;
16220         int transcoders[] = {
16221                 TRANSCODER_A,
16222                 TRANSCODER_B,
16223                 TRANSCODER_C,
16224                 TRANSCODER_EDP,
16225         };
16226         int i;
16227
16228         if (!HAS_DISPLAY(dev_priv))
16229                 return NULL;
16230
16231         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16232         if (error == NULL)
16233                 return NULL;
16234
16235         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16236                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
16237
16238         for_each_pipe(dev_priv, i) {
16239                 error->pipe[i].power_domain_on =
16240                         __intel_display_power_is_enabled(dev_priv,
16241                                                          POWER_DOMAIN_PIPE(i));
16242                 if (!error->pipe[i].power_domain_on)
16243                         continue;
16244
16245                 error->cursor[i].control = I915_READ(CURCNTR(i));
16246                 error->cursor[i].position = I915_READ(CURPOS(i));
16247                 error->cursor[i].base = I915_READ(CURBASE(i));
16248
16249                 error->plane[i].control = I915_READ(DSPCNTR(i));
16250                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16251                 if (INTEL_GEN(dev_priv) <= 3) {
16252                         error->plane[i].size = I915_READ(DSPSIZE(i));
16253                         error->plane[i].pos = I915_READ(DSPPOS(i));
16254                 }
16255                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16256                         error->plane[i].addr = I915_READ(DSPADDR(i));
16257                 if (INTEL_GEN(dev_priv) >= 4) {
16258                         error->plane[i].surface = I915_READ(DSPSURF(i));
16259                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16260                 }
16261
16262                 error->pipe[i].source = I915_READ(PIPESRC(i));
16263
16264                 if (HAS_GMCH_DISPLAY(dev_priv))
16265                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16266         }
16267
16268         /* Note: this does not include DSI transcoders. */
16269         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16270         if (HAS_DDI(dev_priv))
16271                 error->num_transcoders++; /* Account for eDP. */
16272
16273         for (i = 0; i < error->num_transcoders; i++) {
16274                 enum transcoder cpu_transcoder = transcoders[i];
16275
16276                 error->transcoder[i].power_domain_on =
16277                         __intel_display_power_is_enabled(dev_priv,
16278                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16279                 if (!error->transcoder[i].power_domain_on)
16280                         continue;
16281
16282                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16283
16284                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16285                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16286                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16287                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16288                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16289                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16290                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16291         }
16292
16293         return error;
16294 }
16295
16296 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16297
16298 void
16299 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16300                                 struct intel_display_error_state *error)
16301 {
16302         struct drm_i915_private *dev_priv = m->i915;
16303         int i;
16304
16305         if (!error)
16306                 return;
16307
16308         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16309         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16310                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16311                            error->power_well_driver);
16312         for_each_pipe(dev_priv, i) {
16313                 err_printf(m, "Pipe [%d]:\n", i);
16314                 err_printf(m, "  Power: %s\n",
16315                            onoff(error->pipe[i].power_domain_on));
16316                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16317                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16318
16319                 err_printf(m, "Plane [%d]:\n", i);
16320                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16321                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16322                 if (INTEL_GEN(dev_priv) <= 3) {
16323                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16324                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16325                 }
16326                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16327                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16328                 if (INTEL_GEN(dev_priv) >= 4) {
16329                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16330                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16331                 }
16332
16333                 err_printf(m, "Cursor [%d]:\n", i);
16334                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16335                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16336                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16337         }
16338
16339         for (i = 0; i < error->num_transcoders; i++) {
16340                 err_printf(m, "CPU transcoder: %s\n",
16341                            transcoder_name(error->transcoder[i].cpu_transcoder));
16342                 err_printf(m, "  Power: %s\n",
16343                            onoff(error->transcoder[i].power_domain_on));
16344                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16345                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16346                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16347                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16348                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16349                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16350                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16351         }
16352 }
16353
16354 #endif