]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/gpu/drm/i915/intel_display.c
drm/i915: Always read out M2_N2 in intel_cpu_transcoder_get_m_n, v2.
[linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "i915_gem_clflush.h"
41 #include "intel_dsi.h"
42 #include "i915_trace.h"
43 #include <drm/drm_atomic.h>
44 #include <drm/drm_atomic_helper.h>
45 #include <drm/drm_dp_helper.h>
46 #include <drm/drm_crtc_helper.h>
47 #include <drm/drm_plane_helper.h>
48 #include <drm/drm_rect.h>
49 #include <drm/drm_atomic_uapi.h>
50 #include <linux/dma_remapping.h>
51 #include <linux/reservation.h>
52
53 /* Primary plane formats for gen <= 3 */
54 static const uint32_t i8xx_primary_formats[] = {
55         DRM_FORMAT_C8,
56         DRM_FORMAT_RGB565,
57         DRM_FORMAT_XRGB1555,
58         DRM_FORMAT_XRGB8888,
59 };
60
61 /* Primary plane formats for gen >= 4 */
62 static const uint32_t i965_primary_formats[] = {
63         DRM_FORMAT_C8,
64         DRM_FORMAT_RGB565,
65         DRM_FORMAT_XRGB8888,
66         DRM_FORMAT_XBGR8888,
67         DRM_FORMAT_XRGB2101010,
68         DRM_FORMAT_XBGR2101010,
69 };
70
71 static const uint64_t i9xx_format_modifiers[] = {
72         I915_FORMAT_MOD_X_TILED,
73         DRM_FORMAT_MOD_LINEAR,
74         DRM_FORMAT_MOD_INVALID
75 };
76
77 /* Cursor formats */
78 static const uint32_t intel_cursor_formats[] = {
79         DRM_FORMAT_ARGB8888,
80 };
81
82 static const uint64_t cursor_format_modifiers[] = {
83         DRM_FORMAT_MOD_LINEAR,
84         DRM_FORMAT_MOD_INVALID
85 };
86
87 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
88                                 struct intel_crtc_state *pipe_config);
89 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
90                                    struct intel_crtc_state *pipe_config);
91
92 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
93                                   struct drm_i915_gem_object *obj,
94                                   struct drm_mode_fb_cmd2 *mode_cmd);
95 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state);
96 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state);
97 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
98                                          const struct intel_link_m_n *m_n,
99                                          const struct intel_link_m_n *m2_n2);
100 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state);
101 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state);
102 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state);
103 static void haswell_set_pipemisc(const struct intel_crtc_state *crtc_state);
104 static void vlv_prepare_pll(struct intel_crtc *crtc,
105                             const struct intel_crtc_state *pipe_config);
106 static void chv_prepare_pll(struct intel_crtc *crtc,
107                             const struct intel_crtc_state *pipe_config);
108 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
109 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
110 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
111                                     struct intel_crtc_state *crtc_state);
112 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state);
113 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state);
114 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state);
115 static void intel_modeset_setup_hw_state(struct drm_device *dev,
116                                          struct drm_modeset_acquire_ctx *ctx);
117 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
118
119 struct intel_limit {
120         struct {
121                 int min, max;
122         } dot, vco, n, m, m1, m2, p, p1;
123
124         struct {
125                 int dot_limit;
126                 int p2_slow, p2_fast;
127         } p2;
128 };
129
130 /* returns HPLL frequency in kHz */
131 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
132 {
133         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
134
135         /* Obtain SKU information */
136         mutex_lock(&dev_priv->sb_lock);
137         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
138                 CCK_FUSE_HPLL_FREQ_MASK;
139         mutex_unlock(&dev_priv->sb_lock);
140
141         return vco_freq[hpll_freq] * 1000;
142 }
143
144 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
145                       const char *name, u32 reg, int ref_freq)
146 {
147         u32 val;
148         int divider;
149
150         mutex_lock(&dev_priv->sb_lock);
151         val = vlv_cck_read(dev_priv, reg);
152         mutex_unlock(&dev_priv->sb_lock);
153
154         divider = val & CCK_FREQUENCY_VALUES;
155
156         WARN((val & CCK_FREQUENCY_STATUS) !=
157              (divider << CCK_FREQUENCY_STATUS_SHIFT),
158              "%s change in progress\n", name);
159
160         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
161 }
162
163 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
164                            const char *name, u32 reg)
165 {
166         if (dev_priv->hpll_freq == 0)
167                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
168
169         return vlv_get_cck_clock(dev_priv, name, reg,
170                                  dev_priv->hpll_freq);
171 }
172
173 static void intel_update_czclk(struct drm_i915_private *dev_priv)
174 {
175         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
176                 return;
177
178         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
179                                                       CCK_CZ_CLOCK_CONTROL);
180
181         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
182 }
183
184 static inline u32 /* units of 100MHz */
185 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
186                     const struct intel_crtc_state *pipe_config)
187 {
188         if (HAS_DDI(dev_priv))
189                 return pipe_config->port_clock; /* SPLL */
190         else
191                 return dev_priv->fdi_pll_freq;
192 }
193
194 static const struct intel_limit intel_limits_i8xx_dac = {
195         .dot = { .min = 25000, .max = 350000 },
196         .vco = { .min = 908000, .max = 1512000 },
197         .n = { .min = 2, .max = 16 },
198         .m = { .min = 96, .max = 140 },
199         .m1 = { .min = 18, .max = 26 },
200         .m2 = { .min = 6, .max = 16 },
201         .p = { .min = 4, .max = 128 },
202         .p1 = { .min = 2, .max = 33 },
203         .p2 = { .dot_limit = 165000,
204                 .p2_slow = 4, .p2_fast = 2 },
205 };
206
207 static const struct intel_limit intel_limits_i8xx_dvo = {
208         .dot = { .min = 25000, .max = 350000 },
209         .vco = { .min = 908000, .max = 1512000 },
210         .n = { .min = 2, .max = 16 },
211         .m = { .min = 96, .max = 140 },
212         .m1 = { .min = 18, .max = 26 },
213         .m2 = { .min = 6, .max = 16 },
214         .p = { .min = 4, .max = 128 },
215         .p1 = { .min = 2, .max = 33 },
216         .p2 = { .dot_limit = 165000,
217                 .p2_slow = 4, .p2_fast = 4 },
218 };
219
220 static const struct intel_limit intel_limits_i8xx_lvds = {
221         .dot = { .min = 25000, .max = 350000 },
222         .vco = { .min = 908000, .max = 1512000 },
223         .n = { .min = 2, .max = 16 },
224         .m = { .min = 96, .max = 140 },
225         .m1 = { .min = 18, .max = 26 },
226         .m2 = { .min = 6, .max = 16 },
227         .p = { .min = 4, .max = 128 },
228         .p1 = { .min = 1, .max = 6 },
229         .p2 = { .dot_limit = 165000,
230                 .p2_slow = 14, .p2_fast = 7 },
231 };
232
233 static const struct intel_limit intel_limits_i9xx_sdvo = {
234         .dot = { .min = 20000, .max = 400000 },
235         .vco = { .min = 1400000, .max = 2800000 },
236         .n = { .min = 1, .max = 6 },
237         .m = { .min = 70, .max = 120 },
238         .m1 = { .min = 8, .max = 18 },
239         .m2 = { .min = 3, .max = 7 },
240         .p = { .min = 5, .max = 80 },
241         .p1 = { .min = 1, .max = 8 },
242         .p2 = { .dot_limit = 200000,
243                 .p2_slow = 10, .p2_fast = 5 },
244 };
245
246 static const struct intel_limit intel_limits_i9xx_lvds = {
247         .dot = { .min = 20000, .max = 400000 },
248         .vco = { .min = 1400000, .max = 2800000 },
249         .n = { .min = 1, .max = 6 },
250         .m = { .min = 70, .max = 120 },
251         .m1 = { .min = 8, .max = 18 },
252         .m2 = { .min = 3, .max = 7 },
253         .p = { .min = 7, .max = 98 },
254         .p1 = { .min = 1, .max = 8 },
255         .p2 = { .dot_limit = 112000,
256                 .p2_slow = 14, .p2_fast = 7 },
257 };
258
259
260 static const struct intel_limit intel_limits_g4x_sdvo = {
261         .dot = { .min = 25000, .max = 270000 },
262         .vco = { .min = 1750000, .max = 3500000},
263         .n = { .min = 1, .max = 4 },
264         .m = { .min = 104, .max = 138 },
265         .m1 = { .min = 17, .max = 23 },
266         .m2 = { .min = 5, .max = 11 },
267         .p = { .min = 10, .max = 30 },
268         .p1 = { .min = 1, .max = 3},
269         .p2 = { .dot_limit = 270000,
270                 .p2_slow = 10,
271                 .p2_fast = 10
272         },
273 };
274
275 static const struct intel_limit intel_limits_g4x_hdmi = {
276         .dot = { .min = 22000, .max = 400000 },
277         .vco = { .min = 1750000, .max = 3500000},
278         .n = { .min = 1, .max = 4 },
279         .m = { .min = 104, .max = 138 },
280         .m1 = { .min = 16, .max = 23 },
281         .m2 = { .min = 5, .max = 11 },
282         .p = { .min = 5, .max = 80 },
283         .p1 = { .min = 1, .max = 8},
284         .p2 = { .dot_limit = 165000,
285                 .p2_slow = 10, .p2_fast = 5 },
286 };
287
288 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
289         .dot = { .min = 20000, .max = 115000 },
290         .vco = { .min = 1750000, .max = 3500000 },
291         .n = { .min = 1, .max = 3 },
292         .m = { .min = 104, .max = 138 },
293         .m1 = { .min = 17, .max = 23 },
294         .m2 = { .min = 5, .max = 11 },
295         .p = { .min = 28, .max = 112 },
296         .p1 = { .min = 2, .max = 8 },
297         .p2 = { .dot_limit = 0,
298                 .p2_slow = 14, .p2_fast = 14
299         },
300 };
301
302 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
303         .dot = { .min = 80000, .max = 224000 },
304         .vco = { .min = 1750000, .max = 3500000 },
305         .n = { .min = 1, .max = 3 },
306         .m = { .min = 104, .max = 138 },
307         .m1 = { .min = 17, .max = 23 },
308         .m2 = { .min = 5, .max = 11 },
309         .p = { .min = 14, .max = 42 },
310         .p1 = { .min = 2, .max = 6 },
311         .p2 = { .dot_limit = 0,
312                 .p2_slow = 7, .p2_fast = 7
313         },
314 };
315
316 static const struct intel_limit intel_limits_pineview_sdvo = {
317         .dot = { .min = 20000, .max = 400000},
318         .vco = { .min = 1700000, .max = 3500000 },
319         /* Pineview's Ncounter is a ring counter */
320         .n = { .min = 3, .max = 6 },
321         .m = { .min = 2, .max = 256 },
322         /* Pineview only has one combined m divider, which we treat as m2. */
323         .m1 = { .min = 0, .max = 0 },
324         .m2 = { .min = 0, .max = 254 },
325         .p = { .min = 5, .max = 80 },
326         .p1 = { .min = 1, .max = 8 },
327         .p2 = { .dot_limit = 200000,
328                 .p2_slow = 10, .p2_fast = 5 },
329 };
330
331 static const struct intel_limit intel_limits_pineview_lvds = {
332         .dot = { .min = 20000, .max = 400000 },
333         .vco = { .min = 1700000, .max = 3500000 },
334         .n = { .min = 3, .max = 6 },
335         .m = { .min = 2, .max = 256 },
336         .m1 = { .min = 0, .max = 0 },
337         .m2 = { .min = 0, .max = 254 },
338         .p = { .min = 7, .max = 112 },
339         .p1 = { .min = 1, .max = 8 },
340         .p2 = { .dot_limit = 112000,
341                 .p2_slow = 14, .p2_fast = 14 },
342 };
343
344 /* Ironlake / Sandybridge
345  *
346  * We calculate clock using (register_value + 2) for N/M1/M2, so here
347  * the range value for them is (actual_value - 2).
348  */
349 static const struct intel_limit intel_limits_ironlake_dac = {
350         .dot = { .min = 25000, .max = 350000 },
351         .vco = { .min = 1760000, .max = 3510000 },
352         .n = { .min = 1, .max = 5 },
353         .m = { .min = 79, .max = 127 },
354         .m1 = { .min = 12, .max = 22 },
355         .m2 = { .min = 5, .max = 9 },
356         .p = { .min = 5, .max = 80 },
357         .p1 = { .min = 1, .max = 8 },
358         .p2 = { .dot_limit = 225000,
359                 .p2_slow = 10, .p2_fast = 5 },
360 };
361
362 static const struct intel_limit intel_limits_ironlake_single_lvds = {
363         .dot = { .min = 25000, .max = 350000 },
364         .vco = { .min = 1760000, .max = 3510000 },
365         .n = { .min = 1, .max = 3 },
366         .m = { .min = 79, .max = 118 },
367         .m1 = { .min = 12, .max = 22 },
368         .m2 = { .min = 5, .max = 9 },
369         .p = { .min = 28, .max = 112 },
370         .p1 = { .min = 2, .max = 8 },
371         .p2 = { .dot_limit = 225000,
372                 .p2_slow = 14, .p2_fast = 14 },
373 };
374
375 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
376         .dot = { .min = 25000, .max = 350000 },
377         .vco = { .min = 1760000, .max = 3510000 },
378         .n = { .min = 1, .max = 3 },
379         .m = { .min = 79, .max = 127 },
380         .m1 = { .min = 12, .max = 22 },
381         .m2 = { .min = 5, .max = 9 },
382         .p = { .min = 14, .max = 56 },
383         .p1 = { .min = 2, .max = 8 },
384         .p2 = { .dot_limit = 225000,
385                 .p2_slow = 7, .p2_fast = 7 },
386 };
387
388 /* LVDS 100mhz refclk limits. */
389 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
390         .dot = { .min = 25000, .max = 350000 },
391         .vco = { .min = 1760000, .max = 3510000 },
392         .n = { .min = 1, .max = 2 },
393         .m = { .min = 79, .max = 126 },
394         .m1 = { .min = 12, .max = 22 },
395         .m2 = { .min = 5, .max = 9 },
396         .p = { .min = 28, .max = 112 },
397         .p1 = { .min = 2, .max = 8 },
398         .p2 = { .dot_limit = 225000,
399                 .p2_slow = 14, .p2_fast = 14 },
400 };
401
402 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
403         .dot = { .min = 25000, .max = 350000 },
404         .vco = { .min = 1760000, .max = 3510000 },
405         .n = { .min = 1, .max = 3 },
406         .m = { .min = 79, .max = 126 },
407         .m1 = { .min = 12, .max = 22 },
408         .m2 = { .min = 5, .max = 9 },
409         .p = { .min = 14, .max = 42 },
410         .p1 = { .min = 2, .max = 6 },
411         .p2 = { .dot_limit = 225000,
412                 .p2_slow = 7, .p2_fast = 7 },
413 };
414
415 static const struct intel_limit intel_limits_vlv = {
416          /*
417           * These are the data rate limits (measured in fast clocks)
418           * since those are the strictest limits we have. The fast
419           * clock and actual rate limits are more relaxed, so checking
420           * them would make no difference.
421           */
422         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
423         .vco = { .min = 4000000, .max = 6000000 },
424         .n = { .min = 1, .max = 7 },
425         .m1 = { .min = 2, .max = 3 },
426         .m2 = { .min = 11, .max = 156 },
427         .p1 = { .min = 2, .max = 3 },
428         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
429 };
430
431 static const struct intel_limit intel_limits_chv = {
432         /*
433          * These are the data rate limits (measured in fast clocks)
434          * since those are the strictest limits we have.  The fast
435          * clock and actual rate limits are more relaxed, so checking
436          * them would make no difference.
437          */
438         .dot = { .min = 25000 * 5, .max = 540000 * 5},
439         .vco = { .min = 4800000, .max = 6480000 },
440         .n = { .min = 1, .max = 1 },
441         .m1 = { .min = 2, .max = 2 },
442         .m2 = { .min = 24 << 22, .max = 175 << 22 },
443         .p1 = { .min = 2, .max = 4 },
444         .p2 = { .p2_slow = 1, .p2_fast = 14 },
445 };
446
447 static const struct intel_limit intel_limits_bxt = {
448         /* FIXME: find real dot limits */
449         .dot = { .min = 0, .max = INT_MAX },
450         .vco = { .min = 4800000, .max = 6700000 },
451         .n = { .min = 1, .max = 1 },
452         .m1 = { .min = 2, .max = 2 },
453         /* FIXME: find real m2 limits */
454         .m2 = { .min = 2 << 22, .max = 255 << 22 },
455         .p1 = { .min = 2, .max = 4 },
456         .p2 = { .p2_slow = 1, .p2_fast = 20 },
457 };
458
459 static void
460 skl_wa_528(struct drm_i915_private *dev_priv, int pipe, bool enable)
461 {
462         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
463                 return;
464
465         if (enable)
466                 I915_WRITE(CHICKEN_PIPESL_1(pipe), HSW_FBCQ_DIS);
467         else
468                 I915_WRITE(CHICKEN_PIPESL_1(pipe), 0);
469 }
470
471 static void
472 skl_wa_clkgate(struct drm_i915_private *dev_priv, int pipe, bool enable)
473 {
474         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
475                 return;
476
477         if (enable)
478                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
479                            DUPS1_GATING_DIS | DUPS2_GATING_DIS);
480         else
481                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
482                            I915_READ(CLKGATE_DIS_PSL(pipe)) &
483                            ~(DUPS1_GATING_DIS | DUPS2_GATING_DIS));
484 }
485
486 static bool
487 needs_modeset(const struct drm_crtc_state *state)
488 {
489         return drm_atomic_crtc_needs_modeset(state);
490 }
491
492 /*
493  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
494  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
495  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
496  * The helpers' return value is the rate of the clock that is fed to the
497  * display engine's pipe which can be the above fast dot clock rate or a
498  * divided-down version of it.
499  */
500 /* m1 is reserved as 0 in Pineview, n is a ring counter */
501 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
502 {
503         clock->m = clock->m2 + 2;
504         clock->p = clock->p1 * clock->p2;
505         if (WARN_ON(clock->n == 0 || clock->p == 0))
506                 return 0;
507         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
508         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
509
510         return clock->dot;
511 }
512
513 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
514 {
515         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
516 }
517
518 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
519 {
520         clock->m = i9xx_dpll_compute_m(clock);
521         clock->p = clock->p1 * clock->p2;
522         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
523                 return 0;
524         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
525         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
526
527         return clock->dot;
528 }
529
530 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
531 {
532         clock->m = clock->m1 * clock->m2;
533         clock->p = clock->p1 * clock->p2;
534         if (WARN_ON(clock->n == 0 || clock->p == 0))
535                 return 0;
536         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
537         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
538
539         return clock->dot / 5;
540 }
541
542 int chv_calc_dpll_params(int refclk, struct dpll *clock)
543 {
544         clock->m = clock->m1 * clock->m2;
545         clock->p = clock->p1 * clock->p2;
546         if (WARN_ON(clock->n == 0 || clock->p == 0))
547                 return 0;
548         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
549                         clock->n << 22);
550         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
551
552         return clock->dot / 5;
553 }
554
555 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
556
557 /*
558  * Returns whether the given set of divisors are valid for a given refclk with
559  * the given connectors.
560  */
561 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
562                                const struct intel_limit *limit,
563                                const struct dpll *clock)
564 {
565         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
566                 INTELPllInvalid("n out of range\n");
567         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
568                 INTELPllInvalid("p1 out of range\n");
569         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
570                 INTELPllInvalid("m2 out of range\n");
571         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
572                 INTELPllInvalid("m1 out of range\n");
573
574         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
575             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
576                 if (clock->m1 <= clock->m2)
577                         INTELPllInvalid("m1 <= m2\n");
578
579         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
580             !IS_GEN9_LP(dev_priv)) {
581                 if (clock->p < limit->p.min || limit->p.max < clock->p)
582                         INTELPllInvalid("p out of range\n");
583                 if (clock->m < limit->m.min || limit->m.max < clock->m)
584                         INTELPllInvalid("m out of range\n");
585         }
586
587         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
588                 INTELPllInvalid("vco out of range\n");
589         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
590          * connector, etc., rather than just a single range.
591          */
592         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
593                 INTELPllInvalid("dot out of range\n");
594
595         return true;
596 }
597
598 static int
599 i9xx_select_p2_div(const struct intel_limit *limit,
600                    const struct intel_crtc_state *crtc_state,
601                    int target)
602 {
603         struct drm_device *dev = crtc_state->base.crtc->dev;
604
605         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
606                 /*
607                  * For LVDS just rely on its current settings for dual-channel.
608                  * We haven't figured out how to reliably set up different
609                  * single/dual channel state, if we even can.
610                  */
611                 if (intel_is_dual_link_lvds(dev))
612                         return limit->p2.p2_fast;
613                 else
614                         return limit->p2.p2_slow;
615         } else {
616                 if (target < limit->p2.dot_limit)
617                         return limit->p2.p2_slow;
618                 else
619                         return limit->p2.p2_fast;
620         }
621 }
622
623 /*
624  * Returns a set of divisors for the desired target clock with the given
625  * refclk, or FALSE.  The returned values represent the clock equation:
626  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
627  *
628  * Target and reference clocks are specified in kHz.
629  *
630  * If match_clock is provided, then best_clock P divider must match the P
631  * divider from @match_clock used for LVDS downclocking.
632  */
633 static bool
634 i9xx_find_best_dpll(const struct intel_limit *limit,
635                     struct intel_crtc_state *crtc_state,
636                     int target, int refclk, struct dpll *match_clock,
637                     struct dpll *best_clock)
638 {
639         struct drm_device *dev = crtc_state->base.crtc->dev;
640         struct dpll clock;
641         int err = target;
642
643         memset(best_clock, 0, sizeof(*best_clock));
644
645         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
646
647         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
648              clock.m1++) {
649                 for (clock.m2 = limit->m2.min;
650                      clock.m2 <= limit->m2.max; clock.m2++) {
651                         if (clock.m2 >= clock.m1)
652                                 break;
653                         for (clock.n = limit->n.min;
654                              clock.n <= limit->n.max; clock.n++) {
655                                 for (clock.p1 = limit->p1.min;
656                                         clock.p1 <= limit->p1.max; clock.p1++) {
657                                         int this_err;
658
659                                         i9xx_calc_dpll_params(refclk, &clock);
660                                         if (!intel_PLL_is_valid(to_i915(dev),
661                                                                 limit,
662                                                                 &clock))
663                                                 continue;
664                                         if (match_clock &&
665                                             clock.p != match_clock->p)
666                                                 continue;
667
668                                         this_err = abs(clock.dot - target);
669                                         if (this_err < err) {
670                                                 *best_clock = clock;
671                                                 err = this_err;
672                                         }
673                                 }
674                         }
675                 }
676         }
677
678         return (err != target);
679 }
680
681 /*
682  * Returns a set of divisors for the desired target clock with the given
683  * refclk, or FALSE.  The returned values represent the clock equation:
684  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
685  *
686  * Target and reference clocks are specified in kHz.
687  *
688  * If match_clock is provided, then best_clock P divider must match the P
689  * divider from @match_clock used for LVDS downclocking.
690  */
691 static bool
692 pnv_find_best_dpll(const struct intel_limit *limit,
693                    struct intel_crtc_state *crtc_state,
694                    int target, int refclk, struct dpll *match_clock,
695                    struct dpll *best_clock)
696 {
697         struct drm_device *dev = crtc_state->base.crtc->dev;
698         struct dpll clock;
699         int err = target;
700
701         memset(best_clock, 0, sizeof(*best_clock));
702
703         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
704
705         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
706              clock.m1++) {
707                 for (clock.m2 = limit->m2.min;
708                      clock.m2 <= limit->m2.max; clock.m2++) {
709                         for (clock.n = limit->n.min;
710                              clock.n <= limit->n.max; clock.n++) {
711                                 for (clock.p1 = limit->p1.min;
712                                         clock.p1 <= limit->p1.max; clock.p1++) {
713                                         int this_err;
714
715                                         pnv_calc_dpll_params(refclk, &clock);
716                                         if (!intel_PLL_is_valid(to_i915(dev),
717                                                                 limit,
718                                                                 &clock))
719                                                 continue;
720                                         if (match_clock &&
721                                             clock.p != match_clock->p)
722                                                 continue;
723
724                                         this_err = abs(clock.dot - target);
725                                         if (this_err < err) {
726                                                 *best_clock = clock;
727                                                 err = this_err;
728                                         }
729                                 }
730                         }
731                 }
732         }
733
734         return (err != target);
735 }
736
737 /*
738  * Returns a set of divisors for the desired target clock with the given
739  * refclk, or FALSE.  The returned values represent the clock equation:
740  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
741  *
742  * Target and reference clocks are specified in kHz.
743  *
744  * If match_clock is provided, then best_clock P divider must match the P
745  * divider from @match_clock used for LVDS downclocking.
746  */
747 static bool
748 g4x_find_best_dpll(const struct intel_limit *limit,
749                    struct intel_crtc_state *crtc_state,
750                    int target, int refclk, struct dpll *match_clock,
751                    struct dpll *best_clock)
752 {
753         struct drm_device *dev = crtc_state->base.crtc->dev;
754         struct dpll clock;
755         int max_n;
756         bool found = false;
757         /* approximately equals target * 0.00585 */
758         int err_most = (target >> 8) + (target >> 9);
759
760         memset(best_clock, 0, sizeof(*best_clock));
761
762         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
763
764         max_n = limit->n.max;
765         /* based on hardware requirement, prefer smaller n to precision */
766         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
767                 /* based on hardware requirement, prefere larger m1,m2 */
768                 for (clock.m1 = limit->m1.max;
769                      clock.m1 >= limit->m1.min; clock.m1--) {
770                         for (clock.m2 = limit->m2.max;
771                              clock.m2 >= limit->m2.min; clock.m2--) {
772                                 for (clock.p1 = limit->p1.max;
773                                      clock.p1 >= limit->p1.min; clock.p1--) {
774                                         int this_err;
775
776                                         i9xx_calc_dpll_params(refclk, &clock);
777                                         if (!intel_PLL_is_valid(to_i915(dev),
778                                                                 limit,
779                                                                 &clock))
780                                                 continue;
781
782                                         this_err = abs(clock.dot - target);
783                                         if (this_err < err_most) {
784                                                 *best_clock = clock;
785                                                 err_most = this_err;
786                                                 max_n = clock.n;
787                                                 found = true;
788                                         }
789                                 }
790                         }
791                 }
792         }
793         return found;
794 }
795
796 /*
797  * Check if the calculated PLL configuration is more optimal compared to the
798  * best configuration and error found so far. Return the calculated error.
799  */
800 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
801                                const struct dpll *calculated_clock,
802                                const struct dpll *best_clock,
803                                unsigned int best_error_ppm,
804                                unsigned int *error_ppm)
805 {
806         /*
807          * For CHV ignore the error and consider only the P value.
808          * Prefer a bigger P value based on HW requirements.
809          */
810         if (IS_CHERRYVIEW(to_i915(dev))) {
811                 *error_ppm = 0;
812
813                 return calculated_clock->p > best_clock->p;
814         }
815
816         if (WARN_ON_ONCE(!target_freq))
817                 return false;
818
819         *error_ppm = div_u64(1000000ULL *
820                                 abs(target_freq - calculated_clock->dot),
821                              target_freq);
822         /*
823          * Prefer a better P value over a better (smaller) error if the error
824          * is small. Ensure this preference for future configurations too by
825          * setting the error to 0.
826          */
827         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
828                 *error_ppm = 0;
829
830                 return true;
831         }
832
833         return *error_ppm + 10 < best_error_ppm;
834 }
835
836 /*
837  * Returns a set of divisors for the desired target clock with the given
838  * refclk, or FALSE.  The returned values represent the clock equation:
839  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
840  */
841 static bool
842 vlv_find_best_dpll(const struct intel_limit *limit,
843                    struct intel_crtc_state *crtc_state,
844                    int target, int refclk, struct dpll *match_clock,
845                    struct dpll *best_clock)
846 {
847         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
848         struct drm_device *dev = crtc->base.dev;
849         struct dpll clock;
850         unsigned int bestppm = 1000000;
851         /* min update 19.2 MHz */
852         int max_n = min(limit->n.max, refclk / 19200);
853         bool found = false;
854
855         target *= 5; /* fast clock */
856
857         memset(best_clock, 0, sizeof(*best_clock));
858
859         /* based on hardware requirement, prefer smaller n to precision */
860         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
861                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
862                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
863                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
864                                 clock.p = clock.p1 * clock.p2;
865                                 /* based on hardware requirement, prefer bigger m1,m2 values */
866                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
867                                         unsigned int ppm;
868
869                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
870                                                                      refclk * clock.m1);
871
872                                         vlv_calc_dpll_params(refclk, &clock);
873
874                                         if (!intel_PLL_is_valid(to_i915(dev),
875                                                                 limit,
876                                                                 &clock))
877                                                 continue;
878
879                                         if (!vlv_PLL_is_optimal(dev, target,
880                                                                 &clock,
881                                                                 best_clock,
882                                                                 bestppm, &ppm))
883                                                 continue;
884
885                                         *best_clock = clock;
886                                         bestppm = ppm;
887                                         found = true;
888                                 }
889                         }
890                 }
891         }
892
893         return found;
894 }
895
896 /*
897  * Returns a set of divisors for the desired target clock with the given
898  * refclk, or FALSE.  The returned values represent the clock equation:
899  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
900  */
901 static bool
902 chv_find_best_dpll(const struct intel_limit *limit,
903                    struct intel_crtc_state *crtc_state,
904                    int target, int refclk, struct dpll *match_clock,
905                    struct dpll *best_clock)
906 {
907         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
908         struct drm_device *dev = crtc->base.dev;
909         unsigned int best_error_ppm;
910         struct dpll clock;
911         uint64_t m2;
912         int found = false;
913
914         memset(best_clock, 0, sizeof(*best_clock));
915         best_error_ppm = 1000000;
916
917         /*
918          * Based on hardware doc, the n always set to 1, and m1 always
919          * set to 2.  If requires to support 200Mhz refclk, we need to
920          * revisit this because n may not 1 anymore.
921          */
922         clock.n = 1, clock.m1 = 2;
923         target *= 5;    /* fast clock */
924
925         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
926                 for (clock.p2 = limit->p2.p2_fast;
927                                 clock.p2 >= limit->p2.p2_slow;
928                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
929                         unsigned int error_ppm;
930
931                         clock.p = clock.p1 * clock.p2;
932
933                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
934                                         clock.n) << 22, refclk * clock.m1);
935
936                         if (m2 > INT_MAX/clock.m1)
937                                 continue;
938
939                         clock.m2 = m2;
940
941                         chv_calc_dpll_params(refclk, &clock);
942
943                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
944                                 continue;
945
946                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
947                                                 best_error_ppm, &error_ppm))
948                                 continue;
949
950                         *best_clock = clock;
951                         best_error_ppm = error_ppm;
952                         found = true;
953                 }
954         }
955
956         return found;
957 }
958
959 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
960                         struct dpll *best_clock)
961 {
962         int refclk = 100000;
963         const struct intel_limit *limit = &intel_limits_bxt;
964
965         return chv_find_best_dpll(limit, crtc_state,
966                                   target_clock, refclk, NULL, best_clock);
967 }
968
969 bool intel_crtc_active(struct intel_crtc *crtc)
970 {
971         /* Be paranoid as we can arrive here with only partial
972          * state retrieved from the hardware during setup.
973          *
974          * We can ditch the adjusted_mode.crtc_clock check as soon
975          * as Haswell has gained clock readout/fastboot support.
976          *
977          * We can ditch the crtc->primary->state->fb check as soon as we can
978          * properly reconstruct framebuffers.
979          *
980          * FIXME: The intel_crtc->active here should be switched to
981          * crtc->state->active once we have proper CRTC states wired up
982          * for atomic.
983          */
984         return crtc->active && crtc->base.primary->state->fb &&
985                 crtc->config->base.adjusted_mode.crtc_clock;
986 }
987
988 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
989                                              enum pipe pipe)
990 {
991         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
992
993         return crtc->config->cpu_transcoder;
994 }
995
996 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
997                                     enum pipe pipe)
998 {
999         i915_reg_t reg = PIPEDSL(pipe);
1000         u32 line1, line2;
1001         u32 line_mask;
1002
1003         if (IS_GEN2(dev_priv))
1004                 line_mask = DSL_LINEMASK_GEN2;
1005         else
1006                 line_mask = DSL_LINEMASK_GEN3;
1007
1008         line1 = I915_READ(reg) & line_mask;
1009         msleep(5);
1010         line2 = I915_READ(reg) & line_mask;
1011
1012         return line1 != line2;
1013 }
1014
1015 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1016 {
1017         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1018         enum pipe pipe = crtc->pipe;
1019
1020         /* Wait for the display line to settle/start moving */
1021         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1022                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1023                           pipe_name(pipe), onoff(state));
1024 }
1025
1026 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1027 {
1028         wait_for_pipe_scanline_moving(crtc, false);
1029 }
1030
1031 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1032 {
1033         wait_for_pipe_scanline_moving(crtc, true);
1034 }
1035
1036 static void
1037 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1038 {
1039         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1040         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1041
1042         if (INTEL_GEN(dev_priv) >= 4) {
1043                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1044                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1045
1046                 /* Wait for the Pipe State to go off */
1047                 if (intel_wait_for_register(dev_priv,
1048                                             reg, I965_PIPECONF_ACTIVE, 0,
1049                                             100))
1050                         WARN(1, "pipe_off wait timed out\n");
1051         } else {
1052                 intel_wait_for_pipe_scanline_stopped(crtc);
1053         }
1054 }
1055
1056 /* Only for pre-ILK configs */
1057 void assert_pll(struct drm_i915_private *dev_priv,
1058                 enum pipe pipe, bool state)
1059 {
1060         u32 val;
1061         bool cur_state;
1062
1063         val = I915_READ(DPLL(pipe));
1064         cur_state = !!(val & DPLL_VCO_ENABLE);
1065         I915_STATE_WARN(cur_state != state,
1066              "PLL state assertion failure (expected %s, current %s)\n",
1067                         onoff(state), onoff(cur_state));
1068 }
1069
1070 /* XXX: the dsi pll is shared between MIPI DSI ports */
1071 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1072 {
1073         u32 val;
1074         bool cur_state;
1075
1076         mutex_lock(&dev_priv->sb_lock);
1077         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1078         mutex_unlock(&dev_priv->sb_lock);
1079
1080         cur_state = val & DSI_PLL_VCO_EN;
1081         I915_STATE_WARN(cur_state != state,
1082              "DSI PLL state assertion failure (expected %s, current %s)\n",
1083                         onoff(state), onoff(cur_state));
1084 }
1085
1086 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1087                           enum pipe pipe, bool state)
1088 {
1089         bool cur_state;
1090         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1091                                                                       pipe);
1092
1093         if (HAS_DDI(dev_priv)) {
1094                 /* DDI does not have a specific FDI_TX register */
1095                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1096                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1097         } else {
1098                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1099                 cur_state = !!(val & FDI_TX_ENABLE);
1100         }
1101         I915_STATE_WARN(cur_state != state,
1102              "FDI TX state assertion failure (expected %s, current %s)\n",
1103                         onoff(state), onoff(cur_state));
1104 }
1105 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1106 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1107
1108 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1109                           enum pipe pipe, bool state)
1110 {
1111         u32 val;
1112         bool cur_state;
1113
1114         val = I915_READ(FDI_RX_CTL(pipe));
1115         cur_state = !!(val & FDI_RX_ENABLE);
1116         I915_STATE_WARN(cur_state != state,
1117              "FDI RX state assertion failure (expected %s, current %s)\n",
1118                         onoff(state), onoff(cur_state));
1119 }
1120 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1121 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1122
1123 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1124                                       enum pipe pipe)
1125 {
1126         u32 val;
1127
1128         /* ILK FDI PLL is always enabled */
1129         if (IS_GEN5(dev_priv))
1130                 return;
1131
1132         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1133         if (HAS_DDI(dev_priv))
1134                 return;
1135
1136         val = I915_READ(FDI_TX_CTL(pipe));
1137         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1138 }
1139
1140 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1141                        enum pipe pipe, bool state)
1142 {
1143         u32 val;
1144         bool cur_state;
1145
1146         val = I915_READ(FDI_RX_CTL(pipe));
1147         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1148         I915_STATE_WARN(cur_state != state,
1149              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1150                         onoff(state), onoff(cur_state));
1151 }
1152
1153 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1154 {
1155         i915_reg_t pp_reg;
1156         u32 val;
1157         enum pipe panel_pipe = INVALID_PIPE;
1158         bool locked = true;
1159
1160         if (WARN_ON(HAS_DDI(dev_priv)))
1161                 return;
1162
1163         if (HAS_PCH_SPLIT(dev_priv)) {
1164                 u32 port_sel;
1165
1166                 pp_reg = PP_CONTROL(0);
1167                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1168
1169                 switch (port_sel) {
1170                 case PANEL_PORT_SELECT_LVDS:
1171                         intel_lvds_port_enabled(dev_priv, PCH_LVDS, &panel_pipe);
1172                         break;
1173                 case PANEL_PORT_SELECT_DPA:
1174                         intel_dp_port_enabled(dev_priv, DP_A, PORT_A, &panel_pipe);
1175                         break;
1176                 case PANEL_PORT_SELECT_DPC:
1177                         intel_dp_port_enabled(dev_priv, PCH_DP_C, PORT_C, &panel_pipe);
1178                         break;
1179                 case PANEL_PORT_SELECT_DPD:
1180                         intel_dp_port_enabled(dev_priv, PCH_DP_D, PORT_D, &panel_pipe);
1181                         break;
1182                 default:
1183                         MISSING_CASE(port_sel);
1184                         break;
1185                 }
1186         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1187                 /* presumably write lock depends on pipe, not port select */
1188                 pp_reg = PP_CONTROL(pipe);
1189                 panel_pipe = pipe;
1190         } else {
1191                 u32 port_sel;
1192
1193                 pp_reg = PP_CONTROL(0);
1194                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1195
1196                 WARN_ON(port_sel != PANEL_PORT_SELECT_LVDS);
1197                 intel_lvds_port_enabled(dev_priv, LVDS, &panel_pipe);
1198         }
1199
1200         val = I915_READ(pp_reg);
1201         if (!(val & PANEL_POWER_ON) ||
1202             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1203                 locked = false;
1204
1205         I915_STATE_WARN(panel_pipe == pipe && locked,
1206              "panel assertion failure, pipe %c regs locked\n",
1207              pipe_name(pipe));
1208 }
1209
1210 void assert_pipe(struct drm_i915_private *dev_priv,
1211                  enum pipe pipe, bool state)
1212 {
1213         bool cur_state;
1214         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1215                                                                       pipe);
1216         enum intel_display_power_domain power_domain;
1217
1218         /* we keep both pipes enabled on 830 */
1219         if (IS_I830(dev_priv))
1220                 state = true;
1221
1222         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1223         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1224                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1225                 cur_state = !!(val & PIPECONF_ENABLE);
1226
1227                 intel_display_power_put(dev_priv, power_domain);
1228         } else {
1229                 cur_state = false;
1230         }
1231
1232         I915_STATE_WARN(cur_state != state,
1233              "pipe %c assertion failure (expected %s, current %s)\n",
1234                         pipe_name(pipe), onoff(state), onoff(cur_state));
1235 }
1236
1237 static void assert_plane(struct intel_plane *plane, bool state)
1238 {
1239         enum pipe pipe;
1240         bool cur_state;
1241
1242         cur_state = plane->get_hw_state(plane, &pipe);
1243
1244         I915_STATE_WARN(cur_state != state,
1245                         "%s assertion failure (expected %s, current %s)\n",
1246                         plane->base.name, onoff(state), onoff(cur_state));
1247 }
1248
1249 #define assert_plane_enabled(p) assert_plane(p, true)
1250 #define assert_plane_disabled(p) assert_plane(p, false)
1251
1252 static void assert_planes_disabled(struct intel_crtc *crtc)
1253 {
1254         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1255         struct intel_plane *plane;
1256
1257         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1258                 assert_plane_disabled(plane);
1259 }
1260
1261 static void assert_vblank_disabled(struct drm_crtc *crtc)
1262 {
1263         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1264                 drm_crtc_vblank_put(crtc);
1265 }
1266
1267 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1268                                     enum pipe pipe)
1269 {
1270         u32 val;
1271         bool enabled;
1272
1273         val = I915_READ(PCH_TRANSCONF(pipe));
1274         enabled = !!(val & TRANS_ENABLE);
1275         I915_STATE_WARN(enabled,
1276              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1277              pipe_name(pipe));
1278 }
1279
1280 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1281                                    enum pipe pipe, enum port port,
1282                                    i915_reg_t dp_reg)
1283 {
1284         enum pipe port_pipe;
1285         bool state;
1286
1287         state = intel_dp_port_enabled(dev_priv, dp_reg, port, &port_pipe);
1288
1289         I915_STATE_WARN(state && port_pipe == pipe,
1290                         "PCH DP %c enabled on transcoder %c, should be disabled\n",
1291                         port_name(port), pipe_name(pipe));
1292
1293         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1294                         "IBX PCH DP %c still using transcoder B\n",
1295                         port_name(port));
1296 }
1297
1298 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1299                                      enum pipe pipe, enum port port,
1300                                      i915_reg_t hdmi_reg)
1301 {
1302         enum pipe port_pipe;
1303         bool state;
1304
1305         state = intel_sdvo_port_enabled(dev_priv, hdmi_reg, &port_pipe);
1306
1307         I915_STATE_WARN(state && port_pipe == pipe,
1308                         "PCH HDMI %c enabled on transcoder %c, should be disabled\n",
1309                         port_name(port), pipe_name(pipe));
1310
1311         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1312                         "IBX PCH HDMI %c still using transcoder B\n",
1313                         port_name(port));
1314 }
1315
1316 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1317                                       enum pipe pipe)
1318 {
1319         enum pipe port_pipe;
1320
1321         assert_pch_dp_disabled(dev_priv, pipe, PORT_B, PCH_DP_B);
1322         assert_pch_dp_disabled(dev_priv, pipe, PORT_C, PCH_DP_C);
1323         assert_pch_dp_disabled(dev_priv, pipe, PORT_D, PCH_DP_D);
1324
1325         I915_STATE_WARN(intel_crt_port_enabled(dev_priv, PCH_ADPA, &port_pipe) &&
1326                         port_pipe == pipe,
1327                         "PCH VGA enabled on transcoder %c, should be disabled\n",
1328                         pipe_name(pipe));
1329
1330         I915_STATE_WARN(intel_lvds_port_enabled(dev_priv, PCH_LVDS, &port_pipe) &&
1331                         port_pipe == pipe,
1332                         "PCH LVDS enabled on transcoder %c, should be disabled\n",
1333                         pipe_name(pipe));
1334
1335         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_B, PCH_HDMIB);
1336         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_C, PCH_HDMIC);
1337         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_D, PCH_HDMID);
1338 }
1339
1340 static void _vlv_enable_pll(struct intel_crtc *crtc,
1341                             const struct intel_crtc_state *pipe_config)
1342 {
1343         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1344         enum pipe pipe = crtc->pipe;
1345
1346         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1347         POSTING_READ(DPLL(pipe));
1348         udelay(150);
1349
1350         if (intel_wait_for_register(dev_priv,
1351                                     DPLL(pipe),
1352                                     DPLL_LOCK_VLV,
1353                                     DPLL_LOCK_VLV,
1354                                     1))
1355                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1356 }
1357
1358 static void vlv_enable_pll(struct intel_crtc *crtc,
1359                            const struct intel_crtc_state *pipe_config)
1360 {
1361         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1362         enum pipe pipe = crtc->pipe;
1363
1364         assert_pipe_disabled(dev_priv, pipe);
1365
1366         /* PLL is protected by panel, make sure we can write it */
1367         assert_panel_unlocked(dev_priv, pipe);
1368
1369         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1370                 _vlv_enable_pll(crtc, pipe_config);
1371
1372         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1373         POSTING_READ(DPLL_MD(pipe));
1374 }
1375
1376
1377 static void _chv_enable_pll(struct intel_crtc *crtc,
1378                             const struct intel_crtc_state *pipe_config)
1379 {
1380         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1381         enum pipe pipe = crtc->pipe;
1382         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1383         u32 tmp;
1384
1385         mutex_lock(&dev_priv->sb_lock);
1386
1387         /* Enable back the 10bit clock to display controller */
1388         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1389         tmp |= DPIO_DCLKP_EN;
1390         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1391
1392         mutex_unlock(&dev_priv->sb_lock);
1393
1394         /*
1395          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1396          */
1397         udelay(1);
1398
1399         /* Enable PLL */
1400         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1401
1402         /* Check PLL is locked */
1403         if (intel_wait_for_register(dev_priv,
1404                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1405                                     1))
1406                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1407 }
1408
1409 static void chv_enable_pll(struct intel_crtc *crtc,
1410                            const struct intel_crtc_state *pipe_config)
1411 {
1412         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1413         enum pipe pipe = crtc->pipe;
1414
1415         assert_pipe_disabled(dev_priv, pipe);
1416
1417         /* PLL is protected by panel, make sure we can write it */
1418         assert_panel_unlocked(dev_priv, pipe);
1419
1420         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1421                 _chv_enable_pll(crtc, pipe_config);
1422
1423         if (pipe != PIPE_A) {
1424                 /*
1425                  * WaPixelRepeatModeFixForC0:chv
1426                  *
1427                  * DPLLCMD is AWOL. Use chicken bits to propagate
1428                  * the value from DPLLBMD to either pipe B or C.
1429                  */
1430                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1431                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1432                 I915_WRITE(CBR4_VLV, 0);
1433                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1434
1435                 /*
1436                  * DPLLB VGA mode also seems to cause problems.
1437                  * We should always have it disabled.
1438                  */
1439                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1440         } else {
1441                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1442                 POSTING_READ(DPLL_MD(pipe));
1443         }
1444 }
1445
1446 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1447 {
1448         struct intel_crtc *crtc;
1449         int count = 0;
1450
1451         for_each_intel_crtc(&dev_priv->drm, crtc) {
1452                 count += crtc->base.state->active &&
1453                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1454         }
1455
1456         return count;
1457 }
1458
1459 static void i9xx_enable_pll(struct intel_crtc *crtc,
1460                             const struct intel_crtc_state *crtc_state)
1461 {
1462         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1463         i915_reg_t reg = DPLL(crtc->pipe);
1464         u32 dpll = crtc_state->dpll_hw_state.dpll;
1465         int i;
1466
1467         assert_pipe_disabled(dev_priv, crtc->pipe);
1468
1469         /* PLL is protected by panel, make sure we can write it */
1470         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1471                 assert_panel_unlocked(dev_priv, crtc->pipe);
1472
1473         /* Enable DVO 2x clock on both PLLs if necessary */
1474         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1475                 /*
1476                  * It appears to be important that we don't enable this
1477                  * for the current pipe before otherwise configuring the
1478                  * PLL. No idea how this should be handled if multiple
1479                  * DVO outputs are enabled simultaneosly.
1480                  */
1481                 dpll |= DPLL_DVO_2X_MODE;
1482                 I915_WRITE(DPLL(!crtc->pipe),
1483                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1484         }
1485
1486         /*
1487          * Apparently we need to have VGA mode enabled prior to changing
1488          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1489          * dividers, even though the register value does change.
1490          */
1491         I915_WRITE(reg, 0);
1492
1493         I915_WRITE(reg, dpll);
1494
1495         /* Wait for the clocks to stabilize. */
1496         POSTING_READ(reg);
1497         udelay(150);
1498
1499         if (INTEL_GEN(dev_priv) >= 4) {
1500                 I915_WRITE(DPLL_MD(crtc->pipe),
1501                            crtc_state->dpll_hw_state.dpll_md);
1502         } else {
1503                 /* The pixel multiplier can only be updated once the
1504                  * DPLL is enabled and the clocks are stable.
1505                  *
1506                  * So write it again.
1507                  */
1508                 I915_WRITE(reg, dpll);
1509         }
1510
1511         /* We do this three times for luck */
1512         for (i = 0; i < 3; i++) {
1513                 I915_WRITE(reg, dpll);
1514                 POSTING_READ(reg);
1515                 udelay(150); /* wait for warmup */
1516         }
1517 }
1518
1519 static void i9xx_disable_pll(const struct intel_crtc_state *crtc_state)
1520 {
1521         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1522         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1523         enum pipe pipe = crtc->pipe;
1524
1525         /* Disable DVO 2x clock on both PLLs if necessary */
1526         if (IS_I830(dev_priv) &&
1527             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO) &&
1528             !intel_num_dvo_pipes(dev_priv)) {
1529                 I915_WRITE(DPLL(PIPE_B),
1530                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1531                 I915_WRITE(DPLL(PIPE_A),
1532                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1533         }
1534
1535         /* Don't disable pipe or pipe PLLs if needed */
1536         if (IS_I830(dev_priv))
1537                 return;
1538
1539         /* Make sure the pipe isn't still relying on us */
1540         assert_pipe_disabled(dev_priv, pipe);
1541
1542         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1543         POSTING_READ(DPLL(pipe));
1544 }
1545
1546 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1547 {
1548         u32 val;
1549
1550         /* Make sure the pipe isn't still relying on us */
1551         assert_pipe_disabled(dev_priv, pipe);
1552
1553         val = DPLL_INTEGRATED_REF_CLK_VLV |
1554                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1555         if (pipe != PIPE_A)
1556                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1557
1558         I915_WRITE(DPLL(pipe), val);
1559         POSTING_READ(DPLL(pipe));
1560 }
1561
1562 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1563 {
1564         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1565         u32 val;
1566
1567         /* Make sure the pipe isn't still relying on us */
1568         assert_pipe_disabled(dev_priv, pipe);
1569
1570         val = DPLL_SSC_REF_CLK_CHV |
1571                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1572         if (pipe != PIPE_A)
1573                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1574
1575         I915_WRITE(DPLL(pipe), val);
1576         POSTING_READ(DPLL(pipe));
1577
1578         mutex_lock(&dev_priv->sb_lock);
1579
1580         /* Disable 10bit clock to display controller */
1581         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1582         val &= ~DPIO_DCLKP_EN;
1583         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1584
1585         mutex_unlock(&dev_priv->sb_lock);
1586 }
1587
1588 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1589                          struct intel_digital_port *dport,
1590                          unsigned int expected_mask)
1591 {
1592         u32 port_mask;
1593         i915_reg_t dpll_reg;
1594
1595         switch (dport->base.port) {
1596         case PORT_B:
1597                 port_mask = DPLL_PORTB_READY_MASK;
1598                 dpll_reg = DPLL(0);
1599                 break;
1600         case PORT_C:
1601                 port_mask = DPLL_PORTC_READY_MASK;
1602                 dpll_reg = DPLL(0);
1603                 expected_mask <<= 4;
1604                 break;
1605         case PORT_D:
1606                 port_mask = DPLL_PORTD_READY_MASK;
1607                 dpll_reg = DPIO_PHY_STATUS;
1608                 break;
1609         default:
1610                 BUG();
1611         }
1612
1613         if (intel_wait_for_register(dev_priv,
1614                                     dpll_reg, port_mask, expected_mask,
1615                                     1000))
1616                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1617                      port_name(dport->base.port),
1618                      I915_READ(dpll_reg) & port_mask, expected_mask);
1619 }
1620
1621 static void ironlake_enable_pch_transcoder(const struct intel_crtc_state *crtc_state)
1622 {
1623         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
1624         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1625         enum pipe pipe = crtc->pipe;
1626         i915_reg_t reg;
1627         uint32_t val, pipeconf_val;
1628
1629         /* Make sure PCH DPLL is enabled */
1630         assert_shared_dpll_enabled(dev_priv, crtc_state->shared_dpll);
1631
1632         /* FDI must be feeding us bits for PCH ports */
1633         assert_fdi_tx_enabled(dev_priv, pipe);
1634         assert_fdi_rx_enabled(dev_priv, pipe);
1635
1636         if (HAS_PCH_CPT(dev_priv)) {
1637                 /* Workaround: Set the timing override bit before enabling the
1638                  * pch transcoder. */
1639                 reg = TRANS_CHICKEN2(pipe);
1640                 val = I915_READ(reg);
1641                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1642                 I915_WRITE(reg, val);
1643         }
1644
1645         reg = PCH_TRANSCONF(pipe);
1646         val = I915_READ(reg);
1647         pipeconf_val = I915_READ(PIPECONF(pipe));
1648
1649         if (HAS_PCH_IBX(dev_priv)) {
1650                 /*
1651                  * Make the BPC in transcoder be consistent with
1652                  * that in pipeconf reg. For HDMI we must use 8bpc
1653                  * here for both 8bpc and 12bpc.
1654                  */
1655                 val &= ~PIPECONF_BPC_MASK;
1656                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
1657                         val |= PIPECONF_8BPC;
1658                 else
1659                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1660         }
1661
1662         val &= ~TRANS_INTERLACE_MASK;
1663         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1664                 if (HAS_PCH_IBX(dev_priv) &&
1665                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
1666                         val |= TRANS_LEGACY_INTERLACED_ILK;
1667                 else
1668                         val |= TRANS_INTERLACED;
1669         else
1670                 val |= TRANS_PROGRESSIVE;
1671
1672         I915_WRITE(reg, val | TRANS_ENABLE);
1673         if (intel_wait_for_register(dev_priv,
1674                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1675                                     100))
1676                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1677 }
1678
1679 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1680                                       enum transcoder cpu_transcoder)
1681 {
1682         u32 val, pipeconf_val;
1683
1684         /* FDI must be feeding us bits for PCH ports */
1685         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1686         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1687
1688         /* Workaround: set timing override bit. */
1689         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1690         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1691         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1692
1693         val = TRANS_ENABLE;
1694         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1695
1696         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1697             PIPECONF_INTERLACED_ILK)
1698                 val |= TRANS_INTERLACED;
1699         else
1700                 val |= TRANS_PROGRESSIVE;
1701
1702         I915_WRITE(LPT_TRANSCONF, val);
1703         if (intel_wait_for_register(dev_priv,
1704                                     LPT_TRANSCONF,
1705                                     TRANS_STATE_ENABLE,
1706                                     TRANS_STATE_ENABLE,
1707                                     100))
1708                 DRM_ERROR("Failed to enable PCH transcoder\n");
1709 }
1710
1711 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1712                                             enum pipe pipe)
1713 {
1714         i915_reg_t reg;
1715         uint32_t val;
1716
1717         /* FDI relies on the transcoder */
1718         assert_fdi_tx_disabled(dev_priv, pipe);
1719         assert_fdi_rx_disabled(dev_priv, pipe);
1720
1721         /* Ports must be off as well */
1722         assert_pch_ports_disabled(dev_priv, pipe);
1723
1724         reg = PCH_TRANSCONF(pipe);
1725         val = I915_READ(reg);
1726         val &= ~TRANS_ENABLE;
1727         I915_WRITE(reg, val);
1728         /* wait for PCH transcoder off, transcoder state */
1729         if (intel_wait_for_register(dev_priv,
1730                                     reg, TRANS_STATE_ENABLE, 0,
1731                                     50))
1732                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1733
1734         if (HAS_PCH_CPT(dev_priv)) {
1735                 /* Workaround: Clear the timing override chicken bit again. */
1736                 reg = TRANS_CHICKEN2(pipe);
1737                 val = I915_READ(reg);
1738                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1739                 I915_WRITE(reg, val);
1740         }
1741 }
1742
1743 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1744 {
1745         u32 val;
1746
1747         val = I915_READ(LPT_TRANSCONF);
1748         val &= ~TRANS_ENABLE;
1749         I915_WRITE(LPT_TRANSCONF, val);
1750         /* wait for PCH transcoder off, transcoder state */
1751         if (intel_wait_for_register(dev_priv,
1752                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1753                                     50))
1754                 DRM_ERROR("Failed to disable PCH transcoder\n");
1755
1756         /* Workaround: clear timing override bit. */
1757         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1758         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1759         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1760 }
1761
1762 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1763 {
1764         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1765
1766         if (HAS_PCH_LPT(dev_priv))
1767                 return PIPE_A;
1768         else
1769                 return crtc->pipe;
1770 }
1771
1772 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1773 {
1774         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1775         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1776         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1777         enum pipe pipe = crtc->pipe;
1778         i915_reg_t reg;
1779         u32 val;
1780
1781         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1782
1783         assert_planes_disabled(crtc);
1784
1785         /*
1786          * A pipe without a PLL won't actually be able to drive bits from
1787          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1788          * need the check.
1789          */
1790         if (HAS_GMCH_DISPLAY(dev_priv)) {
1791                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1792                         assert_dsi_pll_enabled(dev_priv);
1793                 else
1794                         assert_pll_enabled(dev_priv, pipe);
1795         } else {
1796                 if (new_crtc_state->has_pch_encoder) {
1797                         /* if driving the PCH, we need FDI enabled */
1798                         assert_fdi_rx_pll_enabled(dev_priv,
1799                                                   intel_crtc_pch_transcoder(crtc));
1800                         assert_fdi_tx_pll_enabled(dev_priv,
1801                                                   (enum pipe) cpu_transcoder);
1802                 }
1803                 /* FIXME: assert CPU port conditions for SNB+ */
1804         }
1805
1806         reg = PIPECONF(cpu_transcoder);
1807         val = I915_READ(reg);
1808         if (val & PIPECONF_ENABLE) {
1809                 /* we keep both pipes enabled on 830 */
1810                 WARN_ON(!IS_I830(dev_priv));
1811                 return;
1812         }
1813
1814         I915_WRITE(reg, val | PIPECONF_ENABLE);
1815         POSTING_READ(reg);
1816
1817         /*
1818          * Until the pipe starts PIPEDSL reads will return a stale value,
1819          * which causes an apparent vblank timestamp jump when PIPEDSL
1820          * resets to its proper value. That also messes up the frame count
1821          * when it's derived from the timestamps. So let's wait for the
1822          * pipe to start properly before we call drm_crtc_vblank_on()
1823          */
1824         if (dev_priv->drm.max_vblank_count == 0)
1825                 intel_wait_for_pipe_scanline_moving(crtc);
1826 }
1827
1828 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1829 {
1830         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1831         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1832         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1833         enum pipe pipe = crtc->pipe;
1834         i915_reg_t reg;
1835         u32 val;
1836
1837         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1838
1839         /*
1840          * Make sure planes won't keep trying to pump pixels to us,
1841          * or we might hang the display.
1842          */
1843         assert_planes_disabled(crtc);
1844
1845         reg = PIPECONF(cpu_transcoder);
1846         val = I915_READ(reg);
1847         if ((val & PIPECONF_ENABLE) == 0)
1848                 return;
1849
1850         /*
1851          * Double wide has implications for planes
1852          * so best keep it disabled when not needed.
1853          */
1854         if (old_crtc_state->double_wide)
1855                 val &= ~PIPECONF_DOUBLE_WIDE;
1856
1857         /* Don't disable pipe or pipe PLLs if needed */
1858         if (!IS_I830(dev_priv))
1859                 val &= ~PIPECONF_ENABLE;
1860
1861         I915_WRITE(reg, val);
1862         if ((val & PIPECONF_ENABLE) == 0)
1863                 intel_wait_for_pipe_off(old_crtc_state);
1864 }
1865
1866 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1867 {
1868         return IS_GEN2(dev_priv) ? 2048 : 4096;
1869 }
1870
1871 static unsigned int
1872 intel_tile_width_bytes(const struct drm_framebuffer *fb, int color_plane)
1873 {
1874         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1875         unsigned int cpp = fb->format->cpp[color_plane];
1876
1877         switch (fb->modifier) {
1878         case DRM_FORMAT_MOD_LINEAR:
1879                 return cpp;
1880         case I915_FORMAT_MOD_X_TILED:
1881                 if (IS_GEN2(dev_priv))
1882                         return 128;
1883                 else
1884                         return 512;
1885         case I915_FORMAT_MOD_Y_TILED_CCS:
1886                 if (color_plane == 1)
1887                         return 128;
1888                 /* fall through */
1889         case I915_FORMAT_MOD_Y_TILED:
1890                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
1891                         return 128;
1892                 else
1893                         return 512;
1894         case I915_FORMAT_MOD_Yf_TILED_CCS:
1895                 if (color_plane == 1)
1896                         return 128;
1897                 /* fall through */
1898         case I915_FORMAT_MOD_Yf_TILED:
1899                 switch (cpp) {
1900                 case 1:
1901                         return 64;
1902                 case 2:
1903                 case 4:
1904                         return 128;
1905                 case 8:
1906                 case 16:
1907                         return 256;
1908                 default:
1909                         MISSING_CASE(cpp);
1910                         return cpp;
1911                 }
1912                 break;
1913         default:
1914                 MISSING_CASE(fb->modifier);
1915                 return cpp;
1916         }
1917 }
1918
1919 static unsigned int
1920 intel_tile_height(const struct drm_framebuffer *fb, int color_plane)
1921 {
1922         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
1923                 return 1;
1924         else
1925                 return intel_tile_size(to_i915(fb->dev)) /
1926                         intel_tile_width_bytes(fb, color_plane);
1927 }
1928
1929 /* Return the tile dimensions in pixel units */
1930 static void intel_tile_dims(const struct drm_framebuffer *fb, int color_plane,
1931                             unsigned int *tile_width,
1932                             unsigned int *tile_height)
1933 {
1934         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, color_plane);
1935         unsigned int cpp = fb->format->cpp[color_plane];
1936
1937         *tile_width = tile_width_bytes / cpp;
1938         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1939 }
1940
1941 unsigned int
1942 intel_fb_align_height(const struct drm_framebuffer *fb,
1943                       int color_plane, unsigned int height)
1944 {
1945         unsigned int tile_height = intel_tile_height(fb, color_plane);
1946
1947         return ALIGN(height, tile_height);
1948 }
1949
1950 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
1951 {
1952         unsigned int size = 0;
1953         int i;
1954
1955         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
1956                 size += rot_info->plane[i].width * rot_info->plane[i].height;
1957
1958         return size;
1959 }
1960
1961 static void
1962 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
1963                         const struct drm_framebuffer *fb,
1964                         unsigned int rotation)
1965 {
1966         view->type = I915_GGTT_VIEW_NORMAL;
1967         if (drm_rotation_90_or_270(rotation)) {
1968                 view->type = I915_GGTT_VIEW_ROTATED;
1969                 view->rotated = to_intel_framebuffer(fb)->rot_info;
1970         }
1971 }
1972
1973 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
1974 {
1975         if (IS_I830(dev_priv))
1976                 return 16 * 1024;
1977         else if (IS_I85X(dev_priv))
1978                 return 256;
1979         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
1980                 return 32;
1981         else
1982                 return 4 * 1024;
1983 }
1984
1985 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
1986 {
1987         if (INTEL_GEN(dev_priv) >= 9)
1988                 return 256 * 1024;
1989         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
1990                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
1991                 return 128 * 1024;
1992         else if (INTEL_GEN(dev_priv) >= 4)
1993                 return 4 * 1024;
1994         else
1995                 return 0;
1996 }
1997
1998 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
1999                                          int color_plane)
2000 {
2001         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2002
2003         /* AUX_DIST needs only 4K alignment */
2004         if (color_plane == 1)
2005                 return 4096;
2006
2007         switch (fb->modifier) {
2008         case DRM_FORMAT_MOD_LINEAR:
2009                 return intel_linear_alignment(dev_priv);
2010         case I915_FORMAT_MOD_X_TILED:
2011                 if (INTEL_GEN(dev_priv) >= 9)
2012                         return 256 * 1024;
2013                 return 0;
2014         case I915_FORMAT_MOD_Y_TILED_CCS:
2015         case I915_FORMAT_MOD_Yf_TILED_CCS:
2016         case I915_FORMAT_MOD_Y_TILED:
2017         case I915_FORMAT_MOD_Yf_TILED:
2018                 return 1 * 1024 * 1024;
2019         default:
2020                 MISSING_CASE(fb->modifier);
2021                 return 0;
2022         }
2023 }
2024
2025 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2026 {
2027         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2028         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2029
2030         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2031 }
2032
2033 struct i915_vma *
2034 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2035                            const struct i915_ggtt_view *view,
2036                            bool uses_fence,
2037                            unsigned long *out_flags)
2038 {
2039         struct drm_device *dev = fb->dev;
2040         struct drm_i915_private *dev_priv = to_i915(dev);
2041         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2042         struct i915_vma *vma;
2043         unsigned int pinctl;
2044         u32 alignment;
2045
2046         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2047
2048         alignment = intel_surf_alignment(fb, 0);
2049
2050         /* Note that the w/a also requires 64 PTE of padding following the
2051          * bo. We currently fill all unused PTE with the shadow page and so
2052          * we should always have valid PTE following the scanout preventing
2053          * the VT-d warning.
2054          */
2055         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2056                 alignment = 256 * 1024;
2057
2058         /*
2059          * Global gtt pte registers are special registers which actually forward
2060          * writes to a chunk of system memory. Which means that there is no risk
2061          * that the register values disappear as soon as we call
2062          * intel_runtime_pm_put(), so it is correct to wrap only the
2063          * pin/unpin/fence and not more.
2064          */
2065         intel_runtime_pm_get(dev_priv);
2066
2067         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2068
2069         pinctl = 0;
2070
2071         /* Valleyview is definitely limited to scanning out the first
2072          * 512MiB. Lets presume this behaviour was inherited from the
2073          * g4x display engine and that all earlier gen are similarly
2074          * limited. Testing suggests that it is a little more
2075          * complicated than this. For example, Cherryview appears quite
2076          * happy to scanout from anywhere within its global aperture.
2077          */
2078         if (HAS_GMCH_DISPLAY(dev_priv))
2079                 pinctl |= PIN_MAPPABLE;
2080
2081         vma = i915_gem_object_pin_to_display_plane(obj,
2082                                                    alignment, view, pinctl);
2083         if (IS_ERR(vma))
2084                 goto err;
2085
2086         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2087                 int ret;
2088
2089                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2090                  * fence, whereas 965+ only requires a fence if using
2091                  * framebuffer compression.  For simplicity, we always, when
2092                  * possible, install a fence as the cost is not that onerous.
2093                  *
2094                  * If we fail to fence the tiled scanout, then either the
2095                  * modeset will reject the change (which is highly unlikely as
2096                  * the affected systems, all but one, do not have unmappable
2097                  * space) or we will not be able to enable full powersaving
2098                  * techniques (also likely not to apply due to various limits
2099                  * FBC and the like impose on the size of the buffer, which
2100                  * presumably we violated anyway with this unmappable buffer).
2101                  * Anyway, it is presumably better to stumble onwards with
2102                  * something and try to run the system in a "less than optimal"
2103                  * mode that matches the user configuration.
2104                  */
2105                 ret = i915_vma_pin_fence(vma);
2106                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2107                         i915_gem_object_unpin_from_display_plane(vma);
2108                         vma = ERR_PTR(ret);
2109                         goto err;
2110                 }
2111
2112                 if (ret == 0 && vma->fence)
2113                         *out_flags |= PLANE_HAS_FENCE;
2114         }
2115
2116         i915_vma_get(vma);
2117 err:
2118         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2119
2120         intel_runtime_pm_put(dev_priv);
2121         return vma;
2122 }
2123
2124 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2125 {
2126         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2127
2128         if (flags & PLANE_HAS_FENCE)
2129                 i915_vma_unpin_fence(vma);
2130         i915_gem_object_unpin_from_display_plane(vma);
2131         i915_vma_put(vma);
2132 }
2133
2134 static int intel_fb_pitch(const struct drm_framebuffer *fb, int color_plane,
2135                           unsigned int rotation)
2136 {
2137         if (drm_rotation_90_or_270(rotation))
2138                 return to_intel_framebuffer(fb)->rotated[color_plane].pitch;
2139         else
2140                 return fb->pitches[color_plane];
2141 }
2142
2143 /*
2144  * Convert the x/y offsets into a linear offset.
2145  * Only valid with 0/180 degree rotation, which is fine since linear
2146  * offset is only used with linear buffers on pre-hsw and tiled buffers
2147  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2148  */
2149 u32 intel_fb_xy_to_linear(int x, int y,
2150                           const struct intel_plane_state *state,
2151                           int color_plane)
2152 {
2153         const struct drm_framebuffer *fb = state->base.fb;
2154         unsigned int cpp = fb->format->cpp[color_plane];
2155         unsigned int pitch = state->color_plane[color_plane].stride;
2156
2157         return y * pitch + x * cpp;
2158 }
2159
2160 /*
2161  * Add the x/y offsets derived from fb->offsets[] to the user
2162  * specified plane src x/y offsets. The resulting x/y offsets
2163  * specify the start of scanout from the beginning of the gtt mapping.
2164  */
2165 void intel_add_fb_offsets(int *x, int *y,
2166                           const struct intel_plane_state *state,
2167                           int color_plane)
2168
2169 {
2170         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2171         unsigned int rotation = state->base.rotation;
2172
2173         if (drm_rotation_90_or_270(rotation)) {
2174                 *x += intel_fb->rotated[color_plane].x;
2175                 *y += intel_fb->rotated[color_plane].y;
2176         } else {
2177                 *x += intel_fb->normal[color_plane].x;
2178                 *y += intel_fb->normal[color_plane].y;
2179         }
2180 }
2181
2182 static u32 intel_adjust_tile_offset(int *x, int *y,
2183                                     unsigned int tile_width,
2184                                     unsigned int tile_height,
2185                                     unsigned int tile_size,
2186                                     unsigned int pitch_tiles,
2187                                     u32 old_offset,
2188                                     u32 new_offset)
2189 {
2190         unsigned int pitch_pixels = pitch_tiles * tile_width;
2191         unsigned int tiles;
2192
2193         WARN_ON(old_offset & (tile_size - 1));
2194         WARN_ON(new_offset & (tile_size - 1));
2195         WARN_ON(new_offset > old_offset);
2196
2197         tiles = (old_offset - new_offset) / tile_size;
2198
2199         *y += tiles / pitch_tiles * tile_height;
2200         *x += tiles % pitch_tiles * tile_width;
2201
2202         /* minimize x in case it got needlessly big */
2203         *y += *x / pitch_pixels * tile_height;
2204         *x %= pitch_pixels;
2205
2206         return new_offset;
2207 }
2208
2209 static u32 intel_adjust_aligned_offset(int *x, int *y,
2210                                        const struct drm_framebuffer *fb,
2211                                        int color_plane,
2212                                        unsigned int rotation,
2213                                        unsigned int pitch,
2214                                        u32 old_offset, u32 new_offset)
2215 {
2216         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2217         unsigned int cpp = fb->format->cpp[color_plane];
2218
2219         WARN_ON(new_offset > old_offset);
2220
2221         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2222                 unsigned int tile_size, tile_width, tile_height;
2223                 unsigned int pitch_tiles;
2224
2225                 tile_size = intel_tile_size(dev_priv);
2226                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2227
2228                 if (drm_rotation_90_or_270(rotation)) {
2229                         pitch_tiles = pitch / tile_height;
2230                         swap(tile_width, tile_height);
2231                 } else {
2232                         pitch_tiles = pitch / (tile_width * cpp);
2233                 }
2234
2235                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2236                                          tile_size, pitch_tiles,
2237                                          old_offset, new_offset);
2238         } else {
2239                 old_offset += *y * pitch + *x * cpp;
2240
2241                 *y = (old_offset - new_offset) / pitch;
2242                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2243         }
2244
2245         return new_offset;
2246 }
2247
2248 /*
2249  * Adjust the tile offset by moving the difference into
2250  * the x/y offsets.
2251  */
2252 static u32 intel_plane_adjust_aligned_offset(int *x, int *y,
2253                                              const struct intel_plane_state *state,
2254                                              int color_plane,
2255                                              u32 old_offset, u32 new_offset)
2256 {
2257         return intel_adjust_aligned_offset(x, y, state->base.fb, color_plane,
2258                                            state->base.rotation,
2259                                            state->color_plane[color_plane].stride,
2260                                            old_offset, new_offset);
2261 }
2262
2263 /*
2264  * Computes the aligned offset to the base tile and adjusts
2265  * x, y. bytes per pixel is assumed to be a power-of-two.
2266  *
2267  * In the 90/270 rotated case, x and y are assumed
2268  * to be already rotated to match the rotated GTT view, and
2269  * pitch is the tile_height aligned framebuffer height.
2270  *
2271  * This function is used when computing the derived information
2272  * under intel_framebuffer, so using any of that information
2273  * here is not allowed. Anything under drm_framebuffer can be
2274  * used. This is why the user has to pass in the pitch since it
2275  * is specified in the rotated orientation.
2276  */
2277 static u32 intel_compute_aligned_offset(struct drm_i915_private *dev_priv,
2278                                         int *x, int *y,
2279                                         const struct drm_framebuffer *fb,
2280                                         int color_plane,
2281                                         unsigned int pitch,
2282                                         unsigned int rotation,
2283                                         u32 alignment)
2284 {
2285         uint64_t fb_modifier = fb->modifier;
2286         unsigned int cpp = fb->format->cpp[color_plane];
2287         u32 offset, offset_aligned;
2288
2289         if (alignment)
2290                 alignment--;
2291
2292         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2293                 unsigned int tile_size, tile_width, tile_height;
2294                 unsigned int tile_rows, tiles, pitch_tiles;
2295
2296                 tile_size = intel_tile_size(dev_priv);
2297                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2298
2299                 if (drm_rotation_90_or_270(rotation)) {
2300                         pitch_tiles = pitch / tile_height;
2301                         swap(tile_width, tile_height);
2302                 } else {
2303                         pitch_tiles = pitch / (tile_width * cpp);
2304                 }
2305
2306                 tile_rows = *y / tile_height;
2307                 *y %= tile_height;
2308
2309                 tiles = *x / tile_width;
2310                 *x %= tile_width;
2311
2312                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2313                 offset_aligned = offset & ~alignment;
2314
2315                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2316                                          tile_size, pitch_tiles,
2317                                          offset, offset_aligned);
2318         } else {
2319                 offset = *y * pitch + *x * cpp;
2320                 offset_aligned = offset & ~alignment;
2321
2322                 *y = (offset & alignment) / pitch;
2323                 *x = ((offset & alignment) - *y * pitch) / cpp;
2324         }
2325
2326         return offset_aligned;
2327 }
2328
2329 static u32 intel_plane_compute_aligned_offset(int *x, int *y,
2330                                               const struct intel_plane_state *state,
2331                                               int color_plane)
2332 {
2333         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2334         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2335         const struct drm_framebuffer *fb = state->base.fb;
2336         unsigned int rotation = state->base.rotation;
2337         int pitch = state->color_plane[color_plane].stride;
2338         u32 alignment;
2339
2340         if (intel_plane->id == PLANE_CURSOR)
2341                 alignment = intel_cursor_alignment(dev_priv);
2342         else
2343                 alignment = intel_surf_alignment(fb, color_plane);
2344
2345         return intel_compute_aligned_offset(dev_priv, x, y, fb, color_plane,
2346                                             pitch, rotation, alignment);
2347 }
2348
2349 /* Convert the fb->offset[] into x/y offsets */
2350 static int intel_fb_offset_to_xy(int *x, int *y,
2351                                  const struct drm_framebuffer *fb,
2352                                  int color_plane)
2353 {
2354         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2355
2356         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2357             fb->offsets[color_plane] % intel_tile_size(dev_priv))
2358                 return -EINVAL;
2359
2360         *x = 0;
2361         *y = 0;
2362
2363         intel_adjust_aligned_offset(x, y,
2364                                     fb, color_plane, DRM_MODE_ROTATE_0,
2365                                     fb->pitches[color_plane],
2366                                     fb->offsets[color_plane], 0);
2367
2368         return 0;
2369 }
2370
2371 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2372 {
2373         switch (fb_modifier) {
2374         case I915_FORMAT_MOD_X_TILED:
2375                 return I915_TILING_X;
2376         case I915_FORMAT_MOD_Y_TILED:
2377         case I915_FORMAT_MOD_Y_TILED_CCS:
2378                 return I915_TILING_Y;
2379         default:
2380                 return I915_TILING_NONE;
2381         }
2382 }
2383
2384 /*
2385  * From the Sky Lake PRM:
2386  * "The Color Control Surface (CCS) contains the compression status of
2387  *  the cache-line pairs. The compression state of the cache-line pair
2388  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2389  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2390  *  cache-line-pairs. CCS is always Y tiled."
2391  *
2392  * Since cache line pairs refers to horizontally adjacent cache lines,
2393  * each cache line in the CCS corresponds to an area of 32x16 cache
2394  * lines on the main surface. Since each pixel is 4 bytes, this gives
2395  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2396  * main surface.
2397  */
2398 static const struct drm_format_info ccs_formats[] = {
2399         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2400         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2401         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2402         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2403 };
2404
2405 static const struct drm_format_info *
2406 lookup_format_info(const struct drm_format_info formats[],
2407                    int num_formats, u32 format)
2408 {
2409         int i;
2410
2411         for (i = 0; i < num_formats; i++) {
2412                 if (formats[i].format == format)
2413                         return &formats[i];
2414         }
2415
2416         return NULL;
2417 }
2418
2419 static const struct drm_format_info *
2420 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2421 {
2422         switch (cmd->modifier[0]) {
2423         case I915_FORMAT_MOD_Y_TILED_CCS:
2424         case I915_FORMAT_MOD_Yf_TILED_CCS:
2425                 return lookup_format_info(ccs_formats,
2426                                           ARRAY_SIZE(ccs_formats),
2427                                           cmd->pixel_format);
2428         default:
2429                 return NULL;
2430         }
2431 }
2432
2433 bool is_ccs_modifier(u64 modifier)
2434 {
2435         return modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2436                modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
2437 }
2438
2439 static int
2440 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2441                    struct drm_framebuffer *fb)
2442 {
2443         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2444         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2445         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2446         u32 gtt_offset_rotated = 0;
2447         unsigned int max_size = 0;
2448         int i, num_planes = fb->format->num_planes;
2449         unsigned int tile_size = intel_tile_size(dev_priv);
2450
2451         for (i = 0; i < num_planes; i++) {
2452                 unsigned int width, height;
2453                 unsigned int cpp, size;
2454                 u32 offset;
2455                 int x, y;
2456                 int ret;
2457
2458                 cpp = fb->format->cpp[i];
2459                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2460                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2461
2462                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2463                 if (ret) {
2464                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2465                                       i, fb->offsets[i]);
2466                         return ret;
2467                 }
2468
2469                 if (is_ccs_modifier(fb->modifier) && i == 1) {
2470                         int hsub = fb->format->hsub;
2471                         int vsub = fb->format->vsub;
2472                         int tile_width, tile_height;
2473                         int main_x, main_y;
2474                         int ccs_x, ccs_y;
2475
2476                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2477                         tile_width *= hsub;
2478                         tile_height *= vsub;
2479
2480                         ccs_x = (x * hsub) % tile_width;
2481                         ccs_y = (y * vsub) % tile_height;
2482                         main_x = intel_fb->normal[0].x % tile_width;
2483                         main_y = intel_fb->normal[0].y % tile_height;
2484
2485                         /*
2486                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2487                          * x/y offsets must match between CCS and the main surface.
2488                          */
2489                         if (main_x != ccs_x || main_y != ccs_y) {
2490                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2491                                               main_x, main_y,
2492                                               ccs_x, ccs_y,
2493                                               intel_fb->normal[0].x,
2494                                               intel_fb->normal[0].y,
2495                                               x, y);
2496                                 return -EINVAL;
2497                         }
2498                 }
2499
2500                 /*
2501                  * The fence (if used) is aligned to the start of the object
2502                  * so having the framebuffer wrap around across the edge of the
2503                  * fenced region doesn't really work. We have no API to configure
2504                  * the fence start offset within the object (nor could we probably
2505                  * on gen2/3). So it's just easier if we just require that the
2506                  * fb layout agrees with the fence layout. We already check that the
2507                  * fb stride matches the fence stride elsewhere.
2508                  */
2509                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2510                     (x + width) * cpp > fb->pitches[i]) {
2511                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2512                                       i, fb->offsets[i]);
2513                         return -EINVAL;
2514                 }
2515
2516                 /*
2517                  * First pixel of the framebuffer from
2518                  * the start of the normal gtt mapping.
2519                  */
2520                 intel_fb->normal[i].x = x;
2521                 intel_fb->normal[i].y = y;
2522
2523                 offset = intel_compute_aligned_offset(dev_priv, &x, &y, fb, i,
2524                                                       fb->pitches[i],
2525                                                       DRM_MODE_ROTATE_0,
2526                                                       tile_size);
2527                 offset /= tile_size;
2528
2529                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2530                         unsigned int tile_width, tile_height;
2531                         unsigned int pitch_tiles;
2532                         struct drm_rect r;
2533
2534                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2535
2536                         rot_info->plane[i].offset = offset;
2537                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2538                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2539                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2540
2541                         intel_fb->rotated[i].pitch =
2542                                 rot_info->plane[i].height * tile_height;
2543
2544                         /* how many tiles does this plane need */
2545                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2546                         /*
2547                          * If the plane isn't horizontally tile aligned,
2548                          * we need one more tile.
2549                          */
2550                         if (x != 0)
2551                                 size++;
2552
2553                         /* rotate the x/y offsets to match the GTT view */
2554                         r.x1 = x;
2555                         r.y1 = y;
2556                         r.x2 = x + width;
2557                         r.y2 = y + height;
2558                         drm_rect_rotate(&r,
2559                                         rot_info->plane[i].width * tile_width,
2560                                         rot_info->plane[i].height * tile_height,
2561                                         DRM_MODE_ROTATE_270);
2562                         x = r.x1;
2563                         y = r.y1;
2564
2565                         /* rotate the tile dimensions to match the GTT view */
2566                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2567                         swap(tile_width, tile_height);
2568
2569                         /*
2570                          * We only keep the x/y offsets, so push all of the
2571                          * gtt offset into the x/y offsets.
2572                          */
2573                         intel_adjust_tile_offset(&x, &y,
2574                                                  tile_width, tile_height,
2575                                                  tile_size, pitch_tiles,
2576                                                  gtt_offset_rotated * tile_size, 0);
2577
2578                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2579
2580                         /*
2581                          * First pixel of the framebuffer from
2582                          * the start of the rotated gtt mapping.
2583                          */
2584                         intel_fb->rotated[i].x = x;
2585                         intel_fb->rotated[i].y = y;
2586                 } else {
2587                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2588                                             x * cpp, tile_size);
2589                 }
2590
2591                 /* how many tiles in total needed in the bo */
2592                 max_size = max(max_size, offset + size);
2593         }
2594
2595         if (mul_u32_u32(max_size, tile_size) > obj->base.size) {
2596                 DRM_DEBUG_KMS("fb too big for bo (need %llu bytes, have %zu bytes)\n",
2597                               mul_u32_u32(max_size, tile_size), obj->base.size);
2598                 return -EINVAL;
2599         }
2600
2601         return 0;
2602 }
2603
2604 static int i9xx_format_to_fourcc(int format)
2605 {
2606         switch (format) {
2607         case DISPPLANE_8BPP:
2608                 return DRM_FORMAT_C8;
2609         case DISPPLANE_BGRX555:
2610                 return DRM_FORMAT_XRGB1555;
2611         case DISPPLANE_BGRX565:
2612                 return DRM_FORMAT_RGB565;
2613         default:
2614         case DISPPLANE_BGRX888:
2615                 return DRM_FORMAT_XRGB8888;
2616         case DISPPLANE_RGBX888:
2617                 return DRM_FORMAT_XBGR8888;
2618         case DISPPLANE_BGRX101010:
2619                 return DRM_FORMAT_XRGB2101010;
2620         case DISPPLANE_RGBX101010:
2621                 return DRM_FORMAT_XBGR2101010;
2622         }
2623 }
2624
2625 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2626 {
2627         switch (format) {
2628         case PLANE_CTL_FORMAT_RGB_565:
2629                 return DRM_FORMAT_RGB565;
2630         case PLANE_CTL_FORMAT_NV12:
2631                 return DRM_FORMAT_NV12;
2632         default:
2633         case PLANE_CTL_FORMAT_XRGB_8888:
2634                 if (rgb_order) {
2635                         if (alpha)
2636                                 return DRM_FORMAT_ABGR8888;
2637                         else
2638                                 return DRM_FORMAT_XBGR8888;
2639                 } else {
2640                         if (alpha)
2641                                 return DRM_FORMAT_ARGB8888;
2642                         else
2643                                 return DRM_FORMAT_XRGB8888;
2644                 }
2645         case PLANE_CTL_FORMAT_XRGB_2101010:
2646                 if (rgb_order)
2647                         return DRM_FORMAT_XBGR2101010;
2648                 else
2649                         return DRM_FORMAT_XRGB2101010;
2650         }
2651 }
2652
2653 static bool
2654 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2655                               struct intel_initial_plane_config *plane_config)
2656 {
2657         struct drm_device *dev = crtc->base.dev;
2658         struct drm_i915_private *dev_priv = to_i915(dev);
2659         struct drm_i915_gem_object *obj = NULL;
2660         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2661         struct drm_framebuffer *fb = &plane_config->fb->base;
2662         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2663         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2664                                     PAGE_SIZE);
2665
2666         size_aligned -= base_aligned;
2667
2668         if (plane_config->size == 0)
2669                 return false;
2670
2671         /* If the FB is too big, just don't use it since fbdev is not very
2672          * important and we should probably use that space with FBC or other
2673          * features. */
2674         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2675                 return false;
2676
2677         mutex_lock(&dev->struct_mutex);
2678         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2679                                                              base_aligned,
2680                                                              base_aligned,
2681                                                              size_aligned);
2682         mutex_unlock(&dev->struct_mutex);
2683         if (!obj)
2684                 return false;
2685
2686         if (plane_config->tiling == I915_TILING_X)
2687                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2688
2689         mode_cmd.pixel_format = fb->format->format;
2690         mode_cmd.width = fb->width;
2691         mode_cmd.height = fb->height;
2692         mode_cmd.pitches[0] = fb->pitches[0];
2693         mode_cmd.modifier[0] = fb->modifier;
2694         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2695
2696         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2697                 DRM_DEBUG_KMS("intel fb init failed\n");
2698                 goto out_unref_obj;
2699         }
2700
2701
2702         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2703         return true;
2704
2705 out_unref_obj:
2706         i915_gem_object_put(obj);
2707         return false;
2708 }
2709
2710 static void
2711 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2712                         struct intel_plane_state *plane_state,
2713                         bool visible)
2714 {
2715         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2716
2717         plane_state->base.visible = visible;
2718
2719         if (visible)
2720                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
2721         else
2722                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
2723 }
2724
2725 static void fixup_active_planes(struct intel_crtc_state *crtc_state)
2726 {
2727         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
2728         struct drm_plane *plane;
2729
2730         /*
2731          * Active_planes aliases if multiple "primary" or cursor planes
2732          * have been used on the same (or wrong) pipe. plane_mask uses
2733          * unique ids, hence we can use that to reconstruct active_planes.
2734          */
2735         crtc_state->active_planes = 0;
2736
2737         drm_for_each_plane_mask(plane, &dev_priv->drm,
2738                                 crtc_state->base.plane_mask)
2739                 crtc_state->active_planes |= BIT(to_intel_plane(plane)->id);
2740 }
2741
2742 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2743                                          struct intel_plane *plane)
2744 {
2745         struct intel_crtc_state *crtc_state =
2746                 to_intel_crtc_state(crtc->base.state);
2747         struct intel_plane_state *plane_state =
2748                 to_intel_plane_state(plane->base.state);
2749
2750         DRM_DEBUG_KMS("Disabling [PLANE:%d:%s] on [CRTC:%d:%s]\n",
2751                       plane->base.base.id, plane->base.name,
2752                       crtc->base.base.id, crtc->base.name);
2753
2754         intel_set_plane_visible(crtc_state, plane_state, false);
2755         fixup_active_planes(crtc_state);
2756
2757         if (plane->id == PLANE_PRIMARY)
2758                 intel_pre_disable_primary_noatomic(&crtc->base);
2759
2760         trace_intel_disable_plane(&plane->base, crtc);
2761         plane->disable_plane(plane, crtc);
2762 }
2763
2764 static void
2765 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2766                              struct intel_initial_plane_config *plane_config)
2767 {
2768         struct drm_device *dev = intel_crtc->base.dev;
2769         struct drm_i915_private *dev_priv = to_i915(dev);
2770         struct drm_crtc *c;
2771         struct drm_i915_gem_object *obj;
2772         struct drm_plane *primary = intel_crtc->base.primary;
2773         struct drm_plane_state *plane_state = primary->state;
2774         struct intel_plane *intel_plane = to_intel_plane(primary);
2775         struct intel_plane_state *intel_state =
2776                 to_intel_plane_state(plane_state);
2777         struct drm_framebuffer *fb;
2778
2779         if (!plane_config->fb)
2780                 return;
2781
2782         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2783                 fb = &plane_config->fb->base;
2784                 goto valid_fb;
2785         }
2786
2787         kfree(plane_config->fb);
2788
2789         /*
2790          * Failed to alloc the obj, check to see if we should share
2791          * an fb with another CRTC instead
2792          */
2793         for_each_crtc(dev, c) {
2794                 struct intel_plane_state *state;
2795
2796                 if (c == &intel_crtc->base)
2797                         continue;
2798
2799                 if (!to_intel_crtc(c)->active)
2800                         continue;
2801
2802                 state = to_intel_plane_state(c->primary->state);
2803                 if (!state->vma)
2804                         continue;
2805
2806                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2807                         fb = state->base.fb;
2808                         drm_framebuffer_get(fb);
2809                         goto valid_fb;
2810                 }
2811         }
2812
2813         /*
2814          * We've failed to reconstruct the BIOS FB.  Current display state
2815          * indicates that the primary plane is visible, but has a NULL FB,
2816          * which will lead to problems later if we don't fix it up.  The
2817          * simplest solution is to just disable the primary plane now and
2818          * pretend the BIOS never had it enabled.
2819          */
2820         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2821
2822         return;
2823
2824 valid_fb:
2825         intel_fill_fb_ggtt_view(&intel_state->view, fb,
2826                                 intel_state->base.rotation);
2827         intel_state->color_plane[0].stride =
2828                 intel_fb_pitch(fb, 0, intel_state->base.rotation);
2829
2830         mutex_lock(&dev->struct_mutex);
2831         intel_state->vma =
2832                 intel_pin_and_fence_fb_obj(fb,
2833                                            &intel_state->view,
2834                                            intel_plane_uses_fence(intel_state),
2835                                            &intel_state->flags);
2836         mutex_unlock(&dev->struct_mutex);
2837         if (IS_ERR(intel_state->vma)) {
2838                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2839                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2840
2841                 intel_state->vma = NULL;
2842                 drm_framebuffer_put(fb);
2843                 return;
2844         }
2845
2846         obj = intel_fb_obj(fb);
2847         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
2848
2849         plane_state->src_x = 0;
2850         plane_state->src_y = 0;
2851         plane_state->src_w = fb->width << 16;
2852         plane_state->src_h = fb->height << 16;
2853
2854         plane_state->crtc_x = 0;
2855         plane_state->crtc_y = 0;
2856         plane_state->crtc_w = fb->width;
2857         plane_state->crtc_h = fb->height;
2858
2859         intel_state->base.src = drm_plane_state_src(plane_state);
2860         intel_state->base.dst = drm_plane_state_dest(plane_state);
2861
2862         if (i915_gem_object_is_tiled(obj))
2863                 dev_priv->preserve_bios_swizzle = true;
2864
2865         plane_state->fb = fb;
2866         plane_state->crtc = &intel_crtc->base;
2867
2868         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2869                   &obj->frontbuffer_bits);
2870 }
2871
2872 static int skl_max_plane_width(const struct drm_framebuffer *fb,
2873                                int color_plane,
2874                                unsigned int rotation)
2875 {
2876         int cpp = fb->format->cpp[color_plane];
2877
2878         switch (fb->modifier) {
2879         case DRM_FORMAT_MOD_LINEAR:
2880         case I915_FORMAT_MOD_X_TILED:
2881                 switch (cpp) {
2882                 case 8:
2883                         return 4096;
2884                 case 4:
2885                 case 2:
2886                 case 1:
2887                         return 8192;
2888                 default:
2889                         MISSING_CASE(cpp);
2890                         break;
2891                 }
2892                 break;
2893         case I915_FORMAT_MOD_Y_TILED_CCS:
2894         case I915_FORMAT_MOD_Yf_TILED_CCS:
2895                 /* FIXME AUX plane? */
2896         case I915_FORMAT_MOD_Y_TILED:
2897         case I915_FORMAT_MOD_Yf_TILED:
2898                 switch (cpp) {
2899                 case 8:
2900                         return 2048;
2901                 case 4:
2902                         return 4096;
2903                 case 2:
2904                 case 1:
2905                         return 8192;
2906                 default:
2907                         MISSING_CASE(cpp);
2908                         break;
2909                 }
2910                 break;
2911         default:
2912                 MISSING_CASE(fb->modifier);
2913         }
2914
2915         return 2048;
2916 }
2917
2918 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2919                                            int main_x, int main_y, u32 main_offset)
2920 {
2921         const struct drm_framebuffer *fb = plane_state->base.fb;
2922         int hsub = fb->format->hsub;
2923         int vsub = fb->format->vsub;
2924         int aux_x = plane_state->color_plane[1].x;
2925         int aux_y = plane_state->color_plane[1].y;
2926         u32 aux_offset = plane_state->color_plane[1].offset;
2927         u32 alignment = intel_surf_alignment(fb, 1);
2928
2929         while (aux_offset >= main_offset && aux_y <= main_y) {
2930                 int x, y;
2931
2932                 if (aux_x == main_x && aux_y == main_y)
2933                         break;
2934
2935                 if (aux_offset == 0)
2936                         break;
2937
2938                 x = aux_x / hsub;
2939                 y = aux_y / vsub;
2940                 aux_offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 1,
2941                                                                aux_offset, aux_offset - alignment);
2942                 aux_x = x * hsub + aux_x % hsub;
2943                 aux_y = y * vsub + aux_y % vsub;
2944         }
2945
2946         if (aux_x != main_x || aux_y != main_y)
2947                 return false;
2948
2949         plane_state->color_plane[1].offset = aux_offset;
2950         plane_state->color_plane[1].x = aux_x;
2951         plane_state->color_plane[1].y = aux_y;
2952
2953         return true;
2954 }
2955
2956 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2957 {
2958         const struct drm_framebuffer *fb = plane_state->base.fb;
2959         unsigned int rotation = plane_state->base.rotation;
2960         int x = plane_state->base.src.x1 >> 16;
2961         int y = plane_state->base.src.y1 >> 16;
2962         int w = drm_rect_width(&plane_state->base.src) >> 16;
2963         int h = drm_rect_height(&plane_state->base.src) >> 16;
2964         int max_width = skl_max_plane_width(fb, 0, rotation);
2965         int max_height = 4096;
2966         u32 alignment, offset, aux_offset = plane_state->color_plane[1].offset;
2967
2968         if (w > max_width || h > max_height) {
2969                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2970                               w, h, max_width, max_height);
2971                 return -EINVAL;
2972         }
2973
2974         intel_add_fb_offsets(&x, &y, plane_state, 0);
2975         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 0);
2976         alignment = intel_surf_alignment(fb, 0);
2977
2978         /*
2979          * AUX surface offset is specified as the distance from the
2980          * main surface offset, and it must be non-negative. Make
2981          * sure that is what we will get.
2982          */
2983         if (offset > aux_offset)
2984                 offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
2985                                                            offset, aux_offset & ~(alignment - 1));
2986
2987         /*
2988          * When using an X-tiled surface, the plane blows up
2989          * if the x offset + width exceed the stride.
2990          *
2991          * TODO: linear and Y-tiled seem fine, Yf untested,
2992          */
2993         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
2994                 int cpp = fb->format->cpp[0];
2995
2996                 while ((x + w) * cpp > plane_state->color_plane[0].stride) {
2997                         if (offset == 0) {
2998                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
2999                                 return -EINVAL;
3000                         }
3001
3002                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3003                                                                    offset, offset - alignment);
3004                 }
3005         }
3006
3007         /*
3008          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3009          * they match with the main surface x/y offsets.
3010          */
3011         if (is_ccs_modifier(fb->modifier)) {
3012                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3013                         if (offset == 0)
3014                                 break;
3015
3016                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3017                                                                    offset, offset - alignment);
3018                 }
3019
3020                 if (x != plane_state->color_plane[1].x || y != plane_state->color_plane[1].y) {
3021                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3022                         return -EINVAL;
3023                 }
3024         }
3025
3026         plane_state->color_plane[0].offset = offset;
3027         plane_state->color_plane[0].x = x;
3028         plane_state->color_plane[0].y = y;
3029
3030         return 0;
3031 }
3032
3033 static int
3034 skl_check_nv12_surface(struct intel_plane_state *plane_state)
3035 {
3036         /* Display WA #1106 */
3037         if (plane_state->base.rotation !=
3038             (DRM_MODE_REFLECT_X | DRM_MODE_ROTATE_90) &&
3039             plane_state->base.rotation != DRM_MODE_ROTATE_270)
3040                 return 0;
3041
3042         /*
3043          * src coordinates are rotated here.
3044          * We check height but report it as width
3045          */
3046         if (((drm_rect_height(&plane_state->base.src) >> 16) % 4) != 0) {
3047                 DRM_DEBUG_KMS("src width must be multiple "
3048                               "of 4 for rotated NV12\n");
3049                 return -EINVAL;
3050         }
3051
3052         return 0;
3053 }
3054
3055 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3056 {
3057         const struct drm_framebuffer *fb = plane_state->base.fb;
3058         unsigned int rotation = plane_state->base.rotation;
3059         int max_width = skl_max_plane_width(fb, 1, rotation);
3060         int max_height = 4096;
3061         int x = plane_state->base.src.x1 >> 17;
3062         int y = plane_state->base.src.y1 >> 17;
3063         int w = drm_rect_width(&plane_state->base.src) >> 17;
3064         int h = drm_rect_height(&plane_state->base.src) >> 17;
3065         u32 offset;
3066
3067         intel_add_fb_offsets(&x, &y, plane_state, 1);
3068         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3069
3070         /* FIXME not quite sure how/if these apply to the chroma plane */
3071         if (w > max_width || h > max_height) {
3072                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3073                               w, h, max_width, max_height);
3074                 return -EINVAL;
3075         }
3076
3077         plane_state->color_plane[1].offset = offset;
3078         plane_state->color_plane[1].x = x;
3079         plane_state->color_plane[1].y = y;
3080
3081         return 0;
3082 }
3083
3084 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3085 {
3086         const struct drm_framebuffer *fb = plane_state->base.fb;
3087         int src_x = plane_state->base.src.x1 >> 16;
3088         int src_y = plane_state->base.src.y1 >> 16;
3089         int hsub = fb->format->hsub;
3090         int vsub = fb->format->vsub;
3091         int x = src_x / hsub;
3092         int y = src_y / vsub;
3093         u32 offset;
3094
3095         intel_add_fb_offsets(&x, &y, plane_state, 1);
3096         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3097
3098         plane_state->color_plane[1].offset = offset;
3099         plane_state->color_plane[1].x = x * hsub + src_x % hsub;
3100         plane_state->color_plane[1].y = y * vsub + src_y % vsub;
3101
3102         return 0;
3103 }
3104
3105 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3106 {
3107         const struct drm_framebuffer *fb = plane_state->base.fb;
3108         unsigned int rotation = plane_state->base.rotation;
3109         int ret;
3110
3111         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3112         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3113         plane_state->color_plane[1].stride = intel_fb_pitch(fb, 1, rotation);
3114
3115         ret = intel_plane_check_stride(plane_state);
3116         if (ret)
3117                 return ret;
3118
3119         /* HW only has 8 bits pixel precision, disable plane if invisible */
3120         if (!(plane_state->base.alpha >> 8))
3121                 plane_state->base.visible = false;
3122
3123         if (!plane_state->base.visible)
3124                 return 0;
3125
3126         /* Rotate src coordinates to match rotated GTT view */
3127         if (drm_rotation_90_or_270(rotation))
3128                 drm_rect_rotate(&plane_state->base.src,
3129                                 fb->width << 16, fb->height << 16,
3130                                 DRM_MODE_ROTATE_270);
3131
3132         /*
3133          * Handle the AUX surface first since
3134          * the main surface setup depends on it.
3135          */
3136         if (fb->format->format == DRM_FORMAT_NV12) {
3137                 ret = skl_check_nv12_surface(plane_state);
3138                 if (ret)
3139                         return ret;
3140                 ret = skl_check_nv12_aux_surface(plane_state);
3141                 if (ret)
3142                         return ret;
3143         } else if (is_ccs_modifier(fb->modifier)) {
3144                 ret = skl_check_ccs_aux_surface(plane_state);
3145                 if (ret)
3146                         return ret;
3147         } else {
3148                 plane_state->color_plane[1].offset = ~0xfff;
3149                 plane_state->color_plane[1].x = 0;
3150                 plane_state->color_plane[1].y = 0;
3151         }
3152
3153         ret = skl_check_main_surface(plane_state);
3154         if (ret)
3155                 return ret;
3156
3157         return 0;
3158 }
3159
3160 unsigned int
3161 i9xx_plane_max_stride(struct intel_plane *plane,
3162                       u32 pixel_format, u64 modifier,
3163                       unsigned int rotation)
3164 {
3165         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3166
3167         if (!HAS_GMCH_DISPLAY(dev_priv)) {
3168                 return 32*1024;
3169         } else if (INTEL_GEN(dev_priv) >= 4) {
3170                 if (modifier == I915_FORMAT_MOD_X_TILED)
3171                         return 16*1024;
3172                 else
3173                         return 32*1024;
3174         } else if (INTEL_GEN(dev_priv) >= 3) {
3175                 if (modifier == I915_FORMAT_MOD_X_TILED)
3176                         return 8*1024;
3177                 else
3178                         return 16*1024;
3179         } else {
3180                 if (plane->i9xx_plane == PLANE_C)
3181                         return 4*1024;
3182                 else
3183                         return 8*1024;
3184         }
3185 }
3186
3187 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3188                           const struct intel_plane_state *plane_state)
3189 {
3190         struct drm_i915_private *dev_priv =
3191                 to_i915(plane_state->base.plane->dev);
3192         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3193         const struct drm_framebuffer *fb = plane_state->base.fb;
3194         unsigned int rotation = plane_state->base.rotation;
3195         u32 dspcntr;
3196
3197         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3198
3199         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3200             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3201                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3202
3203         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3204                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3205
3206         if (INTEL_GEN(dev_priv) < 5)
3207                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3208
3209         switch (fb->format->format) {
3210         case DRM_FORMAT_C8:
3211                 dspcntr |= DISPPLANE_8BPP;
3212                 break;
3213         case DRM_FORMAT_XRGB1555:
3214                 dspcntr |= DISPPLANE_BGRX555;
3215                 break;
3216         case DRM_FORMAT_RGB565:
3217                 dspcntr |= DISPPLANE_BGRX565;
3218                 break;
3219         case DRM_FORMAT_XRGB8888:
3220                 dspcntr |= DISPPLANE_BGRX888;
3221                 break;
3222         case DRM_FORMAT_XBGR8888:
3223                 dspcntr |= DISPPLANE_RGBX888;
3224                 break;
3225         case DRM_FORMAT_XRGB2101010:
3226                 dspcntr |= DISPPLANE_BGRX101010;
3227                 break;
3228         case DRM_FORMAT_XBGR2101010:
3229                 dspcntr |= DISPPLANE_RGBX101010;
3230                 break;
3231         default:
3232                 MISSING_CASE(fb->format->format);
3233                 return 0;
3234         }
3235
3236         if (INTEL_GEN(dev_priv) >= 4 &&
3237             fb->modifier == I915_FORMAT_MOD_X_TILED)
3238                 dspcntr |= DISPPLANE_TILED;
3239
3240         if (rotation & DRM_MODE_ROTATE_180)
3241                 dspcntr |= DISPPLANE_ROTATE_180;
3242
3243         if (rotation & DRM_MODE_REFLECT_X)
3244                 dspcntr |= DISPPLANE_MIRROR;
3245
3246         return dspcntr;
3247 }
3248
3249 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3250 {
3251         struct drm_i915_private *dev_priv =
3252                 to_i915(plane_state->base.plane->dev);
3253         const struct drm_framebuffer *fb = plane_state->base.fb;
3254         unsigned int rotation = plane_state->base.rotation;
3255         int src_x = plane_state->base.src.x1 >> 16;
3256         int src_y = plane_state->base.src.y1 >> 16;
3257         u32 offset;
3258         int ret;
3259
3260         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3261         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3262
3263         ret = intel_plane_check_stride(plane_state);
3264         if (ret)
3265                 return ret;
3266
3267         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3268
3269         if (INTEL_GEN(dev_priv) >= 4)
3270                 offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
3271                                                             plane_state, 0);
3272         else
3273                 offset = 0;
3274
3275         /* HSW/BDW do this automagically in hardware */
3276         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3277                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3278                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3279
3280                 if (rotation & DRM_MODE_ROTATE_180) {
3281                         src_x += src_w - 1;
3282                         src_y += src_h - 1;
3283                 } else if (rotation & DRM_MODE_REFLECT_X) {
3284                         src_x += src_w - 1;
3285                 }
3286         }
3287
3288         plane_state->color_plane[0].offset = offset;
3289         plane_state->color_plane[0].x = src_x;
3290         plane_state->color_plane[0].y = src_y;
3291
3292         return 0;
3293 }
3294
3295 static int
3296 i9xx_plane_check(struct intel_crtc_state *crtc_state,
3297                  struct intel_plane_state *plane_state)
3298 {
3299         int ret;
3300
3301         ret = chv_plane_check_rotation(plane_state);
3302         if (ret)
3303                 return ret;
3304
3305         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
3306                                                   &crtc_state->base,
3307                                                   DRM_PLANE_HELPER_NO_SCALING,
3308                                                   DRM_PLANE_HELPER_NO_SCALING,
3309                                                   false, true);
3310         if (ret)
3311                 return ret;
3312
3313         if (!plane_state->base.visible)
3314                 return 0;
3315
3316         ret = intel_plane_check_src_coordinates(plane_state);
3317         if (ret)
3318                 return ret;
3319
3320         ret = i9xx_check_plane_surface(plane_state);
3321         if (ret)
3322                 return ret;
3323
3324         plane_state->ctl = i9xx_plane_ctl(crtc_state, plane_state);
3325
3326         return 0;
3327 }
3328
3329 static void i9xx_update_plane(struct intel_plane *plane,
3330                               const struct intel_crtc_state *crtc_state,
3331                               const struct intel_plane_state *plane_state)
3332 {
3333         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3334         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3335         u32 linear_offset;
3336         u32 dspcntr = plane_state->ctl;
3337         i915_reg_t reg = DSPCNTR(i9xx_plane);
3338         int x = plane_state->color_plane[0].x;
3339         int y = plane_state->color_plane[0].y;
3340         unsigned long irqflags;
3341         u32 dspaddr_offset;
3342
3343         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3344
3345         if (INTEL_GEN(dev_priv) >= 4)
3346                 dspaddr_offset = plane_state->color_plane[0].offset;
3347         else
3348                 dspaddr_offset = linear_offset;
3349
3350         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3351
3352         if (INTEL_GEN(dev_priv) < 4) {
3353                 /* pipesrc and dspsize control the size that is scaled from,
3354                  * which should always be the user's requested size.
3355                  */
3356                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3357                               ((crtc_state->pipe_src_h - 1) << 16) |
3358                               (crtc_state->pipe_src_w - 1));
3359                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3360         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3361                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3362                               ((crtc_state->pipe_src_h - 1) << 16) |
3363                               (crtc_state->pipe_src_w - 1));
3364                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3365                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3366         }
3367
3368         I915_WRITE_FW(reg, dspcntr);
3369
3370         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), plane_state->color_plane[0].stride);
3371         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3372                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3373                               intel_plane_ggtt_offset(plane_state) +
3374                               dspaddr_offset);
3375                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3376         } else if (INTEL_GEN(dev_priv) >= 4) {
3377                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3378                               intel_plane_ggtt_offset(plane_state) +
3379                               dspaddr_offset);
3380                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3381                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3382         } else {
3383                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3384                               intel_plane_ggtt_offset(plane_state) +
3385                               dspaddr_offset);
3386         }
3387         POSTING_READ_FW(reg);
3388
3389         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3390 }
3391
3392 static void i9xx_disable_plane(struct intel_plane *plane,
3393                                struct intel_crtc *crtc)
3394 {
3395         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3396         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3397         unsigned long irqflags;
3398
3399         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3400
3401         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3402         if (INTEL_GEN(dev_priv) >= 4)
3403                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3404         else
3405                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3406         POSTING_READ_FW(DSPCNTR(i9xx_plane));
3407
3408         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3409 }
3410
3411 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3412                                     enum pipe *pipe)
3413 {
3414         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3415         enum intel_display_power_domain power_domain;
3416         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3417         bool ret;
3418         u32 val;
3419
3420         /*
3421          * Not 100% correct for planes that can move between pipes,
3422          * but that's only the case for gen2-4 which don't have any
3423          * display power wells.
3424          */
3425         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3426         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3427                 return false;
3428
3429         val = I915_READ(DSPCNTR(i9xx_plane));
3430
3431         ret = val & DISPLAY_PLANE_ENABLE;
3432
3433         if (INTEL_GEN(dev_priv) >= 5)
3434                 *pipe = plane->pipe;
3435         else
3436                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3437                         DISPPLANE_SEL_PIPE_SHIFT;
3438
3439         intel_display_power_put(dev_priv, power_domain);
3440
3441         return ret;
3442 }
3443
3444 static u32
3445 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int color_plane)
3446 {
3447         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3448                 return 64;
3449         else
3450                 return intel_tile_width_bytes(fb, color_plane);
3451 }
3452
3453 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3454 {
3455         struct drm_device *dev = intel_crtc->base.dev;
3456         struct drm_i915_private *dev_priv = to_i915(dev);
3457
3458         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3459         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3460         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3461 }
3462
3463 /*
3464  * This function detaches (aka. unbinds) unused scalers in hardware
3465  */
3466 static void skl_detach_scalers(const struct intel_crtc_state *crtc_state)
3467 {
3468         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
3469         const struct intel_crtc_scaler_state *scaler_state =
3470                 &crtc_state->scaler_state;
3471         int i;
3472
3473         /* loop through and disable scalers that aren't in use */
3474         for (i = 0; i < intel_crtc->num_scalers; i++) {
3475                 if (!scaler_state->scalers[i].in_use)
3476                         skl_detach_scaler(intel_crtc, i);
3477         }
3478 }
3479
3480 u32 skl_plane_stride(const struct intel_plane_state *plane_state,
3481                      int color_plane)
3482 {
3483         const struct drm_framebuffer *fb = plane_state->base.fb;
3484         unsigned int rotation = plane_state->base.rotation;
3485         u32 stride = plane_state->color_plane[color_plane].stride;
3486
3487         if (color_plane >= fb->format->num_planes)
3488                 return 0;
3489
3490         /*
3491          * The stride is either expressed as a multiple of 64 bytes chunks for
3492          * linear buffers or in number of tiles for tiled buffers.
3493          */
3494         if (drm_rotation_90_or_270(rotation))
3495                 stride /= intel_tile_height(fb, color_plane);
3496         else
3497                 stride /= intel_fb_stride_alignment(fb, color_plane);
3498
3499         return stride;
3500 }
3501
3502 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3503 {
3504         switch (pixel_format) {
3505         case DRM_FORMAT_C8:
3506                 return PLANE_CTL_FORMAT_INDEXED;
3507         case DRM_FORMAT_RGB565:
3508                 return PLANE_CTL_FORMAT_RGB_565;
3509         case DRM_FORMAT_XBGR8888:
3510         case DRM_FORMAT_ABGR8888:
3511                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3512         case DRM_FORMAT_XRGB8888:
3513         case DRM_FORMAT_ARGB8888:
3514                 return PLANE_CTL_FORMAT_XRGB_8888;
3515         case DRM_FORMAT_XRGB2101010:
3516                 return PLANE_CTL_FORMAT_XRGB_2101010;
3517         case DRM_FORMAT_XBGR2101010:
3518                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3519         case DRM_FORMAT_YUYV:
3520                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3521         case DRM_FORMAT_YVYU:
3522                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3523         case DRM_FORMAT_UYVY:
3524                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3525         case DRM_FORMAT_VYUY:
3526                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3527         case DRM_FORMAT_NV12:
3528                 return PLANE_CTL_FORMAT_NV12;
3529         default:
3530                 MISSING_CASE(pixel_format);
3531         }
3532
3533         return 0;
3534 }
3535
3536 static u32 skl_plane_ctl_alpha(const struct intel_plane_state *plane_state)
3537 {
3538         if (!plane_state->base.fb->format->has_alpha)
3539                 return PLANE_CTL_ALPHA_DISABLE;
3540
3541         switch (plane_state->base.pixel_blend_mode) {
3542         case DRM_MODE_BLEND_PIXEL_NONE:
3543                 return PLANE_CTL_ALPHA_DISABLE;
3544         case DRM_MODE_BLEND_PREMULTI:
3545                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3546         case DRM_MODE_BLEND_COVERAGE:
3547                 return PLANE_CTL_ALPHA_HW_PREMULTIPLY;
3548         default:
3549                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3550                 return PLANE_CTL_ALPHA_DISABLE;
3551         }
3552 }
3553
3554 static u32 glk_plane_color_ctl_alpha(const struct intel_plane_state *plane_state)
3555 {
3556         if (!plane_state->base.fb->format->has_alpha)
3557                 return PLANE_COLOR_ALPHA_DISABLE;
3558
3559         switch (plane_state->base.pixel_blend_mode) {
3560         case DRM_MODE_BLEND_PIXEL_NONE:
3561                 return PLANE_COLOR_ALPHA_DISABLE;
3562         case DRM_MODE_BLEND_PREMULTI:
3563                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3564         case DRM_MODE_BLEND_COVERAGE:
3565                 return PLANE_COLOR_ALPHA_HW_PREMULTIPLY;
3566         default:
3567                 MISSING_CASE(plane_state->base.pixel_blend_mode);
3568                 return PLANE_COLOR_ALPHA_DISABLE;
3569         }
3570 }
3571
3572 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3573 {
3574         switch (fb_modifier) {
3575         case DRM_FORMAT_MOD_LINEAR:
3576                 break;
3577         case I915_FORMAT_MOD_X_TILED:
3578                 return PLANE_CTL_TILED_X;
3579         case I915_FORMAT_MOD_Y_TILED:
3580                 return PLANE_CTL_TILED_Y;
3581         case I915_FORMAT_MOD_Y_TILED_CCS:
3582                 return PLANE_CTL_TILED_Y | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3583         case I915_FORMAT_MOD_Yf_TILED:
3584                 return PLANE_CTL_TILED_YF;
3585         case I915_FORMAT_MOD_Yf_TILED_CCS:
3586                 return PLANE_CTL_TILED_YF | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3587         default:
3588                 MISSING_CASE(fb_modifier);
3589         }
3590
3591         return 0;
3592 }
3593
3594 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3595 {
3596         switch (rotate) {
3597         case DRM_MODE_ROTATE_0:
3598                 break;
3599         /*
3600          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3601          * while i915 HW rotation is clockwise, thats why this swapping.
3602          */
3603         case DRM_MODE_ROTATE_90:
3604                 return PLANE_CTL_ROTATE_270;
3605         case DRM_MODE_ROTATE_180:
3606                 return PLANE_CTL_ROTATE_180;
3607         case DRM_MODE_ROTATE_270:
3608                 return PLANE_CTL_ROTATE_90;
3609         default:
3610                 MISSING_CASE(rotate);
3611         }
3612
3613         return 0;
3614 }
3615
3616 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3617 {
3618         switch (reflect) {
3619         case 0:
3620                 break;
3621         case DRM_MODE_REFLECT_X:
3622                 return PLANE_CTL_FLIP_HORIZONTAL;
3623         case DRM_MODE_REFLECT_Y:
3624         default:
3625                 MISSING_CASE(reflect);
3626         }
3627
3628         return 0;
3629 }
3630
3631 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3632                   const struct intel_plane_state *plane_state)
3633 {
3634         struct drm_i915_private *dev_priv =
3635                 to_i915(plane_state->base.plane->dev);
3636         const struct drm_framebuffer *fb = plane_state->base.fb;
3637         unsigned int rotation = plane_state->base.rotation;
3638         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3639         u32 plane_ctl;
3640
3641         plane_ctl = PLANE_CTL_ENABLE;
3642
3643         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3644                 plane_ctl |= skl_plane_ctl_alpha(plane_state);
3645                 plane_ctl |=
3646                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3647                         PLANE_CTL_PIPE_CSC_ENABLE |
3648                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3649
3650                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3651                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3652
3653                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3654                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3655         }
3656
3657         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3658         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3659         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3660
3661         if (INTEL_GEN(dev_priv) >= 10)
3662                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3663                                                 DRM_MODE_REFLECT_MASK);
3664
3665         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3666                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3667         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3668                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3669
3670         return plane_ctl;
3671 }
3672
3673 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3674                         const struct intel_plane_state *plane_state)
3675 {
3676         struct drm_i915_private *dev_priv =
3677                 to_i915(plane_state->base.plane->dev);
3678         const struct drm_framebuffer *fb = plane_state->base.fb;
3679         u32 plane_color_ctl = 0;
3680
3681         if (INTEL_GEN(dev_priv) < 11) {
3682                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3683                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3684         }
3685         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3686         plane_color_ctl |= glk_plane_color_ctl_alpha(plane_state);
3687
3688         if (fb->format->is_yuv) {
3689                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3690                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3691                 else
3692                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3693
3694                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3695                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3696         }
3697
3698         return plane_color_ctl;
3699 }
3700
3701 static int
3702 __intel_display_resume(struct drm_device *dev,
3703                        struct drm_atomic_state *state,
3704                        struct drm_modeset_acquire_ctx *ctx)
3705 {
3706         struct drm_crtc_state *crtc_state;
3707         struct drm_crtc *crtc;
3708         int i, ret;
3709
3710         intel_modeset_setup_hw_state(dev, ctx);
3711         i915_redisable_vga(to_i915(dev));
3712
3713         if (!state)
3714                 return 0;
3715
3716         /*
3717          * We've duplicated the state, pointers to the old state are invalid.
3718          *
3719          * Don't attempt to use the old state until we commit the duplicated state.
3720          */
3721         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3722                 /*
3723                  * Force recalculation even if we restore
3724                  * current state. With fast modeset this may not result
3725                  * in a modeset when the state is compatible.
3726                  */
3727                 crtc_state->mode_changed = true;
3728         }
3729
3730         /* ignore any reset values/BIOS leftovers in the WM registers */
3731         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3732                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3733
3734         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3735
3736         WARN_ON(ret == -EDEADLK);
3737         return ret;
3738 }
3739
3740 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3741 {
3742         return intel_has_gpu_reset(dev_priv) &&
3743                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3744 }
3745
3746 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3747 {
3748         struct drm_device *dev = &dev_priv->drm;
3749         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3750         struct drm_atomic_state *state;
3751         int ret;
3752
3753         /* reset doesn't touch the display */
3754         if (!i915_modparams.force_reset_modeset_test &&
3755             !gpu_reset_clobbers_display(dev_priv))
3756                 return;
3757
3758         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3759         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3760         wake_up_all(&dev_priv->gpu_error.wait_queue);
3761
3762         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3763                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3764                 i915_gem_set_wedged(dev_priv);
3765         }
3766
3767         /*
3768          * Need mode_config.mutex so that we don't
3769          * trample ongoing ->detect() and whatnot.
3770          */
3771         mutex_lock(&dev->mode_config.mutex);
3772         drm_modeset_acquire_init(ctx, 0);
3773         while (1) {
3774                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3775                 if (ret != -EDEADLK)
3776                         break;
3777
3778                 drm_modeset_backoff(ctx);
3779         }
3780         /*
3781          * Disabling the crtcs gracefully seems nicer. Also the
3782          * g33 docs say we should at least disable all the planes.
3783          */
3784         state = drm_atomic_helper_duplicate_state(dev, ctx);
3785         if (IS_ERR(state)) {
3786                 ret = PTR_ERR(state);
3787                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3788                 return;
3789         }
3790
3791         ret = drm_atomic_helper_disable_all(dev, ctx);
3792         if (ret) {
3793                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3794                 drm_atomic_state_put(state);
3795                 return;
3796         }
3797
3798         dev_priv->modeset_restore_state = state;
3799         state->acquire_ctx = ctx;
3800 }
3801
3802 void intel_finish_reset(struct drm_i915_private *dev_priv)
3803 {
3804         struct drm_device *dev = &dev_priv->drm;
3805         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3806         struct drm_atomic_state *state;
3807         int ret;
3808
3809         /* reset doesn't touch the display */
3810         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
3811                 return;
3812
3813         state = fetch_and_zero(&dev_priv->modeset_restore_state);
3814         if (!state)
3815                 goto unlock;
3816
3817         /* reset doesn't touch the display */
3818         if (!gpu_reset_clobbers_display(dev_priv)) {
3819                 /* for testing only restore the display */
3820                 ret = __intel_display_resume(dev, state, ctx);
3821                 if (ret)
3822                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3823         } else {
3824                 /*
3825                  * The display has been reset as well,
3826                  * so need a full re-initialization.
3827                  */
3828                 intel_runtime_pm_disable_interrupts(dev_priv);
3829                 intel_runtime_pm_enable_interrupts(dev_priv);
3830
3831                 intel_pps_unlock_regs_wa(dev_priv);
3832                 intel_modeset_init_hw(dev);
3833                 intel_init_clock_gating(dev_priv);
3834
3835                 spin_lock_irq(&dev_priv->irq_lock);
3836                 if (dev_priv->display.hpd_irq_setup)
3837                         dev_priv->display.hpd_irq_setup(dev_priv);
3838                 spin_unlock_irq(&dev_priv->irq_lock);
3839
3840                 ret = __intel_display_resume(dev, state, ctx);
3841                 if (ret)
3842                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3843
3844                 intel_hpd_init(dev_priv);
3845         }
3846
3847         drm_atomic_state_put(state);
3848 unlock:
3849         drm_modeset_drop_locks(ctx);
3850         drm_modeset_acquire_fini(ctx);
3851         mutex_unlock(&dev->mode_config.mutex);
3852
3853         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3854 }
3855
3856 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3857                                      const struct intel_crtc_state *new_crtc_state)
3858 {
3859         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3860         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3861
3862         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3863         crtc->base.mode = new_crtc_state->base.mode;
3864
3865         /*
3866          * Update pipe size and adjust fitter if needed: the reason for this is
3867          * that in compute_mode_changes we check the native mode (not the pfit
3868          * mode) to see if we can flip rather than do a full mode set. In the
3869          * fastboot case, we'll flip, but if we don't update the pipesrc and
3870          * pfit state, we'll end up with a big fb scanned out into the wrong
3871          * sized surface.
3872          */
3873
3874         I915_WRITE(PIPESRC(crtc->pipe),
3875                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3876                    (new_crtc_state->pipe_src_h - 1));
3877
3878         /* on skylake this is done by detaching scalers */
3879         if (INTEL_GEN(dev_priv) >= 9) {
3880                 skl_detach_scalers(new_crtc_state);
3881
3882                 if (new_crtc_state->pch_pfit.enabled)
3883                         skylake_pfit_enable(new_crtc_state);
3884         } else if (HAS_PCH_SPLIT(dev_priv)) {
3885                 if (new_crtc_state->pch_pfit.enabled)
3886                         ironlake_pfit_enable(new_crtc_state);
3887                 else if (old_crtc_state->pch_pfit.enabled)
3888                         ironlake_pfit_disable(old_crtc_state);
3889         }
3890 }
3891
3892 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3893 {
3894         struct drm_device *dev = crtc->base.dev;
3895         struct drm_i915_private *dev_priv = to_i915(dev);
3896         int pipe = crtc->pipe;
3897         i915_reg_t reg;
3898         u32 temp;
3899
3900         /* enable normal train */
3901         reg = FDI_TX_CTL(pipe);
3902         temp = I915_READ(reg);
3903         if (IS_IVYBRIDGE(dev_priv)) {
3904                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3905                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3906         } else {
3907                 temp &= ~FDI_LINK_TRAIN_NONE;
3908                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3909         }
3910         I915_WRITE(reg, temp);
3911
3912         reg = FDI_RX_CTL(pipe);
3913         temp = I915_READ(reg);
3914         if (HAS_PCH_CPT(dev_priv)) {
3915                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3916                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3917         } else {
3918                 temp &= ~FDI_LINK_TRAIN_NONE;
3919                 temp |= FDI_LINK_TRAIN_NONE;
3920         }
3921         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3922
3923         /* wait one idle pattern time */
3924         POSTING_READ(reg);
3925         udelay(1000);
3926
3927         /* IVB wants error correction enabled */
3928         if (IS_IVYBRIDGE(dev_priv))
3929                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3930                            FDI_FE_ERRC_ENABLE);
3931 }
3932
3933 /* The FDI link training functions for ILK/Ibexpeak. */
3934 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3935                                     const struct intel_crtc_state *crtc_state)
3936 {
3937         struct drm_device *dev = crtc->base.dev;
3938         struct drm_i915_private *dev_priv = to_i915(dev);
3939         int pipe = crtc->pipe;
3940         i915_reg_t reg;
3941         u32 temp, tries;
3942
3943         /* FDI needs bits from pipe first */
3944         assert_pipe_enabled(dev_priv, pipe);
3945
3946         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3947            for train result */
3948         reg = FDI_RX_IMR(pipe);
3949         temp = I915_READ(reg);
3950         temp &= ~FDI_RX_SYMBOL_LOCK;
3951         temp &= ~FDI_RX_BIT_LOCK;
3952         I915_WRITE(reg, temp);
3953         I915_READ(reg);
3954         udelay(150);
3955
3956         /* enable CPU FDI TX and PCH FDI RX */
3957         reg = FDI_TX_CTL(pipe);
3958         temp = I915_READ(reg);
3959         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3960         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3961         temp &= ~FDI_LINK_TRAIN_NONE;
3962         temp |= FDI_LINK_TRAIN_PATTERN_1;
3963         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3964
3965         reg = FDI_RX_CTL(pipe);
3966         temp = I915_READ(reg);
3967         temp &= ~FDI_LINK_TRAIN_NONE;
3968         temp |= FDI_LINK_TRAIN_PATTERN_1;
3969         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3970
3971         POSTING_READ(reg);
3972         udelay(150);
3973
3974         /* Ironlake workaround, enable clock pointer after FDI enable*/
3975         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3976         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3977                    FDI_RX_PHASE_SYNC_POINTER_EN);
3978
3979         reg = FDI_RX_IIR(pipe);
3980         for (tries = 0; tries < 5; tries++) {
3981                 temp = I915_READ(reg);
3982                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3983
3984                 if ((temp & FDI_RX_BIT_LOCK)) {
3985                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3986                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3987                         break;
3988                 }
3989         }
3990         if (tries == 5)
3991                 DRM_ERROR("FDI train 1 fail!\n");
3992
3993         /* Train 2 */
3994         reg = FDI_TX_CTL(pipe);
3995         temp = I915_READ(reg);
3996         temp &= ~FDI_LINK_TRAIN_NONE;
3997         temp |= FDI_LINK_TRAIN_PATTERN_2;
3998         I915_WRITE(reg, temp);
3999
4000         reg = FDI_RX_CTL(pipe);
4001         temp = I915_READ(reg);
4002         temp &= ~FDI_LINK_TRAIN_NONE;
4003         temp |= FDI_LINK_TRAIN_PATTERN_2;
4004         I915_WRITE(reg, temp);
4005
4006         POSTING_READ(reg);
4007         udelay(150);
4008
4009         reg = FDI_RX_IIR(pipe);
4010         for (tries = 0; tries < 5; tries++) {
4011                 temp = I915_READ(reg);
4012                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4013
4014                 if (temp & FDI_RX_SYMBOL_LOCK) {
4015                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4016                         DRM_DEBUG_KMS("FDI train 2 done.\n");
4017                         break;
4018                 }
4019         }
4020         if (tries == 5)
4021                 DRM_ERROR("FDI train 2 fail!\n");
4022
4023         DRM_DEBUG_KMS("FDI train done\n");
4024
4025 }
4026
4027 static const int snb_b_fdi_train_param[] = {
4028         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4029         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4030         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4031         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4032 };
4033
4034 /* The FDI link training functions for SNB/Cougarpoint. */
4035 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4036                                 const struct intel_crtc_state *crtc_state)
4037 {
4038         struct drm_device *dev = crtc->base.dev;
4039         struct drm_i915_private *dev_priv = to_i915(dev);
4040         int pipe = crtc->pipe;
4041         i915_reg_t reg;
4042         u32 temp, i, retry;
4043
4044         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4045            for train result */
4046         reg = FDI_RX_IMR(pipe);
4047         temp = I915_READ(reg);
4048         temp &= ~FDI_RX_SYMBOL_LOCK;
4049         temp &= ~FDI_RX_BIT_LOCK;
4050         I915_WRITE(reg, temp);
4051
4052         POSTING_READ(reg);
4053         udelay(150);
4054
4055         /* enable CPU FDI TX and PCH FDI RX */
4056         reg = FDI_TX_CTL(pipe);
4057         temp = I915_READ(reg);
4058         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4059         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4060         temp &= ~FDI_LINK_TRAIN_NONE;
4061         temp |= FDI_LINK_TRAIN_PATTERN_1;
4062         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4063         /* SNB-B */
4064         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4065         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4066
4067         I915_WRITE(FDI_RX_MISC(pipe),
4068                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4069
4070         reg = FDI_RX_CTL(pipe);
4071         temp = I915_READ(reg);
4072         if (HAS_PCH_CPT(dev_priv)) {
4073                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4074                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4075         } else {
4076                 temp &= ~FDI_LINK_TRAIN_NONE;
4077                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4078         }
4079         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4080
4081         POSTING_READ(reg);
4082         udelay(150);
4083
4084         for (i = 0; i < 4; i++) {
4085                 reg = FDI_TX_CTL(pipe);
4086                 temp = I915_READ(reg);
4087                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4088                 temp |= snb_b_fdi_train_param[i];
4089                 I915_WRITE(reg, temp);
4090
4091                 POSTING_READ(reg);
4092                 udelay(500);
4093
4094                 for (retry = 0; retry < 5; retry++) {
4095                         reg = FDI_RX_IIR(pipe);
4096                         temp = I915_READ(reg);
4097                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4098                         if (temp & FDI_RX_BIT_LOCK) {
4099                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4100                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4101                                 break;
4102                         }
4103                         udelay(50);
4104                 }
4105                 if (retry < 5)
4106                         break;
4107         }
4108         if (i == 4)
4109                 DRM_ERROR("FDI train 1 fail!\n");
4110
4111         /* Train 2 */
4112         reg = FDI_TX_CTL(pipe);
4113         temp = I915_READ(reg);
4114         temp &= ~FDI_LINK_TRAIN_NONE;
4115         temp |= FDI_LINK_TRAIN_PATTERN_2;
4116         if (IS_GEN6(dev_priv)) {
4117                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4118                 /* SNB-B */
4119                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4120         }
4121         I915_WRITE(reg, temp);
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_2_CPT;
4128         } else {
4129                 temp &= ~FDI_LINK_TRAIN_NONE;
4130                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4131         }
4132         I915_WRITE(reg, temp);
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_SYMBOL_LOCK) {
4152                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4153                                 DRM_DEBUG_KMS("FDI train 2 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 2 fail!\n");
4163
4164         DRM_DEBUG_KMS("FDI train done.\n");
4165 }
4166
4167 /* Manual link training for Ivy Bridge A0 parts */
4168 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4169                                       const struct intel_crtc_state *crtc_state)
4170 {
4171         struct drm_device *dev = crtc->base.dev;
4172         struct drm_i915_private *dev_priv = to_i915(dev);
4173         int pipe = crtc->pipe;
4174         i915_reg_t reg;
4175         u32 temp, i, j;
4176
4177         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4178            for train result */
4179         reg = FDI_RX_IMR(pipe);
4180         temp = I915_READ(reg);
4181         temp &= ~FDI_RX_SYMBOL_LOCK;
4182         temp &= ~FDI_RX_BIT_LOCK;
4183         I915_WRITE(reg, temp);
4184
4185         POSTING_READ(reg);
4186         udelay(150);
4187
4188         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4189                       I915_READ(FDI_RX_IIR(pipe)));
4190
4191         /* Try each vswing and preemphasis setting twice before moving on */
4192         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4193                 /* disable first in case we need to retry */
4194                 reg = FDI_TX_CTL(pipe);
4195                 temp = I915_READ(reg);
4196                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4197                 temp &= ~FDI_TX_ENABLE;
4198                 I915_WRITE(reg, temp);
4199
4200                 reg = FDI_RX_CTL(pipe);
4201                 temp = I915_READ(reg);
4202                 temp &= ~FDI_LINK_TRAIN_AUTO;
4203                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4204                 temp &= ~FDI_RX_ENABLE;
4205                 I915_WRITE(reg, temp);
4206
4207                 /* enable CPU FDI TX and PCH FDI RX */
4208                 reg = FDI_TX_CTL(pipe);
4209                 temp = I915_READ(reg);
4210                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4211                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4212                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4213                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4214                 temp |= snb_b_fdi_train_param[j/2];
4215                 temp |= FDI_COMPOSITE_SYNC;
4216                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4217
4218                 I915_WRITE(FDI_RX_MISC(pipe),
4219                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4220
4221                 reg = FDI_RX_CTL(pipe);
4222                 temp = I915_READ(reg);
4223                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4224                 temp |= FDI_COMPOSITE_SYNC;
4225                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4226
4227                 POSTING_READ(reg);
4228                 udelay(1); /* should be 0.5us */
4229
4230                 for (i = 0; i < 4; i++) {
4231                         reg = FDI_RX_IIR(pipe);
4232                         temp = I915_READ(reg);
4233                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4234
4235                         if (temp & FDI_RX_BIT_LOCK ||
4236                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4237                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4238                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4239                                               i);
4240                                 break;
4241                         }
4242                         udelay(1); /* should be 0.5us */
4243                 }
4244                 if (i == 4) {
4245                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4246                         continue;
4247                 }
4248
4249                 /* Train 2 */
4250                 reg = FDI_TX_CTL(pipe);
4251                 temp = I915_READ(reg);
4252                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4253                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4254                 I915_WRITE(reg, temp);
4255
4256                 reg = FDI_RX_CTL(pipe);
4257                 temp = I915_READ(reg);
4258                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4259                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4260                 I915_WRITE(reg, temp);
4261
4262                 POSTING_READ(reg);
4263                 udelay(2); /* should be 1.5us */
4264
4265                 for (i = 0; i < 4; i++) {
4266                         reg = FDI_RX_IIR(pipe);
4267                         temp = I915_READ(reg);
4268                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4269
4270                         if (temp & FDI_RX_SYMBOL_LOCK ||
4271                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4272                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4273                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4274                                               i);
4275                                 goto train_done;
4276                         }
4277                         udelay(2); /* should be 1.5us */
4278                 }
4279                 if (i == 4)
4280                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4281         }
4282
4283 train_done:
4284         DRM_DEBUG_KMS("FDI train done.\n");
4285 }
4286
4287 static void ironlake_fdi_pll_enable(const struct intel_crtc_state *crtc_state)
4288 {
4289         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
4290         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4291         int pipe = intel_crtc->pipe;
4292         i915_reg_t reg;
4293         u32 temp;
4294
4295         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4296         reg = FDI_RX_CTL(pipe);
4297         temp = I915_READ(reg);
4298         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4299         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4300         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4301         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4302
4303         POSTING_READ(reg);
4304         udelay(200);
4305
4306         /* Switch from Rawclk to PCDclk */
4307         temp = I915_READ(reg);
4308         I915_WRITE(reg, temp | FDI_PCDCLK);
4309
4310         POSTING_READ(reg);
4311         udelay(200);
4312
4313         /* Enable CPU FDI TX PLL, always on for Ironlake */
4314         reg = FDI_TX_CTL(pipe);
4315         temp = I915_READ(reg);
4316         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4317                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4318
4319                 POSTING_READ(reg);
4320                 udelay(100);
4321         }
4322 }
4323
4324 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4325 {
4326         struct drm_device *dev = intel_crtc->base.dev;
4327         struct drm_i915_private *dev_priv = to_i915(dev);
4328         int pipe = intel_crtc->pipe;
4329         i915_reg_t reg;
4330         u32 temp;
4331
4332         /* Switch from PCDclk to Rawclk */
4333         reg = FDI_RX_CTL(pipe);
4334         temp = I915_READ(reg);
4335         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4336
4337         /* Disable CPU FDI TX PLL */
4338         reg = FDI_TX_CTL(pipe);
4339         temp = I915_READ(reg);
4340         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4341
4342         POSTING_READ(reg);
4343         udelay(100);
4344
4345         reg = FDI_RX_CTL(pipe);
4346         temp = I915_READ(reg);
4347         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4348
4349         /* Wait for the clocks to turn off. */
4350         POSTING_READ(reg);
4351         udelay(100);
4352 }
4353
4354 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4355 {
4356         struct drm_device *dev = crtc->dev;
4357         struct drm_i915_private *dev_priv = to_i915(dev);
4358         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4359         int pipe = intel_crtc->pipe;
4360         i915_reg_t reg;
4361         u32 temp;
4362
4363         /* disable CPU FDI tx and PCH FDI rx */
4364         reg = FDI_TX_CTL(pipe);
4365         temp = I915_READ(reg);
4366         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4367         POSTING_READ(reg);
4368
4369         reg = FDI_RX_CTL(pipe);
4370         temp = I915_READ(reg);
4371         temp &= ~(0x7 << 16);
4372         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4373         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4374
4375         POSTING_READ(reg);
4376         udelay(100);
4377
4378         /* Ironlake workaround, disable clock pointer after downing FDI */
4379         if (HAS_PCH_IBX(dev_priv))
4380                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4381
4382         /* still set train pattern 1 */
4383         reg = FDI_TX_CTL(pipe);
4384         temp = I915_READ(reg);
4385         temp &= ~FDI_LINK_TRAIN_NONE;
4386         temp |= FDI_LINK_TRAIN_PATTERN_1;
4387         I915_WRITE(reg, temp);
4388
4389         reg = FDI_RX_CTL(pipe);
4390         temp = I915_READ(reg);
4391         if (HAS_PCH_CPT(dev_priv)) {
4392                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4393                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4394         } else {
4395                 temp &= ~FDI_LINK_TRAIN_NONE;
4396                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4397         }
4398         /* BPC in FDI rx is consistent with that in PIPECONF */
4399         temp &= ~(0x07 << 16);
4400         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4401         I915_WRITE(reg, temp);
4402
4403         POSTING_READ(reg);
4404         udelay(100);
4405 }
4406
4407 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4408 {
4409         struct drm_crtc *crtc;
4410         bool cleanup_done;
4411
4412         drm_for_each_crtc(crtc, &dev_priv->drm) {
4413                 struct drm_crtc_commit *commit;
4414                 spin_lock(&crtc->commit_lock);
4415                 commit = list_first_entry_or_null(&crtc->commit_list,
4416                                                   struct drm_crtc_commit, commit_entry);
4417                 cleanup_done = commit ?
4418                         try_wait_for_completion(&commit->cleanup_done) : true;
4419                 spin_unlock(&crtc->commit_lock);
4420
4421                 if (cleanup_done)
4422                         continue;
4423
4424                 drm_crtc_wait_one_vblank(crtc);
4425
4426                 return true;
4427         }
4428
4429         return false;
4430 }
4431
4432 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4433 {
4434         u32 temp;
4435
4436         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4437
4438         mutex_lock(&dev_priv->sb_lock);
4439
4440         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4441         temp |= SBI_SSCCTL_DISABLE;
4442         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4443
4444         mutex_unlock(&dev_priv->sb_lock);
4445 }
4446
4447 /* Program iCLKIP clock to the desired frequency */
4448 static void lpt_program_iclkip(struct intel_crtc *crtc)
4449 {
4450         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4451         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4452         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4453         u32 temp;
4454
4455         lpt_disable_iclkip(dev_priv);
4456
4457         /* The iCLK virtual clock root frequency is in MHz,
4458          * but the adjusted_mode->crtc_clock in in KHz. To get the
4459          * divisors, it is necessary to divide one by another, so we
4460          * convert the virtual clock precision to KHz here for higher
4461          * precision.
4462          */
4463         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4464                 u32 iclk_virtual_root_freq = 172800 * 1000;
4465                 u32 iclk_pi_range = 64;
4466                 u32 desired_divisor;
4467
4468                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4469                                                     clock << auxdiv);
4470                 divsel = (desired_divisor / iclk_pi_range) - 2;
4471                 phaseinc = desired_divisor % iclk_pi_range;
4472
4473                 /*
4474                  * Near 20MHz is a corner case which is
4475                  * out of range for the 7-bit divisor
4476                  */
4477                 if (divsel <= 0x7f)
4478                         break;
4479         }
4480
4481         /* This should not happen with any sane values */
4482         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4483                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4484         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4485                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4486
4487         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4488                         clock,
4489                         auxdiv,
4490                         divsel,
4491                         phasedir,
4492                         phaseinc);
4493
4494         mutex_lock(&dev_priv->sb_lock);
4495
4496         /* Program SSCDIVINTPHASE6 */
4497         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4498         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4499         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4500         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4501         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4502         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4503         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4504         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4505
4506         /* Program SSCAUXDIV */
4507         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4508         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4509         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4510         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4511
4512         /* Enable modulator and associated divider */
4513         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4514         temp &= ~SBI_SSCCTL_DISABLE;
4515         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4516
4517         mutex_unlock(&dev_priv->sb_lock);
4518
4519         /* Wait for initialization time */
4520         udelay(24);
4521
4522         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4523 }
4524
4525 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4526 {
4527         u32 divsel, phaseinc, auxdiv;
4528         u32 iclk_virtual_root_freq = 172800 * 1000;
4529         u32 iclk_pi_range = 64;
4530         u32 desired_divisor;
4531         u32 temp;
4532
4533         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4534                 return 0;
4535
4536         mutex_lock(&dev_priv->sb_lock);
4537
4538         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4539         if (temp & SBI_SSCCTL_DISABLE) {
4540                 mutex_unlock(&dev_priv->sb_lock);
4541                 return 0;
4542         }
4543
4544         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4545         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4546                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4547         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4548                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4549
4550         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4551         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4552                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4553
4554         mutex_unlock(&dev_priv->sb_lock);
4555
4556         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4557
4558         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4559                                  desired_divisor << auxdiv);
4560 }
4561
4562 static void ironlake_pch_transcoder_set_timings(const struct intel_crtc_state *crtc_state,
4563                                                 enum pipe pch_transcoder)
4564 {
4565         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4566         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4567         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4568
4569         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4570                    I915_READ(HTOTAL(cpu_transcoder)));
4571         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4572                    I915_READ(HBLANK(cpu_transcoder)));
4573         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4574                    I915_READ(HSYNC(cpu_transcoder)));
4575
4576         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4577                    I915_READ(VTOTAL(cpu_transcoder)));
4578         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4579                    I915_READ(VBLANK(cpu_transcoder)));
4580         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4581                    I915_READ(VSYNC(cpu_transcoder)));
4582         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4583                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4584 }
4585
4586 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4587 {
4588         struct drm_i915_private *dev_priv = to_i915(dev);
4589         uint32_t temp;
4590
4591         temp = I915_READ(SOUTH_CHICKEN1);
4592         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4593                 return;
4594
4595         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4596         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4597
4598         temp &= ~FDI_BC_BIFURCATION_SELECT;
4599         if (enable)
4600                 temp |= FDI_BC_BIFURCATION_SELECT;
4601
4602         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4603         I915_WRITE(SOUTH_CHICKEN1, temp);
4604         POSTING_READ(SOUTH_CHICKEN1);
4605 }
4606
4607 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4608 {
4609         struct drm_device *dev = intel_crtc->base.dev;
4610
4611         switch (intel_crtc->pipe) {
4612         case PIPE_A:
4613                 break;
4614         case PIPE_B:
4615                 if (intel_crtc->config->fdi_lanes > 2)
4616                         cpt_set_fdi_bc_bifurcation(dev, false);
4617                 else
4618                         cpt_set_fdi_bc_bifurcation(dev, true);
4619
4620                 break;
4621         case PIPE_C:
4622                 cpt_set_fdi_bc_bifurcation(dev, true);
4623
4624                 break;
4625         default:
4626                 BUG();
4627         }
4628 }
4629
4630 /*
4631  * Finds the encoder associated with the given CRTC. This can only be
4632  * used when we know that the CRTC isn't feeding multiple encoders!
4633  */
4634 static struct intel_encoder *
4635 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
4636                            const struct intel_crtc_state *crtc_state)
4637 {
4638         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4639         const struct drm_connector_state *connector_state;
4640         const struct drm_connector *connector;
4641         struct intel_encoder *encoder = NULL;
4642         int num_encoders = 0;
4643         int i;
4644
4645         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
4646                 if (connector_state->crtc != &crtc->base)
4647                         continue;
4648
4649                 encoder = to_intel_encoder(connector_state->best_encoder);
4650                 num_encoders++;
4651         }
4652
4653         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
4654              num_encoders, pipe_name(crtc->pipe));
4655
4656         return encoder;
4657 }
4658
4659 /*
4660  * Enable PCH resources required for PCH ports:
4661  *   - PCH PLLs
4662  *   - FDI training & RX/TX
4663  *   - update transcoder timings
4664  *   - DP transcoding bits
4665  *   - transcoder
4666  */
4667 static void ironlake_pch_enable(const struct intel_atomic_state *state,
4668                                 const struct intel_crtc_state *crtc_state)
4669 {
4670         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4671         struct drm_device *dev = crtc->base.dev;
4672         struct drm_i915_private *dev_priv = to_i915(dev);
4673         int pipe = crtc->pipe;
4674         u32 temp;
4675
4676         assert_pch_transcoder_disabled(dev_priv, pipe);
4677
4678         if (IS_IVYBRIDGE(dev_priv))
4679                 ivybridge_update_fdi_bc_bifurcation(crtc);
4680
4681         /* Write the TU size bits before fdi link training, so that error
4682          * detection works. */
4683         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4684                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4685
4686         /* For PCH output, training FDI link */
4687         dev_priv->display.fdi_link_train(crtc, crtc_state);
4688
4689         /* We need to program the right clock selection before writing the pixel
4690          * mutliplier into the DPLL. */
4691         if (HAS_PCH_CPT(dev_priv)) {
4692                 u32 sel;
4693
4694                 temp = I915_READ(PCH_DPLL_SEL);
4695                 temp |= TRANS_DPLL_ENABLE(pipe);
4696                 sel = TRANS_DPLLB_SEL(pipe);
4697                 if (crtc_state->shared_dpll ==
4698                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4699                         temp |= sel;
4700                 else
4701                         temp &= ~sel;
4702                 I915_WRITE(PCH_DPLL_SEL, temp);
4703         }
4704
4705         /* XXX: pch pll's can be enabled any time before we enable the PCH
4706          * transcoder, and we actually should do this to not upset any PCH
4707          * transcoder that already use the clock when we share it.
4708          *
4709          * Note that enable_shared_dpll tries to do the right thing, but
4710          * get_shared_dpll unconditionally resets the pll - we need that to have
4711          * the right LVDS enable sequence. */
4712         intel_enable_shared_dpll(crtc_state);
4713
4714         /* set transcoder timing, panel must allow it */
4715         assert_panel_unlocked(dev_priv, pipe);
4716         ironlake_pch_transcoder_set_timings(crtc_state, pipe);
4717
4718         intel_fdi_normal_train(crtc);
4719
4720         /* For PCH DP, enable TRANS_DP_CTL */
4721         if (HAS_PCH_CPT(dev_priv) &&
4722             intel_crtc_has_dp_encoder(crtc_state)) {
4723                 const struct drm_display_mode *adjusted_mode =
4724                         &crtc_state->base.adjusted_mode;
4725                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4726                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4727                 enum port port;
4728
4729                 temp = I915_READ(reg);
4730                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4731                           TRANS_DP_SYNC_MASK |
4732                           TRANS_DP_BPC_MASK);
4733                 temp |= TRANS_DP_OUTPUT_ENABLE;
4734                 temp |= bpc << 9; /* same format but at 11:9 */
4735
4736                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4737                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4738                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4739                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4740
4741                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
4742                 WARN_ON(port < PORT_B || port > PORT_D);
4743                 temp |= TRANS_DP_PORT_SEL(port);
4744
4745                 I915_WRITE(reg, temp);
4746         }
4747
4748         ironlake_enable_pch_transcoder(crtc_state);
4749 }
4750
4751 static void lpt_pch_enable(const struct intel_atomic_state *state,
4752                            const struct intel_crtc_state *crtc_state)
4753 {
4754         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4755         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4756         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4757
4758         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4759
4760         lpt_program_iclkip(crtc);
4761
4762         /* Set transcoder timing. */
4763         ironlake_pch_transcoder_set_timings(crtc_state, PIPE_A);
4764
4765         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4766 }
4767
4768 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4769 {
4770         struct drm_i915_private *dev_priv = to_i915(dev);
4771         i915_reg_t dslreg = PIPEDSL(pipe);
4772         u32 temp;
4773
4774         temp = I915_READ(dslreg);
4775         udelay(500);
4776         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4777                 if (wait_for(I915_READ(dslreg) != temp, 5))
4778                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4779         }
4780 }
4781
4782 /*
4783  * The hardware phase 0.0 refers to the center of the pixel.
4784  * We want to start from the top/left edge which is phase
4785  * -0.5. That matches how the hardware calculates the scaling
4786  * factors (from top-left of the first pixel to bottom-right
4787  * of the last pixel, as opposed to the pixel centers).
4788  *
4789  * For 4:2:0 subsampled chroma planes we obviously have to
4790  * adjust that so that the chroma sample position lands in
4791  * the right spot.
4792  *
4793  * Note that for packed YCbCr 4:2:2 formats there is no way to
4794  * control chroma siting. The hardware simply replicates the
4795  * chroma samples for both of the luma samples, and thus we don't
4796  * actually get the expected MPEG2 chroma siting convention :(
4797  * The same behaviour is observed on pre-SKL platforms as well.
4798  */
4799 u16 skl_scaler_calc_phase(int sub, bool chroma_cosited)
4800 {
4801         int phase = -0x8000;
4802         u16 trip = 0;
4803
4804         if (chroma_cosited)
4805                 phase += (sub - 1) * 0x8000 / sub;
4806
4807         if (phase < 0)
4808                 phase = 0x10000 + phase;
4809         else
4810                 trip = PS_PHASE_TRIP;
4811
4812         return ((phase >> 2) & PS_PHASE_MASK) | trip;
4813 }
4814
4815 static int
4816 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4817                   unsigned int scaler_user, int *scaler_id,
4818                   int src_w, int src_h, int dst_w, int dst_h,
4819                   bool plane_scaler_check,
4820                   uint32_t pixel_format)
4821 {
4822         struct intel_crtc_scaler_state *scaler_state =
4823                 &crtc_state->scaler_state;
4824         struct intel_crtc *intel_crtc =
4825                 to_intel_crtc(crtc_state->base.crtc);
4826         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4827         const struct drm_display_mode *adjusted_mode =
4828                 &crtc_state->base.adjusted_mode;
4829         int need_scaling;
4830
4831         /*
4832          * Src coordinates are already rotated by 270 degrees for
4833          * the 90/270 degree plane rotation cases (to match the
4834          * GTT mapping), hence no need to account for rotation here.
4835          */
4836         need_scaling = src_w != dst_w || src_h != dst_h;
4837
4838         if (plane_scaler_check)
4839                 if (pixel_format == DRM_FORMAT_NV12)
4840                         need_scaling = true;
4841
4842         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 &&
4843             scaler_user == SKL_CRTC_INDEX)
4844                 need_scaling = true;
4845
4846         /*
4847          * Scaling/fitting not supported in IF-ID mode in GEN9+
4848          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4849          * Once NV12 is enabled, handle it here while allocating scaler
4850          * for NV12.
4851          */
4852         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4853             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4854                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4855                 return -EINVAL;
4856         }
4857
4858         /*
4859          * if plane is being disabled or scaler is no more required or force detach
4860          *  - free scaler binded to this plane/crtc
4861          *  - in order to do this, update crtc->scaler_usage
4862          *
4863          * Here scaler state in crtc_state is set free so that
4864          * scaler can be assigned to other user. Actual register
4865          * update to free the scaler is done in plane/panel-fit programming.
4866          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4867          */
4868         if (force_detach || !need_scaling) {
4869                 if (*scaler_id >= 0) {
4870                         scaler_state->scaler_users &= ~(1 << scaler_user);
4871                         scaler_state->scalers[*scaler_id].in_use = 0;
4872
4873                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4874                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4875                                 intel_crtc->pipe, scaler_user, *scaler_id,
4876                                 scaler_state->scaler_users);
4877                         *scaler_id = -1;
4878                 }
4879                 return 0;
4880         }
4881
4882         if (plane_scaler_check && pixel_format == DRM_FORMAT_NV12 &&
4883             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
4884                 DRM_DEBUG_KMS("NV12: src dimensions not met\n");
4885                 return -EINVAL;
4886         }
4887
4888         /* range checks */
4889         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4890             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4891             (IS_GEN11(dev_priv) &&
4892              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
4893               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
4894             (!IS_GEN11(dev_priv) &&
4895              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4896               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
4897                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4898                         "size is out of scaler range\n",
4899                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4900                 return -EINVAL;
4901         }
4902
4903         /* mark this plane as a scaler user in crtc_state */
4904         scaler_state->scaler_users |= (1 << scaler_user);
4905         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4906                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4907                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4908                 scaler_state->scaler_users);
4909
4910         return 0;
4911 }
4912
4913 /**
4914  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4915  *
4916  * @state: crtc's scaler state
4917  *
4918  * Return
4919  *     0 - scaler_usage updated successfully
4920  *    error - requested scaling cannot be supported or other error condition
4921  */
4922 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4923 {
4924         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4925
4926         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4927                                  &state->scaler_state.scaler_id,
4928                                  state->pipe_src_w, state->pipe_src_h,
4929                                  adjusted_mode->crtc_hdisplay,
4930                                  adjusted_mode->crtc_vdisplay, false, 0);
4931 }
4932
4933 /**
4934  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4935  * @crtc_state: crtc's scaler state
4936  * @plane_state: atomic plane state to update
4937  *
4938  * Return
4939  *     0 - scaler_usage updated successfully
4940  *    error - requested scaling cannot be supported or other error condition
4941  */
4942 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4943                                    struct intel_plane_state *plane_state)
4944 {
4945
4946         struct intel_plane *intel_plane =
4947                 to_intel_plane(plane_state->base.plane);
4948         struct drm_framebuffer *fb = plane_state->base.fb;
4949         int ret;
4950
4951         bool force_detach = !fb || !plane_state->base.visible;
4952
4953         ret = skl_update_scaler(crtc_state, force_detach,
4954                                 drm_plane_index(&intel_plane->base),
4955                                 &plane_state->scaler_id,
4956                                 drm_rect_width(&plane_state->base.src) >> 16,
4957                                 drm_rect_height(&plane_state->base.src) >> 16,
4958                                 drm_rect_width(&plane_state->base.dst),
4959                                 drm_rect_height(&plane_state->base.dst),
4960                                 fb ? true : false, fb ? fb->format->format : 0);
4961
4962         if (ret || plane_state->scaler_id < 0)
4963                 return ret;
4964
4965         /* check colorkey */
4966         if (plane_state->ckey.flags) {
4967                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4968                               intel_plane->base.base.id,
4969                               intel_plane->base.name);
4970                 return -EINVAL;
4971         }
4972
4973         /* Check src format */
4974         switch (fb->format->format) {
4975         case DRM_FORMAT_RGB565:
4976         case DRM_FORMAT_XBGR8888:
4977         case DRM_FORMAT_XRGB8888:
4978         case DRM_FORMAT_ABGR8888:
4979         case DRM_FORMAT_ARGB8888:
4980         case DRM_FORMAT_XRGB2101010:
4981         case DRM_FORMAT_XBGR2101010:
4982         case DRM_FORMAT_YUYV:
4983         case DRM_FORMAT_YVYU:
4984         case DRM_FORMAT_UYVY:
4985         case DRM_FORMAT_VYUY:
4986         case DRM_FORMAT_NV12:
4987                 break;
4988         default:
4989                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4990                               intel_plane->base.base.id, intel_plane->base.name,
4991                               fb->base.id, fb->format->format);
4992                 return -EINVAL;
4993         }
4994
4995         return 0;
4996 }
4997
4998 static void skylake_scaler_disable(struct intel_crtc *crtc)
4999 {
5000         int i;
5001
5002         for (i = 0; i < crtc->num_scalers; i++)
5003                 skl_detach_scaler(crtc, i);
5004 }
5005
5006 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state)
5007 {
5008         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5009         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5010         enum pipe pipe = crtc->pipe;
5011         const struct intel_crtc_scaler_state *scaler_state =
5012                 &crtc_state->scaler_state;
5013
5014         if (crtc_state->pch_pfit.enabled) {
5015                 u16 uv_rgb_hphase, uv_rgb_vphase;
5016                 int id;
5017
5018                 if (WARN_ON(crtc_state->scaler_state.scaler_id < 0))
5019                         return;
5020
5021                 uv_rgb_hphase = skl_scaler_calc_phase(1, false);
5022                 uv_rgb_vphase = skl_scaler_calc_phase(1, false);
5023
5024                 id = scaler_state->scaler_id;
5025                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5026                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5027                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5028                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5029                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5030                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5031                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc_state->pch_pfit.pos);
5032                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc_state->pch_pfit.size);
5033         }
5034 }
5035
5036 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state)
5037 {
5038         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5039         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5040         int pipe = crtc->pipe;
5041
5042         if (crtc_state->pch_pfit.enabled) {
5043                 /* Force use of hard-coded filter coefficients
5044                  * as some pre-programmed values are broken,
5045                  * e.g. x201.
5046                  */
5047                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5048                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5049                                                  PF_PIPE_SEL_IVB(pipe));
5050                 else
5051                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5052                 I915_WRITE(PF_WIN_POS(pipe), crtc_state->pch_pfit.pos);
5053                 I915_WRITE(PF_WIN_SZ(pipe), crtc_state->pch_pfit.size);
5054         }
5055 }
5056
5057 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5058 {
5059         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5060         struct drm_device *dev = crtc->base.dev;
5061         struct drm_i915_private *dev_priv = to_i915(dev);
5062
5063         if (!crtc_state->ips_enabled)
5064                 return;
5065
5066         /*
5067          * We can only enable IPS after we enable a plane and wait for a vblank
5068          * This function is called from post_plane_update, which is run after
5069          * a vblank wait.
5070          */
5071         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5072
5073         if (IS_BROADWELL(dev_priv)) {
5074                 mutex_lock(&dev_priv->pcu_lock);
5075                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5076                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5077                 mutex_unlock(&dev_priv->pcu_lock);
5078                 /* Quoting Art Runyan: "its not safe to expect any particular
5079                  * value in IPS_CTL bit 31 after enabling IPS through the
5080                  * mailbox." Moreover, the mailbox may return a bogus state,
5081                  * so we need to just enable it and continue on.
5082                  */
5083         } else {
5084                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5085                 /* The bit only becomes 1 in the next vblank, so this wait here
5086                  * is essentially intel_wait_for_vblank. If we don't have this
5087                  * and don't wait for vblanks until the end of crtc_enable, then
5088                  * the HW state readout code will complain that the expected
5089                  * IPS_CTL value is not the one we read. */
5090                 if (intel_wait_for_register(dev_priv,
5091                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5092                                             50))
5093                         DRM_ERROR("Timed out waiting for IPS enable\n");
5094         }
5095 }
5096
5097 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5098 {
5099         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5100         struct drm_device *dev = crtc->base.dev;
5101         struct drm_i915_private *dev_priv = to_i915(dev);
5102
5103         if (!crtc_state->ips_enabled)
5104                 return;
5105
5106         if (IS_BROADWELL(dev_priv)) {
5107                 mutex_lock(&dev_priv->pcu_lock);
5108                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5109                 mutex_unlock(&dev_priv->pcu_lock);
5110                 /*
5111                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5112                  * 42ms timeout value leads to occasional timeouts so use 100ms
5113                  * instead.
5114                  */
5115                 if (intel_wait_for_register(dev_priv,
5116                                             IPS_CTL, IPS_ENABLE, 0,
5117                                             100))
5118                         DRM_ERROR("Timed out waiting for IPS disable\n");
5119         } else {
5120                 I915_WRITE(IPS_CTL, 0);
5121                 POSTING_READ(IPS_CTL);
5122         }
5123
5124         /* We need to wait for a vblank before we can disable the plane. */
5125         intel_wait_for_vblank(dev_priv, crtc->pipe);
5126 }
5127
5128 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5129 {
5130         if (intel_crtc->overlay) {
5131                 struct drm_device *dev = intel_crtc->base.dev;
5132
5133                 mutex_lock(&dev->struct_mutex);
5134                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5135                 mutex_unlock(&dev->struct_mutex);
5136         }
5137
5138         /* Let userspace switch the overlay on again. In most cases userspace
5139          * has to recompute where to put it anyway.
5140          */
5141 }
5142
5143 /**
5144  * intel_post_enable_primary - Perform operations after enabling primary plane
5145  * @crtc: the CRTC whose primary plane was just enabled
5146  * @new_crtc_state: the enabling state
5147  *
5148  * Performs potentially sleeping operations that must be done after the primary
5149  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5150  * called due to an explicit primary plane update, or due to an implicit
5151  * re-enable that is caused when a sprite plane is updated to no longer
5152  * completely hide the primary plane.
5153  */
5154 static void
5155 intel_post_enable_primary(struct drm_crtc *crtc,
5156                           const struct intel_crtc_state *new_crtc_state)
5157 {
5158         struct drm_device *dev = crtc->dev;
5159         struct drm_i915_private *dev_priv = to_i915(dev);
5160         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5161         int pipe = intel_crtc->pipe;
5162
5163         /*
5164          * Gen2 reports pipe underruns whenever all planes are disabled.
5165          * So don't enable underrun reporting before at least some planes
5166          * are enabled.
5167          * FIXME: Need to fix the logic to work when we turn off all planes
5168          * but leave the pipe running.
5169          */
5170         if (IS_GEN2(dev_priv))
5171                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5172
5173         /* Underruns don't always raise interrupts, so check manually. */
5174         intel_check_cpu_fifo_underruns(dev_priv);
5175         intel_check_pch_fifo_underruns(dev_priv);
5176 }
5177
5178 /* FIXME get rid of this and use pre_plane_update */
5179 static void
5180 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5181 {
5182         struct drm_device *dev = crtc->dev;
5183         struct drm_i915_private *dev_priv = to_i915(dev);
5184         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5185         int pipe = intel_crtc->pipe;
5186
5187         /*
5188          * Gen2 reports pipe underruns whenever all planes are disabled.
5189          * So disable underrun reporting before all the planes get disabled.
5190          */
5191         if (IS_GEN2(dev_priv))
5192                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5193
5194         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5195
5196         /*
5197          * Vblank time updates from the shadow to live plane control register
5198          * are blocked if the memory self-refresh mode is active at that
5199          * moment. So to make sure the plane gets truly disabled, disable
5200          * first the self-refresh mode. The self-refresh enable bit in turn
5201          * will be checked/applied by the HW only at the next frame start
5202          * event which is after the vblank start event, so we need to have a
5203          * wait-for-vblank between disabling the plane and the pipe.
5204          */
5205         if (HAS_GMCH_DISPLAY(dev_priv) &&
5206             intel_set_memory_cxsr(dev_priv, false))
5207                 intel_wait_for_vblank(dev_priv, pipe);
5208 }
5209
5210 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5211                                        const struct intel_crtc_state *new_crtc_state)
5212 {
5213         if (!old_crtc_state->ips_enabled)
5214                 return false;
5215
5216         if (needs_modeset(&new_crtc_state->base))
5217                 return true;
5218
5219         return !new_crtc_state->ips_enabled;
5220 }
5221
5222 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5223                                        const struct intel_crtc_state *new_crtc_state)
5224 {
5225         if (!new_crtc_state->ips_enabled)
5226                 return false;
5227
5228         if (needs_modeset(&new_crtc_state->base))
5229                 return true;
5230
5231         /*
5232          * We can't read out IPS on broadwell, assume the worst and
5233          * forcibly enable IPS on the first fastset.
5234          */
5235         if (new_crtc_state->update_pipe &&
5236             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5237                 return true;
5238
5239         return !old_crtc_state->ips_enabled;
5240 }
5241
5242 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5243                           const struct intel_crtc_state *crtc_state)
5244 {
5245         if (!crtc_state->nv12_planes)
5246                 return false;
5247
5248         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
5249                 return false;
5250
5251         if ((INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv)) ||
5252             IS_CANNONLAKE(dev_priv))
5253                 return true;
5254
5255         return false;
5256 }
5257
5258 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5259 {
5260         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5261         struct drm_device *dev = crtc->base.dev;
5262         struct drm_i915_private *dev_priv = to_i915(dev);
5263         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5264         struct intel_crtc_state *pipe_config =
5265                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5266                                                 crtc);
5267         struct drm_plane *primary = crtc->base.primary;
5268         struct drm_plane_state *old_primary_state =
5269                 drm_atomic_get_old_plane_state(old_state, primary);
5270
5271         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5272
5273         if (pipe_config->update_wm_post && pipe_config->base.active)
5274                 intel_update_watermarks(crtc);
5275
5276         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5277                 hsw_enable_ips(pipe_config);
5278
5279         if (old_primary_state) {
5280                 struct drm_plane_state *new_primary_state =
5281                         drm_atomic_get_new_plane_state(old_state, primary);
5282
5283                 intel_fbc_post_update(crtc);
5284
5285                 if (new_primary_state->visible &&
5286                     (needs_modeset(&pipe_config->base) ||
5287                      !old_primary_state->visible))
5288                         intel_post_enable_primary(&crtc->base, pipe_config);
5289         }
5290
5291         /* Display WA 827 */
5292         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5293             !needs_nv12_wa(dev_priv, pipe_config)) {
5294                 skl_wa_clkgate(dev_priv, crtc->pipe, false);
5295                 skl_wa_528(dev_priv, crtc->pipe, false);
5296         }
5297 }
5298
5299 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5300                                    struct intel_crtc_state *pipe_config)
5301 {
5302         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5303         struct drm_device *dev = crtc->base.dev;
5304         struct drm_i915_private *dev_priv = to_i915(dev);
5305         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5306         struct drm_plane *primary = crtc->base.primary;
5307         struct drm_plane_state *old_primary_state =
5308                 drm_atomic_get_old_plane_state(old_state, primary);
5309         bool modeset = needs_modeset(&pipe_config->base);
5310         struct intel_atomic_state *old_intel_state =
5311                 to_intel_atomic_state(old_state);
5312
5313         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5314                 hsw_disable_ips(old_crtc_state);
5315
5316         if (old_primary_state) {
5317                 struct intel_plane_state *new_primary_state =
5318                         intel_atomic_get_new_plane_state(old_intel_state,
5319                                                          to_intel_plane(primary));
5320
5321                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5322                 /*
5323                  * Gen2 reports pipe underruns whenever all planes are disabled.
5324                  * So disable underrun reporting before all the planes get disabled.
5325                  */
5326                 if (IS_GEN2(dev_priv) && old_primary_state->visible &&
5327                     (modeset || !new_primary_state->base.visible))
5328                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5329         }
5330
5331         /* Display WA 827 */
5332         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5333             needs_nv12_wa(dev_priv, pipe_config)) {
5334                 skl_wa_clkgate(dev_priv, crtc->pipe, true);
5335                 skl_wa_528(dev_priv, crtc->pipe, true);
5336         }
5337
5338         /*
5339          * Vblank time updates from the shadow to live plane control register
5340          * are blocked if the memory self-refresh mode is active at that
5341          * moment. So to make sure the plane gets truly disabled, disable
5342          * first the self-refresh mode. The self-refresh enable bit in turn
5343          * will be checked/applied by the HW only at the next frame start
5344          * event which is after the vblank start event, so we need to have a
5345          * wait-for-vblank between disabling the plane and the pipe.
5346          */
5347         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5348             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5349                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5350
5351         /*
5352          * IVB workaround: must disable low power watermarks for at least
5353          * one frame before enabling scaling.  LP watermarks can be re-enabled
5354          * when scaling is disabled.
5355          *
5356          * WaCxSRDisabledForSpriteScaling:ivb
5357          */
5358         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev) &&
5359             old_crtc_state->base.active)
5360                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5361
5362         /*
5363          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5364          * watermark programming here.
5365          */
5366         if (needs_modeset(&pipe_config->base))
5367                 return;
5368
5369         /*
5370          * For platforms that support atomic watermarks, program the
5371          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5372          * will be the intermediate values that are safe for both pre- and
5373          * post- vblank; when vblank happens, the 'active' values will be set
5374          * to the final 'target' values and we'll do this again to get the
5375          * optimal watermarks.  For gen9+ platforms, the values we program here
5376          * will be the final target values which will get automatically latched
5377          * at vblank time; no further programming will be necessary.
5378          *
5379          * If a platform hasn't been transitioned to atomic watermarks yet,
5380          * we'll continue to update watermarks the old way, if flags tell
5381          * us to.
5382          */
5383         if (dev_priv->display.initial_watermarks != NULL)
5384                 dev_priv->display.initial_watermarks(old_intel_state,
5385                                                      pipe_config);
5386         else if (pipe_config->update_wm_pre)
5387                 intel_update_watermarks(crtc);
5388 }
5389
5390 static void intel_crtc_disable_planes(struct intel_crtc *crtc, unsigned plane_mask)
5391 {
5392         struct drm_device *dev = crtc->base.dev;
5393         struct intel_plane *plane;
5394         unsigned fb_bits = 0;
5395
5396         intel_crtc_dpms_overlay_disable(crtc);
5397
5398         for_each_intel_plane_on_crtc(dev, crtc, plane) {
5399                 if (plane_mask & BIT(plane->id)) {
5400                         plane->disable_plane(plane, crtc);
5401
5402                         fb_bits |= plane->frontbuffer_bit;
5403                 }
5404         }
5405
5406         intel_frontbuffer_flip(to_i915(dev), fb_bits);
5407 }
5408
5409 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5410                                           struct intel_crtc_state *crtc_state,
5411                                           struct drm_atomic_state *old_state)
5412 {
5413         struct drm_connector_state *conn_state;
5414         struct drm_connector *conn;
5415         int i;
5416
5417         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5418                 struct intel_encoder *encoder =
5419                         to_intel_encoder(conn_state->best_encoder);
5420
5421                 if (conn_state->crtc != crtc)
5422                         continue;
5423
5424                 if (encoder->pre_pll_enable)
5425                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5426         }
5427 }
5428
5429 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5430                                       struct intel_crtc_state *crtc_state,
5431                                       struct drm_atomic_state *old_state)
5432 {
5433         struct drm_connector_state *conn_state;
5434         struct drm_connector *conn;
5435         int i;
5436
5437         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5438                 struct intel_encoder *encoder =
5439                         to_intel_encoder(conn_state->best_encoder);
5440
5441                 if (conn_state->crtc != crtc)
5442                         continue;
5443
5444                 if (encoder->pre_enable)
5445                         encoder->pre_enable(encoder, crtc_state, conn_state);
5446         }
5447 }
5448
5449 static void intel_encoders_enable(struct drm_crtc *crtc,
5450                                   struct intel_crtc_state *crtc_state,
5451                                   struct drm_atomic_state *old_state)
5452 {
5453         struct drm_connector_state *conn_state;
5454         struct drm_connector *conn;
5455         int i;
5456
5457         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5458                 struct intel_encoder *encoder =
5459                         to_intel_encoder(conn_state->best_encoder);
5460
5461                 if (conn_state->crtc != crtc)
5462                         continue;
5463
5464                 encoder->enable(encoder, crtc_state, conn_state);
5465                 intel_opregion_notify_encoder(encoder, true);
5466         }
5467 }
5468
5469 static void intel_encoders_disable(struct drm_crtc *crtc,
5470                                    struct intel_crtc_state *old_crtc_state,
5471                                    struct drm_atomic_state *old_state)
5472 {
5473         struct drm_connector_state *old_conn_state;
5474         struct drm_connector *conn;
5475         int i;
5476
5477         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5478                 struct intel_encoder *encoder =
5479                         to_intel_encoder(old_conn_state->best_encoder);
5480
5481                 if (old_conn_state->crtc != crtc)
5482                         continue;
5483
5484                 intel_opregion_notify_encoder(encoder, false);
5485                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5486         }
5487 }
5488
5489 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5490                                         struct intel_crtc_state *old_crtc_state,
5491                                         struct drm_atomic_state *old_state)
5492 {
5493         struct drm_connector_state *old_conn_state;
5494         struct drm_connector *conn;
5495         int i;
5496
5497         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5498                 struct intel_encoder *encoder =
5499                         to_intel_encoder(old_conn_state->best_encoder);
5500
5501                 if (old_conn_state->crtc != crtc)
5502                         continue;
5503
5504                 if (encoder->post_disable)
5505                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5506         }
5507 }
5508
5509 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5510                                             struct intel_crtc_state *old_crtc_state,
5511                                             struct drm_atomic_state *old_state)
5512 {
5513         struct drm_connector_state *old_conn_state;
5514         struct drm_connector *conn;
5515         int i;
5516
5517         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5518                 struct intel_encoder *encoder =
5519                         to_intel_encoder(old_conn_state->best_encoder);
5520
5521                 if (old_conn_state->crtc != crtc)
5522                         continue;
5523
5524                 if (encoder->post_pll_disable)
5525                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5526         }
5527 }
5528
5529 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5530                                  struct drm_atomic_state *old_state)
5531 {
5532         struct drm_crtc *crtc = pipe_config->base.crtc;
5533         struct drm_device *dev = crtc->dev;
5534         struct drm_i915_private *dev_priv = to_i915(dev);
5535         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5536         int pipe = intel_crtc->pipe;
5537         struct intel_atomic_state *old_intel_state =
5538                 to_intel_atomic_state(old_state);
5539
5540         if (WARN_ON(intel_crtc->active))
5541                 return;
5542
5543         /*
5544          * Sometimes spurious CPU pipe underruns happen during FDI
5545          * training, at least with VGA+HDMI cloning. Suppress them.
5546          *
5547          * On ILK we get an occasional spurious CPU pipe underruns
5548          * between eDP port A enable and vdd enable. Also PCH port
5549          * enable seems to result in the occasional CPU pipe underrun.
5550          *
5551          * Spurious PCH underruns also occur during PCH enabling.
5552          */
5553         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5554         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5555
5556         if (pipe_config->has_pch_encoder)
5557                 intel_prepare_shared_dpll(pipe_config);
5558
5559         if (intel_crtc_has_dp_encoder(pipe_config))
5560                 intel_dp_set_m_n(pipe_config, M1_N1);
5561
5562         intel_set_pipe_timings(pipe_config);
5563         intel_set_pipe_src_size(pipe_config);
5564
5565         if (pipe_config->has_pch_encoder) {
5566                 intel_cpu_transcoder_set_m_n(pipe_config,
5567                                              &pipe_config->fdi_m_n, NULL);
5568         }
5569
5570         ironlake_set_pipeconf(pipe_config);
5571
5572         intel_crtc->active = true;
5573
5574         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5575
5576         if (pipe_config->has_pch_encoder) {
5577                 /* Note: FDI PLL enabling _must_ be done before we enable the
5578                  * cpu pipes, hence this is separate from all the other fdi/pch
5579                  * enabling. */
5580                 ironlake_fdi_pll_enable(pipe_config);
5581         } else {
5582                 assert_fdi_tx_disabled(dev_priv, pipe);
5583                 assert_fdi_rx_disabled(dev_priv, pipe);
5584         }
5585
5586         ironlake_pfit_enable(pipe_config);
5587
5588         /*
5589          * On ILK+ LUT must be loaded before the pipe is running but with
5590          * clocks enabled
5591          */
5592         intel_color_load_luts(&pipe_config->base);
5593
5594         if (dev_priv->display.initial_watermarks != NULL)
5595                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5596         intel_enable_pipe(pipe_config);
5597
5598         if (pipe_config->has_pch_encoder)
5599                 ironlake_pch_enable(old_intel_state, pipe_config);
5600
5601         assert_vblank_disabled(crtc);
5602         drm_crtc_vblank_on(crtc);
5603
5604         intel_encoders_enable(crtc, pipe_config, old_state);
5605
5606         if (HAS_PCH_CPT(dev_priv))
5607                 cpt_verify_modeset(dev, intel_crtc->pipe);
5608
5609         /*
5610          * Must wait for vblank to avoid spurious PCH FIFO underruns.
5611          * And a second vblank wait is needed at least on ILK with
5612          * some interlaced HDMI modes. Let's do the double wait always
5613          * in case there are more corner cases we don't know about.
5614          */
5615         if (pipe_config->has_pch_encoder) {
5616                 intel_wait_for_vblank(dev_priv, pipe);
5617                 intel_wait_for_vblank(dev_priv, pipe);
5618         }
5619         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5620         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5621 }
5622
5623 /* IPS only exists on ULT machines and is tied to pipe A. */
5624 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5625 {
5626         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5627 }
5628
5629 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5630                                             enum pipe pipe, bool apply)
5631 {
5632         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5633         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5634
5635         if (apply)
5636                 val |= mask;
5637         else
5638                 val &= ~mask;
5639
5640         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5641 }
5642
5643 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5644 {
5645         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5646         enum pipe pipe = crtc->pipe;
5647         uint32_t val;
5648
5649         val = MBUS_DBOX_A_CREDIT(2);
5650         val |= MBUS_DBOX_BW_CREDIT(1);
5651         val |= MBUS_DBOX_B_CREDIT(8);
5652
5653         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5654 }
5655
5656 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5657                                 struct drm_atomic_state *old_state)
5658 {
5659         struct drm_crtc *crtc = pipe_config->base.crtc;
5660         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5661         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5662         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5663         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
5664         struct intel_atomic_state *old_intel_state =
5665                 to_intel_atomic_state(old_state);
5666         bool psl_clkgate_wa;
5667         u32 pipe_chicken;
5668
5669         if (WARN_ON(intel_crtc->active))
5670                 return;
5671
5672         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5673
5674         if (pipe_config->shared_dpll)
5675                 intel_enable_shared_dpll(pipe_config);
5676
5677         if (INTEL_GEN(dev_priv) >= 11)
5678                 icl_map_plls_to_ports(crtc, pipe_config, old_state);
5679
5680         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5681
5682         if (intel_crtc_has_dp_encoder(pipe_config))
5683                 intel_dp_set_m_n(pipe_config, M1_N1);
5684
5685         if (!transcoder_is_dsi(cpu_transcoder))
5686                 intel_set_pipe_timings(pipe_config);
5687
5688         intel_set_pipe_src_size(pipe_config);
5689
5690         if (cpu_transcoder != TRANSCODER_EDP &&
5691             !transcoder_is_dsi(cpu_transcoder)) {
5692                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5693                            pipe_config->pixel_multiplier - 1);
5694         }
5695
5696         if (pipe_config->has_pch_encoder) {
5697                 intel_cpu_transcoder_set_m_n(pipe_config,
5698                                              &pipe_config->fdi_m_n, NULL);
5699         }
5700
5701         if (!transcoder_is_dsi(cpu_transcoder))
5702                 haswell_set_pipeconf(pipe_config);
5703
5704         haswell_set_pipemisc(pipe_config);
5705
5706         intel_color_set_csc(&pipe_config->base);
5707
5708         intel_crtc->active = true;
5709
5710         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5711         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5712                          pipe_config->pch_pfit.enabled;
5713         if (psl_clkgate_wa)
5714                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5715
5716         if (INTEL_GEN(dev_priv) >= 9)
5717                 skylake_pfit_enable(pipe_config);
5718         else
5719                 ironlake_pfit_enable(pipe_config);
5720
5721         /*
5722          * On ILK+ LUT must be loaded before the pipe is running but with
5723          * clocks enabled
5724          */
5725         intel_color_load_luts(&pipe_config->base);
5726
5727         /*
5728          * Display WA #1153: enable hardware to bypass the alpha math
5729          * and rounding for per-pixel values 00 and 0xff
5730          */
5731         if (INTEL_GEN(dev_priv) >= 11) {
5732                 pipe_chicken = I915_READ(PIPE_CHICKEN(pipe));
5733                 if (!(pipe_chicken & PER_PIXEL_ALPHA_BYPASS_EN))
5734                         I915_WRITE_FW(PIPE_CHICKEN(pipe),
5735                                       pipe_chicken | PER_PIXEL_ALPHA_BYPASS_EN);
5736         }
5737
5738         intel_ddi_set_pipe_settings(pipe_config);
5739         if (!transcoder_is_dsi(cpu_transcoder))
5740                 intel_ddi_enable_transcoder_func(pipe_config);
5741
5742         if (dev_priv->display.initial_watermarks != NULL)
5743                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5744
5745         if (INTEL_GEN(dev_priv) >= 11)
5746                 icl_pipe_mbus_enable(intel_crtc);
5747
5748         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5749         if (!transcoder_is_dsi(cpu_transcoder))
5750                 intel_enable_pipe(pipe_config);
5751
5752         if (pipe_config->has_pch_encoder)
5753                 lpt_pch_enable(old_intel_state, pipe_config);
5754
5755         if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DP_MST))
5756                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5757
5758         assert_vblank_disabled(crtc);
5759         drm_crtc_vblank_on(crtc);
5760
5761         intel_encoders_enable(crtc, pipe_config, old_state);
5762
5763         if (psl_clkgate_wa) {
5764                 intel_wait_for_vblank(dev_priv, pipe);
5765                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5766         }
5767
5768         /* If we change the relative order between pipe/planes enabling, we need
5769          * to change the workaround. */
5770         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5771         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5772                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5773                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5774         }
5775 }
5776
5777 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state)
5778 {
5779         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5780         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5781         enum pipe pipe = crtc->pipe;
5782
5783         /* To avoid upsetting the power well on haswell only disable the pfit if
5784          * it's in use. The hw state code will make sure we get this right. */
5785         if (old_crtc_state->pch_pfit.enabled) {
5786                 I915_WRITE(PF_CTL(pipe), 0);
5787                 I915_WRITE(PF_WIN_POS(pipe), 0);
5788                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5789         }
5790 }
5791
5792 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5793                                   struct drm_atomic_state *old_state)
5794 {
5795         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5796         struct drm_device *dev = crtc->dev;
5797         struct drm_i915_private *dev_priv = to_i915(dev);
5798         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5799         int pipe = intel_crtc->pipe;
5800
5801         /*
5802          * Sometimes spurious CPU pipe underruns happen when the
5803          * pipe is already disabled, but FDI RX/TX is still enabled.
5804          * Happens at least with VGA+HDMI cloning. Suppress them.
5805          */
5806         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5807         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5808
5809         intel_encoders_disable(crtc, old_crtc_state, old_state);
5810
5811         drm_crtc_vblank_off(crtc);
5812         assert_vblank_disabled(crtc);
5813
5814         intel_disable_pipe(old_crtc_state);
5815
5816         ironlake_pfit_disable(old_crtc_state);
5817
5818         if (old_crtc_state->has_pch_encoder)
5819                 ironlake_fdi_disable(crtc);
5820
5821         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5822
5823         if (old_crtc_state->has_pch_encoder) {
5824                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5825
5826                 if (HAS_PCH_CPT(dev_priv)) {
5827                         i915_reg_t reg;
5828                         u32 temp;
5829
5830                         /* disable TRANS_DP_CTL */
5831                         reg = TRANS_DP_CTL(pipe);
5832                         temp = I915_READ(reg);
5833                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5834                                   TRANS_DP_PORT_SEL_MASK);
5835                         temp |= TRANS_DP_PORT_SEL_NONE;
5836                         I915_WRITE(reg, temp);
5837
5838                         /* disable DPLL_SEL */
5839                         temp = I915_READ(PCH_DPLL_SEL);
5840                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5841                         I915_WRITE(PCH_DPLL_SEL, temp);
5842                 }
5843
5844                 ironlake_fdi_pll_disable(intel_crtc);
5845         }
5846
5847         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5848         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5849 }
5850
5851 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5852                                  struct drm_atomic_state *old_state)
5853 {
5854         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5855         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5856         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5857         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
5858
5859         intel_encoders_disable(crtc, old_crtc_state, old_state);
5860
5861         drm_crtc_vblank_off(crtc);
5862         assert_vblank_disabled(crtc);
5863
5864         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5865         if (!transcoder_is_dsi(cpu_transcoder))
5866                 intel_disable_pipe(old_crtc_state);
5867
5868         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
5869                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
5870
5871         if (!transcoder_is_dsi(cpu_transcoder))
5872                 intel_ddi_disable_transcoder_func(old_crtc_state);
5873
5874         if (INTEL_GEN(dev_priv) >= 9)
5875                 skylake_scaler_disable(intel_crtc);
5876         else
5877                 ironlake_pfit_disable(old_crtc_state);
5878
5879         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5880
5881         if (INTEL_GEN(dev_priv) >= 11)
5882                 icl_unmap_plls_to_ports(crtc, old_crtc_state, old_state);
5883 }
5884
5885 static void i9xx_pfit_enable(const struct intel_crtc_state *crtc_state)
5886 {
5887         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5888         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5889
5890         if (!crtc_state->gmch_pfit.control)
5891                 return;
5892
5893         /*
5894          * The panel fitter should only be adjusted whilst the pipe is disabled,
5895          * according to register description and PRM.
5896          */
5897         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5898         assert_pipe_disabled(dev_priv, crtc->pipe);
5899
5900         I915_WRITE(PFIT_PGM_RATIOS, crtc_state->gmch_pfit.pgm_ratios);
5901         I915_WRITE(PFIT_CONTROL, crtc_state->gmch_pfit.control);
5902
5903         /* Border color in case we don't scale up to the full screen. Black by
5904          * default, change to something else for debugging. */
5905         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5906 }
5907
5908 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
5909 {
5910         if (IS_ICELAKE(dev_priv))
5911                 return port >= PORT_C && port <= PORT_F;
5912
5913         return false;
5914 }
5915
5916 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
5917 {
5918         if (!intel_port_is_tc(dev_priv, port))
5919                 return PORT_TC_NONE;
5920
5921         return port - PORT_C;
5922 }
5923
5924 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5925 {
5926         switch (port) {
5927         case PORT_A:
5928                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5929         case PORT_B:
5930                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5931         case PORT_C:
5932                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5933         case PORT_D:
5934                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5935         case PORT_E:
5936                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5937         case PORT_F:
5938                 return POWER_DOMAIN_PORT_DDI_F_LANES;
5939         default:
5940                 MISSING_CASE(port);
5941                 return POWER_DOMAIN_PORT_OTHER;
5942         }
5943 }
5944
5945 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5946                                   struct intel_crtc_state *crtc_state)
5947 {
5948         struct drm_device *dev = crtc->dev;
5949         struct drm_i915_private *dev_priv = to_i915(dev);
5950         struct drm_encoder *encoder;
5951         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5952         enum pipe pipe = intel_crtc->pipe;
5953         u64 mask;
5954         enum transcoder transcoder = crtc_state->cpu_transcoder;
5955
5956         if (!crtc_state->base.active)
5957                 return 0;
5958
5959         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
5960         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
5961         if (crtc_state->pch_pfit.enabled ||
5962             crtc_state->pch_pfit.force_thru)
5963                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5964
5965         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5966                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5967
5968                 mask |= BIT_ULL(intel_encoder->power_domain);
5969         }
5970
5971         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5972                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
5973
5974         if (crtc_state->shared_dpll)
5975                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5976
5977         return mask;
5978 }
5979
5980 static u64
5981 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5982                                struct intel_crtc_state *crtc_state)
5983 {
5984         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5985         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5986         enum intel_display_power_domain domain;
5987         u64 domains, new_domains, old_domains;
5988
5989         old_domains = intel_crtc->enabled_power_domains;
5990         intel_crtc->enabled_power_domains = new_domains =
5991                 get_crtc_power_domains(crtc, crtc_state);
5992
5993         domains = new_domains & ~old_domains;
5994
5995         for_each_power_domain(domain, domains)
5996                 intel_display_power_get(dev_priv, domain);
5997
5998         return old_domains & ~new_domains;
5999 }
6000
6001 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
6002                                       u64 domains)
6003 {
6004         enum intel_display_power_domain domain;
6005
6006         for_each_power_domain(domain, domains)
6007                 intel_display_power_put(dev_priv, domain);
6008 }
6009
6010 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6011                                    struct drm_atomic_state *old_state)
6012 {
6013         struct intel_atomic_state *old_intel_state =
6014                 to_intel_atomic_state(old_state);
6015         struct drm_crtc *crtc = pipe_config->base.crtc;
6016         struct drm_device *dev = crtc->dev;
6017         struct drm_i915_private *dev_priv = to_i915(dev);
6018         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6019         int pipe = intel_crtc->pipe;
6020
6021         if (WARN_ON(intel_crtc->active))
6022                 return;
6023
6024         if (intel_crtc_has_dp_encoder(pipe_config))
6025                 intel_dp_set_m_n(pipe_config, M1_N1);
6026
6027         intel_set_pipe_timings(pipe_config);
6028         intel_set_pipe_src_size(pipe_config);
6029
6030         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6031                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6032                 I915_WRITE(CHV_CANVAS(pipe), 0);
6033         }
6034
6035         i9xx_set_pipeconf(pipe_config);
6036
6037         intel_color_set_csc(&pipe_config->base);
6038
6039         intel_crtc->active = true;
6040
6041         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6042
6043         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6044
6045         if (IS_CHERRYVIEW(dev_priv)) {
6046                 chv_prepare_pll(intel_crtc, pipe_config);
6047                 chv_enable_pll(intel_crtc, pipe_config);
6048         } else {
6049                 vlv_prepare_pll(intel_crtc, pipe_config);
6050                 vlv_enable_pll(intel_crtc, pipe_config);
6051         }
6052
6053         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6054
6055         i9xx_pfit_enable(pipe_config);
6056
6057         intel_color_load_luts(&pipe_config->base);
6058
6059         dev_priv->display.initial_watermarks(old_intel_state,
6060                                              pipe_config);
6061         intel_enable_pipe(pipe_config);
6062
6063         assert_vblank_disabled(crtc);
6064         drm_crtc_vblank_on(crtc);
6065
6066         intel_encoders_enable(crtc, pipe_config, old_state);
6067 }
6068
6069 static void i9xx_set_pll_dividers(const struct intel_crtc_state *crtc_state)
6070 {
6071         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6072         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6073
6074         I915_WRITE(FP0(crtc->pipe), crtc_state->dpll_hw_state.fp0);
6075         I915_WRITE(FP1(crtc->pipe), crtc_state->dpll_hw_state.fp1);
6076 }
6077
6078 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6079                              struct drm_atomic_state *old_state)
6080 {
6081         struct intel_atomic_state *old_intel_state =
6082                 to_intel_atomic_state(old_state);
6083         struct drm_crtc *crtc = pipe_config->base.crtc;
6084         struct drm_device *dev = crtc->dev;
6085         struct drm_i915_private *dev_priv = to_i915(dev);
6086         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6087         enum pipe pipe = intel_crtc->pipe;
6088
6089         if (WARN_ON(intel_crtc->active))
6090                 return;
6091
6092         i9xx_set_pll_dividers(pipe_config);
6093
6094         if (intel_crtc_has_dp_encoder(pipe_config))
6095                 intel_dp_set_m_n(pipe_config, M1_N1);
6096
6097         intel_set_pipe_timings(pipe_config);
6098         intel_set_pipe_src_size(pipe_config);
6099
6100         i9xx_set_pipeconf(pipe_config);
6101
6102         intel_crtc->active = true;
6103
6104         if (!IS_GEN2(dev_priv))
6105                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6106
6107         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6108
6109         i9xx_enable_pll(intel_crtc, pipe_config);
6110
6111         i9xx_pfit_enable(pipe_config);
6112
6113         intel_color_load_luts(&pipe_config->base);
6114
6115         if (dev_priv->display.initial_watermarks != NULL)
6116                 dev_priv->display.initial_watermarks(old_intel_state,
6117                                                      pipe_config);
6118         else
6119                 intel_update_watermarks(intel_crtc);
6120         intel_enable_pipe(pipe_config);
6121
6122         assert_vblank_disabled(crtc);
6123         drm_crtc_vblank_on(crtc);
6124
6125         intel_encoders_enable(crtc, pipe_config, old_state);
6126 }
6127
6128 static void i9xx_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6129 {
6130         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6131         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6132
6133         if (!old_crtc_state->gmch_pfit.control)
6134                 return;
6135
6136         assert_pipe_disabled(dev_priv, crtc->pipe);
6137
6138         DRM_DEBUG_KMS("disabling pfit, current: 0x%08x\n",
6139                       I915_READ(PFIT_CONTROL));
6140         I915_WRITE(PFIT_CONTROL, 0);
6141 }
6142
6143 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6144                               struct drm_atomic_state *old_state)
6145 {
6146         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6147         struct drm_device *dev = crtc->dev;
6148         struct drm_i915_private *dev_priv = to_i915(dev);
6149         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6150         int pipe = intel_crtc->pipe;
6151
6152         /*
6153          * On gen2 planes are double buffered but the pipe isn't, so we must
6154          * wait for planes to fully turn off before disabling the pipe.
6155          */
6156         if (IS_GEN2(dev_priv))
6157                 intel_wait_for_vblank(dev_priv, pipe);
6158
6159         intel_encoders_disable(crtc, old_crtc_state, old_state);
6160
6161         drm_crtc_vblank_off(crtc);
6162         assert_vblank_disabled(crtc);
6163
6164         intel_disable_pipe(old_crtc_state);
6165
6166         i9xx_pfit_disable(old_crtc_state);
6167
6168         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6169
6170         if (!intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DSI)) {
6171                 if (IS_CHERRYVIEW(dev_priv))
6172                         chv_disable_pll(dev_priv, pipe);
6173                 else if (IS_VALLEYVIEW(dev_priv))
6174                         vlv_disable_pll(dev_priv, pipe);
6175                 else
6176                         i9xx_disable_pll(old_crtc_state);
6177         }
6178
6179         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6180
6181         if (!IS_GEN2(dev_priv))
6182                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6183
6184         if (!dev_priv->display.initial_watermarks)
6185                 intel_update_watermarks(intel_crtc);
6186
6187         /* clock the pipe down to 640x480@60 to potentially save power */
6188         if (IS_I830(dev_priv))
6189                 i830_enable_pipe(dev_priv, pipe);
6190 }
6191
6192 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6193                                         struct drm_modeset_acquire_ctx *ctx)
6194 {
6195         struct intel_encoder *encoder;
6196         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6197         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6198         enum intel_display_power_domain domain;
6199         struct intel_plane *plane;
6200         u64 domains;
6201         struct drm_atomic_state *state;
6202         struct intel_crtc_state *crtc_state;
6203         int ret;
6204
6205         if (!intel_crtc->active)
6206                 return;
6207
6208         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6209                 const struct intel_plane_state *plane_state =
6210                         to_intel_plane_state(plane->base.state);
6211
6212                 if (plane_state->base.visible)
6213                         intel_plane_disable_noatomic(intel_crtc, plane);
6214         }
6215
6216         state = drm_atomic_state_alloc(crtc->dev);
6217         if (!state) {
6218                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6219                               crtc->base.id, crtc->name);
6220                 return;
6221         }
6222
6223         state->acquire_ctx = ctx;
6224
6225         /* Everything's already locked, -EDEADLK can't happen. */
6226         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6227         ret = drm_atomic_add_affected_connectors(state, crtc);
6228
6229         WARN_ON(IS_ERR(crtc_state) || ret);
6230
6231         dev_priv->display.crtc_disable(crtc_state, state);
6232
6233         drm_atomic_state_put(state);
6234
6235         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6236                       crtc->base.id, crtc->name);
6237
6238         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6239         crtc->state->active = false;
6240         intel_crtc->active = false;
6241         crtc->enabled = false;
6242         crtc->state->connector_mask = 0;
6243         crtc->state->encoder_mask = 0;
6244
6245         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6246                 encoder->base.crtc = NULL;
6247
6248         intel_fbc_disable(intel_crtc);
6249         intel_update_watermarks(intel_crtc);
6250         intel_disable_shared_dpll(to_intel_crtc_state(crtc->state));
6251
6252         domains = intel_crtc->enabled_power_domains;
6253         for_each_power_domain(domain, domains)
6254                 intel_display_power_put(dev_priv, domain);
6255         intel_crtc->enabled_power_domains = 0;
6256
6257         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6258         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6259         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6260 }
6261
6262 /*
6263  * turn all crtc's off, but do not adjust state
6264  * This has to be paired with a call to intel_modeset_setup_hw_state.
6265  */
6266 int intel_display_suspend(struct drm_device *dev)
6267 {
6268         struct drm_i915_private *dev_priv = to_i915(dev);
6269         struct drm_atomic_state *state;
6270         int ret;
6271
6272         state = drm_atomic_helper_suspend(dev);
6273         ret = PTR_ERR_OR_ZERO(state);
6274         if (ret)
6275                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6276         else
6277                 dev_priv->modeset_restore_state = state;
6278         return ret;
6279 }
6280
6281 void intel_encoder_destroy(struct drm_encoder *encoder)
6282 {
6283         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6284
6285         drm_encoder_cleanup(encoder);
6286         kfree(intel_encoder);
6287 }
6288
6289 /* Cross check the actual hw state with our own modeset state tracking (and it's
6290  * internal consistency). */
6291 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6292                                          struct drm_connector_state *conn_state)
6293 {
6294         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6295
6296         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6297                       connector->base.base.id,
6298                       connector->base.name);
6299
6300         if (connector->get_hw_state(connector)) {
6301                 struct intel_encoder *encoder = connector->encoder;
6302
6303                 I915_STATE_WARN(!crtc_state,
6304                          "connector enabled without attached crtc\n");
6305
6306                 if (!crtc_state)
6307                         return;
6308
6309                 I915_STATE_WARN(!crtc_state->active,
6310                       "connector is active, but attached crtc isn't\n");
6311
6312                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6313                         return;
6314
6315                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6316                         "atomic encoder doesn't match attached encoder\n");
6317
6318                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6319                         "attached encoder crtc differs from connector crtc\n");
6320         } else {
6321                 I915_STATE_WARN(crtc_state && crtc_state->active,
6322                         "attached crtc is active, but connector isn't\n");
6323                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6324                         "best encoder set without crtc!\n");
6325         }
6326 }
6327
6328 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6329 {
6330         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6331                 return crtc_state->fdi_lanes;
6332
6333         return 0;
6334 }
6335
6336 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6337                                      struct intel_crtc_state *pipe_config)
6338 {
6339         struct drm_i915_private *dev_priv = to_i915(dev);
6340         struct drm_atomic_state *state = pipe_config->base.state;
6341         struct intel_crtc *other_crtc;
6342         struct intel_crtc_state *other_crtc_state;
6343
6344         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6345                       pipe_name(pipe), pipe_config->fdi_lanes);
6346         if (pipe_config->fdi_lanes > 4) {
6347                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6348                               pipe_name(pipe), pipe_config->fdi_lanes);
6349                 return -EINVAL;
6350         }
6351
6352         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6353                 if (pipe_config->fdi_lanes > 2) {
6354                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6355                                       pipe_config->fdi_lanes);
6356                         return -EINVAL;
6357                 } else {
6358                         return 0;
6359                 }
6360         }
6361
6362         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6363                 return 0;
6364
6365         /* Ivybridge 3 pipe is really complicated */
6366         switch (pipe) {
6367         case PIPE_A:
6368                 return 0;
6369         case PIPE_B:
6370                 if (pipe_config->fdi_lanes <= 2)
6371                         return 0;
6372
6373                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6374                 other_crtc_state =
6375                         intel_atomic_get_crtc_state(state, other_crtc);
6376                 if (IS_ERR(other_crtc_state))
6377                         return PTR_ERR(other_crtc_state);
6378
6379                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6380                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6381                                       pipe_name(pipe), pipe_config->fdi_lanes);
6382                         return -EINVAL;
6383                 }
6384                 return 0;
6385         case PIPE_C:
6386                 if (pipe_config->fdi_lanes > 2) {
6387                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6388                                       pipe_name(pipe), pipe_config->fdi_lanes);
6389                         return -EINVAL;
6390                 }
6391
6392                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6393                 other_crtc_state =
6394                         intel_atomic_get_crtc_state(state, other_crtc);
6395                 if (IS_ERR(other_crtc_state))
6396                         return PTR_ERR(other_crtc_state);
6397
6398                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6399                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6400                         return -EINVAL;
6401                 }
6402                 return 0;
6403         default:
6404                 BUG();
6405         }
6406 }
6407
6408 #define RETRY 1
6409 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6410                                        struct intel_crtc_state *pipe_config)
6411 {
6412         struct drm_device *dev = intel_crtc->base.dev;
6413         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6414         int lane, link_bw, fdi_dotclock, ret;
6415         bool needs_recompute = false;
6416
6417 retry:
6418         /* FDI is a binary signal running at ~2.7GHz, encoding
6419          * each output octet as 10 bits. The actual frequency
6420          * is stored as a divider into a 100MHz clock, and the
6421          * mode pixel clock is stored in units of 1KHz.
6422          * Hence the bw of each lane in terms of the mode signal
6423          * is:
6424          */
6425         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6426
6427         fdi_dotclock = adjusted_mode->crtc_clock;
6428
6429         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6430                                            pipe_config->pipe_bpp);
6431
6432         pipe_config->fdi_lanes = lane;
6433
6434         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6435                                link_bw, &pipe_config->fdi_m_n, false);
6436
6437         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6438         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6439                 pipe_config->pipe_bpp -= 2*3;
6440                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6441                               pipe_config->pipe_bpp);
6442                 needs_recompute = true;
6443                 pipe_config->bw_constrained = true;
6444
6445                 goto retry;
6446         }
6447
6448         if (needs_recompute)
6449                 return RETRY;
6450
6451         return ret;
6452 }
6453
6454 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6455 {
6456         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6457         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6458
6459         /* IPS only exists on ULT machines and is tied to pipe A. */
6460         if (!hsw_crtc_supports_ips(crtc))
6461                 return false;
6462
6463         if (!i915_modparams.enable_ips)
6464                 return false;
6465
6466         if (crtc_state->pipe_bpp > 24)
6467                 return false;
6468
6469         /*
6470          * We compare against max which means we must take
6471          * the increased cdclk requirement into account when
6472          * calculating the new cdclk.
6473          *
6474          * Should measure whether using a lower cdclk w/o IPS
6475          */
6476         if (IS_BROADWELL(dev_priv) &&
6477             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6478                 return false;
6479
6480         return true;
6481 }
6482
6483 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6484 {
6485         struct drm_i915_private *dev_priv =
6486                 to_i915(crtc_state->base.crtc->dev);
6487         struct intel_atomic_state *intel_state =
6488                 to_intel_atomic_state(crtc_state->base.state);
6489
6490         if (!hsw_crtc_state_ips_capable(crtc_state))
6491                 return false;
6492
6493         if (crtc_state->ips_force_disable)
6494                 return false;
6495
6496         /* IPS should be fine as long as at least one plane is enabled. */
6497         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6498                 return false;
6499
6500         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6501         if (IS_BROADWELL(dev_priv) &&
6502             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6503                 return false;
6504
6505         return true;
6506 }
6507
6508 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6509 {
6510         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6511
6512         /* GDG double wide on either pipe, otherwise pipe A only */
6513         return INTEL_GEN(dev_priv) < 4 &&
6514                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6515 }
6516
6517 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6518 {
6519         uint32_t pixel_rate;
6520
6521         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6522
6523         /*
6524          * We only use IF-ID interlacing. If we ever use
6525          * PF-ID we'll need to adjust the pixel_rate here.
6526          */
6527
6528         if (pipe_config->pch_pfit.enabled) {
6529                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6530                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6531
6532                 pipe_w = pipe_config->pipe_src_w;
6533                 pipe_h = pipe_config->pipe_src_h;
6534
6535                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6536                 pfit_h = pfit_size & 0xFFFF;
6537                 if (pipe_w < pfit_w)
6538                         pipe_w = pfit_w;
6539                 if (pipe_h < pfit_h)
6540                         pipe_h = pfit_h;
6541
6542                 if (WARN_ON(!pfit_w || !pfit_h))
6543                         return pixel_rate;
6544
6545                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6546                                      pfit_w * pfit_h);
6547         }
6548
6549         return pixel_rate;
6550 }
6551
6552 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6553 {
6554         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6555
6556         if (HAS_GMCH_DISPLAY(dev_priv))
6557                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6558                 crtc_state->pixel_rate =
6559                         crtc_state->base.adjusted_mode.crtc_clock;
6560         else
6561                 crtc_state->pixel_rate =
6562                         ilk_pipe_pixel_rate(crtc_state);
6563 }
6564
6565 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6566                                      struct intel_crtc_state *pipe_config)
6567 {
6568         struct drm_device *dev = crtc->base.dev;
6569         struct drm_i915_private *dev_priv = to_i915(dev);
6570         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6571         int clock_limit = dev_priv->max_dotclk_freq;
6572
6573         if (INTEL_GEN(dev_priv) < 4) {
6574                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6575
6576                 /*
6577                  * Enable double wide mode when the dot clock
6578                  * is > 90% of the (display) core speed.
6579                  */
6580                 if (intel_crtc_supports_double_wide(crtc) &&
6581                     adjusted_mode->crtc_clock > clock_limit) {
6582                         clock_limit = dev_priv->max_dotclk_freq;
6583                         pipe_config->double_wide = true;
6584                 }
6585         }
6586
6587         if (adjusted_mode->crtc_clock > clock_limit) {
6588                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6589                               adjusted_mode->crtc_clock, clock_limit,
6590                               yesno(pipe_config->double_wide));
6591                 return -EINVAL;
6592         }
6593
6594         if ((pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
6595              pipe_config->output_format == INTEL_OUTPUT_FORMAT_YCBCR444) &&
6596              pipe_config->base.ctm) {
6597                 /*
6598                  * There is only one pipe CSC unit per pipe, and we need that
6599                  * for output conversion from RGB->YCBCR. So if CTM is already
6600                  * applied we can't support YCBCR420 output.
6601                  */
6602                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6603                 return -EINVAL;
6604         }
6605
6606         /*
6607          * Pipe horizontal size must be even in:
6608          * - DVO ganged mode
6609          * - LVDS dual channel mode
6610          * - Double wide pipe
6611          */
6612         if (pipe_config->pipe_src_w & 1) {
6613                 if (pipe_config->double_wide) {
6614                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6615                         return -EINVAL;
6616                 }
6617
6618                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6619                     intel_is_dual_link_lvds(dev)) {
6620                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6621                         return -EINVAL;
6622                 }
6623         }
6624
6625         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6626          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6627          */
6628         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6629                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6630                 return -EINVAL;
6631
6632         intel_crtc_compute_pixel_rate(pipe_config);
6633
6634         if (pipe_config->has_pch_encoder)
6635                 return ironlake_fdi_compute_config(crtc, pipe_config);
6636
6637         return 0;
6638 }
6639
6640 static void
6641 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6642 {
6643         while (*num > DATA_LINK_M_N_MASK ||
6644                *den > DATA_LINK_M_N_MASK) {
6645                 *num >>= 1;
6646                 *den >>= 1;
6647         }
6648 }
6649
6650 static void compute_m_n(unsigned int m, unsigned int n,
6651                         uint32_t *ret_m, uint32_t *ret_n,
6652                         bool constant_n)
6653 {
6654         /*
6655          * Several DP dongles in particular seem to be fussy about
6656          * too large link M/N values. Give N value as 0x8000 that
6657          * should be acceptable by specific devices. 0x8000 is the
6658          * specified fixed N value for asynchronous clock mode,
6659          * which the devices expect also in synchronous clock mode.
6660          */
6661         if (constant_n)
6662                 *ret_n = 0x8000;
6663         else
6664                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6665
6666         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6667         intel_reduce_m_n_ratio(ret_m, ret_n);
6668 }
6669
6670 void
6671 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6672                        int pixel_clock, int link_clock,
6673                        struct intel_link_m_n *m_n,
6674                        bool constant_n)
6675 {
6676         m_n->tu = 64;
6677
6678         compute_m_n(bits_per_pixel * pixel_clock,
6679                     link_clock * nlanes * 8,
6680                     &m_n->gmch_m, &m_n->gmch_n,
6681                     constant_n);
6682
6683         compute_m_n(pixel_clock, link_clock,
6684                     &m_n->link_m, &m_n->link_n,
6685                     constant_n);
6686 }
6687
6688 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6689 {
6690         if (i915_modparams.panel_use_ssc >= 0)
6691                 return i915_modparams.panel_use_ssc != 0;
6692         return dev_priv->vbt.lvds_use_ssc
6693                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6694 }
6695
6696 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6697 {
6698         return (1 << dpll->n) << 16 | dpll->m2;
6699 }
6700
6701 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6702 {
6703         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6704 }
6705
6706 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6707                                      struct intel_crtc_state *crtc_state,
6708                                      struct dpll *reduced_clock)
6709 {
6710         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6711         u32 fp, fp2 = 0;
6712
6713         if (IS_PINEVIEW(dev_priv)) {
6714                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6715                 if (reduced_clock)
6716                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6717         } else {
6718                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6719                 if (reduced_clock)
6720                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6721         }
6722
6723         crtc_state->dpll_hw_state.fp0 = fp;
6724
6725         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6726             reduced_clock) {
6727                 crtc_state->dpll_hw_state.fp1 = fp2;
6728         } else {
6729                 crtc_state->dpll_hw_state.fp1 = fp;
6730         }
6731 }
6732
6733 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6734                 pipe)
6735 {
6736         u32 reg_val;
6737
6738         /*
6739          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6740          * and set it to a reasonable value instead.
6741          */
6742         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6743         reg_val &= 0xffffff00;
6744         reg_val |= 0x00000030;
6745         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6746
6747         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6748         reg_val &= 0x00ffffff;
6749         reg_val |= 0x8c000000;
6750         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6751
6752         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6753         reg_val &= 0xffffff00;
6754         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6755
6756         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6757         reg_val &= 0x00ffffff;
6758         reg_val |= 0xb0000000;
6759         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6760 }
6761
6762 static void intel_pch_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
6763                                          const struct intel_link_m_n *m_n)
6764 {
6765         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6766         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6767         enum pipe pipe = crtc->pipe;
6768
6769         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6770         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6771         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6772         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6773 }
6774
6775 static bool transcoder_has_m2_n2(struct drm_i915_private *dev_priv,
6776                                  enum transcoder transcoder)
6777 {
6778         if (IS_HASWELL(dev_priv))
6779                 return transcoder == TRANSCODER_EDP;
6780
6781         /*
6782          * Strictly speaking some registers are available before
6783          * gen7, but we only support DRRS on gen7+
6784          */
6785         return IS_GEN7(dev_priv) || IS_CHERRYVIEW(dev_priv);
6786 }
6787
6788 static void intel_cpu_transcoder_set_m_n(const struct intel_crtc_state *crtc_state,
6789                                          const struct intel_link_m_n *m_n,
6790                                          const struct intel_link_m_n *m2_n2)
6791 {
6792         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6793         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6794         enum pipe pipe = crtc->pipe;
6795         enum transcoder transcoder = crtc_state->cpu_transcoder;
6796
6797         if (INTEL_GEN(dev_priv) >= 5) {
6798                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6799                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6800                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6801                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6802                 /*
6803                  *  M2_N2 registers are set only if DRRS is supported
6804                  * (to make sure the registers are not unnecessarily accessed).
6805                  */
6806                 if (m2_n2 && crtc_state->has_drrs &&
6807                     transcoder_has_m2_n2(dev_priv, transcoder)) {
6808                         I915_WRITE(PIPE_DATA_M2(transcoder),
6809                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6810                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6811                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6812                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6813                 }
6814         } else {
6815                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6816                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6817                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6818                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6819         }
6820 }
6821
6822 void intel_dp_set_m_n(const struct intel_crtc_state *crtc_state, enum link_m_n_set m_n)
6823 {
6824         const struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6825
6826         if (m_n == M1_N1) {
6827                 dp_m_n = &crtc_state->dp_m_n;
6828                 dp_m2_n2 = &crtc_state->dp_m2_n2;
6829         } else if (m_n == M2_N2) {
6830
6831                 /*
6832                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6833                  * needs to be programmed into M1_N1.
6834                  */
6835                 dp_m_n = &crtc_state->dp_m2_n2;
6836         } else {
6837                 DRM_ERROR("Unsupported divider value\n");
6838                 return;
6839         }
6840
6841         if (crtc_state->has_pch_encoder)
6842                 intel_pch_transcoder_set_m_n(crtc_state, &crtc_state->dp_m_n);
6843         else
6844                 intel_cpu_transcoder_set_m_n(crtc_state, dp_m_n, dp_m2_n2);
6845 }
6846
6847 static void vlv_compute_dpll(struct intel_crtc *crtc,
6848                              struct intel_crtc_state *pipe_config)
6849 {
6850         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6851                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6852         if (crtc->pipe != PIPE_A)
6853                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6854
6855         /* DPLL not used with DSI, but still need the rest set up */
6856         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6857                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6858                         DPLL_EXT_BUFFER_ENABLE_VLV;
6859
6860         pipe_config->dpll_hw_state.dpll_md =
6861                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6862 }
6863
6864 static void chv_compute_dpll(struct intel_crtc *crtc,
6865                              struct intel_crtc_state *pipe_config)
6866 {
6867         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6868                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6869         if (crtc->pipe != PIPE_A)
6870                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6871
6872         /* DPLL not used with DSI, but still need the rest set up */
6873         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6874                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6875
6876         pipe_config->dpll_hw_state.dpll_md =
6877                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6878 }
6879
6880 static void vlv_prepare_pll(struct intel_crtc *crtc,
6881                             const struct intel_crtc_state *pipe_config)
6882 {
6883         struct drm_device *dev = crtc->base.dev;
6884         struct drm_i915_private *dev_priv = to_i915(dev);
6885         enum pipe pipe = crtc->pipe;
6886         u32 mdiv;
6887         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6888         u32 coreclk, reg_val;
6889
6890         /* Enable Refclk */
6891         I915_WRITE(DPLL(pipe),
6892                    pipe_config->dpll_hw_state.dpll &
6893                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6894
6895         /* No need to actually set up the DPLL with DSI */
6896         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6897                 return;
6898
6899         mutex_lock(&dev_priv->sb_lock);
6900
6901         bestn = pipe_config->dpll.n;
6902         bestm1 = pipe_config->dpll.m1;
6903         bestm2 = pipe_config->dpll.m2;
6904         bestp1 = pipe_config->dpll.p1;
6905         bestp2 = pipe_config->dpll.p2;
6906
6907         /* See eDP HDMI DPIO driver vbios notes doc */
6908
6909         /* PLL B needs special handling */
6910         if (pipe == PIPE_B)
6911                 vlv_pllb_recal_opamp(dev_priv, pipe);
6912
6913         /* Set up Tx target for periodic Rcomp update */
6914         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6915
6916         /* Disable target IRef on PLL */
6917         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6918         reg_val &= 0x00ffffff;
6919         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6920
6921         /* Disable fast lock */
6922         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6923
6924         /* Set idtafcrecal before PLL is enabled */
6925         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6926         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6927         mdiv |= ((bestn << DPIO_N_SHIFT));
6928         mdiv |= (1 << DPIO_K_SHIFT);
6929
6930         /*
6931          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6932          * but we don't support that).
6933          * Note: don't use the DAC post divider as it seems unstable.
6934          */
6935         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6936         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6937
6938         mdiv |= DPIO_ENABLE_CALIBRATION;
6939         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6940
6941         /* Set HBR and RBR LPF coefficients */
6942         if (pipe_config->port_clock == 162000 ||
6943             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_ANALOG) ||
6944             intel_crtc_has_type(pipe_config, INTEL_OUTPUT_HDMI))
6945                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6946                                  0x009f0003);
6947         else
6948                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6949                                  0x00d0000f);
6950
6951         if (intel_crtc_has_dp_encoder(pipe_config)) {
6952                 /* Use SSC source */
6953                 if (pipe == PIPE_A)
6954                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6955                                          0x0df40000);
6956                 else
6957                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6958                                          0x0df70000);
6959         } else { /* HDMI or VGA */
6960                 /* Use bend source */
6961                 if (pipe == PIPE_A)
6962                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6963                                          0x0df70000);
6964                 else
6965                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6966                                          0x0df40000);
6967         }
6968
6969         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6970         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6971         if (intel_crtc_has_dp_encoder(pipe_config))
6972                 coreclk |= 0x01000000;
6973         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6974
6975         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6976         mutex_unlock(&dev_priv->sb_lock);
6977 }
6978
6979 static void chv_prepare_pll(struct intel_crtc *crtc,
6980                             const struct intel_crtc_state *pipe_config)
6981 {
6982         struct drm_device *dev = crtc->base.dev;
6983         struct drm_i915_private *dev_priv = to_i915(dev);
6984         enum pipe pipe = crtc->pipe;
6985         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6986         u32 loopfilter, tribuf_calcntr;
6987         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6988         u32 dpio_val;
6989         int vco;
6990
6991         /* Enable Refclk and SSC */
6992         I915_WRITE(DPLL(pipe),
6993                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6994
6995         /* No need to actually set up the DPLL with DSI */
6996         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6997                 return;
6998
6999         bestn = pipe_config->dpll.n;
7000         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7001         bestm1 = pipe_config->dpll.m1;
7002         bestm2 = pipe_config->dpll.m2 >> 22;
7003         bestp1 = pipe_config->dpll.p1;
7004         bestp2 = pipe_config->dpll.p2;
7005         vco = pipe_config->dpll.vco;
7006         dpio_val = 0;
7007         loopfilter = 0;
7008
7009         mutex_lock(&dev_priv->sb_lock);
7010
7011         /* p1 and p2 divider */
7012         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7013                         5 << DPIO_CHV_S1_DIV_SHIFT |
7014                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7015                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7016                         1 << DPIO_CHV_K_DIV_SHIFT);
7017
7018         /* Feedback post-divider - m2 */
7019         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7020
7021         /* Feedback refclk divider - n and m1 */
7022         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7023                         DPIO_CHV_M1_DIV_BY_2 |
7024                         1 << DPIO_CHV_N_DIV_SHIFT);
7025
7026         /* M2 fraction division */
7027         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7028
7029         /* M2 fraction division enable */
7030         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7031         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7032         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7033         if (bestm2_frac)
7034                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7035         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7036
7037         /* Program digital lock detect threshold */
7038         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7039         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7040                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7041         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7042         if (!bestm2_frac)
7043                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7044         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7045
7046         /* Loop filter */
7047         if (vco == 5400000) {
7048                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7049                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7050                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7051                 tribuf_calcntr = 0x9;
7052         } else if (vco <= 6200000) {
7053                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7054                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7055                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7056                 tribuf_calcntr = 0x9;
7057         } else if (vco <= 6480000) {
7058                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7059                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7060                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7061                 tribuf_calcntr = 0x8;
7062         } else {
7063                 /* Not supported. Apply the same limits as in the max case */
7064                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7065                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7066                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7067                 tribuf_calcntr = 0;
7068         }
7069         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7070
7071         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7072         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7073         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7074         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7075
7076         /* AFC Recal */
7077         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7078                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7079                         DPIO_AFC_RECAL);
7080
7081         mutex_unlock(&dev_priv->sb_lock);
7082 }
7083
7084 /**
7085  * vlv_force_pll_on - forcibly enable just the PLL
7086  * @dev_priv: i915 private structure
7087  * @pipe: pipe PLL to enable
7088  * @dpll: PLL configuration
7089  *
7090  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7091  * in cases where we need the PLL enabled even when @pipe is not going to
7092  * be enabled.
7093  */
7094 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7095                      const struct dpll *dpll)
7096 {
7097         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7098         struct intel_crtc_state *pipe_config;
7099
7100         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7101         if (!pipe_config)
7102                 return -ENOMEM;
7103
7104         pipe_config->base.crtc = &crtc->base;
7105         pipe_config->pixel_multiplier = 1;
7106         pipe_config->dpll = *dpll;
7107
7108         if (IS_CHERRYVIEW(dev_priv)) {
7109                 chv_compute_dpll(crtc, pipe_config);
7110                 chv_prepare_pll(crtc, pipe_config);
7111                 chv_enable_pll(crtc, pipe_config);
7112         } else {
7113                 vlv_compute_dpll(crtc, pipe_config);
7114                 vlv_prepare_pll(crtc, pipe_config);
7115                 vlv_enable_pll(crtc, pipe_config);
7116         }
7117
7118         kfree(pipe_config);
7119
7120         return 0;
7121 }
7122
7123 /**
7124  * vlv_force_pll_off - forcibly disable just the PLL
7125  * @dev_priv: i915 private structure
7126  * @pipe: pipe PLL to disable
7127  *
7128  * Disable the PLL for @pipe. To be used in cases where we need
7129  * the PLL enabled even when @pipe is not going to be enabled.
7130  */
7131 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7132 {
7133         if (IS_CHERRYVIEW(dev_priv))
7134                 chv_disable_pll(dev_priv, pipe);
7135         else
7136                 vlv_disable_pll(dev_priv, pipe);
7137 }
7138
7139 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7140                               struct intel_crtc_state *crtc_state,
7141                               struct dpll *reduced_clock)
7142 {
7143         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7144         u32 dpll;
7145         struct dpll *clock = &crtc_state->dpll;
7146
7147         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7148
7149         dpll = DPLL_VGA_MODE_DIS;
7150
7151         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7152                 dpll |= DPLLB_MODE_LVDS;
7153         else
7154                 dpll |= DPLLB_MODE_DAC_SERIAL;
7155
7156         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7157             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7158                 dpll |= (crtc_state->pixel_multiplier - 1)
7159                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7160         }
7161
7162         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7163             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7164                 dpll |= DPLL_SDVO_HIGH_SPEED;
7165
7166         if (intel_crtc_has_dp_encoder(crtc_state))
7167                 dpll |= DPLL_SDVO_HIGH_SPEED;
7168
7169         /* compute bitmask from p1 value */
7170         if (IS_PINEVIEW(dev_priv))
7171                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7172         else {
7173                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7174                 if (IS_G4X(dev_priv) && reduced_clock)
7175                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7176         }
7177         switch (clock->p2) {
7178         case 5:
7179                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7180                 break;
7181         case 7:
7182                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7183                 break;
7184         case 10:
7185                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7186                 break;
7187         case 14:
7188                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7189                 break;
7190         }
7191         if (INTEL_GEN(dev_priv) >= 4)
7192                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7193
7194         if (crtc_state->sdvo_tv_clock)
7195                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7196         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7197                  intel_panel_use_ssc(dev_priv))
7198                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7199         else
7200                 dpll |= PLL_REF_INPUT_DREFCLK;
7201
7202         dpll |= DPLL_VCO_ENABLE;
7203         crtc_state->dpll_hw_state.dpll = dpll;
7204
7205         if (INTEL_GEN(dev_priv) >= 4) {
7206                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7207                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7208                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7209         }
7210 }
7211
7212 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7213                               struct intel_crtc_state *crtc_state,
7214                               struct dpll *reduced_clock)
7215 {
7216         struct drm_device *dev = crtc->base.dev;
7217         struct drm_i915_private *dev_priv = to_i915(dev);
7218         u32 dpll;
7219         struct dpll *clock = &crtc_state->dpll;
7220
7221         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7222
7223         dpll = DPLL_VGA_MODE_DIS;
7224
7225         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7226                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7227         } else {
7228                 if (clock->p1 == 2)
7229                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7230                 else
7231                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7232                 if (clock->p2 == 4)
7233                         dpll |= PLL_P2_DIVIDE_BY_4;
7234         }
7235
7236         if (!IS_I830(dev_priv) &&
7237             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7238                 dpll |= DPLL_DVO_2X_MODE;
7239
7240         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7241             intel_panel_use_ssc(dev_priv))
7242                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7243         else
7244                 dpll |= PLL_REF_INPUT_DREFCLK;
7245
7246         dpll |= DPLL_VCO_ENABLE;
7247         crtc_state->dpll_hw_state.dpll = dpll;
7248 }
7249
7250 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state)
7251 {
7252         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7253         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7254         enum pipe pipe = crtc->pipe;
7255         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
7256         const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
7257         uint32_t crtc_vtotal, crtc_vblank_end;
7258         int vsyncshift = 0;
7259
7260         /* We need to be careful not to changed the adjusted mode, for otherwise
7261          * the hw state checker will get angry at the mismatch. */
7262         crtc_vtotal = adjusted_mode->crtc_vtotal;
7263         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7264
7265         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7266                 /* the chip adds 2 halflines automatically */
7267                 crtc_vtotal -= 1;
7268                 crtc_vblank_end -= 1;
7269
7270                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7271                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7272                 else
7273                         vsyncshift = adjusted_mode->crtc_hsync_start -
7274                                 adjusted_mode->crtc_htotal / 2;
7275                 if (vsyncshift < 0)
7276                         vsyncshift += adjusted_mode->crtc_htotal;
7277         }
7278
7279         if (INTEL_GEN(dev_priv) > 3)
7280                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7281
7282         I915_WRITE(HTOTAL(cpu_transcoder),
7283                    (adjusted_mode->crtc_hdisplay - 1) |
7284                    ((adjusted_mode->crtc_htotal - 1) << 16));
7285         I915_WRITE(HBLANK(cpu_transcoder),
7286                    (adjusted_mode->crtc_hblank_start - 1) |
7287                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7288         I915_WRITE(HSYNC(cpu_transcoder),
7289                    (adjusted_mode->crtc_hsync_start - 1) |
7290                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7291
7292         I915_WRITE(VTOTAL(cpu_transcoder),
7293                    (adjusted_mode->crtc_vdisplay - 1) |
7294                    ((crtc_vtotal - 1) << 16));
7295         I915_WRITE(VBLANK(cpu_transcoder),
7296                    (adjusted_mode->crtc_vblank_start - 1) |
7297                    ((crtc_vblank_end - 1) << 16));
7298         I915_WRITE(VSYNC(cpu_transcoder),
7299                    (adjusted_mode->crtc_vsync_start - 1) |
7300                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7301
7302         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7303          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7304          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7305          * bits. */
7306         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7307             (pipe == PIPE_B || pipe == PIPE_C))
7308                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7309
7310 }
7311
7312 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state)
7313 {
7314         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7315         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7316         enum pipe pipe = crtc->pipe;
7317
7318         /* pipesrc controls the size that is scaled from, which should
7319          * always be the user's requested size.
7320          */
7321         I915_WRITE(PIPESRC(pipe),
7322                    ((crtc_state->pipe_src_w - 1) << 16) |
7323                    (crtc_state->pipe_src_h - 1));
7324 }
7325
7326 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7327                                    struct intel_crtc_state *pipe_config)
7328 {
7329         struct drm_device *dev = crtc->base.dev;
7330         struct drm_i915_private *dev_priv = to_i915(dev);
7331         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7332         uint32_t tmp;
7333
7334         tmp = I915_READ(HTOTAL(cpu_transcoder));
7335         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7336         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7337         tmp = I915_READ(HBLANK(cpu_transcoder));
7338         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7339         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7340         tmp = I915_READ(HSYNC(cpu_transcoder));
7341         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7342         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7343
7344         tmp = I915_READ(VTOTAL(cpu_transcoder));
7345         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7346         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7347         tmp = I915_READ(VBLANK(cpu_transcoder));
7348         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7349         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7350         tmp = I915_READ(VSYNC(cpu_transcoder));
7351         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7352         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7353
7354         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7355                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7356                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7357                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7358         }
7359 }
7360
7361 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7362                                     struct intel_crtc_state *pipe_config)
7363 {
7364         struct drm_device *dev = crtc->base.dev;
7365         struct drm_i915_private *dev_priv = to_i915(dev);
7366         u32 tmp;
7367
7368         tmp = I915_READ(PIPESRC(crtc->pipe));
7369         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7370         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7371
7372         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7373         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7374 }
7375
7376 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7377                                  struct intel_crtc_state *pipe_config)
7378 {
7379         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7380         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7381         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7382         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7383
7384         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7385         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7386         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7387         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7388
7389         mode->flags = pipe_config->base.adjusted_mode.flags;
7390         mode->type = DRM_MODE_TYPE_DRIVER;
7391
7392         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7393
7394         mode->hsync = drm_mode_hsync(mode);
7395         mode->vrefresh = drm_mode_vrefresh(mode);
7396         drm_mode_set_name(mode);
7397 }
7398
7399 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state)
7400 {
7401         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7402         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7403         uint32_t pipeconf;
7404
7405         pipeconf = 0;
7406
7407         /* we keep both pipes enabled on 830 */
7408         if (IS_I830(dev_priv))
7409                 pipeconf |= I915_READ(PIPECONF(crtc->pipe)) & PIPECONF_ENABLE;
7410
7411         if (crtc_state->double_wide)
7412                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7413
7414         /* only g4x and later have fancy bpc/dither controls */
7415         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7416             IS_CHERRYVIEW(dev_priv)) {
7417                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7418                 if (crtc_state->dither && crtc_state->pipe_bpp != 30)
7419                         pipeconf |= PIPECONF_DITHER_EN |
7420                                     PIPECONF_DITHER_TYPE_SP;
7421
7422                 switch (crtc_state->pipe_bpp) {
7423                 case 18:
7424                         pipeconf |= PIPECONF_6BPC;
7425                         break;
7426                 case 24:
7427                         pipeconf |= PIPECONF_8BPC;
7428                         break;
7429                 case 30:
7430                         pipeconf |= PIPECONF_10BPC;
7431                         break;
7432                 default:
7433                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7434                         BUG();
7435                 }
7436         }
7437
7438         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7439                 if (INTEL_GEN(dev_priv) < 4 ||
7440                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7441                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7442                 else
7443                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7444         } else
7445                 pipeconf |= PIPECONF_PROGRESSIVE;
7446
7447         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7448              crtc_state->limited_color_range)
7449                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7450
7451         I915_WRITE(PIPECONF(crtc->pipe), pipeconf);
7452         POSTING_READ(PIPECONF(crtc->pipe));
7453 }
7454
7455 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7456                                    struct intel_crtc_state *crtc_state)
7457 {
7458         struct drm_device *dev = crtc->base.dev;
7459         struct drm_i915_private *dev_priv = to_i915(dev);
7460         const struct intel_limit *limit;
7461         int refclk = 48000;
7462
7463         memset(&crtc_state->dpll_hw_state, 0,
7464                sizeof(crtc_state->dpll_hw_state));
7465
7466         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7467                 if (intel_panel_use_ssc(dev_priv)) {
7468                         refclk = dev_priv->vbt.lvds_ssc_freq;
7469                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7470                 }
7471
7472                 limit = &intel_limits_i8xx_lvds;
7473         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7474                 limit = &intel_limits_i8xx_dvo;
7475         } else {
7476                 limit = &intel_limits_i8xx_dac;
7477         }
7478
7479         if (!crtc_state->clock_set &&
7480             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7481                                  refclk, NULL, &crtc_state->dpll)) {
7482                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7483                 return -EINVAL;
7484         }
7485
7486         i8xx_compute_dpll(crtc, crtc_state, NULL);
7487
7488         return 0;
7489 }
7490
7491 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7492                                   struct intel_crtc_state *crtc_state)
7493 {
7494         struct drm_device *dev = crtc->base.dev;
7495         struct drm_i915_private *dev_priv = to_i915(dev);
7496         const struct intel_limit *limit;
7497         int refclk = 96000;
7498
7499         memset(&crtc_state->dpll_hw_state, 0,
7500                sizeof(crtc_state->dpll_hw_state));
7501
7502         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7503                 if (intel_panel_use_ssc(dev_priv)) {
7504                         refclk = dev_priv->vbt.lvds_ssc_freq;
7505                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7506                 }
7507
7508                 if (intel_is_dual_link_lvds(dev))
7509                         limit = &intel_limits_g4x_dual_channel_lvds;
7510                 else
7511                         limit = &intel_limits_g4x_single_channel_lvds;
7512         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7513                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7514                 limit = &intel_limits_g4x_hdmi;
7515         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7516                 limit = &intel_limits_g4x_sdvo;
7517         } else {
7518                 /* The option is for other outputs */
7519                 limit = &intel_limits_i9xx_sdvo;
7520         }
7521
7522         if (!crtc_state->clock_set &&
7523             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7524                                 refclk, NULL, &crtc_state->dpll)) {
7525                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7526                 return -EINVAL;
7527         }
7528
7529         i9xx_compute_dpll(crtc, crtc_state, NULL);
7530
7531         return 0;
7532 }
7533
7534 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7535                                   struct intel_crtc_state *crtc_state)
7536 {
7537         struct drm_device *dev = crtc->base.dev;
7538         struct drm_i915_private *dev_priv = to_i915(dev);
7539         const struct intel_limit *limit;
7540         int refclk = 96000;
7541
7542         memset(&crtc_state->dpll_hw_state, 0,
7543                sizeof(crtc_state->dpll_hw_state));
7544
7545         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7546                 if (intel_panel_use_ssc(dev_priv)) {
7547                         refclk = dev_priv->vbt.lvds_ssc_freq;
7548                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7549                 }
7550
7551                 limit = &intel_limits_pineview_lvds;
7552         } else {
7553                 limit = &intel_limits_pineview_sdvo;
7554         }
7555
7556         if (!crtc_state->clock_set &&
7557             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7558                                 refclk, NULL, &crtc_state->dpll)) {
7559                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7560                 return -EINVAL;
7561         }
7562
7563         i9xx_compute_dpll(crtc, crtc_state, NULL);
7564
7565         return 0;
7566 }
7567
7568 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7569                                    struct intel_crtc_state *crtc_state)
7570 {
7571         struct drm_device *dev = crtc->base.dev;
7572         struct drm_i915_private *dev_priv = to_i915(dev);
7573         const struct intel_limit *limit;
7574         int refclk = 96000;
7575
7576         memset(&crtc_state->dpll_hw_state, 0,
7577                sizeof(crtc_state->dpll_hw_state));
7578
7579         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7580                 if (intel_panel_use_ssc(dev_priv)) {
7581                         refclk = dev_priv->vbt.lvds_ssc_freq;
7582                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7583                 }
7584
7585                 limit = &intel_limits_i9xx_lvds;
7586         } else {
7587                 limit = &intel_limits_i9xx_sdvo;
7588         }
7589
7590         if (!crtc_state->clock_set &&
7591             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7592                                  refclk, NULL, &crtc_state->dpll)) {
7593                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7594                 return -EINVAL;
7595         }
7596
7597         i9xx_compute_dpll(crtc, crtc_state, NULL);
7598
7599         return 0;
7600 }
7601
7602 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7603                                   struct intel_crtc_state *crtc_state)
7604 {
7605         int refclk = 100000;
7606         const struct intel_limit *limit = &intel_limits_chv;
7607
7608         memset(&crtc_state->dpll_hw_state, 0,
7609                sizeof(crtc_state->dpll_hw_state));
7610
7611         if (!crtc_state->clock_set &&
7612             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7613                                 refclk, NULL, &crtc_state->dpll)) {
7614                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7615                 return -EINVAL;
7616         }
7617
7618         chv_compute_dpll(crtc, crtc_state);
7619
7620         return 0;
7621 }
7622
7623 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7624                                   struct intel_crtc_state *crtc_state)
7625 {
7626         int refclk = 100000;
7627         const struct intel_limit *limit = &intel_limits_vlv;
7628
7629         memset(&crtc_state->dpll_hw_state, 0,
7630                sizeof(crtc_state->dpll_hw_state));
7631
7632         if (!crtc_state->clock_set &&
7633             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7634                                 refclk, NULL, &crtc_state->dpll)) {
7635                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7636                 return -EINVAL;
7637         }
7638
7639         vlv_compute_dpll(crtc, crtc_state);
7640
7641         return 0;
7642 }
7643
7644 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7645                                  struct intel_crtc_state *pipe_config)
7646 {
7647         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7648         uint32_t tmp;
7649
7650         if (INTEL_GEN(dev_priv) <= 3 &&
7651             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7652                 return;
7653
7654         tmp = I915_READ(PFIT_CONTROL);
7655         if (!(tmp & PFIT_ENABLE))
7656                 return;
7657
7658         /* Check whether the pfit is attached to our pipe. */
7659         if (INTEL_GEN(dev_priv) < 4) {
7660                 if (crtc->pipe != PIPE_B)
7661                         return;
7662         } else {
7663                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7664                         return;
7665         }
7666
7667         pipe_config->gmch_pfit.control = tmp;
7668         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7669 }
7670
7671 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7672                                struct intel_crtc_state *pipe_config)
7673 {
7674         struct drm_device *dev = crtc->base.dev;
7675         struct drm_i915_private *dev_priv = to_i915(dev);
7676         int pipe = pipe_config->cpu_transcoder;
7677         struct dpll clock;
7678         u32 mdiv;
7679         int refclk = 100000;
7680
7681         /* In case of DSI, DPLL will not be used */
7682         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7683                 return;
7684
7685         mutex_lock(&dev_priv->sb_lock);
7686         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7687         mutex_unlock(&dev_priv->sb_lock);
7688
7689         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7690         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7691         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7692         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7693         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7694
7695         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7696 }
7697
7698 static void
7699 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7700                               struct intel_initial_plane_config *plane_config)
7701 {
7702         struct drm_device *dev = crtc->base.dev;
7703         struct drm_i915_private *dev_priv = to_i915(dev);
7704         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7705         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7706         enum pipe pipe;
7707         u32 val, base, offset;
7708         int fourcc, pixel_format;
7709         unsigned int aligned_height;
7710         struct drm_framebuffer *fb;
7711         struct intel_framebuffer *intel_fb;
7712
7713         if (!plane->get_hw_state(plane, &pipe))
7714                 return;
7715
7716         WARN_ON(pipe != crtc->pipe);
7717
7718         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7719         if (!intel_fb) {
7720                 DRM_DEBUG_KMS("failed to alloc fb\n");
7721                 return;
7722         }
7723
7724         fb = &intel_fb->base;
7725
7726         fb->dev = dev;
7727
7728         val = I915_READ(DSPCNTR(i9xx_plane));
7729
7730         if (INTEL_GEN(dev_priv) >= 4) {
7731                 if (val & DISPPLANE_TILED) {
7732                         plane_config->tiling = I915_TILING_X;
7733                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7734                 }
7735         }
7736
7737         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7738         fourcc = i9xx_format_to_fourcc(pixel_format);
7739         fb->format = drm_format_info(fourcc);
7740
7741         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7742                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7743                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7744         } else if (INTEL_GEN(dev_priv) >= 4) {
7745                 if (plane_config->tiling)
7746                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7747                 else
7748                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7749                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7750         } else {
7751                 base = I915_READ(DSPADDR(i9xx_plane));
7752         }
7753         plane_config->base = base;
7754
7755         val = I915_READ(PIPESRC(pipe));
7756         fb->width = ((val >> 16) & 0xfff) + 1;
7757         fb->height = ((val >> 0) & 0xfff) + 1;
7758
7759         val = I915_READ(DSPSTRIDE(i9xx_plane));
7760         fb->pitches[0] = val & 0xffffffc0;
7761
7762         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7763
7764         plane_config->size = fb->pitches[0] * aligned_height;
7765
7766         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7767                       crtc->base.name, plane->base.name, fb->width, fb->height,
7768                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7769                       plane_config->size);
7770
7771         plane_config->fb = intel_fb;
7772 }
7773
7774 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7775                                struct intel_crtc_state *pipe_config)
7776 {
7777         struct drm_device *dev = crtc->base.dev;
7778         struct drm_i915_private *dev_priv = to_i915(dev);
7779         int pipe = pipe_config->cpu_transcoder;
7780         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7781         struct dpll clock;
7782         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7783         int refclk = 100000;
7784
7785         /* In case of DSI, DPLL will not be used */
7786         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7787                 return;
7788
7789         mutex_lock(&dev_priv->sb_lock);
7790         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7791         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7792         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7793         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7794         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7795         mutex_unlock(&dev_priv->sb_lock);
7796
7797         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7798         clock.m2 = (pll_dw0 & 0xff) << 22;
7799         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7800                 clock.m2 |= pll_dw2 & 0x3fffff;
7801         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7802         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7803         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7804
7805         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7806 }
7807
7808 static void intel_get_crtc_ycbcr_config(struct intel_crtc *crtc,
7809                                         struct intel_crtc_state *pipe_config)
7810 {
7811         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7812         enum intel_output_format output = INTEL_OUTPUT_FORMAT_RGB;
7813
7814         pipe_config->lspcon_downsampling = false;
7815
7816         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
7817                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
7818
7819                 if (tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV) {
7820                         bool ycbcr420_enabled = tmp & PIPEMISC_YUV420_ENABLE;
7821                         bool blend = tmp & PIPEMISC_YUV420_MODE_FULL_BLEND;
7822
7823                         if (ycbcr420_enabled) {
7824                                 /* We support 4:2:0 in full blend mode only */
7825                                 if (!blend)
7826                                         output = INTEL_OUTPUT_FORMAT_INVALID;
7827                                 else if (!(IS_GEMINILAKE(dev_priv) ||
7828                                            INTEL_GEN(dev_priv) >= 10))
7829                                         output = INTEL_OUTPUT_FORMAT_INVALID;
7830                                 else
7831                                         output = INTEL_OUTPUT_FORMAT_YCBCR420;
7832                         } else {
7833                                 /*
7834                                  * Currently there is no interface defined to
7835                                  * check user preference between RGB/YCBCR444
7836                                  * or YCBCR420. So the only possible case for
7837                                  * YCBCR444 usage is driving YCBCR420 output
7838                                  * with LSPCON, when pipe is configured for
7839                                  * YCBCR444 output and LSPCON takes care of
7840                                  * downsampling it.
7841                                  */
7842                                 pipe_config->lspcon_downsampling = true;
7843                                 output = INTEL_OUTPUT_FORMAT_YCBCR444;
7844                         }
7845                 }
7846         }
7847
7848         pipe_config->output_format = output;
7849 }
7850
7851 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7852                                  struct intel_crtc_state *pipe_config)
7853 {
7854         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7855         enum intel_display_power_domain power_domain;
7856         uint32_t tmp;
7857         bool ret;
7858
7859         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7860         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7861                 return false;
7862
7863         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
7864         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7865         pipe_config->shared_dpll = NULL;
7866
7867         ret = false;
7868
7869         tmp = I915_READ(PIPECONF(crtc->pipe));
7870         if (!(tmp & PIPECONF_ENABLE))
7871                 goto out;
7872
7873         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7874             IS_CHERRYVIEW(dev_priv)) {
7875                 switch (tmp & PIPECONF_BPC_MASK) {
7876                 case PIPECONF_6BPC:
7877                         pipe_config->pipe_bpp = 18;
7878                         break;
7879                 case PIPECONF_8BPC:
7880                         pipe_config->pipe_bpp = 24;
7881                         break;
7882                 case PIPECONF_10BPC:
7883                         pipe_config->pipe_bpp = 30;
7884                         break;
7885                 default:
7886                         break;
7887                 }
7888         }
7889
7890         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7891             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7892                 pipe_config->limited_color_range = true;
7893
7894         if (INTEL_GEN(dev_priv) < 4)
7895                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7896
7897         intel_get_pipe_timings(crtc, pipe_config);
7898         intel_get_pipe_src_size(crtc, pipe_config);
7899
7900         i9xx_get_pfit_config(crtc, pipe_config);
7901
7902         if (INTEL_GEN(dev_priv) >= 4) {
7903                 /* No way to read it out on pipes B and C */
7904                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7905                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7906                 else
7907                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7908                 pipe_config->pixel_multiplier =
7909                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7910                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7911                 pipe_config->dpll_hw_state.dpll_md = tmp;
7912         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7913                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7914                 tmp = I915_READ(DPLL(crtc->pipe));
7915                 pipe_config->pixel_multiplier =
7916                         ((tmp & SDVO_MULTIPLIER_MASK)
7917                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7918         } else {
7919                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7920                  * port and will be fixed up in the encoder->get_config
7921                  * function. */
7922                 pipe_config->pixel_multiplier = 1;
7923         }
7924         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7925         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7926                 /*
7927                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7928                  * on 830. Filter it out here so that we don't
7929                  * report errors due to that.
7930                  */
7931                 if (IS_I830(dev_priv))
7932                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7933
7934                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7935                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7936         } else {
7937                 /* Mask out read-only status bits. */
7938                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7939                                                      DPLL_PORTC_READY_MASK |
7940                                                      DPLL_PORTB_READY_MASK);
7941         }
7942
7943         if (IS_CHERRYVIEW(dev_priv))
7944                 chv_crtc_clock_get(crtc, pipe_config);
7945         else if (IS_VALLEYVIEW(dev_priv))
7946                 vlv_crtc_clock_get(crtc, pipe_config);
7947         else
7948                 i9xx_crtc_clock_get(crtc, pipe_config);
7949
7950         /*
7951          * Normally the dotclock is filled in by the encoder .get_config()
7952          * but in case the pipe is enabled w/o any ports we need a sane
7953          * default.
7954          */
7955         pipe_config->base.adjusted_mode.crtc_clock =
7956                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7957
7958         ret = true;
7959
7960 out:
7961         intel_display_power_put(dev_priv, power_domain);
7962
7963         return ret;
7964 }
7965
7966 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7967 {
7968         struct intel_encoder *encoder;
7969         int i;
7970         u32 val, final;
7971         bool has_lvds = false;
7972         bool has_cpu_edp = false;
7973         bool has_panel = false;
7974         bool has_ck505 = false;
7975         bool can_ssc = false;
7976         bool using_ssc_source = false;
7977
7978         /* We need to take the global config into account */
7979         for_each_intel_encoder(&dev_priv->drm, encoder) {
7980                 switch (encoder->type) {
7981                 case INTEL_OUTPUT_LVDS:
7982                         has_panel = true;
7983                         has_lvds = true;
7984                         break;
7985                 case INTEL_OUTPUT_EDP:
7986                         has_panel = true;
7987                         if (encoder->port == PORT_A)
7988                                 has_cpu_edp = true;
7989                         break;
7990                 default:
7991                         break;
7992                 }
7993         }
7994
7995         if (HAS_PCH_IBX(dev_priv)) {
7996                 has_ck505 = dev_priv->vbt.display_clock_mode;
7997                 can_ssc = has_ck505;
7998         } else {
7999                 has_ck505 = false;
8000                 can_ssc = true;
8001         }
8002
8003         /* Check if any DPLLs are using the SSC source */
8004         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8005                 u32 temp = I915_READ(PCH_DPLL(i));
8006
8007                 if (!(temp & DPLL_VCO_ENABLE))
8008                         continue;
8009
8010                 if ((temp & PLL_REF_INPUT_MASK) ==
8011                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8012                         using_ssc_source = true;
8013                         break;
8014                 }
8015         }
8016
8017         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8018                       has_panel, has_lvds, has_ck505, using_ssc_source);
8019
8020         /* Ironlake: try to setup display ref clock before DPLL
8021          * enabling. This is only under driver's control after
8022          * PCH B stepping, previous chipset stepping should be
8023          * ignoring this setting.
8024          */
8025         val = I915_READ(PCH_DREF_CONTROL);
8026
8027         /* As we must carefully and slowly disable/enable each source in turn,
8028          * compute the final state we want first and check if we need to
8029          * make any changes at all.
8030          */
8031         final = val;
8032         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8033         if (has_ck505)
8034                 final |= DREF_NONSPREAD_CK505_ENABLE;
8035         else
8036                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8037
8038         final &= ~DREF_SSC_SOURCE_MASK;
8039         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8040         final &= ~DREF_SSC1_ENABLE;
8041
8042         if (has_panel) {
8043                 final |= DREF_SSC_SOURCE_ENABLE;
8044
8045                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8046                         final |= DREF_SSC1_ENABLE;
8047
8048                 if (has_cpu_edp) {
8049                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8050                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8051                         else
8052                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8053                 } else
8054                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8055         } else if (using_ssc_source) {
8056                 final |= DREF_SSC_SOURCE_ENABLE;
8057                 final |= DREF_SSC1_ENABLE;
8058         }
8059
8060         if (final == val)
8061                 return;
8062
8063         /* Always enable nonspread source */
8064         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8065
8066         if (has_ck505)
8067                 val |= DREF_NONSPREAD_CK505_ENABLE;
8068         else
8069                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8070
8071         if (has_panel) {
8072                 val &= ~DREF_SSC_SOURCE_MASK;
8073                 val |= DREF_SSC_SOURCE_ENABLE;
8074
8075                 /* SSC must be turned on before enabling the CPU output  */
8076                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8077                         DRM_DEBUG_KMS("Using SSC on panel\n");
8078                         val |= DREF_SSC1_ENABLE;
8079                 } else
8080                         val &= ~DREF_SSC1_ENABLE;
8081
8082                 /* Get SSC going before enabling the outputs */
8083                 I915_WRITE(PCH_DREF_CONTROL, val);
8084                 POSTING_READ(PCH_DREF_CONTROL);
8085                 udelay(200);
8086
8087                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8088
8089                 /* Enable CPU source on CPU attached eDP */
8090                 if (has_cpu_edp) {
8091                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8092                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8093                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8094                         } else
8095                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8096                 } else
8097                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8098
8099                 I915_WRITE(PCH_DREF_CONTROL, val);
8100                 POSTING_READ(PCH_DREF_CONTROL);
8101                 udelay(200);
8102         } else {
8103                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8104
8105                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8106
8107                 /* Turn off CPU output */
8108                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8109
8110                 I915_WRITE(PCH_DREF_CONTROL, val);
8111                 POSTING_READ(PCH_DREF_CONTROL);
8112                 udelay(200);
8113
8114                 if (!using_ssc_source) {
8115                         DRM_DEBUG_KMS("Disabling SSC source\n");
8116
8117                         /* Turn off the SSC source */
8118                         val &= ~DREF_SSC_SOURCE_MASK;
8119                         val |= DREF_SSC_SOURCE_DISABLE;
8120
8121                         /* Turn off SSC1 */
8122                         val &= ~DREF_SSC1_ENABLE;
8123
8124                         I915_WRITE(PCH_DREF_CONTROL, val);
8125                         POSTING_READ(PCH_DREF_CONTROL);
8126                         udelay(200);
8127                 }
8128         }
8129
8130         BUG_ON(val != final);
8131 }
8132
8133 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8134 {
8135         uint32_t tmp;
8136
8137         tmp = I915_READ(SOUTH_CHICKEN2);
8138         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8139         I915_WRITE(SOUTH_CHICKEN2, tmp);
8140
8141         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8142                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8143                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8144
8145         tmp = I915_READ(SOUTH_CHICKEN2);
8146         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8147         I915_WRITE(SOUTH_CHICKEN2, tmp);
8148
8149         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8150                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8151                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8152 }
8153
8154 /* WaMPhyProgramming:hsw */
8155 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8156 {
8157         uint32_t tmp;
8158
8159         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8160         tmp &= ~(0xFF << 24);
8161         tmp |= (0x12 << 24);
8162         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8163
8164         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8165         tmp |= (1 << 11);
8166         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8167
8168         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8169         tmp |= (1 << 11);
8170         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8171
8172         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8173         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8174         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8175
8176         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8177         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8178         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8179
8180         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8181         tmp &= ~(7 << 13);
8182         tmp |= (5 << 13);
8183         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8184
8185         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8186         tmp &= ~(7 << 13);
8187         tmp |= (5 << 13);
8188         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8189
8190         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8191         tmp &= ~0xFF;
8192         tmp |= 0x1C;
8193         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8194
8195         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8196         tmp &= ~0xFF;
8197         tmp |= 0x1C;
8198         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8199
8200         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8201         tmp &= ~(0xFF << 16);
8202         tmp |= (0x1C << 16);
8203         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8204
8205         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8206         tmp &= ~(0xFF << 16);
8207         tmp |= (0x1C << 16);
8208         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8209
8210         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8211         tmp |= (1 << 27);
8212         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8213
8214         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8215         tmp |= (1 << 27);
8216         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8217
8218         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8219         tmp &= ~(0xF << 28);
8220         tmp |= (4 << 28);
8221         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8222
8223         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8224         tmp &= ~(0xF << 28);
8225         tmp |= (4 << 28);
8226         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8227 }
8228
8229 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8230  * Programming" based on the parameters passed:
8231  * - Sequence to enable CLKOUT_DP
8232  * - Sequence to enable CLKOUT_DP without spread
8233  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8234  */
8235 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8236                                  bool with_spread, bool with_fdi)
8237 {
8238         uint32_t reg, tmp;
8239
8240         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8241                 with_spread = true;
8242         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8243             with_fdi, "LP PCH doesn't have FDI\n"))
8244                 with_fdi = false;
8245
8246         mutex_lock(&dev_priv->sb_lock);
8247
8248         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8249         tmp &= ~SBI_SSCCTL_DISABLE;
8250         tmp |= SBI_SSCCTL_PATHALT;
8251         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8252
8253         udelay(24);
8254
8255         if (with_spread) {
8256                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8257                 tmp &= ~SBI_SSCCTL_PATHALT;
8258                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8259
8260                 if (with_fdi) {
8261                         lpt_reset_fdi_mphy(dev_priv);
8262                         lpt_program_fdi_mphy(dev_priv);
8263                 }
8264         }
8265
8266         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8267         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8268         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8269         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8270
8271         mutex_unlock(&dev_priv->sb_lock);
8272 }
8273
8274 /* Sequence to disable CLKOUT_DP */
8275 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8276 {
8277         uint32_t reg, tmp;
8278
8279         mutex_lock(&dev_priv->sb_lock);
8280
8281         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8282         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8283         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8284         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8285
8286         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8287         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8288                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8289                         tmp |= SBI_SSCCTL_PATHALT;
8290                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8291                         udelay(32);
8292                 }
8293                 tmp |= SBI_SSCCTL_DISABLE;
8294                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8295         }
8296
8297         mutex_unlock(&dev_priv->sb_lock);
8298 }
8299
8300 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8301
8302 static const uint16_t sscdivintphase[] = {
8303         [BEND_IDX( 50)] = 0x3B23,
8304         [BEND_IDX( 45)] = 0x3B23,
8305         [BEND_IDX( 40)] = 0x3C23,
8306         [BEND_IDX( 35)] = 0x3C23,
8307         [BEND_IDX( 30)] = 0x3D23,
8308         [BEND_IDX( 25)] = 0x3D23,
8309         [BEND_IDX( 20)] = 0x3E23,
8310         [BEND_IDX( 15)] = 0x3E23,
8311         [BEND_IDX( 10)] = 0x3F23,
8312         [BEND_IDX(  5)] = 0x3F23,
8313         [BEND_IDX(  0)] = 0x0025,
8314         [BEND_IDX( -5)] = 0x0025,
8315         [BEND_IDX(-10)] = 0x0125,
8316         [BEND_IDX(-15)] = 0x0125,
8317         [BEND_IDX(-20)] = 0x0225,
8318         [BEND_IDX(-25)] = 0x0225,
8319         [BEND_IDX(-30)] = 0x0325,
8320         [BEND_IDX(-35)] = 0x0325,
8321         [BEND_IDX(-40)] = 0x0425,
8322         [BEND_IDX(-45)] = 0x0425,
8323         [BEND_IDX(-50)] = 0x0525,
8324 };
8325
8326 /*
8327  * Bend CLKOUT_DP
8328  * steps -50 to 50 inclusive, in steps of 5
8329  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8330  * change in clock period = -(steps / 10) * 5.787 ps
8331  */
8332 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8333 {
8334         uint32_t tmp;
8335         int idx = BEND_IDX(steps);
8336
8337         if (WARN_ON(steps % 5 != 0))
8338                 return;
8339
8340         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8341                 return;
8342
8343         mutex_lock(&dev_priv->sb_lock);
8344
8345         if (steps % 10 != 0)
8346                 tmp = 0xAAAAAAAB;
8347         else
8348                 tmp = 0x00000000;
8349         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8350
8351         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8352         tmp &= 0xffff0000;
8353         tmp |= sscdivintphase[idx];
8354         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8355
8356         mutex_unlock(&dev_priv->sb_lock);
8357 }
8358
8359 #undef BEND_IDX
8360
8361 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8362 {
8363         struct intel_encoder *encoder;
8364         bool has_vga = false;
8365
8366         for_each_intel_encoder(&dev_priv->drm, encoder) {
8367                 switch (encoder->type) {
8368                 case INTEL_OUTPUT_ANALOG:
8369                         has_vga = true;
8370                         break;
8371                 default:
8372                         break;
8373                 }
8374         }
8375
8376         if (has_vga) {
8377                 lpt_bend_clkout_dp(dev_priv, 0);
8378                 lpt_enable_clkout_dp(dev_priv, true, true);
8379         } else {
8380                 lpt_disable_clkout_dp(dev_priv);
8381         }
8382 }
8383
8384 /*
8385  * Initialize reference clocks when the driver loads
8386  */
8387 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8388 {
8389         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8390                 ironlake_init_pch_refclk(dev_priv);
8391         else if (HAS_PCH_LPT(dev_priv))
8392                 lpt_init_pch_refclk(dev_priv);
8393 }
8394
8395 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state)
8396 {
8397         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8398         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8399         enum pipe pipe = crtc->pipe;
8400         uint32_t val;
8401
8402         val = 0;
8403
8404         switch (crtc_state->pipe_bpp) {
8405         case 18:
8406                 val |= PIPECONF_6BPC;
8407                 break;
8408         case 24:
8409                 val |= PIPECONF_8BPC;
8410                 break;
8411         case 30:
8412                 val |= PIPECONF_10BPC;
8413                 break;
8414         case 36:
8415                 val |= PIPECONF_12BPC;
8416                 break;
8417         default:
8418                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8419                 BUG();
8420         }
8421
8422         if (crtc_state->dither)
8423                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8424
8425         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8426                 val |= PIPECONF_INTERLACED_ILK;
8427         else
8428                 val |= PIPECONF_PROGRESSIVE;
8429
8430         if (crtc_state->limited_color_range)
8431                 val |= PIPECONF_COLOR_RANGE_SELECT;
8432
8433         I915_WRITE(PIPECONF(pipe), val);
8434         POSTING_READ(PIPECONF(pipe));
8435 }
8436
8437 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state)
8438 {
8439         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8440         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8441         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
8442         u32 val = 0;
8443
8444         if (IS_HASWELL(dev_priv) && crtc_state->dither)
8445                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8446
8447         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8448                 val |= PIPECONF_INTERLACED_ILK;
8449         else
8450                 val |= PIPECONF_PROGRESSIVE;
8451
8452         I915_WRITE(PIPECONF(cpu_transcoder), val);
8453         POSTING_READ(PIPECONF(cpu_transcoder));
8454 }
8455
8456 static void haswell_set_pipemisc(const struct intel_crtc_state *crtc_state)
8457 {
8458         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
8459         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
8460
8461         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8462                 u32 val = 0;
8463
8464                 switch (crtc_state->pipe_bpp) {
8465                 case 18:
8466                         val |= PIPEMISC_DITHER_6_BPC;
8467                         break;
8468                 case 24:
8469                         val |= PIPEMISC_DITHER_8_BPC;
8470                         break;
8471                 case 30:
8472                         val |= PIPEMISC_DITHER_10_BPC;
8473                         break;
8474                 case 36:
8475                         val |= PIPEMISC_DITHER_12_BPC;
8476                         break;
8477                 default:
8478                         /* Case prevented by pipe_config_set_bpp. */
8479                         BUG();
8480                 }
8481
8482                 if (crtc_state->dither)
8483                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8484
8485                 if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420 ||
8486                     crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR444)
8487                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV;
8488
8489                 if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
8490                         val |= PIPEMISC_YUV420_ENABLE |
8491                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8492
8493                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8494         }
8495 }
8496
8497 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8498 {
8499         /*
8500          * Account for spread spectrum to avoid
8501          * oversubscribing the link. Max center spread
8502          * is 2.5%; use 5% for safety's sake.
8503          */
8504         u32 bps = target_clock * bpp * 21 / 20;
8505         return DIV_ROUND_UP(bps, link_bw * 8);
8506 }
8507
8508 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8509 {
8510         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8511 }
8512
8513 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8514                                   struct intel_crtc_state *crtc_state,
8515                                   struct dpll *reduced_clock)
8516 {
8517         struct drm_crtc *crtc = &intel_crtc->base;
8518         struct drm_device *dev = crtc->dev;
8519         struct drm_i915_private *dev_priv = to_i915(dev);
8520         u32 dpll, fp, fp2;
8521         int factor;
8522
8523         /* Enable autotuning of the PLL clock (if permissible) */
8524         factor = 21;
8525         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8526                 if ((intel_panel_use_ssc(dev_priv) &&
8527                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8528                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8529                         factor = 25;
8530         } else if (crtc_state->sdvo_tv_clock)
8531                 factor = 20;
8532
8533         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8534
8535         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8536                 fp |= FP_CB_TUNE;
8537
8538         if (reduced_clock) {
8539                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8540
8541                 if (reduced_clock->m < factor * reduced_clock->n)
8542                         fp2 |= FP_CB_TUNE;
8543         } else {
8544                 fp2 = fp;
8545         }
8546
8547         dpll = 0;
8548
8549         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8550                 dpll |= DPLLB_MODE_LVDS;
8551         else
8552                 dpll |= DPLLB_MODE_DAC_SERIAL;
8553
8554         dpll |= (crtc_state->pixel_multiplier - 1)
8555                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8556
8557         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8558             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8559                 dpll |= DPLL_SDVO_HIGH_SPEED;
8560
8561         if (intel_crtc_has_dp_encoder(crtc_state))
8562                 dpll |= DPLL_SDVO_HIGH_SPEED;
8563
8564         /*
8565          * The high speed IO clock is only really required for
8566          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8567          * possible to share the DPLL between CRT and HDMI. Enabling
8568          * the clock needlessly does no real harm, except use up a
8569          * bit of power potentially.
8570          *
8571          * We'll limit this to IVB with 3 pipes, since it has only two
8572          * DPLLs and so DPLL sharing is the only way to get three pipes
8573          * driving PCH ports at the same time. On SNB we could do this,
8574          * and potentially avoid enabling the second DPLL, but it's not
8575          * clear if it''s a win or loss power wise. No point in doing
8576          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8577          */
8578         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8579             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8580                 dpll |= DPLL_SDVO_HIGH_SPEED;
8581
8582         /* compute bitmask from p1 value */
8583         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8584         /* also FPA1 */
8585         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8586
8587         switch (crtc_state->dpll.p2) {
8588         case 5:
8589                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8590                 break;
8591         case 7:
8592                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8593                 break;
8594         case 10:
8595                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8596                 break;
8597         case 14:
8598                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8599                 break;
8600         }
8601
8602         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8603             intel_panel_use_ssc(dev_priv))
8604                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8605         else
8606                 dpll |= PLL_REF_INPUT_DREFCLK;
8607
8608         dpll |= DPLL_VCO_ENABLE;
8609
8610         crtc_state->dpll_hw_state.dpll = dpll;
8611         crtc_state->dpll_hw_state.fp0 = fp;
8612         crtc_state->dpll_hw_state.fp1 = fp2;
8613 }
8614
8615 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8616                                        struct intel_crtc_state *crtc_state)
8617 {
8618         struct drm_device *dev = crtc->base.dev;
8619         struct drm_i915_private *dev_priv = to_i915(dev);
8620         const struct intel_limit *limit;
8621         int refclk = 120000;
8622
8623         memset(&crtc_state->dpll_hw_state, 0,
8624                sizeof(crtc_state->dpll_hw_state));
8625
8626         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8627         if (!crtc_state->has_pch_encoder)
8628                 return 0;
8629
8630         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8631                 if (intel_panel_use_ssc(dev_priv)) {
8632                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8633                                       dev_priv->vbt.lvds_ssc_freq);
8634                         refclk = dev_priv->vbt.lvds_ssc_freq;
8635                 }
8636
8637                 if (intel_is_dual_link_lvds(dev)) {
8638                         if (refclk == 100000)
8639                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8640                         else
8641                                 limit = &intel_limits_ironlake_dual_lvds;
8642                 } else {
8643                         if (refclk == 100000)
8644                                 limit = &intel_limits_ironlake_single_lvds_100m;
8645                         else
8646                                 limit = &intel_limits_ironlake_single_lvds;
8647                 }
8648         } else {
8649                 limit = &intel_limits_ironlake_dac;
8650         }
8651
8652         if (!crtc_state->clock_set &&
8653             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8654                                 refclk, NULL, &crtc_state->dpll)) {
8655                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8656                 return -EINVAL;
8657         }
8658
8659         ironlake_compute_dpll(crtc, crtc_state, NULL);
8660
8661         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8662                 DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
8663                               pipe_name(crtc->pipe));
8664                 return -EINVAL;
8665         }
8666
8667         return 0;
8668 }
8669
8670 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8671                                          struct intel_link_m_n *m_n)
8672 {
8673         struct drm_device *dev = crtc->base.dev;
8674         struct drm_i915_private *dev_priv = to_i915(dev);
8675         enum pipe pipe = crtc->pipe;
8676
8677         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8678         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8679         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8680                 & ~TU_SIZE_MASK;
8681         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8682         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8683                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8684 }
8685
8686 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8687                                          enum transcoder transcoder,
8688                                          struct intel_link_m_n *m_n,
8689                                          struct intel_link_m_n *m2_n2)
8690 {
8691         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8692         enum pipe pipe = crtc->pipe;
8693
8694         if (INTEL_GEN(dev_priv) >= 5) {
8695                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8696                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8697                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8698                         & ~TU_SIZE_MASK;
8699                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8700                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8701                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8702
8703                 if (m2_n2 && transcoder_has_m2_n2(dev_priv, transcoder)) {
8704                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8705                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8706                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8707                                         & ~TU_SIZE_MASK;
8708                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8709                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8710                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8711                 }
8712         } else {
8713                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8714                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8715                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8716                         & ~TU_SIZE_MASK;
8717                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8718                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8719                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8720         }
8721 }
8722
8723 void intel_dp_get_m_n(struct intel_crtc *crtc,
8724                       struct intel_crtc_state *pipe_config)
8725 {
8726         if (pipe_config->has_pch_encoder)
8727                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8728         else
8729                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8730                                              &pipe_config->dp_m_n,
8731                                              &pipe_config->dp_m2_n2);
8732 }
8733
8734 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8735                                         struct intel_crtc_state *pipe_config)
8736 {
8737         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8738                                      &pipe_config->fdi_m_n, NULL);
8739 }
8740
8741 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8742                                     struct intel_crtc_state *pipe_config)
8743 {
8744         struct drm_device *dev = crtc->base.dev;
8745         struct drm_i915_private *dev_priv = to_i915(dev);
8746         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8747         uint32_t ps_ctrl = 0;
8748         int id = -1;
8749         int i;
8750
8751         /* find scaler attached to this pipe */
8752         for (i = 0; i < crtc->num_scalers; i++) {
8753                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8754                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8755                         id = i;
8756                         pipe_config->pch_pfit.enabled = true;
8757                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8758                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8759                         break;
8760                 }
8761         }
8762
8763         scaler_state->scaler_id = id;
8764         if (id >= 0) {
8765                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8766         } else {
8767                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8768         }
8769 }
8770
8771 static void
8772 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8773                                  struct intel_initial_plane_config *plane_config)
8774 {
8775         struct drm_device *dev = crtc->base.dev;
8776         struct drm_i915_private *dev_priv = to_i915(dev);
8777         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8778         enum plane_id plane_id = plane->id;
8779         enum pipe pipe;
8780         u32 val, base, offset, stride_mult, tiling, alpha;
8781         int fourcc, pixel_format;
8782         unsigned int aligned_height;
8783         struct drm_framebuffer *fb;
8784         struct intel_framebuffer *intel_fb;
8785
8786         if (!plane->get_hw_state(plane, &pipe))
8787                 return;
8788
8789         WARN_ON(pipe != crtc->pipe);
8790
8791         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8792         if (!intel_fb) {
8793                 DRM_DEBUG_KMS("failed to alloc fb\n");
8794                 return;
8795         }
8796
8797         fb = &intel_fb->base;
8798
8799         fb->dev = dev;
8800
8801         val = I915_READ(PLANE_CTL(pipe, plane_id));
8802
8803         if (INTEL_GEN(dev_priv) >= 11)
8804                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8805         else
8806                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8807
8808         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8809                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8810                 alpha &= PLANE_COLOR_ALPHA_MASK;
8811         } else {
8812                 alpha = val & PLANE_CTL_ALPHA_MASK;
8813         }
8814
8815         fourcc = skl_format_to_fourcc(pixel_format,
8816                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8817         fb->format = drm_format_info(fourcc);
8818
8819         tiling = val & PLANE_CTL_TILED_MASK;
8820         switch (tiling) {
8821         case PLANE_CTL_TILED_LINEAR:
8822                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8823                 break;
8824         case PLANE_CTL_TILED_X:
8825                 plane_config->tiling = I915_TILING_X;
8826                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8827                 break;
8828         case PLANE_CTL_TILED_Y:
8829                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8830                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8831                 else
8832                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8833                 break;
8834         case PLANE_CTL_TILED_YF:
8835                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8836                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8837                 else
8838                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8839                 break;
8840         default:
8841                 MISSING_CASE(tiling);
8842                 goto error;
8843         }
8844
8845         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8846         plane_config->base = base;
8847
8848         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8849
8850         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8851         fb->height = ((val >> 16) & 0xfff) + 1;
8852         fb->width = ((val >> 0) & 0x1fff) + 1;
8853
8854         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8855         stride_mult = intel_fb_stride_alignment(fb, 0);
8856         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8857
8858         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8859
8860         plane_config->size = fb->pitches[0] * aligned_height;
8861
8862         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8863                       crtc->base.name, plane->base.name, fb->width, fb->height,
8864                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8865                       plane_config->size);
8866
8867         plane_config->fb = intel_fb;
8868         return;
8869
8870 error:
8871         kfree(intel_fb);
8872 }
8873
8874 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8875                                      struct intel_crtc_state *pipe_config)
8876 {
8877         struct drm_device *dev = crtc->base.dev;
8878         struct drm_i915_private *dev_priv = to_i915(dev);
8879         uint32_t tmp;
8880
8881         tmp = I915_READ(PF_CTL(crtc->pipe));
8882
8883         if (tmp & PF_ENABLE) {
8884                 pipe_config->pch_pfit.enabled = true;
8885                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8886                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8887
8888                 /* We currently do not free assignements of panel fitters on
8889                  * ivb/hsw (since we don't use the higher upscaling modes which
8890                  * differentiates them) so just WARN about this case for now. */
8891                 if (IS_GEN7(dev_priv)) {
8892                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8893                                 PF_PIPE_SEL_IVB(crtc->pipe));
8894                 }
8895         }
8896 }
8897
8898 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8899                                      struct intel_crtc_state *pipe_config)
8900 {
8901         struct drm_device *dev = crtc->base.dev;
8902         struct drm_i915_private *dev_priv = to_i915(dev);
8903         enum intel_display_power_domain power_domain;
8904         uint32_t tmp;
8905         bool ret;
8906
8907         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8908         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8909                 return false;
8910
8911         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
8912         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8913         pipe_config->shared_dpll = NULL;
8914
8915         ret = false;
8916         tmp = I915_READ(PIPECONF(crtc->pipe));
8917         if (!(tmp & PIPECONF_ENABLE))
8918                 goto out;
8919
8920         switch (tmp & PIPECONF_BPC_MASK) {
8921         case PIPECONF_6BPC:
8922                 pipe_config->pipe_bpp = 18;
8923                 break;
8924         case PIPECONF_8BPC:
8925                 pipe_config->pipe_bpp = 24;
8926                 break;
8927         case PIPECONF_10BPC:
8928                 pipe_config->pipe_bpp = 30;
8929                 break;
8930         case PIPECONF_12BPC:
8931                 pipe_config->pipe_bpp = 36;
8932                 break;
8933         default:
8934                 break;
8935         }
8936
8937         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8938                 pipe_config->limited_color_range = true;
8939
8940         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8941                 struct intel_shared_dpll *pll;
8942                 enum intel_dpll_id pll_id;
8943
8944                 pipe_config->has_pch_encoder = true;
8945
8946                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8947                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8948                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8949
8950                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8951
8952                 if (HAS_PCH_IBX(dev_priv)) {
8953                         /*
8954                          * The pipe->pch transcoder and pch transcoder->pll
8955                          * mapping is fixed.
8956                          */
8957                         pll_id = (enum intel_dpll_id) crtc->pipe;
8958                 } else {
8959                         tmp = I915_READ(PCH_DPLL_SEL);
8960                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8961                                 pll_id = DPLL_ID_PCH_PLL_B;
8962                         else
8963                                 pll_id= DPLL_ID_PCH_PLL_A;
8964                 }
8965
8966                 pipe_config->shared_dpll =
8967                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8968                 pll = pipe_config->shared_dpll;
8969
8970                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
8971                                                 &pipe_config->dpll_hw_state));
8972
8973                 tmp = pipe_config->dpll_hw_state.dpll;
8974                 pipe_config->pixel_multiplier =
8975                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8976                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8977
8978                 ironlake_pch_clock_get(crtc, pipe_config);
8979         } else {
8980                 pipe_config->pixel_multiplier = 1;
8981         }
8982
8983         intel_get_pipe_timings(crtc, pipe_config);
8984         intel_get_pipe_src_size(crtc, pipe_config);
8985
8986         ironlake_get_pfit_config(crtc, pipe_config);
8987
8988         ret = true;
8989
8990 out:
8991         intel_display_power_put(dev_priv, power_domain);
8992
8993         return ret;
8994 }
8995
8996 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8997 {
8998         struct drm_device *dev = &dev_priv->drm;
8999         struct intel_crtc *crtc;
9000
9001         for_each_intel_crtc(dev, crtc)
9002                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9003                      pipe_name(crtc->pipe));
9004
9005         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL2),
9006                         "Display power well on\n");
9007         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9008         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9009         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9010         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
9011         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9012              "CPU PWM1 enabled\n");
9013         if (IS_HASWELL(dev_priv))
9014                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9015                      "CPU PWM2 enabled\n");
9016         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9017              "PCH PWM1 enabled\n");
9018         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9019              "Utility pin enabled\n");
9020         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9021
9022         /*
9023          * In theory we can still leave IRQs enabled, as long as only the HPD
9024          * interrupts remain enabled. We used to check for that, but since it's
9025          * gen-specific and since we only disable LCPLL after we fully disable
9026          * the interrupts, the check below should be enough.
9027          */
9028         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9029 }
9030
9031 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9032 {
9033         if (IS_HASWELL(dev_priv))
9034                 return I915_READ(D_COMP_HSW);
9035         else
9036                 return I915_READ(D_COMP_BDW);
9037 }
9038
9039 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9040 {
9041         if (IS_HASWELL(dev_priv)) {
9042                 mutex_lock(&dev_priv->pcu_lock);
9043                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9044                                             val))
9045                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
9046                 mutex_unlock(&dev_priv->pcu_lock);
9047         } else {
9048                 I915_WRITE(D_COMP_BDW, val);
9049                 POSTING_READ(D_COMP_BDW);
9050         }
9051 }
9052
9053 /*
9054  * This function implements pieces of two sequences from BSpec:
9055  * - Sequence for display software to disable LCPLL
9056  * - Sequence for display software to allow package C8+
9057  * The steps implemented here are just the steps that actually touch the LCPLL
9058  * register. Callers should take care of disabling all the display engine
9059  * functions, doing the mode unset, fixing interrupts, etc.
9060  */
9061 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9062                               bool switch_to_fclk, bool allow_power_down)
9063 {
9064         uint32_t val;
9065
9066         assert_can_disable_lcpll(dev_priv);
9067
9068         val = I915_READ(LCPLL_CTL);
9069
9070         if (switch_to_fclk) {
9071                 val |= LCPLL_CD_SOURCE_FCLK;
9072                 I915_WRITE(LCPLL_CTL, val);
9073
9074                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9075                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9076                         DRM_ERROR("Switching to FCLK failed\n");
9077
9078                 val = I915_READ(LCPLL_CTL);
9079         }
9080
9081         val |= LCPLL_PLL_DISABLE;
9082         I915_WRITE(LCPLL_CTL, val);
9083         POSTING_READ(LCPLL_CTL);
9084
9085         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9086                 DRM_ERROR("LCPLL still locked\n");
9087
9088         val = hsw_read_dcomp(dev_priv);
9089         val |= D_COMP_COMP_DISABLE;
9090         hsw_write_dcomp(dev_priv, val);
9091         ndelay(100);
9092
9093         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9094                      1))
9095                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9096
9097         if (allow_power_down) {
9098                 val = I915_READ(LCPLL_CTL);
9099                 val |= LCPLL_POWER_DOWN_ALLOW;
9100                 I915_WRITE(LCPLL_CTL, val);
9101                 POSTING_READ(LCPLL_CTL);
9102         }
9103 }
9104
9105 /*
9106  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9107  * source.
9108  */
9109 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9110 {
9111         uint32_t val;
9112
9113         val = I915_READ(LCPLL_CTL);
9114
9115         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9116                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9117                 return;
9118
9119         /*
9120          * Make sure we're not on PC8 state before disabling PC8, otherwise
9121          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9122          */
9123         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9124
9125         if (val & LCPLL_POWER_DOWN_ALLOW) {
9126                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9127                 I915_WRITE(LCPLL_CTL, val);
9128                 POSTING_READ(LCPLL_CTL);
9129         }
9130
9131         val = hsw_read_dcomp(dev_priv);
9132         val |= D_COMP_COMP_FORCE;
9133         val &= ~D_COMP_COMP_DISABLE;
9134         hsw_write_dcomp(dev_priv, val);
9135
9136         val = I915_READ(LCPLL_CTL);
9137         val &= ~LCPLL_PLL_DISABLE;
9138         I915_WRITE(LCPLL_CTL, val);
9139
9140         if (intel_wait_for_register(dev_priv,
9141                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9142                                     5))
9143                 DRM_ERROR("LCPLL not locked yet\n");
9144
9145         if (val & LCPLL_CD_SOURCE_FCLK) {
9146                 val = I915_READ(LCPLL_CTL);
9147                 val &= ~LCPLL_CD_SOURCE_FCLK;
9148                 I915_WRITE(LCPLL_CTL, val);
9149
9150                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9151                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9152                         DRM_ERROR("Switching back to LCPLL failed\n");
9153         }
9154
9155         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9156
9157         intel_update_cdclk(dev_priv);
9158         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
9159 }
9160
9161 /*
9162  * Package states C8 and deeper are really deep PC states that can only be
9163  * reached when all the devices on the system allow it, so even if the graphics
9164  * device allows PC8+, it doesn't mean the system will actually get to these
9165  * states. Our driver only allows PC8+ when going into runtime PM.
9166  *
9167  * The requirements for PC8+ are that all the outputs are disabled, the power
9168  * well is disabled and most interrupts are disabled, and these are also
9169  * requirements for runtime PM. When these conditions are met, we manually do
9170  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9171  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9172  * hang the machine.
9173  *
9174  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9175  * the state of some registers, so when we come back from PC8+ we need to
9176  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9177  * need to take care of the registers kept by RC6. Notice that this happens even
9178  * if we don't put the device in PCI D3 state (which is what currently happens
9179  * because of the runtime PM support).
9180  *
9181  * For more, read "Display Sequences for Package C8" on the hardware
9182  * documentation.
9183  */
9184 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9185 {
9186         uint32_t val;
9187
9188         DRM_DEBUG_KMS("Enabling package C8+\n");
9189
9190         if (HAS_PCH_LPT_LP(dev_priv)) {
9191                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9192                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9193                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9194         }
9195
9196         lpt_disable_clkout_dp(dev_priv);
9197         hsw_disable_lcpll(dev_priv, true, true);
9198 }
9199
9200 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9201 {
9202         uint32_t val;
9203
9204         DRM_DEBUG_KMS("Disabling package C8+\n");
9205
9206         hsw_restore_lcpll(dev_priv);
9207         lpt_init_pch_refclk(dev_priv);
9208
9209         if (HAS_PCH_LPT_LP(dev_priv)) {
9210                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9211                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9212                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9213         }
9214 }
9215
9216 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9217                                       struct intel_crtc_state *crtc_state)
9218 {
9219         struct intel_atomic_state *state =
9220                 to_intel_atomic_state(crtc_state->base.state);
9221
9222         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9223                 struct intel_encoder *encoder =
9224                         intel_get_crtc_new_encoder(state, crtc_state);
9225
9226                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9227                         DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9228                                       pipe_name(crtc->pipe));
9229                         return -EINVAL;
9230                 }
9231         }
9232
9233         return 0;
9234 }
9235
9236 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9237                                    enum port port,
9238                                    struct intel_crtc_state *pipe_config)
9239 {
9240         enum intel_dpll_id id;
9241         u32 temp;
9242
9243         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9244         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9245
9246         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9247                 return;
9248
9249         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9250 }
9251
9252 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9253                                 enum port port,
9254                                 struct intel_crtc_state *pipe_config)
9255 {
9256         enum intel_dpll_id id;
9257         u32 temp;
9258
9259         /* TODO: TBT pll not implemented. */
9260         switch (port) {
9261         case PORT_A:
9262         case PORT_B:
9263                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9264                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9265                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9266
9267                 if (WARN_ON(id != DPLL_ID_ICL_DPLL0 && id != DPLL_ID_ICL_DPLL1))
9268                         return;
9269                 break;
9270         case PORT_C:
9271                 id = DPLL_ID_ICL_MGPLL1;
9272                 break;
9273         case PORT_D:
9274                 id = DPLL_ID_ICL_MGPLL2;
9275                 break;
9276         case PORT_E:
9277                 id = DPLL_ID_ICL_MGPLL3;
9278                 break;
9279         case PORT_F:
9280                 id = DPLL_ID_ICL_MGPLL4;
9281                 break;
9282         default:
9283                 MISSING_CASE(port);
9284                 return;
9285         }
9286
9287         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9288 }
9289
9290 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9291                                 enum port port,
9292                                 struct intel_crtc_state *pipe_config)
9293 {
9294         enum intel_dpll_id id;
9295
9296         switch (port) {
9297         case PORT_A:
9298                 id = DPLL_ID_SKL_DPLL0;
9299                 break;
9300         case PORT_B:
9301                 id = DPLL_ID_SKL_DPLL1;
9302                 break;
9303         case PORT_C:
9304                 id = DPLL_ID_SKL_DPLL2;
9305                 break;
9306         default:
9307                 DRM_ERROR("Incorrect port type\n");
9308                 return;
9309         }
9310
9311         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9312 }
9313
9314 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9315                                 enum port port,
9316                                 struct intel_crtc_state *pipe_config)
9317 {
9318         enum intel_dpll_id id;
9319         u32 temp;
9320
9321         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9322         id = temp >> (port * 3 + 1);
9323
9324         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9325                 return;
9326
9327         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9328 }
9329
9330 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9331                                 enum port port,
9332                                 struct intel_crtc_state *pipe_config)
9333 {
9334         enum intel_dpll_id id;
9335         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9336
9337         switch (ddi_pll_sel) {
9338         case PORT_CLK_SEL_WRPLL1:
9339                 id = DPLL_ID_WRPLL1;
9340                 break;
9341         case PORT_CLK_SEL_WRPLL2:
9342                 id = DPLL_ID_WRPLL2;
9343                 break;
9344         case PORT_CLK_SEL_SPLL:
9345                 id = DPLL_ID_SPLL;
9346                 break;
9347         case PORT_CLK_SEL_LCPLL_810:
9348                 id = DPLL_ID_LCPLL_810;
9349                 break;
9350         case PORT_CLK_SEL_LCPLL_1350:
9351                 id = DPLL_ID_LCPLL_1350;
9352                 break;
9353         case PORT_CLK_SEL_LCPLL_2700:
9354                 id = DPLL_ID_LCPLL_2700;
9355                 break;
9356         default:
9357                 MISSING_CASE(ddi_pll_sel);
9358                 /* fall through */
9359         case PORT_CLK_SEL_NONE:
9360                 return;
9361         }
9362
9363         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9364 }
9365
9366 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9367                                      struct intel_crtc_state *pipe_config,
9368                                      u64 *power_domain_mask)
9369 {
9370         struct drm_device *dev = crtc->base.dev;
9371         struct drm_i915_private *dev_priv = to_i915(dev);
9372         enum intel_display_power_domain power_domain;
9373         u32 tmp;
9374
9375         /*
9376          * The pipe->transcoder mapping is fixed with the exception of the eDP
9377          * transcoder handled below.
9378          */
9379         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9380
9381         /*
9382          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9383          * consistency and less surprising code; it's in always on power).
9384          */
9385         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9386         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9387                 enum pipe trans_edp_pipe;
9388                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9389                 default:
9390                         WARN(1, "unknown pipe linked to edp transcoder\n");
9391                         /* fall through */
9392                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9393                 case TRANS_DDI_EDP_INPUT_A_ON:
9394                         trans_edp_pipe = PIPE_A;
9395                         break;
9396                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9397                         trans_edp_pipe = PIPE_B;
9398                         break;
9399                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9400                         trans_edp_pipe = PIPE_C;
9401                         break;
9402                 }
9403
9404                 if (trans_edp_pipe == crtc->pipe)
9405                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9406         }
9407
9408         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9409         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9410                 return false;
9411         *power_domain_mask |= BIT_ULL(power_domain);
9412
9413         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9414
9415         return tmp & PIPECONF_ENABLE;
9416 }
9417
9418 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9419                                          struct intel_crtc_state *pipe_config,
9420                                          u64 *power_domain_mask)
9421 {
9422         struct drm_device *dev = crtc->base.dev;
9423         struct drm_i915_private *dev_priv = to_i915(dev);
9424         enum intel_display_power_domain power_domain;
9425         enum port port;
9426         enum transcoder cpu_transcoder;
9427         u32 tmp;
9428
9429         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9430                 if (port == PORT_A)
9431                         cpu_transcoder = TRANSCODER_DSI_A;
9432                 else
9433                         cpu_transcoder = TRANSCODER_DSI_C;
9434
9435                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9436                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9437                         continue;
9438                 *power_domain_mask |= BIT_ULL(power_domain);
9439
9440                 /*
9441                  * The PLL needs to be enabled with a valid divider
9442                  * configuration, otherwise accessing DSI registers will hang
9443                  * the machine. See BSpec North Display Engine
9444                  * registers/MIPI[BXT]. We can break out here early, since we
9445                  * need the same DSI PLL to be enabled for both DSI ports.
9446                  */
9447                 if (!bxt_dsi_pll_is_enabled(dev_priv))
9448                         break;
9449
9450                 /* XXX: this works for video mode only */
9451                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9452                 if (!(tmp & DPI_ENABLE))
9453                         continue;
9454
9455                 tmp = I915_READ(MIPI_CTRL(port));
9456                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9457                         continue;
9458
9459                 pipe_config->cpu_transcoder = cpu_transcoder;
9460                 break;
9461         }
9462
9463         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9464 }
9465
9466 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9467                                        struct intel_crtc_state *pipe_config)
9468 {
9469         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9470         struct intel_shared_dpll *pll;
9471         enum port port;
9472         uint32_t tmp;
9473
9474         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9475
9476         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9477
9478         if (IS_ICELAKE(dev_priv))
9479                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
9480         else if (IS_CANNONLAKE(dev_priv))
9481                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9482         else if (IS_GEN9_BC(dev_priv))
9483                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9484         else if (IS_GEN9_LP(dev_priv))
9485                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9486         else
9487                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9488
9489         pll = pipe_config->shared_dpll;
9490         if (pll) {
9491                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9492                                                 &pipe_config->dpll_hw_state));
9493         }
9494
9495         /*
9496          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9497          * DDI E. So just check whether this pipe is wired to DDI E and whether
9498          * the PCH transcoder is on.
9499          */
9500         if (INTEL_GEN(dev_priv) < 9 &&
9501             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9502                 pipe_config->has_pch_encoder = true;
9503
9504                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9505                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9506                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9507
9508                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9509         }
9510 }
9511
9512 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9513                                     struct intel_crtc_state *pipe_config)
9514 {
9515         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9516         enum intel_display_power_domain power_domain;
9517         u64 power_domain_mask;
9518         bool active;
9519
9520         intel_crtc_init_scalers(crtc, pipe_config);
9521
9522         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9523         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9524                 return false;
9525         power_domain_mask = BIT_ULL(power_domain);
9526
9527         pipe_config->shared_dpll = NULL;
9528
9529         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9530
9531         if (IS_GEN9_LP(dev_priv) &&
9532             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9533                 WARN_ON(active);
9534                 active = true;
9535         }
9536
9537         if (!active)
9538                 goto out;
9539
9540         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9541                 haswell_get_ddi_port_state(crtc, pipe_config);
9542                 intel_get_pipe_timings(crtc, pipe_config);
9543         }
9544
9545         intel_get_pipe_src_size(crtc, pipe_config);
9546         intel_get_crtc_ycbcr_config(crtc, pipe_config);
9547
9548         pipe_config->gamma_mode =
9549                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9550
9551         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9552         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9553                 power_domain_mask |= BIT_ULL(power_domain);
9554                 if (INTEL_GEN(dev_priv) >= 9)
9555                         skylake_get_pfit_config(crtc, pipe_config);
9556                 else
9557                         ironlake_get_pfit_config(crtc, pipe_config);
9558         }
9559
9560         if (hsw_crtc_supports_ips(crtc)) {
9561                 if (IS_HASWELL(dev_priv))
9562                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9563                 else {
9564                         /*
9565                          * We cannot readout IPS state on broadwell, set to
9566                          * true so we can set it to a defined state on first
9567                          * commit.
9568                          */
9569                         pipe_config->ips_enabled = true;
9570                 }
9571         }
9572
9573         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9574             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9575                 pipe_config->pixel_multiplier =
9576                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9577         } else {
9578                 pipe_config->pixel_multiplier = 1;
9579         }
9580
9581 out:
9582         for_each_power_domain(power_domain, power_domain_mask)
9583                 intel_display_power_put(dev_priv, power_domain);
9584
9585         return active;
9586 }
9587
9588 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9589 {
9590         struct drm_i915_private *dev_priv =
9591                 to_i915(plane_state->base.plane->dev);
9592         const struct drm_framebuffer *fb = plane_state->base.fb;
9593         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9594         u32 base;
9595
9596         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9597                 base = obj->phys_handle->busaddr;
9598         else
9599                 base = intel_plane_ggtt_offset(plane_state);
9600
9601         base += plane_state->color_plane[0].offset;
9602
9603         /* ILK+ do this automagically */
9604         if (HAS_GMCH_DISPLAY(dev_priv) &&
9605             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9606                 base += (plane_state->base.crtc_h *
9607                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9608
9609         return base;
9610 }
9611
9612 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9613 {
9614         int x = plane_state->base.crtc_x;
9615         int y = plane_state->base.crtc_y;
9616         u32 pos = 0;
9617
9618         if (x < 0) {
9619                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9620                 x = -x;
9621         }
9622         pos |= x << CURSOR_X_SHIFT;
9623
9624         if (y < 0) {
9625                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9626                 y = -y;
9627         }
9628         pos |= y << CURSOR_Y_SHIFT;
9629
9630         return pos;
9631 }
9632
9633 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9634 {
9635         const struct drm_mode_config *config =
9636                 &plane_state->base.plane->dev->mode_config;
9637         int width = plane_state->base.crtc_w;
9638         int height = plane_state->base.crtc_h;
9639
9640         return width > 0 && width <= config->cursor_width &&
9641                 height > 0 && height <= config->cursor_height;
9642 }
9643
9644 static int intel_cursor_check_surface(struct intel_plane_state *plane_state)
9645 {
9646         const struct drm_framebuffer *fb = plane_state->base.fb;
9647         unsigned int rotation = plane_state->base.rotation;
9648         int src_x, src_y;
9649         u32 offset;
9650         int ret;
9651
9652         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
9653         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
9654
9655         ret = intel_plane_check_stride(plane_state);
9656         if (ret)
9657                 return ret;
9658
9659         src_x = plane_state->base.src_x >> 16;
9660         src_y = plane_state->base.src_y >> 16;
9661
9662         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9663         offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
9664                                                     plane_state, 0);
9665
9666         if (src_x != 0 || src_y != 0) {
9667                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9668                 return -EINVAL;
9669         }
9670
9671         plane_state->color_plane[0].offset = offset;
9672
9673         return 0;
9674 }
9675
9676 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9677                               struct intel_plane_state *plane_state)
9678 {
9679         const struct drm_framebuffer *fb = plane_state->base.fb;
9680         int ret;
9681
9682         if (fb && fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9683                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9684                 return -EINVAL;
9685         }
9686
9687         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9688                                                   &crtc_state->base,
9689                                                   DRM_PLANE_HELPER_NO_SCALING,
9690                                                   DRM_PLANE_HELPER_NO_SCALING,
9691                                                   true, true);
9692         if (ret)
9693                 return ret;
9694
9695         if (!plane_state->base.visible)
9696                 return 0;
9697
9698         ret = intel_plane_check_src_coordinates(plane_state);
9699         if (ret)
9700                 return ret;
9701
9702         ret = intel_cursor_check_surface(plane_state);
9703         if (ret)
9704                 return ret;
9705
9706         return 0;
9707 }
9708
9709 static unsigned int
9710 i845_cursor_max_stride(struct intel_plane *plane,
9711                        u32 pixel_format, u64 modifier,
9712                        unsigned int rotation)
9713 {
9714         return 2048;
9715 }
9716
9717 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9718                            const struct intel_plane_state *plane_state)
9719 {
9720         return CURSOR_ENABLE |
9721                 CURSOR_GAMMA_ENABLE |
9722                 CURSOR_FORMAT_ARGB |
9723                 CURSOR_STRIDE(plane_state->color_plane[0].stride);
9724 }
9725
9726 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9727 {
9728         int width = plane_state->base.crtc_w;
9729
9730         /*
9731          * 845g/865g are only limited by the width of their cursors,
9732          * the height is arbitrary up to the precision of the register.
9733          */
9734         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9735 }
9736
9737 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
9738                              struct intel_plane_state *plane_state)
9739 {
9740         const struct drm_framebuffer *fb = plane_state->base.fb;
9741         int ret;
9742
9743         ret = intel_check_cursor(crtc_state, plane_state);
9744         if (ret)
9745                 return ret;
9746
9747         /* if we want to turn off the cursor ignore width and height */
9748         if (!fb)
9749                 return 0;
9750
9751         /* Check for which cursor types we support */
9752         if (!i845_cursor_size_ok(plane_state)) {
9753                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9754                           plane_state->base.crtc_w,
9755                           plane_state->base.crtc_h);
9756                 return -EINVAL;
9757         }
9758
9759         WARN_ON(plane_state->base.visible &&
9760                 plane_state->color_plane[0].stride != fb->pitches[0]);
9761
9762         switch (fb->pitches[0]) {
9763         case 256:
9764         case 512:
9765         case 1024:
9766         case 2048:
9767                 break;
9768         default:
9769                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9770                               fb->pitches[0]);
9771                 return -EINVAL;
9772         }
9773
9774         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9775
9776         return 0;
9777 }
9778
9779 static void i845_update_cursor(struct intel_plane *plane,
9780                                const struct intel_crtc_state *crtc_state,
9781                                const struct intel_plane_state *plane_state)
9782 {
9783         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9784         u32 cntl = 0, base = 0, pos = 0, size = 0;
9785         unsigned long irqflags;
9786
9787         if (plane_state && plane_state->base.visible) {
9788                 unsigned int width = plane_state->base.crtc_w;
9789                 unsigned int height = plane_state->base.crtc_h;
9790
9791                 cntl = plane_state->ctl;
9792                 size = (height << 12) | width;
9793
9794                 base = intel_cursor_base(plane_state);
9795                 pos = intel_cursor_position(plane_state);
9796         }
9797
9798         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9799
9800         /* On these chipsets we can only modify the base/size/stride
9801          * whilst the cursor is disabled.
9802          */
9803         if (plane->cursor.base != base ||
9804             plane->cursor.size != size ||
9805             plane->cursor.cntl != cntl) {
9806                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9807                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9808                 I915_WRITE_FW(CURSIZE, size);
9809                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9810                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9811
9812                 plane->cursor.base = base;
9813                 plane->cursor.size = size;
9814                 plane->cursor.cntl = cntl;
9815         } else {
9816                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9817         }
9818
9819         POSTING_READ_FW(CURCNTR(PIPE_A));
9820
9821         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9822 }
9823
9824 static void i845_disable_cursor(struct intel_plane *plane,
9825                                 struct intel_crtc *crtc)
9826 {
9827         i845_update_cursor(plane, NULL, NULL);
9828 }
9829
9830 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
9831                                      enum pipe *pipe)
9832 {
9833         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9834         enum intel_display_power_domain power_domain;
9835         bool ret;
9836
9837         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9838         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9839                 return false;
9840
9841         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9842
9843         *pipe = PIPE_A;
9844
9845         intel_display_power_put(dev_priv, power_domain);
9846
9847         return ret;
9848 }
9849
9850 static unsigned int
9851 i9xx_cursor_max_stride(struct intel_plane *plane,
9852                        u32 pixel_format, u64 modifier,
9853                        unsigned int rotation)
9854 {
9855         return plane->base.dev->mode_config.cursor_width * 4;
9856 }
9857
9858 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9859                            const struct intel_plane_state *plane_state)
9860 {
9861         struct drm_i915_private *dev_priv =
9862                 to_i915(plane_state->base.plane->dev);
9863         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9864         u32 cntl = 0;
9865
9866         if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
9867                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
9868
9869         if (INTEL_GEN(dev_priv) <= 10) {
9870                 cntl |= MCURSOR_GAMMA_ENABLE;
9871
9872                 if (HAS_DDI(dev_priv))
9873                         cntl |= MCURSOR_PIPE_CSC_ENABLE;
9874         }
9875
9876         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
9877                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9878
9879         switch (plane_state->base.crtc_w) {
9880         case 64:
9881                 cntl |= MCURSOR_MODE_64_ARGB_AX;
9882                 break;
9883         case 128:
9884                 cntl |= MCURSOR_MODE_128_ARGB_AX;
9885                 break;
9886         case 256:
9887                 cntl |= MCURSOR_MODE_256_ARGB_AX;
9888                 break;
9889         default:
9890                 MISSING_CASE(plane_state->base.crtc_w);
9891                 return 0;
9892         }
9893
9894         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9895                 cntl |= MCURSOR_ROTATE_180;
9896
9897         return cntl;
9898 }
9899
9900 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9901 {
9902         struct drm_i915_private *dev_priv =
9903                 to_i915(plane_state->base.plane->dev);
9904         int width = plane_state->base.crtc_w;
9905         int height = plane_state->base.crtc_h;
9906
9907         if (!intel_cursor_size_ok(plane_state))
9908                 return false;
9909
9910         /* Cursor width is limited to a few power-of-two sizes */
9911         switch (width) {
9912         case 256:
9913         case 128:
9914         case 64:
9915                 break;
9916         default:
9917                 return false;
9918         }
9919
9920         /*
9921          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9922          * height from 8 lines up to the cursor width, when the
9923          * cursor is not rotated. Everything else requires square
9924          * cursors.
9925          */
9926         if (HAS_CUR_FBC(dev_priv) &&
9927             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9928                 if (height < 8 || height > width)
9929                         return false;
9930         } else {
9931                 if (height != width)
9932                         return false;
9933         }
9934
9935         return true;
9936 }
9937
9938 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
9939                              struct intel_plane_state *plane_state)
9940 {
9941         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
9942         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9943         const struct drm_framebuffer *fb = plane_state->base.fb;
9944         enum pipe pipe = plane->pipe;
9945         int ret;
9946
9947         ret = intel_check_cursor(crtc_state, plane_state);
9948         if (ret)
9949                 return ret;
9950
9951         /* if we want to turn off the cursor ignore width and height */
9952         if (!fb)
9953                 return 0;
9954
9955         /* Check for which cursor types we support */
9956         if (!i9xx_cursor_size_ok(plane_state)) {
9957                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9958                           plane_state->base.crtc_w,
9959                           plane_state->base.crtc_h);
9960                 return -EINVAL;
9961         }
9962
9963         WARN_ON(plane_state->base.visible &&
9964                 plane_state->color_plane[0].stride != fb->pitches[0]);
9965
9966         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9967                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9968                               fb->pitches[0], plane_state->base.crtc_w);
9969                 return -EINVAL;
9970         }
9971
9972         /*
9973          * There's something wrong with the cursor on CHV pipe C.
9974          * If it straddles the left edge of the screen then
9975          * moving it away from the edge or disabling it often
9976          * results in a pipe underrun, and often that can lead to
9977          * dead pipe (constant underrun reported, and it scans
9978          * out just a solid color). To recover from that, the
9979          * display power well must be turned off and on again.
9980          * Refuse the put the cursor into that compromised position.
9981          */
9982         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9983             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9984                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9985                 return -EINVAL;
9986         }
9987
9988         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9989
9990         return 0;
9991 }
9992
9993 static void i9xx_update_cursor(struct intel_plane *plane,
9994                                const struct intel_crtc_state *crtc_state,
9995                                const struct intel_plane_state *plane_state)
9996 {
9997         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9998         enum pipe pipe = plane->pipe;
9999         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
10000         unsigned long irqflags;
10001
10002         if (plane_state && plane_state->base.visible) {
10003                 cntl = plane_state->ctl;
10004
10005                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
10006                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
10007
10008                 base = intel_cursor_base(plane_state);
10009                 pos = intel_cursor_position(plane_state);
10010         }
10011
10012         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10013
10014         /*
10015          * On some platforms writing CURCNTR first will also
10016          * cause CURPOS to be armed by the CURBASE write.
10017          * Without the CURCNTR write the CURPOS write would
10018          * arm itself. Thus we always start the full update
10019          * with a CURCNTR write.
10020          *
10021          * On other platforms CURPOS always requires the
10022          * CURBASE write to arm the update. Additonally
10023          * a write to any of the cursor register will cancel
10024          * an already armed cursor update. Thus leaving out
10025          * the CURBASE write after CURPOS could lead to a
10026          * cursor that doesn't appear to move, or even change
10027          * shape. Thus we always write CURBASE.
10028          *
10029          * CURCNTR and CUR_FBC_CTL are always
10030          * armed by the CURBASE write only.
10031          */
10032         if (plane->cursor.base != base ||
10033             plane->cursor.size != fbc_ctl ||
10034             plane->cursor.cntl != cntl) {
10035                 I915_WRITE_FW(CURCNTR(pipe), cntl);
10036                 if (HAS_CUR_FBC(dev_priv))
10037                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
10038                 I915_WRITE_FW(CURPOS(pipe), pos);
10039                 I915_WRITE_FW(CURBASE(pipe), base);
10040
10041                 plane->cursor.base = base;
10042                 plane->cursor.size = fbc_ctl;
10043                 plane->cursor.cntl = cntl;
10044         } else {
10045                 I915_WRITE_FW(CURPOS(pipe), pos);
10046                 I915_WRITE_FW(CURBASE(pipe), base);
10047         }
10048
10049         POSTING_READ_FW(CURBASE(pipe));
10050
10051         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10052 }
10053
10054 static void i9xx_disable_cursor(struct intel_plane *plane,
10055                                 struct intel_crtc *crtc)
10056 {
10057         i9xx_update_cursor(plane, NULL, NULL);
10058 }
10059
10060 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10061                                      enum pipe *pipe)
10062 {
10063         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10064         enum intel_display_power_domain power_domain;
10065         bool ret;
10066         u32 val;
10067
10068         /*
10069          * Not 100% correct for planes that can move between pipes,
10070          * but that's only the case for gen2-3 which don't have any
10071          * display power wells.
10072          */
10073         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10074         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10075                 return false;
10076
10077         val = I915_READ(CURCNTR(plane->pipe));
10078
10079         ret = val & MCURSOR_MODE;
10080
10081         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10082                 *pipe = plane->pipe;
10083         else
10084                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10085                         MCURSOR_PIPE_SELECT_SHIFT;
10086
10087         intel_display_power_put(dev_priv, power_domain);
10088
10089         return ret;
10090 }
10091
10092 /* VESA 640x480x72Hz mode to set on the pipe */
10093 static const struct drm_display_mode load_detect_mode = {
10094         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10095                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10096 };
10097
10098 struct drm_framebuffer *
10099 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10100                          struct drm_mode_fb_cmd2 *mode_cmd)
10101 {
10102         struct intel_framebuffer *intel_fb;
10103         int ret;
10104
10105         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10106         if (!intel_fb)
10107                 return ERR_PTR(-ENOMEM);
10108
10109         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10110         if (ret)
10111                 goto err;
10112
10113         return &intel_fb->base;
10114
10115 err:
10116         kfree(intel_fb);
10117         return ERR_PTR(ret);
10118 }
10119
10120 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10121                                         struct drm_crtc *crtc)
10122 {
10123         struct drm_plane *plane;
10124         struct drm_plane_state *plane_state;
10125         int ret, i;
10126
10127         ret = drm_atomic_add_affected_planes(state, crtc);
10128         if (ret)
10129                 return ret;
10130
10131         for_each_new_plane_in_state(state, plane, plane_state, i) {
10132                 if (plane_state->crtc != crtc)
10133                         continue;
10134
10135                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10136                 if (ret)
10137                         return ret;
10138
10139                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10140         }
10141
10142         return 0;
10143 }
10144
10145 int intel_get_load_detect_pipe(struct drm_connector *connector,
10146                                const struct drm_display_mode *mode,
10147                                struct intel_load_detect_pipe *old,
10148                                struct drm_modeset_acquire_ctx *ctx)
10149 {
10150         struct intel_crtc *intel_crtc;
10151         struct intel_encoder *intel_encoder =
10152                 intel_attached_encoder(connector);
10153         struct drm_crtc *possible_crtc;
10154         struct drm_encoder *encoder = &intel_encoder->base;
10155         struct drm_crtc *crtc = NULL;
10156         struct drm_device *dev = encoder->dev;
10157         struct drm_i915_private *dev_priv = to_i915(dev);
10158         struct drm_mode_config *config = &dev->mode_config;
10159         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10160         struct drm_connector_state *connector_state;
10161         struct intel_crtc_state *crtc_state;
10162         int ret, i = -1;
10163
10164         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10165                       connector->base.id, connector->name,
10166                       encoder->base.id, encoder->name);
10167
10168         old->restore_state = NULL;
10169
10170         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10171
10172         /*
10173          * Algorithm gets a little messy:
10174          *
10175          *   - if the connector already has an assigned crtc, use it (but make
10176          *     sure it's on first)
10177          *
10178          *   - try to find the first unused crtc that can drive this connector,
10179          *     and use that if we find one
10180          */
10181
10182         /* See if we already have a CRTC for this connector */
10183         if (connector->state->crtc) {
10184                 crtc = connector->state->crtc;
10185
10186                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10187                 if (ret)
10188                         goto fail;
10189
10190                 /* Make sure the crtc and connector are running */
10191                 goto found;
10192         }
10193
10194         /* Find an unused one (if possible) */
10195         for_each_crtc(dev, possible_crtc) {
10196                 i++;
10197                 if (!(encoder->possible_crtcs & (1 << i)))
10198                         continue;
10199
10200                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10201                 if (ret)
10202                         goto fail;
10203
10204                 if (possible_crtc->state->enable) {
10205                         drm_modeset_unlock(&possible_crtc->mutex);
10206                         continue;
10207                 }
10208
10209                 crtc = possible_crtc;
10210                 break;
10211         }
10212
10213         /*
10214          * If we didn't find an unused CRTC, don't use any.
10215          */
10216         if (!crtc) {
10217                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10218                 ret = -ENODEV;
10219                 goto fail;
10220         }
10221
10222 found:
10223         intel_crtc = to_intel_crtc(crtc);
10224
10225         state = drm_atomic_state_alloc(dev);
10226         restore_state = drm_atomic_state_alloc(dev);
10227         if (!state || !restore_state) {
10228                 ret = -ENOMEM;
10229                 goto fail;
10230         }
10231
10232         state->acquire_ctx = ctx;
10233         restore_state->acquire_ctx = ctx;
10234
10235         connector_state = drm_atomic_get_connector_state(state, connector);
10236         if (IS_ERR(connector_state)) {
10237                 ret = PTR_ERR(connector_state);
10238                 goto fail;
10239         }
10240
10241         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10242         if (ret)
10243                 goto fail;
10244
10245         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10246         if (IS_ERR(crtc_state)) {
10247                 ret = PTR_ERR(crtc_state);
10248                 goto fail;
10249         }
10250
10251         crtc_state->base.active = crtc_state->base.enable = true;
10252
10253         if (!mode)
10254                 mode = &load_detect_mode;
10255
10256         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10257         if (ret)
10258                 goto fail;
10259
10260         ret = intel_modeset_disable_planes(state, crtc);
10261         if (ret)
10262                 goto fail;
10263
10264         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10265         if (!ret)
10266                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10267         if (!ret)
10268                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10269         if (ret) {
10270                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10271                 goto fail;
10272         }
10273
10274         ret = drm_atomic_commit(state);
10275         if (ret) {
10276                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10277                 goto fail;
10278         }
10279
10280         old->restore_state = restore_state;
10281         drm_atomic_state_put(state);
10282
10283         /* let the connector get through one full cycle before testing */
10284         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10285         return true;
10286
10287 fail:
10288         if (state) {
10289                 drm_atomic_state_put(state);
10290                 state = NULL;
10291         }
10292         if (restore_state) {
10293                 drm_atomic_state_put(restore_state);
10294                 restore_state = NULL;
10295         }
10296
10297         if (ret == -EDEADLK)
10298                 return ret;
10299
10300         return false;
10301 }
10302
10303 void intel_release_load_detect_pipe(struct drm_connector *connector,
10304                                     struct intel_load_detect_pipe *old,
10305                                     struct drm_modeset_acquire_ctx *ctx)
10306 {
10307         struct intel_encoder *intel_encoder =
10308                 intel_attached_encoder(connector);
10309         struct drm_encoder *encoder = &intel_encoder->base;
10310         struct drm_atomic_state *state = old->restore_state;
10311         int ret;
10312
10313         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10314                       connector->base.id, connector->name,
10315                       encoder->base.id, encoder->name);
10316
10317         if (!state)
10318                 return;
10319
10320         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10321         if (ret)
10322                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10323         drm_atomic_state_put(state);
10324 }
10325
10326 static int i9xx_pll_refclk(struct drm_device *dev,
10327                            const struct intel_crtc_state *pipe_config)
10328 {
10329         struct drm_i915_private *dev_priv = to_i915(dev);
10330         u32 dpll = pipe_config->dpll_hw_state.dpll;
10331
10332         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10333                 return dev_priv->vbt.lvds_ssc_freq;
10334         else if (HAS_PCH_SPLIT(dev_priv))
10335                 return 120000;
10336         else if (!IS_GEN2(dev_priv))
10337                 return 96000;
10338         else
10339                 return 48000;
10340 }
10341
10342 /* Returns the clock of the currently programmed mode of the given pipe. */
10343 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10344                                 struct intel_crtc_state *pipe_config)
10345 {
10346         struct drm_device *dev = crtc->base.dev;
10347         struct drm_i915_private *dev_priv = to_i915(dev);
10348         int pipe = pipe_config->cpu_transcoder;
10349         u32 dpll = pipe_config->dpll_hw_state.dpll;
10350         u32 fp;
10351         struct dpll clock;
10352         int port_clock;
10353         int refclk = i9xx_pll_refclk(dev, pipe_config);
10354
10355         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10356                 fp = pipe_config->dpll_hw_state.fp0;
10357         else
10358                 fp = pipe_config->dpll_hw_state.fp1;
10359
10360         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10361         if (IS_PINEVIEW(dev_priv)) {
10362                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10363                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10364         } else {
10365                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10366                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10367         }
10368
10369         if (!IS_GEN2(dev_priv)) {
10370                 if (IS_PINEVIEW(dev_priv))
10371                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10372                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10373                 else
10374                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10375                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10376
10377                 switch (dpll & DPLL_MODE_MASK) {
10378                 case DPLLB_MODE_DAC_SERIAL:
10379                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10380                                 5 : 10;
10381                         break;
10382                 case DPLLB_MODE_LVDS:
10383                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10384                                 7 : 14;
10385                         break;
10386                 default:
10387                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10388                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10389                         return;
10390                 }
10391
10392                 if (IS_PINEVIEW(dev_priv))
10393                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10394                 else
10395                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10396         } else {
10397                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10398                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10399
10400                 if (is_lvds) {
10401                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10402                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10403
10404                         if (lvds & LVDS_CLKB_POWER_UP)
10405                                 clock.p2 = 7;
10406                         else
10407                                 clock.p2 = 14;
10408                 } else {
10409                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10410                                 clock.p1 = 2;
10411                         else {
10412                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10413                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10414                         }
10415                         if (dpll & PLL_P2_DIVIDE_BY_4)
10416                                 clock.p2 = 4;
10417                         else
10418                                 clock.p2 = 2;
10419                 }
10420
10421                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10422         }
10423
10424         /*
10425          * This value includes pixel_multiplier. We will use
10426          * port_clock to compute adjusted_mode.crtc_clock in the
10427          * encoder's get_config() function.
10428          */
10429         pipe_config->port_clock = port_clock;
10430 }
10431
10432 int intel_dotclock_calculate(int link_freq,
10433                              const struct intel_link_m_n *m_n)
10434 {
10435         /*
10436          * The calculation for the data clock is:
10437          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10438          * But we want to avoid losing precison if possible, so:
10439          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10440          *
10441          * and the link clock is simpler:
10442          * link_clock = (m * link_clock) / n
10443          */
10444
10445         if (!m_n->link_n)
10446                 return 0;
10447
10448         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10449 }
10450
10451 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10452                                    struct intel_crtc_state *pipe_config)
10453 {
10454         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10455
10456         /* read out port_clock from the DPLL */
10457         i9xx_crtc_clock_get(crtc, pipe_config);
10458
10459         /*
10460          * In case there is an active pipe without active ports,
10461          * we may need some idea for the dotclock anyway.
10462          * Calculate one based on the FDI configuration.
10463          */
10464         pipe_config->base.adjusted_mode.crtc_clock =
10465                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10466                                          &pipe_config->fdi_m_n);
10467 }
10468
10469 /* Returns the currently programmed mode of the given encoder. */
10470 struct drm_display_mode *
10471 intel_encoder_current_mode(struct intel_encoder *encoder)
10472 {
10473         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10474         struct intel_crtc_state *crtc_state;
10475         struct drm_display_mode *mode;
10476         struct intel_crtc *crtc;
10477         enum pipe pipe;
10478
10479         if (!encoder->get_hw_state(encoder, &pipe))
10480                 return NULL;
10481
10482         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10483
10484         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10485         if (!mode)
10486                 return NULL;
10487
10488         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10489         if (!crtc_state) {
10490                 kfree(mode);
10491                 return NULL;
10492         }
10493
10494         crtc_state->base.crtc = &crtc->base;
10495
10496         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10497                 kfree(crtc_state);
10498                 kfree(mode);
10499                 return NULL;
10500         }
10501
10502         encoder->get_config(encoder, crtc_state);
10503
10504         intel_mode_from_pipe_config(mode, crtc_state);
10505
10506         kfree(crtc_state);
10507
10508         return mode;
10509 }
10510
10511 static void intel_crtc_destroy(struct drm_crtc *crtc)
10512 {
10513         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10514
10515         drm_crtc_cleanup(crtc);
10516         kfree(intel_crtc);
10517 }
10518
10519 /**
10520  * intel_wm_need_update - Check whether watermarks need updating
10521  * @plane: drm plane
10522  * @state: new plane state
10523  *
10524  * Check current plane state versus the new one to determine whether
10525  * watermarks need to be recalculated.
10526  *
10527  * Returns true or false.
10528  */
10529 static bool intel_wm_need_update(struct drm_plane *plane,
10530                                  struct drm_plane_state *state)
10531 {
10532         struct intel_plane_state *new = to_intel_plane_state(state);
10533         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10534
10535         /* Update watermarks on tiling or size changes. */
10536         if (new->base.visible != cur->base.visible)
10537                 return true;
10538
10539         if (!cur->base.fb || !new->base.fb)
10540                 return false;
10541
10542         if (cur->base.fb->modifier != new->base.fb->modifier ||
10543             cur->base.rotation != new->base.rotation ||
10544             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10545             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10546             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10547             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10548                 return true;
10549
10550         return false;
10551 }
10552
10553 static bool needs_scaling(const struct intel_plane_state *state)
10554 {
10555         int src_w = drm_rect_width(&state->base.src) >> 16;
10556         int src_h = drm_rect_height(&state->base.src) >> 16;
10557         int dst_w = drm_rect_width(&state->base.dst);
10558         int dst_h = drm_rect_height(&state->base.dst);
10559
10560         return (src_w != dst_w || src_h != dst_h);
10561 }
10562
10563 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10564                                     struct drm_crtc_state *crtc_state,
10565                                     const struct intel_plane_state *old_plane_state,
10566                                     struct drm_plane_state *plane_state)
10567 {
10568         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10569         struct drm_crtc *crtc = crtc_state->crtc;
10570         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10571         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10572         struct drm_device *dev = crtc->dev;
10573         struct drm_i915_private *dev_priv = to_i915(dev);
10574         bool mode_changed = needs_modeset(crtc_state);
10575         bool was_crtc_enabled = old_crtc_state->base.active;
10576         bool is_crtc_enabled = crtc_state->active;
10577         bool turn_off, turn_on, visible, was_visible;
10578         struct drm_framebuffer *fb = plane_state->fb;
10579         int ret;
10580
10581         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10582                 ret = skl_update_scaler_plane(
10583                         to_intel_crtc_state(crtc_state),
10584                         to_intel_plane_state(plane_state));
10585                 if (ret)
10586                         return ret;
10587         }
10588
10589         was_visible = old_plane_state->base.visible;
10590         visible = plane_state->visible;
10591
10592         if (!was_crtc_enabled && WARN_ON(was_visible))
10593                 was_visible = false;
10594
10595         /*
10596          * Visibility is calculated as if the crtc was on, but
10597          * after scaler setup everything depends on it being off
10598          * when the crtc isn't active.
10599          *
10600          * FIXME this is wrong for watermarks. Watermarks should also
10601          * be computed as if the pipe would be active. Perhaps move
10602          * per-plane wm computation to the .check_plane() hook, and
10603          * only combine the results from all planes in the current place?
10604          */
10605         if (!is_crtc_enabled) {
10606                 plane_state->visible = visible = false;
10607                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10608         }
10609
10610         if (!was_visible && !visible)
10611                 return 0;
10612
10613         if (fb != old_plane_state->base.fb)
10614                 pipe_config->fb_changed = true;
10615
10616         turn_off = was_visible && (!visible || mode_changed);
10617         turn_on = visible && (!was_visible || mode_changed);
10618
10619         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10620                          intel_crtc->base.base.id, intel_crtc->base.name,
10621                          plane->base.base.id, plane->base.name,
10622                          fb ? fb->base.id : -1);
10623
10624         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10625                          plane->base.base.id, plane->base.name,
10626                          was_visible, visible,
10627                          turn_off, turn_on, mode_changed);
10628
10629         if (turn_on) {
10630                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10631                         pipe_config->update_wm_pre = true;
10632
10633                 /* must disable cxsr around plane enable/disable */
10634                 if (plane->id != PLANE_CURSOR)
10635                         pipe_config->disable_cxsr = true;
10636         } else if (turn_off) {
10637                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10638                         pipe_config->update_wm_post = true;
10639
10640                 /* must disable cxsr around plane enable/disable */
10641                 if (plane->id != PLANE_CURSOR)
10642                         pipe_config->disable_cxsr = true;
10643         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10644                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10645                         /* FIXME bollocks */
10646                         pipe_config->update_wm_pre = true;
10647                         pipe_config->update_wm_post = true;
10648                 }
10649         }
10650
10651         if (visible || was_visible)
10652                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10653
10654         /*
10655          * ILK/SNB DVSACNTR/Sprite Enable
10656          * IVB SPR_CTL/Sprite Enable
10657          * "When in Self Refresh Big FIFO mode, a write to enable the
10658          *  plane will be internally buffered and delayed while Big FIFO
10659          *  mode is exiting."
10660          *
10661          * Which means that enabling the sprite can take an extra frame
10662          * when we start in big FIFO mode (LP1+). Thus we need to drop
10663          * down to LP0 and wait for vblank in order to make sure the
10664          * sprite gets enabled on the next vblank after the register write.
10665          * Doing otherwise would risk enabling the sprite one frame after
10666          * we've already signalled flip completion. We can resume LP1+
10667          * once the sprite has been enabled.
10668          *
10669          *
10670          * WaCxSRDisabledForSpriteScaling:ivb
10671          * IVB SPR_SCALE/Scaling Enable
10672          * "Low Power watermarks must be disabled for at least one
10673          *  frame before enabling sprite scaling, and kept disabled
10674          *  until sprite scaling is disabled."
10675          *
10676          * ILK/SNB DVSASCALE/Scaling Enable
10677          * "When in Self Refresh Big FIFO mode, scaling enable will be
10678          *  masked off while Big FIFO mode is exiting."
10679          *
10680          * Despite the w/a only being listed for IVB we assume that
10681          * the ILK/SNB note has similar ramifications, hence we apply
10682          * the w/a on all three platforms.
10683          */
10684         if (plane->id == PLANE_SPRITE0 &&
10685             (IS_GEN5(dev_priv) || IS_GEN6(dev_priv) ||
10686              IS_IVYBRIDGE(dev_priv)) &&
10687             (turn_on || (!needs_scaling(old_plane_state) &&
10688                          needs_scaling(to_intel_plane_state(plane_state)))))
10689                 pipe_config->disable_lp_wm = true;
10690
10691         return 0;
10692 }
10693
10694 static bool encoders_cloneable(const struct intel_encoder *a,
10695                                const struct intel_encoder *b)
10696 {
10697         /* masks could be asymmetric, so check both ways */
10698         return a == b || (a->cloneable & (1 << b->type) &&
10699                           b->cloneable & (1 << a->type));
10700 }
10701
10702 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10703                                          struct intel_crtc *crtc,
10704                                          struct intel_encoder *encoder)
10705 {
10706         struct intel_encoder *source_encoder;
10707         struct drm_connector *connector;
10708         struct drm_connector_state *connector_state;
10709         int i;
10710
10711         for_each_new_connector_in_state(state, connector, connector_state, i) {
10712                 if (connector_state->crtc != &crtc->base)
10713                         continue;
10714
10715                 source_encoder =
10716                         to_intel_encoder(connector_state->best_encoder);
10717                 if (!encoders_cloneable(encoder, source_encoder))
10718                         return false;
10719         }
10720
10721         return true;
10722 }
10723
10724 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10725                                    struct drm_crtc_state *crtc_state)
10726 {
10727         struct drm_device *dev = crtc->dev;
10728         struct drm_i915_private *dev_priv = to_i915(dev);
10729         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10730         struct intel_crtc_state *pipe_config =
10731                 to_intel_crtc_state(crtc_state);
10732         struct drm_atomic_state *state = crtc_state->state;
10733         int ret;
10734         bool mode_changed = needs_modeset(crtc_state);
10735
10736         if (mode_changed && !crtc_state->active)
10737                 pipe_config->update_wm_post = true;
10738
10739         if (mode_changed && crtc_state->enable &&
10740             dev_priv->display.crtc_compute_clock &&
10741             !WARN_ON(pipe_config->shared_dpll)) {
10742                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10743                                                            pipe_config);
10744                 if (ret)
10745                         return ret;
10746         }
10747
10748         if (crtc_state->color_mgmt_changed) {
10749                 ret = intel_color_check(crtc, crtc_state);
10750                 if (ret)
10751                         return ret;
10752
10753                 /*
10754                  * Changing color management on Intel hardware is
10755                  * handled as part of planes update.
10756                  */
10757                 crtc_state->planes_changed = true;
10758         }
10759
10760         ret = 0;
10761         if (dev_priv->display.compute_pipe_wm) {
10762                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10763                 if (ret) {
10764                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10765                         return ret;
10766                 }
10767         }
10768
10769         if (dev_priv->display.compute_intermediate_wm &&
10770             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10771                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10772                         return 0;
10773
10774                 /*
10775                  * Calculate 'intermediate' watermarks that satisfy both the
10776                  * old state and the new state.  We can program these
10777                  * immediately.
10778                  */
10779                 ret = dev_priv->display.compute_intermediate_wm(dev,
10780                                                                 intel_crtc,
10781                                                                 pipe_config);
10782                 if (ret) {
10783                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10784                         return ret;
10785                 }
10786         } else if (dev_priv->display.compute_intermediate_wm) {
10787                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10788                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10789         }
10790
10791         if (INTEL_GEN(dev_priv) >= 9) {
10792                 if (mode_changed)
10793                         ret = skl_update_scaler_crtc(pipe_config);
10794
10795                 if (!ret)
10796                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10797                                                             pipe_config);
10798                 if (!ret)
10799                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10800                                                          pipe_config);
10801         }
10802
10803         if (HAS_IPS(dev_priv))
10804                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10805
10806         return ret;
10807 }
10808
10809 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10810         .atomic_check = intel_crtc_atomic_check,
10811 };
10812
10813 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10814 {
10815         struct intel_connector *connector;
10816         struct drm_connector_list_iter conn_iter;
10817
10818         drm_connector_list_iter_begin(dev, &conn_iter);
10819         for_each_intel_connector_iter(connector, &conn_iter) {
10820                 if (connector->base.state->crtc)
10821                         drm_connector_put(&connector->base);
10822
10823                 if (connector->base.encoder) {
10824                         connector->base.state->best_encoder =
10825                                 connector->base.encoder;
10826                         connector->base.state->crtc =
10827                                 connector->base.encoder->crtc;
10828
10829                         drm_connector_get(&connector->base);
10830                 } else {
10831                         connector->base.state->best_encoder = NULL;
10832                         connector->base.state->crtc = NULL;
10833                 }
10834         }
10835         drm_connector_list_iter_end(&conn_iter);
10836 }
10837
10838 static void
10839 connected_sink_compute_bpp(struct intel_connector *connector,
10840                            struct intel_crtc_state *pipe_config)
10841 {
10842         const struct drm_display_info *info = &connector->base.display_info;
10843         int bpp = pipe_config->pipe_bpp;
10844
10845         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10846                       connector->base.base.id,
10847                       connector->base.name);
10848
10849         /* Don't use an invalid EDID bpc value */
10850         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10851                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10852                               bpp, info->bpc * 3);
10853                 pipe_config->pipe_bpp = info->bpc * 3;
10854         }
10855
10856         /* Clamp bpp to 8 on screens without EDID 1.4 */
10857         if (info->bpc == 0 && bpp > 24) {
10858                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10859                               bpp);
10860                 pipe_config->pipe_bpp = 24;
10861         }
10862 }
10863
10864 static int
10865 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10866                           struct intel_crtc_state *pipe_config)
10867 {
10868         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10869         struct drm_atomic_state *state;
10870         struct drm_connector *connector;
10871         struct drm_connector_state *connector_state;
10872         int bpp, i;
10873
10874         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10875             IS_CHERRYVIEW(dev_priv)))
10876                 bpp = 10*3;
10877         else if (INTEL_GEN(dev_priv) >= 5)
10878                 bpp = 12*3;
10879         else
10880                 bpp = 8*3;
10881
10882
10883         pipe_config->pipe_bpp = bpp;
10884
10885         state = pipe_config->base.state;
10886
10887         /* Clamp display bpp to EDID value */
10888         for_each_new_connector_in_state(state, connector, connector_state, i) {
10889                 if (connector_state->crtc != &crtc->base)
10890                         continue;
10891
10892                 connected_sink_compute_bpp(to_intel_connector(connector),
10893                                            pipe_config);
10894         }
10895
10896         return bpp;
10897 }
10898
10899 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10900 {
10901         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10902                         "type: 0x%x flags: 0x%x\n",
10903                 mode->crtc_clock,
10904                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10905                 mode->crtc_hsync_end, mode->crtc_htotal,
10906                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10907                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10908 }
10909
10910 static inline void
10911 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10912                       unsigned int lane_count, struct intel_link_m_n *m_n)
10913 {
10914         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10915                       id, lane_count,
10916                       m_n->gmch_m, m_n->gmch_n,
10917                       m_n->link_m, m_n->link_n, m_n->tu);
10918 }
10919
10920 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10921
10922 static const char * const output_type_str[] = {
10923         OUTPUT_TYPE(UNUSED),
10924         OUTPUT_TYPE(ANALOG),
10925         OUTPUT_TYPE(DVO),
10926         OUTPUT_TYPE(SDVO),
10927         OUTPUT_TYPE(LVDS),
10928         OUTPUT_TYPE(TVOUT),
10929         OUTPUT_TYPE(HDMI),
10930         OUTPUT_TYPE(DP),
10931         OUTPUT_TYPE(EDP),
10932         OUTPUT_TYPE(DSI),
10933         OUTPUT_TYPE(DDI),
10934         OUTPUT_TYPE(DP_MST),
10935 };
10936
10937 #undef OUTPUT_TYPE
10938
10939 static void snprintf_output_types(char *buf, size_t len,
10940                                   unsigned int output_types)
10941 {
10942         char *str = buf;
10943         int i;
10944
10945         str[0] = '\0';
10946
10947         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
10948                 int r;
10949
10950                 if ((output_types & BIT(i)) == 0)
10951                         continue;
10952
10953                 r = snprintf(str, len, "%s%s",
10954                              str != buf ? "," : "", output_type_str[i]);
10955                 if (r >= len)
10956                         break;
10957                 str += r;
10958                 len -= r;
10959
10960                 output_types &= ~BIT(i);
10961         }
10962
10963         WARN_ON_ONCE(output_types != 0);
10964 }
10965
10966 static const char * const output_format_str[] = {
10967         [INTEL_OUTPUT_FORMAT_INVALID] = "Invalid",
10968         [INTEL_OUTPUT_FORMAT_RGB] = "RGB",
10969         [INTEL_OUTPUT_FORMAT_YCBCR420] = "YCBCR4:2:0",
10970         [INTEL_OUTPUT_FORMAT_YCBCR444] = "YCBCR4:4:4",
10971 };
10972
10973 static const char *output_formats(enum intel_output_format format)
10974 {
10975         if (format >= ARRAY_SIZE(output_format_str))
10976                 format = INTEL_OUTPUT_FORMAT_INVALID;
10977         return output_format_str[format];
10978 }
10979
10980 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10981                                    struct intel_crtc_state *pipe_config,
10982                                    const char *context)
10983 {
10984         struct drm_device *dev = crtc->base.dev;
10985         struct drm_i915_private *dev_priv = to_i915(dev);
10986         struct drm_plane *plane;
10987         struct intel_plane *intel_plane;
10988         struct intel_plane_state *state;
10989         struct drm_framebuffer *fb;
10990         char buf[64];
10991
10992         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10993                       crtc->base.base.id, crtc->base.name, context);
10994
10995         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
10996         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
10997                       buf, pipe_config->output_types);
10998
10999         DRM_DEBUG_KMS("output format: %s\n",
11000                       output_formats(pipe_config->output_format));
11001
11002         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
11003                       transcoder_name(pipe_config->cpu_transcoder),
11004                       pipe_config->pipe_bpp, pipe_config->dither);
11005
11006         if (pipe_config->has_pch_encoder)
11007                 intel_dump_m_n_config(pipe_config, "fdi",
11008                                       pipe_config->fdi_lanes,
11009                                       &pipe_config->fdi_m_n);
11010
11011         if (intel_crtc_has_dp_encoder(pipe_config)) {
11012                 intel_dump_m_n_config(pipe_config, "dp m_n",
11013                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11014                 if (pipe_config->has_drrs)
11015                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11016                                               pipe_config->lane_count,
11017                                               &pipe_config->dp_m2_n2);
11018         }
11019
11020         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11021                       pipe_config->has_audio, pipe_config->has_infoframe);
11022
11023         DRM_DEBUG_KMS("requested mode:\n");
11024         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11025         DRM_DEBUG_KMS("adjusted mode:\n");
11026         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11027         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11028         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11029                       pipe_config->port_clock,
11030                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11031                       pipe_config->pixel_rate);
11032
11033         if (INTEL_GEN(dev_priv) >= 9)
11034                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11035                               crtc->num_scalers,
11036                               pipe_config->scaler_state.scaler_users,
11037                               pipe_config->scaler_state.scaler_id);
11038
11039         if (HAS_GMCH_DISPLAY(dev_priv))
11040                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11041                               pipe_config->gmch_pfit.control,
11042                               pipe_config->gmch_pfit.pgm_ratios,
11043                               pipe_config->gmch_pfit.lvds_border_bits);
11044         else
11045                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11046                               pipe_config->pch_pfit.pos,
11047                               pipe_config->pch_pfit.size,
11048                               enableddisabled(pipe_config->pch_pfit.enabled));
11049
11050         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11051                       pipe_config->ips_enabled, pipe_config->double_wide);
11052
11053         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11054
11055         DRM_DEBUG_KMS("planes on this crtc\n");
11056         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11057                 struct drm_format_name_buf format_name;
11058                 intel_plane = to_intel_plane(plane);
11059                 if (intel_plane->pipe != crtc->pipe)
11060                         continue;
11061
11062                 state = to_intel_plane_state(plane->state);
11063                 fb = state->base.fb;
11064                 if (!fb) {
11065                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11066                                       plane->base.id, plane->name, state->scaler_id);
11067                         continue;
11068                 }
11069
11070                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11071                               plane->base.id, plane->name,
11072                               fb->base.id, fb->width, fb->height,
11073                               drm_get_format_name(fb->format->format, &format_name));
11074                 if (INTEL_GEN(dev_priv) >= 9)
11075                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11076                                       state->scaler_id,
11077                                       state->base.src.x1 >> 16,
11078                                       state->base.src.y1 >> 16,
11079                                       drm_rect_width(&state->base.src) >> 16,
11080                                       drm_rect_height(&state->base.src) >> 16,
11081                                       state->base.dst.x1, state->base.dst.y1,
11082                                       drm_rect_width(&state->base.dst),
11083                                       drm_rect_height(&state->base.dst));
11084         }
11085 }
11086
11087 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11088 {
11089         struct drm_device *dev = state->dev;
11090         struct drm_connector *connector;
11091         struct drm_connector_list_iter conn_iter;
11092         unsigned int used_ports = 0;
11093         unsigned int used_mst_ports = 0;
11094         bool ret = true;
11095
11096         /*
11097          * Walk the connector list instead of the encoder
11098          * list to detect the problem on ddi platforms
11099          * where there's just one encoder per digital port.
11100          */
11101         drm_connector_list_iter_begin(dev, &conn_iter);
11102         drm_for_each_connector_iter(connector, &conn_iter) {
11103                 struct drm_connector_state *connector_state;
11104                 struct intel_encoder *encoder;
11105
11106                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11107                 if (!connector_state)
11108                         connector_state = connector->state;
11109
11110                 if (!connector_state->best_encoder)
11111                         continue;
11112
11113                 encoder = to_intel_encoder(connector_state->best_encoder);
11114
11115                 WARN_ON(!connector_state->crtc);
11116
11117                 switch (encoder->type) {
11118                         unsigned int port_mask;
11119                 case INTEL_OUTPUT_DDI:
11120                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11121                                 break;
11122                         /* else: fall through */
11123                 case INTEL_OUTPUT_DP:
11124                 case INTEL_OUTPUT_HDMI:
11125                 case INTEL_OUTPUT_EDP:
11126                         port_mask = 1 << encoder->port;
11127
11128                         /* the same port mustn't appear more than once */
11129                         if (used_ports & port_mask)
11130                                 ret = false;
11131
11132                         used_ports |= port_mask;
11133                         break;
11134                 case INTEL_OUTPUT_DP_MST:
11135                         used_mst_ports |=
11136                                 1 << encoder->port;
11137                         break;
11138                 default:
11139                         break;
11140                 }
11141         }
11142         drm_connector_list_iter_end(&conn_iter);
11143
11144         /* can't mix MST and SST/HDMI on the same port */
11145         if (used_ports & used_mst_ports)
11146                 return false;
11147
11148         return ret;
11149 }
11150
11151 static void
11152 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11153 {
11154         struct drm_i915_private *dev_priv =
11155                 to_i915(crtc_state->base.crtc->dev);
11156         struct intel_crtc_scaler_state scaler_state;
11157         struct intel_dpll_hw_state dpll_hw_state;
11158         struct intel_shared_dpll *shared_dpll;
11159         struct intel_crtc_wm_state wm_state;
11160         bool force_thru, ips_force_disable;
11161
11162         /* FIXME: before the switch to atomic started, a new pipe_config was
11163          * kzalloc'd. Code that depends on any field being zero should be
11164          * fixed, so that the crtc_state can be safely duplicated. For now,
11165          * only fields that are know to not cause problems are preserved. */
11166
11167         scaler_state = crtc_state->scaler_state;
11168         shared_dpll = crtc_state->shared_dpll;
11169         dpll_hw_state = crtc_state->dpll_hw_state;
11170         force_thru = crtc_state->pch_pfit.force_thru;
11171         ips_force_disable = crtc_state->ips_force_disable;
11172         if (IS_G4X(dev_priv) ||
11173             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11174                 wm_state = crtc_state->wm;
11175
11176         /* Keep base drm_crtc_state intact, only clear our extended struct */
11177         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11178         memset(&crtc_state->base + 1, 0,
11179                sizeof(*crtc_state) - sizeof(crtc_state->base));
11180
11181         crtc_state->scaler_state = scaler_state;
11182         crtc_state->shared_dpll = shared_dpll;
11183         crtc_state->dpll_hw_state = dpll_hw_state;
11184         crtc_state->pch_pfit.force_thru = force_thru;
11185         crtc_state->ips_force_disable = ips_force_disable;
11186         if (IS_G4X(dev_priv) ||
11187             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11188                 crtc_state->wm = wm_state;
11189 }
11190
11191 static int
11192 intel_modeset_pipe_config(struct drm_crtc *crtc,
11193                           struct intel_crtc_state *pipe_config)
11194 {
11195         struct drm_atomic_state *state = pipe_config->base.state;
11196         struct intel_encoder *encoder;
11197         struct drm_connector *connector;
11198         struct drm_connector_state *connector_state;
11199         int base_bpp, ret = -EINVAL;
11200         int i;
11201         bool retry = true;
11202
11203         clear_intel_crtc_state(pipe_config);
11204
11205         pipe_config->cpu_transcoder =
11206                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11207
11208         /*
11209          * Sanitize sync polarity flags based on requested ones. If neither
11210          * positive or negative polarity is requested, treat this as meaning
11211          * negative polarity.
11212          */
11213         if (!(pipe_config->base.adjusted_mode.flags &
11214               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11215                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11216
11217         if (!(pipe_config->base.adjusted_mode.flags &
11218               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11219                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11220
11221         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11222                                              pipe_config);
11223         if (base_bpp < 0)
11224                 goto fail;
11225
11226         /*
11227          * Determine the real pipe dimensions. Note that stereo modes can
11228          * increase the actual pipe size due to the frame doubling and
11229          * insertion of additional space for blanks between the frame. This
11230          * is stored in the crtc timings. We use the requested mode to do this
11231          * computation to clearly distinguish it from the adjusted mode, which
11232          * can be changed by the connectors in the below retry loop.
11233          */
11234         drm_mode_get_hv_timing(&pipe_config->base.mode,
11235                                &pipe_config->pipe_src_w,
11236                                &pipe_config->pipe_src_h);
11237
11238         for_each_new_connector_in_state(state, connector, connector_state, i) {
11239                 if (connector_state->crtc != crtc)
11240                         continue;
11241
11242                 encoder = to_intel_encoder(connector_state->best_encoder);
11243
11244                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11245                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11246                         goto fail;
11247                 }
11248
11249                 /*
11250                  * Determine output_types before calling the .compute_config()
11251                  * hooks so that the hooks can use this information safely.
11252                  */
11253                 if (encoder->compute_output_type)
11254                         pipe_config->output_types |=
11255                                 BIT(encoder->compute_output_type(encoder, pipe_config,
11256                                                                  connector_state));
11257                 else
11258                         pipe_config->output_types |= BIT(encoder->type);
11259         }
11260
11261 encoder_retry:
11262         /* Ensure the port clock defaults are reset when retrying. */
11263         pipe_config->port_clock = 0;
11264         pipe_config->pixel_multiplier = 1;
11265
11266         /* Fill in default crtc timings, allow encoders to overwrite them. */
11267         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11268                               CRTC_STEREO_DOUBLE);
11269
11270         /* Pass our mode to the connectors and the CRTC to give them a chance to
11271          * adjust it according to limitations or connector properties, and also
11272          * a chance to reject the mode entirely.
11273          */
11274         for_each_new_connector_in_state(state, connector, connector_state, i) {
11275                 if (connector_state->crtc != crtc)
11276                         continue;
11277
11278                 encoder = to_intel_encoder(connector_state->best_encoder);
11279
11280                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
11281                         DRM_DEBUG_KMS("Encoder config failure\n");
11282                         goto fail;
11283                 }
11284         }
11285
11286         /* Set default port clock if not overwritten by the encoder. Needs to be
11287          * done afterwards in case the encoder adjusts the mode. */
11288         if (!pipe_config->port_clock)
11289                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11290                         * pipe_config->pixel_multiplier;
11291
11292         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11293         if (ret < 0) {
11294                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11295                 goto fail;
11296         }
11297
11298         if (ret == RETRY) {
11299                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11300                         ret = -EINVAL;
11301                         goto fail;
11302                 }
11303
11304                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11305                 retry = false;
11306                 goto encoder_retry;
11307         }
11308
11309         /* Dithering seems to not pass-through bits correctly when it should, so
11310          * only enable it on 6bpc panels and when its not a compliance
11311          * test requesting 6bpc video pattern.
11312          */
11313         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11314                 !pipe_config->dither_force_disable;
11315         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11316                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11317
11318 fail:
11319         return ret;
11320 }
11321
11322 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11323 {
11324         int diff;
11325
11326         if (clock1 == clock2)
11327                 return true;
11328
11329         if (!clock1 || !clock2)
11330                 return false;
11331
11332         diff = abs(clock1 - clock2);
11333
11334         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11335                 return true;
11336
11337         return false;
11338 }
11339
11340 static bool
11341 intel_compare_m_n(unsigned int m, unsigned int n,
11342                   unsigned int m2, unsigned int n2,
11343                   bool exact)
11344 {
11345         if (m == m2 && n == n2)
11346                 return true;
11347
11348         if (exact || !m || !n || !m2 || !n2)
11349                 return false;
11350
11351         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11352
11353         if (n > n2) {
11354                 while (n > n2) {
11355                         m2 <<= 1;
11356                         n2 <<= 1;
11357                 }
11358         } else if (n < n2) {
11359                 while (n < n2) {
11360                         m <<= 1;
11361                         n <<= 1;
11362                 }
11363         }
11364
11365         if (n != n2)
11366                 return false;
11367
11368         return intel_fuzzy_clock_check(m, m2);
11369 }
11370
11371 static bool
11372 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11373                        struct intel_link_m_n *m2_n2,
11374                        bool adjust)
11375 {
11376         if (m_n->tu == m2_n2->tu &&
11377             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11378                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11379             intel_compare_m_n(m_n->link_m, m_n->link_n,
11380                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11381                 if (adjust)
11382                         *m2_n2 = *m_n;
11383
11384                 return true;
11385         }
11386
11387         return false;
11388 }
11389
11390 static void __printf(3, 4)
11391 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11392 {
11393         struct va_format vaf;
11394         va_list args;
11395
11396         va_start(args, format);
11397         vaf.fmt = format;
11398         vaf.va = &args;
11399
11400         if (adjust)
11401                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11402         else
11403                 drm_err("mismatch in %s %pV", name, &vaf);
11404
11405         va_end(args);
11406 }
11407
11408 static bool
11409 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11410                           struct intel_crtc_state *current_config,
11411                           struct intel_crtc_state *pipe_config,
11412                           bool adjust)
11413 {
11414         bool ret = true;
11415         bool fixup_inherited = adjust &&
11416                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11417                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11418
11419 #define PIPE_CONF_CHECK_X(name) do { \
11420         if (current_config->name != pipe_config->name) { \
11421                 pipe_config_err(adjust, __stringify(name), \
11422                           "(expected 0x%08x, found 0x%08x)\n", \
11423                           current_config->name, \
11424                           pipe_config->name); \
11425                 ret = false; \
11426         } \
11427 } while (0)
11428
11429 #define PIPE_CONF_CHECK_I(name) do { \
11430         if (current_config->name != pipe_config->name) { \
11431                 pipe_config_err(adjust, __stringify(name), \
11432                           "(expected %i, found %i)\n", \
11433                           current_config->name, \
11434                           pipe_config->name); \
11435                 ret = false; \
11436         } \
11437 } while (0)
11438
11439 #define PIPE_CONF_CHECK_BOOL(name) do { \
11440         if (current_config->name != pipe_config->name) { \
11441                 pipe_config_err(adjust, __stringify(name), \
11442                           "(expected %s, found %s)\n", \
11443                           yesno(current_config->name), \
11444                           yesno(pipe_config->name)); \
11445                 ret = false; \
11446         } \
11447 } while (0)
11448
11449 /*
11450  * Checks state where we only read out the enabling, but not the entire
11451  * state itself (like full infoframes or ELD for audio). These states
11452  * require a full modeset on bootup to fix up.
11453  */
11454 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
11455         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11456                 PIPE_CONF_CHECK_BOOL(name); \
11457         } else { \
11458                 pipe_config_err(adjust, __stringify(name), \
11459                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11460                           yesno(current_config->name), \
11461                           yesno(pipe_config->name)); \
11462                 ret = false; \
11463         } \
11464 } while (0)
11465
11466 #define PIPE_CONF_CHECK_P(name) do { \
11467         if (current_config->name != pipe_config->name) { \
11468                 pipe_config_err(adjust, __stringify(name), \
11469                           "(expected %p, found %p)\n", \
11470                           current_config->name, \
11471                           pipe_config->name); \
11472                 ret = false; \
11473         } \
11474 } while (0)
11475
11476 #define PIPE_CONF_CHECK_M_N(name) do { \
11477         if (!intel_compare_link_m_n(&current_config->name, \
11478                                     &pipe_config->name,\
11479                                     adjust)) { \
11480                 pipe_config_err(adjust, __stringify(name), \
11481                           "(expected tu %i gmch %i/%i link %i/%i, " \
11482                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11483                           current_config->name.tu, \
11484                           current_config->name.gmch_m, \
11485                           current_config->name.gmch_n, \
11486                           current_config->name.link_m, \
11487                           current_config->name.link_n, \
11488                           pipe_config->name.tu, \
11489                           pipe_config->name.gmch_m, \
11490                           pipe_config->name.gmch_n, \
11491                           pipe_config->name.link_m, \
11492                           pipe_config->name.link_n); \
11493                 ret = false; \
11494         } \
11495 } while (0)
11496
11497 /* This is required for BDW+ where there is only one set of registers for
11498  * switching between high and low RR.
11499  * This macro can be used whenever a comparison has to be made between one
11500  * hw state and multiple sw state variables.
11501  */
11502 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
11503         if (!intel_compare_link_m_n(&current_config->name, \
11504                                     &pipe_config->name, adjust) && \
11505             !intel_compare_link_m_n(&current_config->alt_name, \
11506                                     &pipe_config->name, adjust)) { \
11507                 pipe_config_err(adjust, __stringify(name), \
11508                           "(expected tu %i gmch %i/%i link %i/%i, " \
11509                           "or tu %i gmch %i/%i link %i/%i, " \
11510                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11511                           current_config->name.tu, \
11512                           current_config->name.gmch_m, \
11513                           current_config->name.gmch_n, \
11514                           current_config->name.link_m, \
11515                           current_config->name.link_n, \
11516                           current_config->alt_name.tu, \
11517                           current_config->alt_name.gmch_m, \
11518                           current_config->alt_name.gmch_n, \
11519                           current_config->alt_name.link_m, \
11520                           current_config->alt_name.link_n, \
11521                           pipe_config->name.tu, \
11522                           pipe_config->name.gmch_m, \
11523                           pipe_config->name.gmch_n, \
11524                           pipe_config->name.link_m, \
11525                           pipe_config->name.link_n); \
11526                 ret = false; \
11527         } \
11528 } while (0)
11529
11530 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
11531         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11532                 pipe_config_err(adjust, __stringify(name), \
11533                           "(%x) (expected %i, found %i)\n", \
11534                           (mask), \
11535                           current_config->name & (mask), \
11536                           pipe_config->name & (mask)); \
11537                 ret = false; \
11538         } \
11539 } while (0)
11540
11541 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
11542         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11543                 pipe_config_err(adjust, __stringify(name), \
11544                           "(expected %i, found %i)\n", \
11545                           current_config->name, \
11546                           pipe_config->name); \
11547                 ret = false; \
11548         } \
11549 } while (0)
11550
11551 #define PIPE_CONF_QUIRK(quirk)  \
11552         ((current_config->quirks | pipe_config->quirks) & (quirk))
11553
11554         PIPE_CONF_CHECK_I(cpu_transcoder);
11555
11556         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11557         PIPE_CONF_CHECK_I(fdi_lanes);
11558         PIPE_CONF_CHECK_M_N(fdi_m_n);
11559
11560         PIPE_CONF_CHECK_I(lane_count);
11561         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11562
11563         if (INTEL_GEN(dev_priv) < 8) {
11564                 PIPE_CONF_CHECK_M_N(dp_m_n);
11565
11566                 if (current_config->has_drrs)
11567                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11568         } else
11569                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11570
11571         PIPE_CONF_CHECK_X(output_types);
11572
11573         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11574         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11575         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11576         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11577         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11578         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11579
11580         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11581         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11582         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11583         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11584         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11585         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11586
11587         PIPE_CONF_CHECK_I(pixel_multiplier);
11588         PIPE_CONF_CHECK_I(output_format);
11589         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11590         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11591             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11592                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11593
11594         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11595         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11596         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11597
11598         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11599
11600         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11601                               DRM_MODE_FLAG_INTERLACE);
11602
11603         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11604                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11605                                       DRM_MODE_FLAG_PHSYNC);
11606                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11607                                       DRM_MODE_FLAG_NHSYNC);
11608                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11609                                       DRM_MODE_FLAG_PVSYNC);
11610                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11611                                       DRM_MODE_FLAG_NVSYNC);
11612         }
11613
11614         PIPE_CONF_CHECK_X(gmch_pfit.control);
11615         /* pfit ratios are autocomputed by the hw on gen4+ */
11616         if (INTEL_GEN(dev_priv) < 4)
11617                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11618         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11619
11620         if (!adjust) {
11621                 PIPE_CONF_CHECK_I(pipe_src_w);
11622                 PIPE_CONF_CHECK_I(pipe_src_h);
11623
11624                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11625                 if (current_config->pch_pfit.enabled) {
11626                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11627                         PIPE_CONF_CHECK_X(pch_pfit.size);
11628                 }
11629
11630                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11631                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11632         }
11633
11634         PIPE_CONF_CHECK_BOOL(double_wide);
11635
11636         PIPE_CONF_CHECK_P(shared_dpll);
11637         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11638         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11639         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11640         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11641         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11642         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11643         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11644         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11645         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11646         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11647         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11648         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11649         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11650         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11651         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11652         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11653         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11654         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11655         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11656         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11657         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11658         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
11659         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
11660         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
11661         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
11662         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
11663         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
11664         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
11665         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
11666         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
11667         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
11668
11669         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11670         PIPE_CONF_CHECK_X(dsi_pll.div);
11671
11672         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11673                 PIPE_CONF_CHECK_I(pipe_bpp);
11674
11675         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11676         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11677
11678         PIPE_CONF_CHECK_I(min_voltage_level);
11679
11680 #undef PIPE_CONF_CHECK_X
11681 #undef PIPE_CONF_CHECK_I
11682 #undef PIPE_CONF_CHECK_BOOL
11683 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11684 #undef PIPE_CONF_CHECK_P
11685 #undef PIPE_CONF_CHECK_FLAGS
11686 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11687 #undef PIPE_CONF_QUIRK
11688
11689         return ret;
11690 }
11691
11692 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11693                                            const struct intel_crtc_state *pipe_config)
11694 {
11695         if (pipe_config->has_pch_encoder) {
11696                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11697                                                             &pipe_config->fdi_m_n);
11698                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11699
11700                 /*
11701                  * FDI already provided one idea for the dotclock.
11702                  * Yell if the encoder disagrees.
11703                  */
11704                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11705                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11706                      fdi_dotclock, dotclock);
11707         }
11708 }
11709
11710 static void verify_wm_state(struct drm_crtc *crtc,
11711                             struct drm_crtc_state *new_state)
11712 {
11713         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11714         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11715         struct skl_pipe_wm hw_wm, *sw_wm;
11716         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11717         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11718         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11719         const enum pipe pipe = intel_crtc->pipe;
11720         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11721
11722         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11723                 return;
11724
11725         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11726         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11727
11728         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11729         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11730
11731         if (INTEL_GEN(dev_priv) >= 11)
11732                 if (hw_ddb.enabled_slices != sw_ddb->enabled_slices)
11733                         DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
11734                                   sw_ddb->enabled_slices,
11735                                   hw_ddb.enabled_slices);
11736         /* planes */
11737         for_each_universal_plane(dev_priv, pipe, plane) {
11738                 hw_plane_wm = &hw_wm.planes[plane];
11739                 sw_plane_wm = &sw_wm->planes[plane];
11740
11741                 /* Watermarks */
11742                 for (level = 0; level <= max_level; level++) {
11743                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11744                                                 &sw_plane_wm->wm[level]))
11745                                 continue;
11746
11747                         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",
11748                                   pipe_name(pipe), plane + 1, level,
11749                                   sw_plane_wm->wm[level].plane_en,
11750                                   sw_plane_wm->wm[level].plane_res_b,
11751                                   sw_plane_wm->wm[level].plane_res_l,
11752                                   hw_plane_wm->wm[level].plane_en,
11753                                   hw_plane_wm->wm[level].plane_res_b,
11754                                   hw_plane_wm->wm[level].plane_res_l);
11755                 }
11756
11757                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11758                                          &sw_plane_wm->trans_wm)) {
11759                         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",
11760                                   pipe_name(pipe), plane + 1,
11761                                   sw_plane_wm->trans_wm.plane_en,
11762                                   sw_plane_wm->trans_wm.plane_res_b,
11763                                   sw_plane_wm->trans_wm.plane_res_l,
11764                                   hw_plane_wm->trans_wm.plane_en,
11765                                   hw_plane_wm->trans_wm.plane_res_b,
11766                                   hw_plane_wm->trans_wm.plane_res_l);
11767                 }
11768
11769                 /* DDB */
11770                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11771                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11772
11773                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11774                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11775                                   pipe_name(pipe), plane + 1,
11776                                   sw_ddb_entry->start, sw_ddb_entry->end,
11777                                   hw_ddb_entry->start, hw_ddb_entry->end);
11778                 }
11779         }
11780
11781         /*
11782          * cursor
11783          * If the cursor plane isn't active, we may not have updated it's ddb
11784          * allocation. In that case since the ddb allocation will be updated
11785          * once the plane becomes visible, we can skip this check
11786          */
11787         if (1) {
11788                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11789                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11790
11791                 /* Watermarks */
11792                 for (level = 0; level <= max_level; level++) {
11793                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11794                                                 &sw_plane_wm->wm[level]))
11795                                 continue;
11796
11797                         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",
11798                                   pipe_name(pipe), level,
11799                                   sw_plane_wm->wm[level].plane_en,
11800                                   sw_plane_wm->wm[level].plane_res_b,
11801                                   sw_plane_wm->wm[level].plane_res_l,
11802                                   hw_plane_wm->wm[level].plane_en,
11803                                   hw_plane_wm->wm[level].plane_res_b,
11804                                   hw_plane_wm->wm[level].plane_res_l);
11805                 }
11806
11807                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11808                                          &sw_plane_wm->trans_wm)) {
11809                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11810                                   pipe_name(pipe),
11811                                   sw_plane_wm->trans_wm.plane_en,
11812                                   sw_plane_wm->trans_wm.plane_res_b,
11813                                   sw_plane_wm->trans_wm.plane_res_l,
11814                                   hw_plane_wm->trans_wm.plane_en,
11815                                   hw_plane_wm->trans_wm.plane_res_b,
11816                                   hw_plane_wm->trans_wm.plane_res_l);
11817                 }
11818
11819                 /* DDB */
11820                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11821                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11822
11823                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11824                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11825                                   pipe_name(pipe),
11826                                   sw_ddb_entry->start, sw_ddb_entry->end,
11827                                   hw_ddb_entry->start, hw_ddb_entry->end);
11828                 }
11829         }
11830 }
11831
11832 static void
11833 verify_connector_state(struct drm_device *dev,
11834                        struct drm_atomic_state *state,
11835                        struct drm_crtc *crtc)
11836 {
11837         struct drm_connector *connector;
11838         struct drm_connector_state *new_conn_state;
11839         int i;
11840
11841         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11842                 struct drm_encoder *encoder = connector->encoder;
11843                 struct drm_crtc_state *crtc_state = NULL;
11844
11845                 if (new_conn_state->crtc != crtc)
11846                         continue;
11847
11848                 if (crtc)
11849                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11850
11851                 intel_connector_verify_state(crtc_state, new_conn_state);
11852
11853                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11854                      "connector's atomic encoder doesn't match legacy encoder\n");
11855         }
11856 }
11857
11858 static void
11859 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11860 {
11861         struct intel_encoder *encoder;
11862         struct drm_connector *connector;
11863         struct drm_connector_state *old_conn_state, *new_conn_state;
11864         int i;
11865
11866         for_each_intel_encoder(dev, encoder) {
11867                 bool enabled = false, found = false;
11868                 enum pipe pipe;
11869
11870                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11871                               encoder->base.base.id,
11872                               encoder->base.name);
11873
11874                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11875                                                    new_conn_state, i) {
11876                         if (old_conn_state->best_encoder == &encoder->base)
11877                                 found = true;
11878
11879                         if (new_conn_state->best_encoder != &encoder->base)
11880                                 continue;
11881                         found = enabled = true;
11882
11883                         I915_STATE_WARN(new_conn_state->crtc !=
11884                                         encoder->base.crtc,
11885                              "connector's crtc doesn't match encoder crtc\n");
11886                 }
11887
11888                 if (!found)
11889                         continue;
11890
11891                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11892                      "encoder's enabled state mismatch "
11893                      "(expected %i, found %i)\n",
11894                      !!encoder->base.crtc, enabled);
11895
11896                 if (!encoder->base.crtc) {
11897                         bool active;
11898
11899                         active = encoder->get_hw_state(encoder, &pipe);
11900                         I915_STATE_WARN(active,
11901                              "encoder detached but still enabled on pipe %c.\n",
11902                              pipe_name(pipe));
11903                 }
11904         }
11905 }
11906
11907 static void
11908 verify_crtc_state(struct drm_crtc *crtc,
11909                   struct drm_crtc_state *old_crtc_state,
11910                   struct drm_crtc_state *new_crtc_state)
11911 {
11912         struct drm_device *dev = crtc->dev;
11913         struct drm_i915_private *dev_priv = to_i915(dev);
11914         struct intel_encoder *encoder;
11915         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11916         struct intel_crtc_state *pipe_config, *sw_config;
11917         struct drm_atomic_state *old_state;
11918         bool active;
11919
11920         old_state = old_crtc_state->state;
11921         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11922         pipe_config = to_intel_crtc_state(old_crtc_state);
11923         memset(pipe_config, 0, sizeof(*pipe_config));
11924         pipe_config->base.crtc = crtc;
11925         pipe_config->base.state = old_state;
11926
11927         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11928
11929         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11930
11931         /* we keep both pipes enabled on 830 */
11932         if (IS_I830(dev_priv))
11933                 active = new_crtc_state->active;
11934
11935         I915_STATE_WARN(new_crtc_state->active != active,
11936              "crtc active state doesn't match with hw state "
11937              "(expected %i, found %i)\n", new_crtc_state->active, active);
11938
11939         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11940              "transitional active state does not match atomic hw state "
11941              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11942
11943         for_each_encoder_on_crtc(dev, crtc, encoder) {
11944                 enum pipe pipe;
11945
11946                 active = encoder->get_hw_state(encoder, &pipe);
11947                 I915_STATE_WARN(active != new_crtc_state->active,
11948                         "[ENCODER:%i] active %i with crtc active %i\n",
11949                         encoder->base.base.id, active, new_crtc_state->active);
11950
11951                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11952                                 "Encoder connected to wrong pipe %c\n",
11953                                 pipe_name(pipe));
11954
11955                 if (active)
11956                         encoder->get_config(encoder, pipe_config);
11957         }
11958
11959         intel_crtc_compute_pixel_rate(pipe_config);
11960
11961         if (!new_crtc_state->active)
11962                 return;
11963
11964         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11965
11966         sw_config = to_intel_crtc_state(new_crtc_state);
11967         if (!intel_pipe_config_compare(dev_priv, sw_config,
11968                                        pipe_config, false)) {
11969                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11970                 intel_dump_pipe_config(intel_crtc, pipe_config,
11971                                        "[hw state]");
11972                 intel_dump_pipe_config(intel_crtc, sw_config,
11973                                        "[sw state]");
11974         }
11975 }
11976
11977 static void
11978 intel_verify_planes(struct intel_atomic_state *state)
11979 {
11980         struct intel_plane *plane;
11981         const struct intel_plane_state *plane_state;
11982         int i;
11983
11984         for_each_new_intel_plane_in_state(state, plane,
11985                                           plane_state, i)
11986                 assert_plane(plane, plane_state->base.visible);
11987 }
11988
11989 static void
11990 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11991                          struct intel_shared_dpll *pll,
11992                          struct drm_crtc *crtc,
11993                          struct drm_crtc_state *new_state)
11994 {
11995         struct intel_dpll_hw_state dpll_hw_state;
11996         unsigned int crtc_mask;
11997         bool active;
11998
11999         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12000
12001         DRM_DEBUG_KMS("%s\n", pll->info->name);
12002
12003         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
12004
12005         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
12006                 I915_STATE_WARN(!pll->on && pll->active_mask,
12007                      "pll in active use but not on in sw tracking\n");
12008                 I915_STATE_WARN(pll->on && !pll->active_mask,
12009                      "pll is on but not used by any active crtc\n");
12010                 I915_STATE_WARN(pll->on != active,
12011                      "pll on state mismatch (expected %i, found %i)\n",
12012                      pll->on, active);
12013         }
12014
12015         if (!crtc) {
12016                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12017                                 "more active pll users than references: %x vs %x\n",
12018                                 pll->active_mask, pll->state.crtc_mask);
12019
12020                 return;
12021         }
12022
12023         crtc_mask = drm_crtc_mask(crtc);
12024
12025         if (new_state->active)
12026                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12027                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12028                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12029         else
12030                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12031                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12032                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12033
12034         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12035                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12036                         crtc_mask, pll->state.crtc_mask);
12037
12038         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12039                                           &dpll_hw_state,
12040                                           sizeof(dpll_hw_state)),
12041                         "pll hw state mismatch\n");
12042 }
12043
12044 static void
12045 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12046                          struct drm_crtc_state *old_crtc_state,
12047                          struct drm_crtc_state *new_crtc_state)
12048 {
12049         struct drm_i915_private *dev_priv = to_i915(dev);
12050         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12051         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12052
12053         if (new_state->shared_dpll)
12054                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12055
12056         if (old_state->shared_dpll &&
12057             old_state->shared_dpll != new_state->shared_dpll) {
12058                 unsigned int crtc_mask = drm_crtc_mask(crtc);
12059                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12060
12061                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12062                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12063                                 pipe_name(drm_crtc_index(crtc)));
12064                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12065                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12066                                 pipe_name(drm_crtc_index(crtc)));
12067         }
12068 }
12069
12070 static void
12071 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12072                           struct drm_atomic_state *state,
12073                           struct drm_crtc_state *old_state,
12074                           struct drm_crtc_state *new_state)
12075 {
12076         if (!needs_modeset(new_state) &&
12077             !to_intel_crtc_state(new_state)->update_pipe)
12078                 return;
12079
12080         verify_wm_state(crtc, new_state);
12081         verify_connector_state(crtc->dev, state, crtc);
12082         verify_crtc_state(crtc, old_state, new_state);
12083         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12084 }
12085
12086 static void
12087 verify_disabled_dpll_state(struct drm_device *dev)
12088 {
12089         struct drm_i915_private *dev_priv = to_i915(dev);
12090         int i;
12091
12092         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12093                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12094 }
12095
12096 static void
12097 intel_modeset_verify_disabled(struct drm_device *dev,
12098                               struct drm_atomic_state *state)
12099 {
12100         verify_encoder_state(dev, state);
12101         verify_connector_state(dev, state, NULL);
12102         verify_disabled_dpll_state(dev);
12103 }
12104
12105 static void update_scanline_offset(struct intel_crtc *crtc)
12106 {
12107         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12108
12109         /*
12110          * The scanline counter increments at the leading edge of hsync.
12111          *
12112          * On most platforms it starts counting from vtotal-1 on the
12113          * first active line. That means the scanline counter value is
12114          * always one less than what we would expect. Ie. just after
12115          * start of vblank, which also occurs at start of hsync (on the
12116          * last active line), the scanline counter will read vblank_start-1.
12117          *
12118          * On gen2 the scanline counter starts counting from 1 instead
12119          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12120          * to keep the value positive), instead of adding one.
12121          *
12122          * On HSW+ the behaviour of the scanline counter depends on the output
12123          * type. For DP ports it behaves like most other platforms, but on HDMI
12124          * there's an extra 1 line difference. So we need to add two instead of
12125          * one to the value.
12126          *
12127          * On VLV/CHV DSI the scanline counter would appear to increment
12128          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12129          * that means we can't tell whether we're in vblank or not while
12130          * we're on that particular line. We must still set scanline_offset
12131          * to 1 so that the vblank timestamps come out correct when we query
12132          * the scanline counter from within the vblank interrupt handler.
12133          * However if queried just before the start of vblank we'll get an
12134          * answer that's slightly in the future.
12135          */
12136         if (IS_GEN2(dev_priv)) {
12137                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
12138                 int vtotal;
12139
12140                 vtotal = adjusted_mode->crtc_vtotal;
12141                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12142                         vtotal /= 2;
12143
12144                 crtc->scanline_offset = vtotal - 1;
12145         } else if (HAS_DDI(dev_priv) &&
12146                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
12147                 crtc->scanline_offset = 2;
12148         } else
12149                 crtc->scanline_offset = 1;
12150 }
12151
12152 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12153 {
12154         struct drm_device *dev = state->dev;
12155         struct drm_i915_private *dev_priv = to_i915(dev);
12156         struct drm_crtc *crtc;
12157         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12158         int i;
12159
12160         if (!dev_priv->display.crtc_compute_clock)
12161                 return;
12162
12163         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12164                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12165                 struct intel_shared_dpll *old_dpll =
12166                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12167
12168                 if (!needs_modeset(new_crtc_state))
12169                         continue;
12170
12171                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12172
12173                 if (!old_dpll)
12174                         continue;
12175
12176                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12177         }
12178 }
12179
12180 /*
12181  * This implements the workaround described in the "notes" section of the mode
12182  * set sequence documentation. When going from no pipes or single pipe to
12183  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12184  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12185  */
12186 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12187 {
12188         struct drm_crtc_state *crtc_state;
12189         struct intel_crtc *intel_crtc;
12190         struct drm_crtc *crtc;
12191         struct intel_crtc_state *first_crtc_state = NULL;
12192         struct intel_crtc_state *other_crtc_state = NULL;
12193         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12194         int i;
12195
12196         /* look at all crtc's that are going to be enabled in during modeset */
12197         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12198                 intel_crtc = to_intel_crtc(crtc);
12199
12200                 if (!crtc_state->active || !needs_modeset(crtc_state))
12201                         continue;
12202
12203                 if (first_crtc_state) {
12204                         other_crtc_state = to_intel_crtc_state(crtc_state);
12205                         break;
12206                 } else {
12207                         first_crtc_state = to_intel_crtc_state(crtc_state);
12208                         first_pipe = intel_crtc->pipe;
12209                 }
12210         }
12211
12212         /* No workaround needed? */
12213         if (!first_crtc_state)
12214                 return 0;
12215
12216         /* w/a possibly needed, check how many crtc's are already enabled. */
12217         for_each_intel_crtc(state->dev, intel_crtc) {
12218                 struct intel_crtc_state *pipe_config;
12219
12220                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12221                 if (IS_ERR(pipe_config))
12222                         return PTR_ERR(pipe_config);
12223
12224                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12225
12226                 if (!pipe_config->base.active ||
12227                     needs_modeset(&pipe_config->base))
12228                         continue;
12229
12230                 /* 2 or more enabled crtcs means no need for w/a */
12231                 if (enabled_pipe != INVALID_PIPE)
12232                         return 0;
12233
12234                 enabled_pipe = intel_crtc->pipe;
12235         }
12236
12237         if (enabled_pipe != INVALID_PIPE)
12238                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12239         else if (other_crtc_state)
12240                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12241
12242         return 0;
12243 }
12244
12245 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12246 {
12247         struct drm_crtc *crtc;
12248
12249         /* Add all pipes to the state */
12250         for_each_crtc(state->dev, crtc) {
12251                 struct drm_crtc_state *crtc_state;
12252
12253                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12254                 if (IS_ERR(crtc_state))
12255                         return PTR_ERR(crtc_state);
12256         }
12257
12258         return 0;
12259 }
12260
12261 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12262 {
12263         struct drm_crtc *crtc;
12264
12265         /*
12266          * Add all pipes to the state, and force
12267          * a modeset on all the active ones.
12268          */
12269         for_each_crtc(state->dev, crtc) {
12270                 struct drm_crtc_state *crtc_state;
12271                 int ret;
12272
12273                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12274                 if (IS_ERR(crtc_state))
12275                         return PTR_ERR(crtc_state);
12276
12277                 if (!crtc_state->active || needs_modeset(crtc_state))
12278                         continue;
12279
12280                 crtc_state->mode_changed = true;
12281
12282                 ret = drm_atomic_add_affected_connectors(state, crtc);
12283                 if (ret)
12284                         return ret;
12285
12286                 ret = drm_atomic_add_affected_planes(state, crtc);
12287                 if (ret)
12288                         return ret;
12289         }
12290
12291         return 0;
12292 }
12293
12294 static int intel_modeset_checks(struct drm_atomic_state *state)
12295 {
12296         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12297         struct drm_i915_private *dev_priv = to_i915(state->dev);
12298         struct drm_crtc *crtc;
12299         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12300         int ret = 0, i;
12301
12302         if (!check_digital_port_conflicts(state)) {
12303                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12304                 return -EINVAL;
12305         }
12306
12307         intel_state->modeset = true;
12308         intel_state->active_crtcs = dev_priv->active_crtcs;
12309         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12310         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12311
12312         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12313                 if (new_crtc_state->active)
12314                         intel_state->active_crtcs |= 1 << i;
12315                 else
12316                         intel_state->active_crtcs &= ~(1 << i);
12317
12318                 if (old_crtc_state->active != new_crtc_state->active)
12319                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12320         }
12321
12322         /*
12323          * See if the config requires any additional preparation, e.g.
12324          * to adjust global state with pipes off.  We need to do this
12325          * here so we can get the modeset_pipe updated config for the new
12326          * mode set on this crtc.  For other crtcs we need to use the
12327          * adjusted_mode bits in the crtc directly.
12328          */
12329         if (dev_priv->display.modeset_calc_cdclk) {
12330                 ret = dev_priv->display.modeset_calc_cdclk(state);
12331                 if (ret < 0)
12332                         return ret;
12333
12334                 /*
12335                  * Writes to dev_priv->cdclk.logical must protected by
12336                  * holding all the crtc locks, even if we don't end up
12337                  * touching the hardware
12338                  */
12339                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12340                                         &intel_state->cdclk.logical)) {
12341                         ret = intel_lock_all_pipes(state);
12342                         if (ret < 0)
12343                                 return ret;
12344                 }
12345
12346                 /* All pipes must be switched off while we change the cdclk. */
12347                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12348                                               &intel_state->cdclk.actual)) {
12349                         ret = intel_modeset_all_pipes(state);
12350                         if (ret < 0)
12351                                 return ret;
12352                 }
12353
12354                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12355                               intel_state->cdclk.logical.cdclk,
12356                               intel_state->cdclk.actual.cdclk);
12357                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12358                               intel_state->cdclk.logical.voltage_level,
12359                               intel_state->cdclk.actual.voltage_level);
12360         } else {
12361                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12362         }
12363
12364         intel_modeset_clear_plls(state);
12365
12366         if (IS_HASWELL(dev_priv))
12367                 return haswell_mode_set_planes_workaround(state);
12368
12369         return 0;
12370 }
12371
12372 /*
12373  * Handle calculation of various watermark data at the end of the atomic check
12374  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12375  * handlers to ensure that all derived state has been updated.
12376  */
12377 static int calc_watermark_data(struct drm_atomic_state *state)
12378 {
12379         struct drm_device *dev = state->dev;
12380         struct drm_i915_private *dev_priv = to_i915(dev);
12381
12382         /* Is there platform-specific watermark information to calculate? */
12383         if (dev_priv->display.compute_global_watermarks)
12384                 return dev_priv->display.compute_global_watermarks(state);
12385
12386         return 0;
12387 }
12388
12389 /**
12390  * intel_atomic_check - validate state object
12391  * @dev: drm device
12392  * @state: state to validate
12393  */
12394 static int intel_atomic_check(struct drm_device *dev,
12395                               struct drm_atomic_state *state)
12396 {
12397         struct drm_i915_private *dev_priv = to_i915(dev);
12398         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12399         struct drm_crtc *crtc;
12400         struct drm_crtc_state *old_crtc_state, *crtc_state;
12401         int ret, i;
12402         bool any_ms = false;
12403
12404         /* Catch I915_MODE_FLAG_INHERITED */
12405         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12406                                       crtc_state, i) {
12407                 if (crtc_state->mode.private_flags !=
12408                     old_crtc_state->mode.private_flags)
12409                         crtc_state->mode_changed = true;
12410         }
12411
12412         ret = drm_atomic_helper_check_modeset(dev, state);
12413         if (ret)
12414                 return ret;
12415
12416         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12417                 struct intel_crtc_state *pipe_config =
12418                         to_intel_crtc_state(crtc_state);
12419
12420                 if (!needs_modeset(crtc_state))
12421                         continue;
12422
12423                 if (!crtc_state->enable) {
12424                         any_ms = true;
12425                         continue;
12426                 }
12427
12428                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12429                 if (ret) {
12430                         intel_dump_pipe_config(to_intel_crtc(crtc),
12431                                                pipe_config, "[failed]");
12432                         return ret;
12433                 }
12434
12435                 if (i915_modparams.fastboot &&
12436                     intel_pipe_config_compare(dev_priv,
12437                                         to_intel_crtc_state(old_crtc_state),
12438                                         pipe_config, true)) {
12439                         crtc_state->mode_changed = false;
12440                         pipe_config->update_pipe = true;
12441                 }
12442
12443                 if (needs_modeset(crtc_state))
12444                         any_ms = true;
12445
12446                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12447                                        needs_modeset(crtc_state) ?
12448                                        "[modeset]" : "[fastset]");
12449         }
12450
12451         if (any_ms) {
12452                 ret = intel_modeset_checks(state);
12453
12454                 if (ret)
12455                         return ret;
12456         } else {
12457                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12458         }
12459
12460         ret = drm_atomic_helper_check_planes(dev, state);
12461         if (ret)
12462                 return ret;
12463
12464         intel_fbc_choose_crtc(dev_priv, intel_state);
12465         return calc_watermark_data(state);
12466 }
12467
12468 static int intel_atomic_prepare_commit(struct drm_device *dev,
12469                                        struct drm_atomic_state *state)
12470 {
12471         return drm_atomic_helper_prepare_planes(dev, state);
12472 }
12473
12474 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12475 {
12476         struct drm_device *dev = crtc->base.dev;
12477
12478         if (!dev->max_vblank_count)
12479                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12480
12481         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12482 }
12483
12484 static void intel_update_crtc(struct drm_crtc *crtc,
12485                               struct drm_atomic_state *state,
12486                               struct drm_crtc_state *old_crtc_state,
12487                               struct drm_crtc_state *new_crtc_state)
12488 {
12489         struct drm_device *dev = crtc->dev;
12490         struct drm_i915_private *dev_priv = to_i915(dev);
12491         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12492         struct intel_crtc_state *old_intel_cstate = to_intel_crtc_state(old_crtc_state);
12493         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12494         bool modeset = needs_modeset(new_crtc_state);
12495         struct intel_plane_state *new_plane_state =
12496                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
12497                                                  to_intel_plane(crtc->primary));
12498
12499         if (modeset) {
12500                 update_scanline_offset(intel_crtc);
12501                 dev_priv->display.crtc_enable(pipe_config, state);
12502
12503                 /* vblanks work again, re-enable pipe CRC. */
12504                 intel_crtc_enable_pipe_crc(intel_crtc);
12505         } else {
12506                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12507                                        pipe_config);
12508         }
12509
12510         if (new_plane_state)
12511                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
12512
12513         intel_begin_crtc_commit(crtc, old_crtc_state);
12514
12515         intel_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc,
12516                                     old_intel_cstate, pipe_config);
12517
12518         intel_finish_crtc_commit(crtc, old_crtc_state);
12519 }
12520
12521 static void intel_update_crtcs(struct drm_atomic_state *state)
12522 {
12523         struct drm_crtc *crtc;
12524         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12525         int i;
12526
12527         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12528                 if (!new_crtc_state->active)
12529                         continue;
12530
12531                 intel_update_crtc(crtc, state, old_crtc_state,
12532                                   new_crtc_state);
12533         }
12534 }
12535
12536 static void skl_update_crtcs(struct drm_atomic_state *state)
12537 {
12538         struct drm_i915_private *dev_priv = to_i915(state->dev);
12539         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12540         struct drm_crtc *crtc;
12541         struct intel_crtc *intel_crtc;
12542         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12543         struct intel_crtc_state *cstate;
12544         unsigned int updated = 0;
12545         bool progress;
12546         enum pipe pipe;
12547         int i;
12548         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
12549         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
12550
12551         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12552
12553         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12554                 /* ignore allocations for crtc's that have been turned off. */
12555                 if (new_crtc_state->active)
12556                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12557
12558         /* If 2nd DBuf slice required, enable it here */
12559         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
12560                 icl_dbuf_slices_update(dev_priv, required_slices);
12561
12562         /*
12563          * Whenever the number of active pipes changes, we need to make sure we
12564          * update the pipes in the right order so that their ddb allocations
12565          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12566          * cause pipe underruns and other bad stuff.
12567          */
12568         do {
12569                 progress = false;
12570
12571                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12572                         bool vbl_wait = false;
12573                         unsigned int cmask = drm_crtc_mask(crtc);
12574
12575                         intel_crtc = to_intel_crtc(crtc);
12576                         cstate = to_intel_crtc_state(new_crtc_state);
12577                         pipe = intel_crtc->pipe;
12578
12579                         if (updated & cmask || !cstate->base.active)
12580                                 continue;
12581
12582                         if (skl_ddb_allocation_overlaps(dev_priv,
12583                                                         entries,
12584                                                         &cstate->wm.skl.ddb,
12585                                                         i))
12586                                 continue;
12587
12588                         updated |= cmask;
12589                         entries[i] = &cstate->wm.skl.ddb;
12590
12591                         /*
12592                          * If this is an already active pipe, it's DDB changed,
12593                          * and this isn't the last pipe that needs updating
12594                          * then we need to wait for a vblank to pass for the
12595                          * new ddb allocation to take effect.
12596                          */
12597                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12598                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12599                             !new_crtc_state->active_changed &&
12600                             intel_state->wm_results.dirty_pipes != updated)
12601                                 vbl_wait = true;
12602
12603                         intel_update_crtc(crtc, state, old_crtc_state,
12604                                           new_crtc_state);
12605
12606                         if (vbl_wait)
12607                                 intel_wait_for_vblank(dev_priv, pipe);
12608
12609                         progress = true;
12610                 }
12611         } while (progress);
12612
12613         /* If 2nd DBuf slice is no more required disable it */
12614         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
12615                 icl_dbuf_slices_update(dev_priv, required_slices);
12616 }
12617
12618 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12619 {
12620         struct intel_atomic_state *state, *next;
12621         struct llist_node *freed;
12622
12623         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12624         llist_for_each_entry_safe(state, next, freed, freed)
12625                 drm_atomic_state_put(&state->base);
12626 }
12627
12628 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12629 {
12630         struct drm_i915_private *dev_priv =
12631                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12632
12633         intel_atomic_helper_free_state(dev_priv);
12634 }
12635
12636 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12637 {
12638         struct wait_queue_entry wait_fence, wait_reset;
12639         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12640
12641         init_wait_entry(&wait_fence, 0);
12642         init_wait_entry(&wait_reset, 0);
12643         for (;;) {
12644                 prepare_to_wait(&intel_state->commit_ready.wait,
12645                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12646                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12647                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12648
12649
12650                 if (i915_sw_fence_done(&intel_state->commit_ready)
12651                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12652                         break;
12653
12654                 schedule();
12655         }
12656         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12657         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12658 }
12659
12660 static void intel_atomic_cleanup_work(struct work_struct *work)
12661 {
12662         struct drm_atomic_state *state =
12663                 container_of(work, struct drm_atomic_state, commit_work);
12664         struct drm_i915_private *i915 = to_i915(state->dev);
12665
12666         drm_atomic_helper_cleanup_planes(&i915->drm, state);
12667         drm_atomic_helper_commit_cleanup_done(state);
12668         drm_atomic_state_put(state);
12669
12670         intel_atomic_helper_free_state(i915);
12671 }
12672
12673 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12674 {
12675         struct drm_device *dev = state->dev;
12676         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12677         struct drm_i915_private *dev_priv = to_i915(dev);
12678         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12679         struct intel_crtc_state *new_intel_crtc_state, *old_intel_crtc_state;
12680         struct drm_crtc *crtc;
12681         struct intel_crtc *intel_crtc;
12682         u64 put_domains[I915_MAX_PIPES] = {};
12683         int i;
12684
12685         intel_atomic_commit_fence_wait(intel_state);
12686
12687         drm_atomic_helper_wait_for_dependencies(state);
12688
12689         if (intel_state->modeset)
12690                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12691
12692         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12693                 old_intel_crtc_state = to_intel_crtc_state(old_crtc_state);
12694                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
12695                 intel_crtc = to_intel_crtc(crtc);
12696
12697                 if (needs_modeset(new_crtc_state) ||
12698                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12699
12700                         put_domains[intel_crtc->pipe] =
12701                                 modeset_get_crtc_power_domains(crtc,
12702                                         new_intel_crtc_state);
12703                 }
12704
12705                 if (!needs_modeset(new_crtc_state))
12706                         continue;
12707
12708                 intel_pre_plane_update(old_intel_crtc_state, new_intel_crtc_state);
12709
12710                 if (old_crtc_state->active) {
12711                         intel_crtc_disable_planes(intel_crtc, old_intel_crtc_state->active_planes);
12712
12713                         /*
12714                          * We need to disable pipe CRC before disabling the pipe,
12715                          * or we race against vblank off.
12716                          */
12717                         intel_crtc_disable_pipe_crc(intel_crtc);
12718
12719                         dev_priv->display.crtc_disable(old_intel_crtc_state, state);
12720                         intel_crtc->active = false;
12721                         intel_fbc_disable(intel_crtc);
12722                         intel_disable_shared_dpll(old_intel_crtc_state);
12723
12724                         /*
12725                          * Underruns don't always raise
12726                          * interrupts, so check manually.
12727                          */
12728                         intel_check_cpu_fifo_underruns(dev_priv);
12729                         intel_check_pch_fifo_underruns(dev_priv);
12730
12731                         if (!new_crtc_state->active) {
12732                                 /*
12733                                  * Make sure we don't call initial_watermarks
12734                                  * for ILK-style watermark updates.
12735                                  *
12736                                  * No clue what this is supposed to achieve.
12737                                  */
12738                                 if (INTEL_GEN(dev_priv) >= 9)
12739                                         dev_priv->display.initial_watermarks(intel_state,
12740                                                                              new_intel_crtc_state);
12741                         }
12742                 }
12743         }
12744
12745         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12746         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12747                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12748
12749         if (intel_state->modeset) {
12750                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12751
12752                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12753
12754                 /*
12755                  * SKL workaround: bspec recommends we disable the SAGV when we
12756                  * have more then one pipe enabled
12757                  */
12758                 if (!intel_can_enable_sagv(state))
12759                         intel_disable_sagv(dev_priv);
12760
12761                 intel_modeset_verify_disabled(dev, state);
12762         }
12763
12764         /* Complete the events for pipes that have now been disabled */
12765         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12766                 bool modeset = needs_modeset(new_crtc_state);
12767
12768                 /* Complete events for now disable pipes here. */
12769                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12770                         spin_lock_irq(&dev->event_lock);
12771                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12772                         spin_unlock_irq(&dev->event_lock);
12773
12774                         new_crtc_state->event = NULL;
12775                 }
12776         }
12777
12778         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12779         dev_priv->display.update_crtcs(state);
12780
12781         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12782          * already, but still need the state for the delayed optimization. To
12783          * fix this:
12784          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12785          * - schedule that vblank worker _before_ calling hw_done
12786          * - at the start of commit_tail, cancel it _synchrously
12787          * - switch over to the vblank wait helper in the core after that since
12788          *   we don't need out special handling any more.
12789          */
12790         drm_atomic_helper_wait_for_flip_done(dev, state);
12791
12792         /*
12793          * Now that the vblank has passed, we can go ahead and program the
12794          * optimal watermarks on platforms that need two-step watermark
12795          * programming.
12796          *
12797          * TODO: Move this (and other cleanup) to an async worker eventually.
12798          */
12799         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12800                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
12801
12802                 if (dev_priv->display.optimize_watermarks)
12803                         dev_priv->display.optimize_watermarks(intel_state,
12804                                                               new_intel_crtc_state);
12805         }
12806
12807         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12808                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12809
12810                 if (put_domains[i])
12811                         modeset_put_power_domains(dev_priv, put_domains[i]);
12812
12813                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12814         }
12815
12816         if (intel_state->modeset)
12817                 intel_verify_planes(intel_state);
12818
12819         if (intel_state->modeset && intel_can_enable_sagv(state))
12820                 intel_enable_sagv(dev_priv);
12821
12822         drm_atomic_helper_commit_hw_done(state);
12823
12824         if (intel_state->modeset) {
12825                 /* As one of the primary mmio accessors, KMS has a high
12826                  * likelihood of triggering bugs in unclaimed access. After we
12827                  * finish modesetting, see if an error has been flagged, and if
12828                  * so enable debugging for the next modeset - and hope we catch
12829                  * the culprit.
12830                  */
12831                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12832                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12833         }
12834
12835         /*
12836          * Defer the cleanup of the old state to a separate worker to not
12837          * impede the current task (userspace for blocking modesets) that
12838          * are executed inline. For out-of-line asynchronous modesets/flips,
12839          * deferring to a new worker seems overkill, but we would place a
12840          * schedule point (cond_resched()) here anyway to keep latencies
12841          * down.
12842          */
12843         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
12844         queue_work(system_highpri_wq, &state->commit_work);
12845 }
12846
12847 static void intel_atomic_commit_work(struct work_struct *work)
12848 {
12849         struct drm_atomic_state *state =
12850                 container_of(work, struct drm_atomic_state, commit_work);
12851
12852         intel_atomic_commit_tail(state);
12853 }
12854
12855 static int __i915_sw_fence_call
12856 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12857                           enum i915_sw_fence_notify notify)
12858 {
12859         struct intel_atomic_state *state =
12860                 container_of(fence, struct intel_atomic_state, commit_ready);
12861
12862         switch (notify) {
12863         case FENCE_COMPLETE:
12864                 /* we do blocking waits in the worker, nothing to do here */
12865                 break;
12866         case FENCE_FREE:
12867                 {
12868                         struct intel_atomic_helper *helper =
12869                                 &to_i915(state->base.dev)->atomic_helper;
12870
12871                         if (llist_add(&state->freed, &helper->free_list))
12872                                 schedule_work(&helper->free_work);
12873                         break;
12874                 }
12875         }
12876
12877         return NOTIFY_DONE;
12878 }
12879
12880 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12881 {
12882         struct drm_plane_state *old_plane_state, *new_plane_state;
12883         struct drm_plane *plane;
12884         int i;
12885
12886         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12887                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12888                                   intel_fb_obj(new_plane_state->fb),
12889                                   to_intel_plane(plane)->frontbuffer_bit);
12890 }
12891
12892 /**
12893  * intel_atomic_commit - commit validated state object
12894  * @dev: DRM device
12895  * @state: the top-level driver state object
12896  * @nonblock: nonblocking commit
12897  *
12898  * This function commits a top-level state object that has been validated
12899  * with drm_atomic_helper_check().
12900  *
12901  * RETURNS
12902  * Zero for success or -errno.
12903  */
12904 static int intel_atomic_commit(struct drm_device *dev,
12905                                struct drm_atomic_state *state,
12906                                bool nonblock)
12907 {
12908         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12909         struct drm_i915_private *dev_priv = to_i915(dev);
12910         int ret = 0;
12911
12912         drm_atomic_state_get(state);
12913         i915_sw_fence_init(&intel_state->commit_ready,
12914                            intel_atomic_commit_ready);
12915
12916         /*
12917          * The intel_legacy_cursor_update() fast path takes care
12918          * of avoiding the vblank waits for simple cursor
12919          * movement and flips. For cursor on/off and size changes,
12920          * we want to perform the vblank waits so that watermark
12921          * updates happen during the correct frames. Gen9+ have
12922          * double buffered watermarks and so shouldn't need this.
12923          *
12924          * Unset state->legacy_cursor_update before the call to
12925          * drm_atomic_helper_setup_commit() because otherwise
12926          * drm_atomic_helper_wait_for_flip_done() is a noop and
12927          * we get FIFO underruns because we didn't wait
12928          * for vblank.
12929          *
12930          * FIXME doing watermarks and fb cleanup from a vblank worker
12931          * (assuming we had any) would solve these problems.
12932          */
12933         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12934                 struct intel_crtc_state *new_crtc_state;
12935                 struct intel_crtc *crtc;
12936                 int i;
12937
12938                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12939                         if (new_crtc_state->wm.need_postvbl_update ||
12940                             new_crtc_state->update_wm_post)
12941                                 state->legacy_cursor_update = false;
12942         }
12943
12944         ret = intel_atomic_prepare_commit(dev, state);
12945         if (ret) {
12946                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12947                 i915_sw_fence_commit(&intel_state->commit_ready);
12948                 return ret;
12949         }
12950
12951         ret = drm_atomic_helper_setup_commit(state, nonblock);
12952         if (!ret)
12953                 ret = drm_atomic_helper_swap_state(state, true);
12954
12955         if (ret) {
12956                 i915_sw_fence_commit(&intel_state->commit_ready);
12957
12958                 drm_atomic_helper_cleanup_planes(dev, state);
12959                 return ret;
12960         }
12961         dev_priv->wm.distrust_bios_wm = false;
12962         intel_shared_dpll_swap_state(state);
12963         intel_atomic_track_fbs(state);
12964
12965         if (intel_state->modeset) {
12966                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12967                        sizeof(intel_state->min_cdclk));
12968                 memcpy(dev_priv->min_voltage_level,
12969                        intel_state->min_voltage_level,
12970                        sizeof(intel_state->min_voltage_level));
12971                 dev_priv->active_crtcs = intel_state->active_crtcs;
12972                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12973                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12974         }
12975
12976         drm_atomic_state_get(state);
12977         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12978
12979         i915_sw_fence_commit(&intel_state->commit_ready);
12980         if (nonblock && intel_state->modeset) {
12981                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12982         } else if (nonblock) {
12983                 queue_work(system_unbound_wq, &state->commit_work);
12984         } else {
12985                 if (intel_state->modeset)
12986                         flush_workqueue(dev_priv->modeset_wq);
12987                 intel_atomic_commit_tail(state);
12988         }
12989
12990         return 0;
12991 }
12992
12993 static const struct drm_crtc_funcs intel_crtc_funcs = {
12994         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12995         .set_config = drm_atomic_helper_set_config,
12996         .destroy = intel_crtc_destroy,
12997         .page_flip = drm_atomic_helper_page_flip,
12998         .atomic_duplicate_state = intel_crtc_duplicate_state,
12999         .atomic_destroy_state = intel_crtc_destroy_state,
13000         .set_crc_source = intel_crtc_set_crc_source,
13001         .verify_crc_source = intel_crtc_verify_crc_source,
13002         .get_crc_sources = intel_crtc_get_crc_sources,
13003 };
13004
13005 struct wait_rps_boost {
13006         struct wait_queue_entry wait;
13007
13008         struct drm_crtc *crtc;
13009         struct i915_request *request;
13010 };
13011
13012 static int do_rps_boost(struct wait_queue_entry *_wait,
13013                         unsigned mode, int sync, void *key)
13014 {
13015         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
13016         struct i915_request *rq = wait->request;
13017
13018         /*
13019          * If we missed the vblank, but the request is already running it
13020          * is reasonable to assume that it will complete before the next
13021          * vblank without our intervention, so leave RPS alone.
13022          */
13023         if (!i915_request_started(rq))
13024                 gen6_rps_boost(rq, NULL);
13025         i915_request_put(rq);
13026
13027         drm_crtc_vblank_put(wait->crtc);
13028
13029         list_del(&wait->wait.entry);
13030         kfree(wait);
13031         return 1;
13032 }
13033
13034 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
13035                                        struct dma_fence *fence)
13036 {
13037         struct wait_rps_boost *wait;
13038
13039         if (!dma_fence_is_i915(fence))
13040                 return;
13041
13042         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
13043                 return;
13044
13045         if (drm_crtc_vblank_get(crtc))
13046                 return;
13047
13048         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
13049         if (!wait) {
13050                 drm_crtc_vblank_put(crtc);
13051                 return;
13052         }
13053
13054         wait->request = to_request(dma_fence_get(fence));
13055         wait->crtc = crtc;
13056
13057         wait->wait.func = do_rps_boost;
13058         wait->wait.flags = 0;
13059
13060         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
13061 }
13062
13063 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
13064 {
13065         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
13066         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13067         struct drm_framebuffer *fb = plane_state->base.fb;
13068         struct i915_vma *vma;
13069
13070         if (plane->id == PLANE_CURSOR &&
13071             INTEL_INFO(dev_priv)->cursor_needs_physical) {
13072                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13073                 const int align = intel_cursor_alignment(dev_priv);
13074                 int err;
13075
13076                 err = i915_gem_object_attach_phys(obj, align);
13077                 if (err)
13078                         return err;
13079         }
13080
13081         vma = intel_pin_and_fence_fb_obj(fb,
13082                                          &plane_state->view,
13083                                          intel_plane_uses_fence(plane_state),
13084                                          &plane_state->flags);
13085         if (IS_ERR(vma))
13086                 return PTR_ERR(vma);
13087
13088         plane_state->vma = vma;
13089
13090         return 0;
13091 }
13092
13093 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
13094 {
13095         struct i915_vma *vma;
13096
13097         vma = fetch_and_zero(&old_plane_state->vma);
13098         if (vma)
13099                 intel_unpin_fb_vma(vma, old_plane_state->flags);
13100 }
13101
13102 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
13103 {
13104         struct i915_sched_attr attr = {
13105                 .priority = I915_PRIORITY_DISPLAY,
13106         };
13107
13108         i915_gem_object_wait_priority(obj, 0, &attr);
13109 }
13110
13111 /**
13112  * intel_prepare_plane_fb - Prepare fb for usage on plane
13113  * @plane: drm plane to prepare for
13114  * @new_state: the plane state being prepared
13115  *
13116  * Prepares a framebuffer for usage on a display plane.  Generally this
13117  * involves pinning the underlying object and updating the frontbuffer tracking
13118  * bits.  Some older platforms need special physical address handling for
13119  * cursor planes.
13120  *
13121  * Must be called with struct_mutex held.
13122  *
13123  * Returns 0 on success, negative error code on failure.
13124  */
13125 int
13126 intel_prepare_plane_fb(struct drm_plane *plane,
13127                        struct drm_plane_state *new_state)
13128 {
13129         struct intel_atomic_state *intel_state =
13130                 to_intel_atomic_state(new_state->state);
13131         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13132         struct drm_framebuffer *fb = new_state->fb;
13133         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13134         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13135         int ret;
13136
13137         if (old_obj) {
13138                 struct drm_crtc_state *crtc_state =
13139                         drm_atomic_get_new_crtc_state(new_state->state,
13140                                                       plane->state->crtc);
13141
13142                 /* Big Hammer, we also need to ensure that any pending
13143                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13144                  * current scanout is retired before unpinning the old
13145                  * framebuffer. Note that we rely on userspace rendering
13146                  * into the buffer attached to the pipe they are waiting
13147                  * on. If not, userspace generates a GPU hang with IPEHR
13148                  * point to the MI_WAIT_FOR_EVENT.
13149                  *
13150                  * This should only fail upon a hung GPU, in which case we
13151                  * can safely continue.
13152                  */
13153                 if (needs_modeset(crtc_state)) {
13154                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13155                                                               old_obj->resv, NULL,
13156                                                               false, 0,
13157                                                               GFP_KERNEL);
13158                         if (ret < 0)
13159                                 return ret;
13160                 }
13161         }
13162
13163         if (new_state->fence) { /* explicit fencing */
13164                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13165                                                     new_state->fence,
13166                                                     I915_FENCE_TIMEOUT,
13167                                                     GFP_KERNEL);
13168                 if (ret < 0)
13169                         return ret;
13170         }
13171
13172         if (!obj)
13173                 return 0;
13174
13175         ret = i915_gem_object_pin_pages(obj);
13176         if (ret)
13177                 return ret;
13178
13179         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13180         if (ret) {
13181                 i915_gem_object_unpin_pages(obj);
13182                 return ret;
13183         }
13184
13185         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
13186
13187         mutex_unlock(&dev_priv->drm.struct_mutex);
13188         i915_gem_object_unpin_pages(obj);
13189         if (ret)
13190                 return ret;
13191
13192         fb_obj_bump_render_priority(obj);
13193         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13194
13195         if (!new_state->fence) { /* implicit fencing */
13196                 struct dma_fence *fence;
13197
13198                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13199                                                       obj->resv, NULL,
13200                                                       false, I915_FENCE_TIMEOUT,
13201                                                       GFP_KERNEL);
13202                 if (ret < 0)
13203                         return ret;
13204
13205                 fence = reservation_object_get_excl_rcu(obj->resv);
13206                 if (fence) {
13207                         add_rps_boost_after_vblank(new_state->crtc, fence);
13208                         dma_fence_put(fence);
13209                 }
13210         } else {
13211                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
13212         }
13213
13214         /*
13215          * We declare pageflips to be interactive and so merit a small bias
13216          * towards upclocking to deliver the frame on time. By only changing
13217          * the RPS thresholds to sample more regularly and aim for higher
13218          * clocks we can hopefully deliver low power workloads (like kodi)
13219          * that are not quite steady state without resorting to forcing
13220          * maximum clocks following a vblank miss (see do_rps_boost()).
13221          */
13222         if (!intel_state->rps_interactive) {
13223                 intel_rps_mark_interactive(dev_priv, true);
13224                 intel_state->rps_interactive = true;
13225         }
13226
13227         return 0;
13228 }
13229
13230 /**
13231  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13232  * @plane: drm plane to clean up for
13233  * @old_state: the state from the previous modeset
13234  *
13235  * Cleans up a framebuffer that has just been removed from a plane.
13236  *
13237  * Must be called with struct_mutex held.
13238  */
13239 void
13240 intel_cleanup_plane_fb(struct drm_plane *plane,
13241                        struct drm_plane_state *old_state)
13242 {
13243         struct intel_atomic_state *intel_state =
13244                 to_intel_atomic_state(old_state->state);
13245         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13246
13247         if (intel_state->rps_interactive) {
13248                 intel_rps_mark_interactive(dev_priv, false);
13249                 intel_state->rps_interactive = false;
13250         }
13251
13252         /* Should only be called after a successful intel_prepare_plane_fb()! */
13253         mutex_lock(&dev_priv->drm.struct_mutex);
13254         intel_plane_unpin_fb(to_intel_plane_state(old_state));
13255         mutex_unlock(&dev_priv->drm.struct_mutex);
13256 }
13257
13258 int
13259 skl_max_scale(const struct intel_crtc_state *crtc_state,
13260               u32 pixel_format)
13261 {
13262         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
13263         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13264         int max_scale, mult;
13265         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
13266
13267         if (!crtc_state->base.enable)
13268                 return DRM_PLANE_HELPER_NO_SCALING;
13269
13270         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13271         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13272
13273         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
13274                 max_dotclk *= 2;
13275
13276         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13277                 return DRM_PLANE_HELPER_NO_SCALING;
13278
13279         /*
13280          * skl max scale is lower of:
13281          *    close to 3 but not 3, -1 is for that purpose
13282          *            or
13283          *    cdclk/crtc_clock
13284          */
13285         mult = pixel_format == DRM_FORMAT_NV12 ? 2 : 3;
13286         tmpclk1 = (1 << 16) * mult - 1;
13287         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
13288         max_scale = min(tmpclk1, tmpclk2);
13289
13290         return max_scale;
13291 }
13292
13293 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13294                                     struct drm_crtc_state *old_crtc_state)
13295 {
13296         struct drm_device *dev = crtc->dev;
13297         struct drm_i915_private *dev_priv = to_i915(dev);
13298         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13299         struct intel_crtc_state *old_intel_cstate =
13300                 to_intel_crtc_state(old_crtc_state);
13301         struct intel_atomic_state *old_intel_state =
13302                 to_intel_atomic_state(old_crtc_state->state);
13303         struct intel_crtc_state *intel_cstate =
13304                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13305         bool modeset = needs_modeset(&intel_cstate->base);
13306
13307         if (!modeset &&
13308             (intel_cstate->base.color_mgmt_changed ||
13309              intel_cstate->update_pipe)) {
13310                 intel_color_set_csc(&intel_cstate->base);
13311                 intel_color_load_luts(&intel_cstate->base);
13312         }
13313
13314         /* Perform vblank evasion around commit operation */
13315         intel_pipe_update_start(intel_cstate);
13316
13317         if (modeset)
13318                 goto out;
13319
13320         if (intel_cstate->update_pipe)
13321                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
13322         else if (INTEL_GEN(dev_priv) >= 9)
13323                 skl_detach_scalers(intel_cstate);
13324
13325 out:
13326         if (dev_priv->display.atomic_update_watermarks)
13327                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13328                                                            intel_cstate);
13329 }
13330
13331 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
13332                                   struct intel_crtc_state *crtc_state)
13333 {
13334         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13335
13336         if (!IS_GEN2(dev_priv))
13337                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
13338
13339         if (crtc_state->has_pch_encoder) {
13340                 enum pipe pch_transcoder =
13341                         intel_crtc_pch_transcoder(crtc);
13342
13343                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13344         }
13345 }
13346
13347 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13348                                      struct drm_crtc_state *old_crtc_state)
13349 {
13350         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13351         struct intel_atomic_state *old_intel_state =
13352                 to_intel_atomic_state(old_crtc_state->state);
13353         struct intel_crtc_state *new_crtc_state =
13354                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13355
13356         intel_pipe_update_end(new_crtc_state);
13357
13358         if (new_crtc_state->update_pipe &&
13359             !needs_modeset(&new_crtc_state->base) &&
13360             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED)
13361                 intel_crtc_arm_fifo_underrun(intel_crtc, new_crtc_state);
13362 }
13363
13364 /**
13365  * intel_plane_destroy - destroy a plane
13366  * @plane: plane to destroy
13367  *
13368  * Common destruction function for all types of planes (primary, cursor,
13369  * sprite).
13370  */
13371 void intel_plane_destroy(struct drm_plane *plane)
13372 {
13373         drm_plane_cleanup(plane);
13374         kfree(to_intel_plane(plane));
13375 }
13376
13377 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
13378                                             u32 format, u64 modifier)
13379 {
13380         switch (modifier) {
13381         case DRM_FORMAT_MOD_LINEAR:
13382         case I915_FORMAT_MOD_X_TILED:
13383                 break;
13384         default:
13385                 return false;
13386         }
13387
13388         switch (format) {
13389         case DRM_FORMAT_C8:
13390         case DRM_FORMAT_RGB565:
13391         case DRM_FORMAT_XRGB1555:
13392         case DRM_FORMAT_XRGB8888:
13393                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13394                         modifier == I915_FORMAT_MOD_X_TILED;
13395         default:
13396                 return false;
13397         }
13398 }
13399
13400 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
13401                                             u32 format, u64 modifier)
13402 {
13403         switch (modifier) {
13404         case DRM_FORMAT_MOD_LINEAR:
13405         case I915_FORMAT_MOD_X_TILED:
13406                 break;
13407         default:
13408                 return false;
13409         }
13410
13411         switch (format) {
13412         case DRM_FORMAT_C8:
13413         case DRM_FORMAT_RGB565:
13414         case DRM_FORMAT_XRGB8888:
13415         case DRM_FORMAT_XBGR8888:
13416         case DRM_FORMAT_XRGB2101010:
13417         case DRM_FORMAT_XBGR2101010:
13418                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13419                         modifier == I915_FORMAT_MOD_X_TILED;
13420         default:
13421                 return false;
13422         }
13423 }
13424
13425 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
13426                                               u32 format, u64 modifier)
13427 {
13428         return modifier == DRM_FORMAT_MOD_LINEAR &&
13429                 format == DRM_FORMAT_ARGB8888;
13430 }
13431
13432 static const struct drm_plane_funcs i965_plane_funcs = {
13433         .update_plane = drm_atomic_helper_update_plane,
13434         .disable_plane = drm_atomic_helper_disable_plane,
13435         .destroy = intel_plane_destroy,
13436         .atomic_get_property = intel_plane_atomic_get_property,
13437         .atomic_set_property = intel_plane_atomic_set_property,
13438         .atomic_duplicate_state = intel_plane_duplicate_state,
13439         .atomic_destroy_state = intel_plane_destroy_state,
13440         .format_mod_supported = i965_plane_format_mod_supported,
13441 };
13442
13443 static const struct drm_plane_funcs i8xx_plane_funcs = {
13444         .update_plane = drm_atomic_helper_update_plane,
13445         .disable_plane = drm_atomic_helper_disable_plane,
13446         .destroy = intel_plane_destroy,
13447         .atomic_get_property = intel_plane_atomic_get_property,
13448         .atomic_set_property = intel_plane_atomic_set_property,
13449         .atomic_duplicate_state = intel_plane_duplicate_state,
13450         .atomic_destroy_state = intel_plane_destroy_state,
13451         .format_mod_supported = i8xx_plane_format_mod_supported,
13452 };
13453
13454 static int
13455 intel_legacy_cursor_update(struct drm_plane *plane,
13456                            struct drm_crtc *crtc,
13457                            struct drm_framebuffer *fb,
13458                            int crtc_x, int crtc_y,
13459                            unsigned int crtc_w, unsigned int crtc_h,
13460                            uint32_t src_x, uint32_t src_y,
13461                            uint32_t src_w, uint32_t src_h,
13462                            struct drm_modeset_acquire_ctx *ctx)
13463 {
13464         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13465         int ret;
13466         struct drm_plane_state *old_plane_state, *new_plane_state;
13467         struct intel_plane *intel_plane = to_intel_plane(plane);
13468         struct drm_framebuffer *old_fb;
13469         struct intel_crtc_state *crtc_state =
13470                 to_intel_crtc_state(crtc->state);
13471         struct intel_crtc_state *new_crtc_state;
13472
13473         /*
13474          * When crtc is inactive or there is a modeset pending,
13475          * wait for it to complete in the slowpath
13476          */
13477         if (!crtc_state->base.active || needs_modeset(&crtc_state->base) ||
13478             crtc_state->update_pipe)
13479                 goto slow;
13480
13481         old_plane_state = plane->state;
13482         /*
13483          * Don't do an async update if there is an outstanding commit modifying
13484          * the plane.  This prevents our async update's changes from getting
13485          * overridden by a previous synchronous update's state.
13486          */
13487         if (old_plane_state->commit &&
13488             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13489                 goto slow;
13490
13491         /*
13492          * If any parameters change that may affect watermarks,
13493          * take the slowpath. Only changing fb or position should be
13494          * in the fastpath.
13495          */
13496         if (old_plane_state->crtc != crtc ||
13497             old_plane_state->src_w != src_w ||
13498             old_plane_state->src_h != src_h ||
13499             old_plane_state->crtc_w != crtc_w ||
13500             old_plane_state->crtc_h != crtc_h ||
13501             !old_plane_state->fb != !fb)
13502                 goto slow;
13503
13504         new_plane_state = intel_plane_duplicate_state(plane);
13505         if (!new_plane_state)
13506                 return -ENOMEM;
13507
13508         new_crtc_state = to_intel_crtc_state(intel_crtc_duplicate_state(crtc));
13509         if (!new_crtc_state) {
13510                 ret = -ENOMEM;
13511                 goto out_free;
13512         }
13513
13514         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13515
13516         new_plane_state->src_x = src_x;
13517         new_plane_state->src_y = src_y;
13518         new_plane_state->src_w = src_w;
13519         new_plane_state->src_h = src_h;
13520         new_plane_state->crtc_x = crtc_x;
13521         new_plane_state->crtc_y = crtc_y;
13522         new_plane_state->crtc_w = crtc_w;
13523         new_plane_state->crtc_h = crtc_h;
13524
13525         ret = intel_plane_atomic_check_with_state(crtc_state, new_crtc_state,
13526                                                   to_intel_plane_state(old_plane_state),
13527                                                   to_intel_plane_state(new_plane_state));
13528         if (ret)
13529                 goto out_free;
13530
13531         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13532         if (ret)
13533                 goto out_free;
13534
13535         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13536         if (ret)
13537                 goto out_unlock;
13538
13539         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13540
13541         old_fb = old_plane_state->fb;
13542         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13543                           intel_plane->frontbuffer_bit);
13544
13545         /* Swap plane state */
13546         plane->state = new_plane_state;
13547
13548         /*
13549          * We cannot swap crtc_state as it may be in use by an atomic commit or
13550          * page flip that's running simultaneously. If we swap crtc_state and
13551          * destroy the old state, we will cause a use-after-free there.
13552          *
13553          * Only update active_planes, which is needed for our internal
13554          * bookkeeping. Either value will do the right thing when updating
13555          * planes atomically. If the cursor was part of the atomic update then
13556          * we would have taken the slowpath.
13557          */
13558         crtc_state->active_planes = new_crtc_state->active_planes;
13559
13560         if (plane->state->visible) {
13561                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13562                 intel_plane->update_plane(intel_plane, crtc_state,
13563                                           to_intel_plane_state(plane->state));
13564         } else {
13565                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13566                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13567         }
13568
13569         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13570
13571 out_unlock:
13572         mutex_unlock(&dev_priv->drm.struct_mutex);
13573 out_free:
13574         if (new_crtc_state)
13575                 intel_crtc_destroy_state(crtc, &new_crtc_state->base);
13576         if (ret)
13577                 intel_plane_destroy_state(plane, new_plane_state);
13578         else
13579                 intel_plane_destroy_state(plane, old_plane_state);
13580         return ret;
13581
13582 slow:
13583         return drm_atomic_helper_update_plane(plane, crtc, fb,
13584                                               crtc_x, crtc_y, crtc_w, crtc_h,
13585                                               src_x, src_y, src_w, src_h, ctx);
13586 }
13587
13588 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13589         .update_plane = intel_legacy_cursor_update,
13590         .disable_plane = drm_atomic_helper_disable_plane,
13591         .destroy = intel_plane_destroy,
13592         .atomic_get_property = intel_plane_atomic_get_property,
13593         .atomic_set_property = intel_plane_atomic_set_property,
13594         .atomic_duplicate_state = intel_plane_duplicate_state,
13595         .atomic_destroy_state = intel_plane_destroy_state,
13596         .format_mod_supported = intel_cursor_format_mod_supported,
13597 };
13598
13599 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13600                                enum i9xx_plane_id i9xx_plane)
13601 {
13602         if (!HAS_FBC(dev_priv))
13603                 return false;
13604
13605         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13606                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13607         else if (IS_IVYBRIDGE(dev_priv))
13608                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13609                         i9xx_plane == PLANE_C;
13610         else if (INTEL_GEN(dev_priv) >= 4)
13611                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13612         else
13613                 return i9xx_plane == PLANE_A;
13614 }
13615
13616 static struct intel_plane *
13617 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13618 {
13619         struct intel_plane *plane;
13620         const struct drm_plane_funcs *plane_funcs;
13621         unsigned int supported_rotations;
13622         unsigned int possible_crtcs;
13623         const u64 *modifiers;
13624         const u32 *formats;
13625         int num_formats;
13626         int ret;
13627
13628         if (INTEL_GEN(dev_priv) >= 9)
13629                 return skl_universal_plane_create(dev_priv, pipe,
13630                                                   PLANE_PRIMARY);
13631
13632         plane = intel_plane_alloc();
13633         if (IS_ERR(plane))
13634                 return plane;
13635
13636         plane->pipe = pipe;
13637         /*
13638          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13639          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13640          */
13641         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13642                 plane->i9xx_plane = (enum i9xx_plane_id) !pipe;
13643         else
13644                 plane->i9xx_plane = (enum i9xx_plane_id) pipe;
13645         plane->id = PLANE_PRIMARY;
13646         plane->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, plane->id);
13647
13648         plane->has_fbc = i9xx_plane_has_fbc(dev_priv, plane->i9xx_plane);
13649         if (plane->has_fbc) {
13650                 struct intel_fbc *fbc = &dev_priv->fbc;
13651
13652                 fbc->possible_framebuffer_bits |= plane->frontbuffer_bit;
13653         }
13654
13655         if (INTEL_GEN(dev_priv) >= 4) {
13656                 formats = i965_primary_formats;
13657                 num_formats = ARRAY_SIZE(i965_primary_formats);
13658                 modifiers = i9xx_format_modifiers;
13659
13660                 plane->max_stride = i9xx_plane_max_stride;
13661                 plane->update_plane = i9xx_update_plane;
13662                 plane->disable_plane = i9xx_disable_plane;
13663                 plane->get_hw_state = i9xx_plane_get_hw_state;
13664                 plane->check_plane = i9xx_plane_check;
13665
13666                 plane_funcs = &i965_plane_funcs;
13667         } else {
13668                 formats = i8xx_primary_formats;
13669                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13670                 modifiers = i9xx_format_modifiers;
13671
13672                 plane->max_stride = i9xx_plane_max_stride;
13673                 plane->update_plane = i9xx_update_plane;
13674                 plane->disable_plane = i9xx_disable_plane;
13675                 plane->get_hw_state = i9xx_plane_get_hw_state;
13676                 plane->check_plane = i9xx_plane_check;
13677
13678                 plane_funcs = &i8xx_plane_funcs;
13679         }
13680
13681         possible_crtcs = BIT(pipe);
13682
13683         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13684                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
13685                                                possible_crtcs, plane_funcs,
13686                                                formats, num_formats, modifiers,
13687                                                DRM_PLANE_TYPE_PRIMARY,
13688                                                "primary %c", pipe_name(pipe));
13689         else
13690                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
13691                                                possible_crtcs, plane_funcs,
13692                                                formats, num_formats, modifiers,
13693                                                DRM_PLANE_TYPE_PRIMARY,
13694                                                "plane %c",
13695                                                plane_name(plane->i9xx_plane));
13696         if (ret)
13697                 goto fail;
13698
13699         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13700                 supported_rotations =
13701                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13702                         DRM_MODE_REFLECT_X;
13703         } else if (INTEL_GEN(dev_priv) >= 4) {
13704                 supported_rotations =
13705                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13706         } else {
13707                 supported_rotations = DRM_MODE_ROTATE_0;
13708         }
13709
13710         if (INTEL_GEN(dev_priv) >= 4)
13711                 drm_plane_create_rotation_property(&plane->base,
13712                                                    DRM_MODE_ROTATE_0,
13713                                                    supported_rotations);
13714
13715         drm_plane_helper_add(&plane->base, &intel_plane_helper_funcs);
13716
13717         return plane;
13718
13719 fail:
13720         intel_plane_free(plane);
13721
13722         return ERR_PTR(ret);
13723 }
13724
13725 static struct intel_plane *
13726 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13727                           enum pipe pipe)
13728 {
13729         unsigned int possible_crtcs;
13730         struct intel_plane *cursor;
13731         int ret;
13732
13733         cursor = intel_plane_alloc();
13734         if (IS_ERR(cursor))
13735                 return cursor;
13736
13737         cursor->pipe = pipe;
13738         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13739         cursor->id = PLANE_CURSOR;
13740         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13741
13742         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13743                 cursor->max_stride = i845_cursor_max_stride;
13744                 cursor->update_plane = i845_update_cursor;
13745                 cursor->disable_plane = i845_disable_cursor;
13746                 cursor->get_hw_state = i845_cursor_get_hw_state;
13747                 cursor->check_plane = i845_check_cursor;
13748         } else {
13749                 cursor->max_stride = i9xx_cursor_max_stride;
13750                 cursor->update_plane = i9xx_update_cursor;
13751                 cursor->disable_plane = i9xx_disable_cursor;
13752                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13753                 cursor->check_plane = i9xx_check_cursor;
13754         }
13755
13756         cursor->cursor.base = ~0;
13757         cursor->cursor.cntl = ~0;
13758
13759         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13760                 cursor->cursor.size = ~0;
13761
13762         possible_crtcs = BIT(pipe);
13763
13764         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13765                                        possible_crtcs, &intel_cursor_plane_funcs,
13766                                        intel_cursor_formats,
13767                                        ARRAY_SIZE(intel_cursor_formats),
13768                                        cursor_format_modifiers,
13769                                        DRM_PLANE_TYPE_CURSOR,
13770                                        "cursor %c", pipe_name(pipe));
13771         if (ret)
13772                 goto fail;
13773
13774         if (INTEL_GEN(dev_priv) >= 4)
13775                 drm_plane_create_rotation_property(&cursor->base,
13776                                                    DRM_MODE_ROTATE_0,
13777                                                    DRM_MODE_ROTATE_0 |
13778                                                    DRM_MODE_ROTATE_180);
13779
13780         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13781
13782         return cursor;
13783
13784 fail:
13785         intel_plane_free(cursor);
13786
13787         return ERR_PTR(ret);
13788 }
13789
13790 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13791                                     struct intel_crtc_state *crtc_state)
13792 {
13793         struct intel_crtc_scaler_state *scaler_state =
13794                 &crtc_state->scaler_state;
13795         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13796         int i;
13797
13798         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13799         if (!crtc->num_scalers)
13800                 return;
13801
13802         for (i = 0; i < crtc->num_scalers; i++) {
13803                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13804
13805                 scaler->in_use = 0;
13806                 scaler->mode = 0;
13807         }
13808
13809         scaler_state->scaler_id = -1;
13810 }
13811
13812 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13813 {
13814         struct intel_crtc *intel_crtc;
13815         struct intel_crtc_state *crtc_state = NULL;
13816         struct intel_plane *primary = NULL;
13817         struct intel_plane *cursor = NULL;
13818         int sprite, ret;
13819
13820         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13821         if (!intel_crtc)
13822                 return -ENOMEM;
13823
13824         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13825         if (!crtc_state) {
13826                 ret = -ENOMEM;
13827                 goto fail;
13828         }
13829         intel_crtc->config = crtc_state;
13830         intel_crtc->base.state = &crtc_state->base;
13831         crtc_state->base.crtc = &intel_crtc->base;
13832
13833         primary = intel_primary_plane_create(dev_priv, pipe);
13834         if (IS_ERR(primary)) {
13835                 ret = PTR_ERR(primary);
13836                 goto fail;
13837         }
13838         intel_crtc->plane_ids_mask |= BIT(primary->id);
13839
13840         for_each_sprite(dev_priv, pipe, sprite) {
13841                 struct intel_plane *plane;
13842
13843                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13844                 if (IS_ERR(plane)) {
13845                         ret = PTR_ERR(plane);
13846                         goto fail;
13847                 }
13848                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13849         }
13850
13851         cursor = intel_cursor_plane_create(dev_priv, pipe);
13852         if (IS_ERR(cursor)) {
13853                 ret = PTR_ERR(cursor);
13854                 goto fail;
13855         }
13856         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13857
13858         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13859                                         &primary->base, &cursor->base,
13860                                         &intel_crtc_funcs,
13861                                         "pipe %c", pipe_name(pipe));
13862         if (ret)
13863                 goto fail;
13864
13865         intel_crtc->pipe = pipe;
13866
13867         /* initialize shared scalers */
13868         intel_crtc_init_scalers(intel_crtc, crtc_state);
13869
13870         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
13871                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
13872         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
13873
13874         if (INTEL_GEN(dev_priv) < 9) {
13875                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
13876
13877                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13878                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
13879                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
13880         }
13881
13882         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13883
13884         intel_color_init(&intel_crtc->base);
13885
13886         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13887
13888         return 0;
13889
13890 fail:
13891         /*
13892          * drm_mode_config_cleanup() will free up any
13893          * crtcs/planes already initialized.
13894          */
13895         kfree(crtc_state);
13896         kfree(intel_crtc);
13897
13898         return ret;
13899 }
13900
13901 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13902 {
13903         struct drm_device *dev = connector->base.dev;
13904
13905         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13906
13907         if (!connector->base.state->crtc)
13908                 return INVALID_PIPE;
13909
13910         return to_intel_crtc(connector->base.state->crtc)->pipe;
13911 }
13912
13913 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
13914                                       struct drm_file *file)
13915 {
13916         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13917         struct drm_crtc *drmmode_crtc;
13918         struct intel_crtc *crtc;
13919
13920         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
13921         if (!drmmode_crtc)
13922                 return -ENOENT;
13923
13924         crtc = to_intel_crtc(drmmode_crtc);
13925         pipe_from_crtc_id->pipe = crtc->pipe;
13926
13927         return 0;
13928 }
13929
13930 static int intel_encoder_clones(struct intel_encoder *encoder)
13931 {
13932         struct drm_device *dev = encoder->base.dev;
13933         struct intel_encoder *source_encoder;
13934         int index_mask = 0;
13935         int entry = 0;
13936
13937         for_each_intel_encoder(dev, source_encoder) {
13938                 if (encoders_cloneable(encoder, source_encoder))
13939                         index_mask |= (1 << entry);
13940
13941                 entry++;
13942         }
13943
13944         return index_mask;
13945 }
13946
13947 static bool has_edp_a(struct drm_i915_private *dev_priv)
13948 {
13949         if (!IS_MOBILE(dev_priv))
13950                 return false;
13951
13952         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13953                 return false;
13954
13955         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13956                 return false;
13957
13958         return true;
13959 }
13960
13961 static bool intel_crt_present(struct drm_i915_private *dev_priv)
13962 {
13963         if (INTEL_GEN(dev_priv) >= 9)
13964                 return false;
13965
13966         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
13967                 return false;
13968
13969         if (IS_CHERRYVIEW(dev_priv))
13970                 return false;
13971
13972         if (HAS_PCH_LPT_H(dev_priv) &&
13973             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
13974                 return false;
13975
13976         /* DDI E can't be used if DDI A requires 4 lanes */
13977         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
13978                 return false;
13979
13980         if (!dev_priv->vbt.int_crt_support)
13981                 return false;
13982
13983         return true;
13984 }
13985
13986 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
13987 {
13988         int pps_num;
13989         int pps_idx;
13990
13991         if (HAS_DDI(dev_priv))
13992                 return;
13993         /*
13994          * This w/a is needed at least on CPT/PPT, but to be sure apply it
13995          * everywhere where registers can be write protected.
13996          */
13997         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13998                 pps_num = 2;
13999         else
14000                 pps_num = 1;
14001
14002         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14003                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14004
14005                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14006                 I915_WRITE(PP_CONTROL(pps_idx), val);
14007         }
14008 }
14009
14010 static void intel_pps_init(struct drm_i915_private *dev_priv)
14011 {
14012         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14013                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14014         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14015                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14016         else
14017                 dev_priv->pps_mmio_base = PPS_BASE;
14018
14019         intel_pps_unlock_regs_wa(dev_priv);
14020 }
14021
14022 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14023 {
14024         struct intel_encoder *encoder;
14025         bool dpd_is_edp = false;
14026
14027         intel_pps_init(dev_priv);
14028
14029         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14030                 return;
14031
14032         /*
14033          * intel_edp_init_connector() depends on this completing first, to
14034          * prevent the registeration of both eDP and LVDS and the incorrect
14035          * sharing of the PPS.
14036          */
14037         intel_lvds_init(dev_priv);
14038
14039         if (intel_crt_present(dev_priv))
14040                 intel_crt_init(dev_priv);
14041
14042         if (IS_ICELAKE(dev_priv)) {
14043                 intel_ddi_init(dev_priv, PORT_A);
14044                 intel_ddi_init(dev_priv, PORT_B);
14045                 intel_ddi_init(dev_priv, PORT_C);
14046                 intel_ddi_init(dev_priv, PORT_D);
14047                 intel_ddi_init(dev_priv, PORT_E);
14048                 intel_ddi_init(dev_priv, PORT_F);
14049         } else if (IS_GEN9_LP(dev_priv)) {
14050                 /*
14051                  * FIXME: Broxton doesn't support port detection via the
14052                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14053                  * detect the ports.
14054                  */
14055                 intel_ddi_init(dev_priv, PORT_A);
14056                 intel_ddi_init(dev_priv, PORT_B);
14057                 intel_ddi_init(dev_priv, PORT_C);
14058
14059                 vlv_dsi_init(dev_priv);
14060         } else if (HAS_DDI(dev_priv)) {
14061                 int found;
14062
14063                 /*
14064                  * Haswell uses DDI functions to detect digital outputs.
14065                  * On SKL pre-D0 the strap isn't connected, so we assume
14066                  * it's there.
14067                  */
14068                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14069                 /* WaIgnoreDDIAStrap: skl */
14070                 if (found || IS_GEN9_BC(dev_priv))
14071                         intel_ddi_init(dev_priv, PORT_A);
14072
14073                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
14074                  * register */
14075                 found = I915_READ(SFUSE_STRAP);
14076
14077                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14078                         intel_ddi_init(dev_priv, PORT_B);
14079                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14080                         intel_ddi_init(dev_priv, PORT_C);
14081                 if (found & SFUSE_STRAP_DDID_DETECTED)
14082                         intel_ddi_init(dev_priv, PORT_D);
14083                 if (found & SFUSE_STRAP_DDIF_DETECTED)
14084                         intel_ddi_init(dev_priv, PORT_F);
14085                 /*
14086                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14087                  */
14088                 if (IS_GEN9_BC(dev_priv) &&
14089                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14090                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14091                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14092                         intel_ddi_init(dev_priv, PORT_E);
14093
14094         } else if (HAS_PCH_SPLIT(dev_priv)) {
14095                 int found;
14096                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14097
14098                 if (has_edp_a(dev_priv))
14099                         intel_dp_init(dev_priv, DP_A, PORT_A);
14100
14101                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14102                         /* PCH SDVOB multiplex with HDMIB */
14103                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14104                         if (!found)
14105                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14106                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14107                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14108                 }
14109
14110                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14111                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14112
14113                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14114                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14115
14116                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14117                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14118
14119                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14120                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14121         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14122                 bool has_edp, has_port;
14123
14124                 /*
14125                  * The DP_DETECTED bit is the latched state of the DDC
14126                  * SDA pin at boot. However since eDP doesn't require DDC
14127                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14128                  * eDP ports may have been muxed to an alternate function.
14129                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14130                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14131                  * detect eDP ports.
14132                  *
14133                  * Sadly the straps seem to be missing sometimes even for HDMI
14134                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14135                  * and VBT for the presence of the port. Additionally we can't
14136                  * trust the port type the VBT declares as we've seen at least
14137                  * HDMI ports that the VBT claim are DP or eDP.
14138                  */
14139                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14140                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14141                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14142                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14143                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14144                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14145
14146                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14147                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14148                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14149                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14150                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14151                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14152
14153                 if (IS_CHERRYVIEW(dev_priv)) {
14154                         /*
14155                          * eDP not supported on port D,
14156                          * so no need to worry about it
14157                          */
14158                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14159                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14160                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14161                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14162                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14163                 }
14164
14165                 vlv_dsi_init(dev_priv);
14166         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
14167                 bool found = false;
14168
14169                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14170                         DRM_DEBUG_KMS("probing SDVOB\n");
14171                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14172                         if (!found && IS_G4X(dev_priv)) {
14173                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14174                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14175                         }
14176
14177                         if (!found && IS_G4X(dev_priv))
14178                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14179                 }
14180
14181                 /* Before G4X SDVOC doesn't have its own detect register */
14182
14183                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14184                         DRM_DEBUG_KMS("probing SDVOC\n");
14185                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14186                 }
14187
14188                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14189
14190                         if (IS_G4X(dev_priv)) {
14191                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14192                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14193                         }
14194                         if (IS_G4X(dev_priv))
14195                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14196                 }
14197
14198                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14199                         intel_dp_init(dev_priv, DP_D, PORT_D);
14200         } else if (IS_GEN2(dev_priv))
14201                 intel_dvo_init(dev_priv);
14202
14203         if (SUPPORTS_TV(dev_priv))
14204                 intel_tv_init(dev_priv);
14205
14206         intel_psr_init(dev_priv);
14207
14208         for_each_intel_encoder(&dev_priv->drm, encoder) {
14209                 encoder->base.possible_crtcs = encoder->crtc_mask;
14210                 encoder->base.possible_clones =
14211                         intel_encoder_clones(encoder);
14212         }
14213
14214         intel_init_pch_refclk(dev_priv);
14215
14216         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14217 }
14218
14219 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14220 {
14221         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14222         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14223
14224         drm_framebuffer_cleanup(fb);
14225
14226         i915_gem_object_lock(obj);
14227         WARN_ON(!obj->framebuffer_references--);
14228         i915_gem_object_unlock(obj);
14229
14230         i915_gem_object_put(obj);
14231
14232         kfree(intel_fb);
14233 }
14234
14235 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14236                                                 struct drm_file *file,
14237                                                 unsigned int *handle)
14238 {
14239         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14240
14241         if (obj->userptr.mm) {
14242                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14243                 return -EINVAL;
14244         }
14245
14246         return drm_gem_handle_create(file, &obj->base, handle);
14247 }
14248
14249 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14250                                         struct drm_file *file,
14251                                         unsigned flags, unsigned color,
14252                                         struct drm_clip_rect *clips,
14253                                         unsigned num_clips)
14254 {
14255         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14256
14257         i915_gem_object_flush_if_display(obj);
14258         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14259
14260         return 0;
14261 }
14262
14263 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14264         .destroy = intel_user_framebuffer_destroy,
14265         .create_handle = intel_user_framebuffer_create_handle,
14266         .dirty = intel_user_framebuffer_dirty,
14267 };
14268
14269 static
14270 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14271                          uint64_t fb_modifier, uint32_t pixel_format)
14272 {
14273         struct intel_crtc *crtc;
14274         struct intel_plane *plane;
14275
14276         /*
14277          * We assume the primary plane for pipe A has
14278          * the highest stride limits of them all.
14279          */
14280         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
14281         plane = to_intel_plane(crtc->base.primary);
14282
14283         return plane->max_stride(plane, pixel_format, fb_modifier,
14284                                  DRM_MODE_ROTATE_0);
14285 }
14286
14287 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14288                                   struct drm_i915_gem_object *obj,
14289                                   struct drm_mode_fb_cmd2 *mode_cmd)
14290 {
14291         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14292         struct drm_framebuffer *fb = &intel_fb->base;
14293         struct drm_format_name_buf format_name;
14294         u32 pitch_limit;
14295         unsigned int tiling, stride;
14296         int ret = -EINVAL;
14297         int i;
14298
14299         i915_gem_object_lock(obj);
14300         obj->framebuffer_references++;
14301         tiling = i915_gem_object_get_tiling(obj);
14302         stride = i915_gem_object_get_stride(obj);
14303         i915_gem_object_unlock(obj);
14304
14305         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14306                 /*
14307                  * If there's a fence, enforce that
14308                  * the fb modifier and tiling mode match.
14309                  */
14310                 if (tiling != I915_TILING_NONE &&
14311                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14312                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14313                         goto err;
14314                 }
14315         } else {
14316                 if (tiling == I915_TILING_X) {
14317                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14318                 } else if (tiling == I915_TILING_Y) {
14319                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14320                         goto err;
14321                 }
14322         }
14323
14324         /* Passed in modifier sanity checking. */
14325         switch (mode_cmd->modifier[0]) {
14326         case I915_FORMAT_MOD_Y_TILED_CCS:
14327         case I915_FORMAT_MOD_Yf_TILED_CCS:
14328                 switch (mode_cmd->pixel_format) {
14329                 case DRM_FORMAT_XBGR8888:
14330                 case DRM_FORMAT_ABGR8888:
14331                 case DRM_FORMAT_XRGB8888:
14332                 case DRM_FORMAT_ARGB8888:
14333                         break;
14334                 default:
14335                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
14336                         goto err;
14337                 }
14338                 /* fall through */
14339         case I915_FORMAT_MOD_Yf_TILED:
14340                 if (mode_cmd->pixel_format == DRM_FORMAT_C8) {
14341                         DRM_DEBUG_KMS("Indexed format does not support Yf tiling\n");
14342                         goto err;
14343                 }
14344                 /* fall through */
14345         case I915_FORMAT_MOD_Y_TILED:
14346                 if (INTEL_GEN(dev_priv) < 9) {
14347                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14348                                       mode_cmd->modifier[0]);
14349                         goto err;
14350                 }
14351                 break;
14352         case DRM_FORMAT_MOD_LINEAR:
14353         case I915_FORMAT_MOD_X_TILED:
14354                 break;
14355         default:
14356                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14357                               mode_cmd->modifier[0]);
14358                 goto err;
14359         }
14360
14361         /*
14362          * gen2/3 display engine uses the fence if present,
14363          * so the tiling mode must match the fb modifier exactly.
14364          */
14365         if (INTEL_GEN(dev_priv) < 4 &&
14366             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14367                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14368                 goto err;
14369         }
14370
14371         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14372                                            mode_cmd->pixel_format);
14373         if (mode_cmd->pitches[0] > pitch_limit) {
14374                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14375                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14376                               "tiled" : "linear",
14377                               mode_cmd->pitches[0], pitch_limit);
14378                 goto err;
14379         }
14380
14381         /*
14382          * If there's a fence, enforce that
14383          * the fb pitch and fence stride match.
14384          */
14385         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14386                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14387                               mode_cmd->pitches[0], stride);
14388                 goto err;
14389         }
14390
14391         /* Reject formats not supported by any plane early. */
14392         switch (mode_cmd->pixel_format) {
14393         case DRM_FORMAT_C8:
14394         case DRM_FORMAT_RGB565:
14395         case DRM_FORMAT_XRGB8888:
14396         case DRM_FORMAT_ARGB8888:
14397                 break;
14398         case DRM_FORMAT_XRGB1555:
14399                 if (INTEL_GEN(dev_priv) > 3) {
14400                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14401                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14402                         goto err;
14403                 }
14404                 break;
14405         case DRM_FORMAT_ABGR8888:
14406                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14407                     INTEL_GEN(dev_priv) < 9) {
14408                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14409                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14410                         goto err;
14411                 }
14412                 break;
14413         case DRM_FORMAT_XBGR8888:
14414         case DRM_FORMAT_XRGB2101010:
14415         case DRM_FORMAT_XBGR2101010:
14416                 if (INTEL_GEN(dev_priv) < 4) {
14417                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14418                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14419                         goto err;
14420                 }
14421                 break;
14422         case DRM_FORMAT_ABGR2101010:
14423                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14424                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14425                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14426                         goto err;
14427                 }
14428                 break;
14429         case DRM_FORMAT_YUYV:
14430         case DRM_FORMAT_UYVY:
14431         case DRM_FORMAT_YVYU:
14432         case DRM_FORMAT_VYUY:
14433                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14434                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14435                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14436                         goto err;
14437                 }
14438                 break;
14439         case DRM_FORMAT_NV12:
14440                 if (INTEL_GEN(dev_priv) < 9 || IS_SKYLAKE(dev_priv) ||
14441                     IS_BROXTON(dev_priv) || INTEL_GEN(dev_priv) >= 11) {
14442                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14443                                       drm_get_format_name(mode_cmd->pixel_format,
14444                                                           &format_name));
14445                         goto err;
14446                 }
14447                 break;
14448         default:
14449                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14450                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14451                 goto err;
14452         }
14453
14454         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14455         if (mode_cmd->offsets[0] != 0)
14456                 goto err;
14457
14458         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14459
14460         if (fb->format->format == DRM_FORMAT_NV12 &&
14461             (fb->width < SKL_MIN_YUV_420_SRC_W ||
14462              fb->height < SKL_MIN_YUV_420_SRC_H ||
14463              (fb->width % 4) != 0 || (fb->height % 4) != 0)) {
14464                 DRM_DEBUG_KMS("src dimensions not correct for NV12\n");
14465                 return -EINVAL;
14466         }
14467
14468         for (i = 0; i < fb->format->num_planes; i++) {
14469                 u32 stride_alignment;
14470
14471                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14472                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14473                         goto err;
14474                 }
14475
14476                 stride_alignment = intel_fb_stride_alignment(fb, i);
14477
14478                 /*
14479                  * Display WA #0531: skl,bxt,kbl,glk
14480                  *
14481                  * Render decompression and plane width > 3840
14482                  * combined with horizontal panning requires the
14483                  * plane stride to be a multiple of 4. We'll just
14484                  * require the entire fb to accommodate that to avoid
14485                  * potential runtime errors at plane configuration time.
14486                  */
14487                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14488                     is_ccs_modifier(fb->modifier))
14489                         stride_alignment *= 4;
14490
14491                 if (fb->pitches[i] & (stride_alignment - 1)) {
14492                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14493                                       i, fb->pitches[i], stride_alignment);
14494                         goto err;
14495                 }
14496
14497                 fb->obj[i] = &obj->base;
14498         }
14499
14500         ret = intel_fill_fb_info(dev_priv, fb);
14501         if (ret)
14502                 goto err;
14503
14504         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14505         if (ret) {
14506                 DRM_ERROR("framebuffer init failed %d\n", ret);
14507                 goto err;
14508         }
14509
14510         return 0;
14511
14512 err:
14513         i915_gem_object_lock(obj);
14514         obj->framebuffer_references--;
14515         i915_gem_object_unlock(obj);
14516         return ret;
14517 }
14518
14519 static struct drm_framebuffer *
14520 intel_user_framebuffer_create(struct drm_device *dev,
14521                               struct drm_file *filp,
14522                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14523 {
14524         struct drm_framebuffer *fb;
14525         struct drm_i915_gem_object *obj;
14526         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14527
14528         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14529         if (!obj)
14530                 return ERR_PTR(-ENOENT);
14531
14532         fb = intel_framebuffer_create(obj, &mode_cmd);
14533         if (IS_ERR(fb))
14534                 i915_gem_object_put(obj);
14535
14536         return fb;
14537 }
14538
14539 static void intel_atomic_state_free(struct drm_atomic_state *state)
14540 {
14541         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14542
14543         drm_atomic_state_default_release(state);
14544
14545         i915_sw_fence_fini(&intel_state->commit_ready);
14546
14547         kfree(state);
14548 }
14549
14550 static enum drm_mode_status
14551 intel_mode_valid(struct drm_device *dev,
14552                  const struct drm_display_mode *mode)
14553 {
14554         struct drm_i915_private *dev_priv = to_i915(dev);
14555         int hdisplay_max, htotal_max;
14556         int vdisplay_max, vtotal_max;
14557
14558         /*
14559          * Can't reject DBLSCAN here because Xorg ddxen can add piles
14560          * of DBLSCAN modes to the output's mode list when they detect
14561          * the scaling mode property on the connector. And they don't
14562          * ask the kernel to validate those modes in any way until
14563          * modeset time at which point the client gets a protocol error.
14564          * So in order to not upset those clients we silently ignore the
14565          * DBLSCAN flag on such connectors. For other connectors we will
14566          * reject modes with the DBLSCAN flag in encoder->compute_config().
14567          * And we always reject DBLSCAN modes in connector->mode_valid()
14568          * as we never want such modes on the connector's mode list.
14569          */
14570
14571         if (mode->vscan > 1)
14572                 return MODE_NO_VSCAN;
14573
14574         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14575                 return MODE_H_ILLEGAL;
14576
14577         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14578                            DRM_MODE_FLAG_NCSYNC |
14579                            DRM_MODE_FLAG_PCSYNC))
14580                 return MODE_HSYNC;
14581
14582         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14583                            DRM_MODE_FLAG_PIXMUX |
14584                            DRM_MODE_FLAG_CLKDIV2))
14585                 return MODE_BAD;
14586
14587         if (INTEL_GEN(dev_priv) >= 9 ||
14588             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
14589                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
14590                 vdisplay_max = 4096;
14591                 htotal_max = 8192;
14592                 vtotal_max = 8192;
14593         } else if (INTEL_GEN(dev_priv) >= 3) {
14594                 hdisplay_max = 4096;
14595                 vdisplay_max = 4096;
14596                 htotal_max = 8192;
14597                 vtotal_max = 8192;
14598         } else {
14599                 hdisplay_max = 2048;
14600                 vdisplay_max = 2048;
14601                 htotal_max = 4096;
14602                 vtotal_max = 4096;
14603         }
14604
14605         if (mode->hdisplay > hdisplay_max ||
14606             mode->hsync_start > htotal_max ||
14607             mode->hsync_end > htotal_max ||
14608             mode->htotal > htotal_max)
14609                 return MODE_H_ILLEGAL;
14610
14611         if (mode->vdisplay > vdisplay_max ||
14612             mode->vsync_start > vtotal_max ||
14613             mode->vsync_end > vtotal_max ||
14614             mode->vtotal > vtotal_max)
14615                 return MODE_V_ILLEGAL;
14616
14617         return MODE_OK;
14618 }
14619
14620 static const struct drm_mode_config_funcs intel_mode_funcs = {
14621         .fb_create = intel_user_framebuffer_create,
14622         .get_format_info = intel_get_format_info,
14623         .output_poll_changed = intel_fbdev_output_poll_changed,
14624         .mode_valid = intel_mode_valid,
14625         .atomic_check = intel_atomic_check,
14626         .atomic_commit = intel_atomic_commit,
14627         .atomic_state_alloc = intel_atomic_state_alloc,
14628         .atomic_state_clear = intel_atomic_state_clear,
14629         .atomic_state_free = intel_atomic_state_free,
14630 };
14631
14632 /**
14633  * intel_init_display_hooks - initialize the display modesetting hooks
14634  * @dev_priv: device private
14635  */
14636 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14637 {
14638         intel_init_cdclk_hooks(dev_priv);
14639
14640         if (INTEL_GEN(dev_priv) >= 9) {
14641                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14642                 dev_priv->display.get_initial_plane_config =
14643                         skylake_get_initial_plane_config;
14644                 dev_priv->display.crtc_compute_clock =
14645                         haswell_crtc_compute_clock;
14646                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14647                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14648         } else if (HAS_DDI(dev_priv)) {
14649                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14650                 dev_priv->display.get_initial_plane_config =
14651                         i9xx_get_initial_plane_config;
14652                 dev_priv->display.crtc_compute_clock =
14653                         haswell_crtc_compute_clock;
14654                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14655                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14656         } else if (HAS_PCH_SPLIT(dev_priv)) {
14657                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14658                 dev_priv->display.get_initial_plane_config =
14659                         i9xx_get_initial_plane_config;
14660                 dev_priv->display.crtc_compute_clock =
14661                         ironlake_crtc_compute_clock;
14662                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14663                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14664         } else if (IS_CHERRYVIEW(dev_priv)) {
14665                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14666                 dev_priv->display.get_initial_plane_config =
14667                         i9xx_get_initial_plane_config;
14668                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14669                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14670                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14671         } else if (IS_VALLEYVIEW(dev_priv)) {
14672                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14673                 dev_priv->display.get_initial_plane_config =
14674                         i9xx_get_initial_plane_config;
14675                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14676                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14677                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14678         } else if (IS_G4X(dev_priv)) {
14679                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14680                 dev_priv->display.get_initial_plane_config =
14681                         i9xx_get_initial_plane_config;
14682                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14683                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14684                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14685         } else if (IS_PINEVIEW(dev_priv)) {
14686                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14687                 dev_priv->display.get_initial_plane_config =
14688                         i9xx_get_initial_plane_config;
14689                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14690                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14691                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14692         } else if (!IS_GEN2(dev_priv)) {
14693                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14694                 dev_priv->display.get_initial_plane_config =
14695                         i9xx_get_initial_plane_config;
14696                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14697                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14698                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14699         } else {
14700                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14701                 dev_priv->display.get_initial_plane_config =
14702                         i9xx_get_initial_plane_config;
14703                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14704                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14705                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14706         }
14707
14708         if (IS_GEN5(dev_priv)) {
14709                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14710         } else if (IS_GEN6(dev_priv)) {
14711                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14712         } else if (IS_IVYBRIDGE(dev_priv)) {
14713                 /* FIXME: detect B0+ stepping and use auto training */
14714                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14715         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14716                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14717         }
14718
14719         if (INTEL_GEN(dev_priv) >= 9)
14720                 dev_priv->display.update_crtcs = skl_update_crtcs;
14721         else
14722                 dev_priv->display.update_crtcs = intel_update_crtcs;
14723 }
14724
14725 /*
14726  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14727  */
14728 static void quirk_ssc_force_disable(struct drm_device *dev)
14729 {
14730         struct drm_i915_private *dev_priv = to_i915(dev);
14731         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14732         DRM_INFO("applying lvds SSC disable quirk\n");
14733 }
14734
14735 /*
14736  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14737  * brightness value
14738  */
14739 static void quirk_invert_brightness(struct drm_device *dev)
14740 {
14741         struct drm_i915_private *dev_priv = to_i915(dev);
14742         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14743         DRM_INFO("applying inverted panel brightness quirk\n");
14744 }
14745
14746 /* Some VBT's incorrectly indicate no backlight is present */
14747 static void quirk_backlight_present(struct drm_device *dev)
14748 {
14749         struct drm_i915_private *dev_priv = to_i915(dev);
14750         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14751         DRM_INFO("applying backlight present quirk\n");
14752 }
14753
14754 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14755  * which is 300 ms greater than eDP spec T12 min.
14756  */
14757 static void quirk_increase_t12_delay(struct drm_device *dev)
14758 {
14759         struct drm_i915_private *dev_priv = to_i915(dev);
14760
14761         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14762         DRM_INFO("Applying T12 delay quirk\n");
14763 }
14764
14765 /*
14766  * GeminiLake NUC HDMI outputs require additional off time
14767  * this allows the onboard retimer to correctly sync to signal
14768  */
14769 static void quirk_increase_ddi_disabled_time(struct drm_device *dev)
14770 {
14771         struct drm_i915_private *dev_priv = to_i915(dev);
14772
14773         dev_priv->quirks |= QUIRK_INCREASE_DDI_DISABLED_TIME;
14774         DRM_INFO("Applying Increase DDI Disabled quirk\n");
14775 }
14776
14777 struct intel_quirk {
14778         int device;
14779         int subsystem_vendor;
14780         int subsystem_device;
14781         void (*hook)(struct drm_device *dev);
14782 };
14783
14784 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14785 struct intel_dmi_quirk {
14786         void (*hook)(struct drm_device *dev);
14787         const struct dmi_system_id (*dmi_id_list)[];
14788 };
14789
14790 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14791 {
14792         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14793         return 1;
14794 }
14795
14796 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14797         {
14798                 .dmi_id_list = &(const struct dmi_system_id[]) {
14799                         {
14800                                 .callback = intel_dmi_reverse_brightness,
14801                                 .ident = "NCR Corporation",
14802                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14803                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14804                                 },
14805                         },
14806                         { }  /* terminating entry */
14807                 },
14808                 .hook = quirk_invert_brightness,
14809         },
14810 };
14811
14812 static struct intel_quirk intel_quirks[] = {
14813         /* Lenovo U160 cannot use SSC on LVDS */
14814         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14815
14816         /* Sony Vaio Y cannot use SSC on LVDS */
14817         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14818
14819         /* Acer Aspire 5734Z must invert backlight brightness */
14820         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14821
14822         /* Acer/eMachines G725 */
14823         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14824
14825         /* Acer/eMachines e725 */
14826         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14827
14828         /* Acer/Packard Bell NCL20 */
14829         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14830
14831         /* Acer Aspire 4736Z */
14832         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14833
14834         /* Acer Aspire 5336 */
14835         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14836
14837         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14838         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14839
14840         /* Acer C720 Chromebook (Core i3 4005U) */
14841         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14842
14843         /* Apple Macbook 2,1 (Core 2 T7400) */
14844         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14845
14846         /* Apple Macbook 4,1 */
14847         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14848
14849         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14850         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14851
14852         /* HP Chromebook 14 (Celeron 2955U) */
14853         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14854
14855         /* Dell Chromebook 11 */
14856         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14857
14858         /* Dell Chromebook 11 (2015 version) */
14859         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14860
14861         /* Toshiba Satellite P50-C-18C */
14862         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14863
14864         /* GeminiLake NUC */
14865         { 0x3185, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14866         { 0x3184, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14867         /* ASRock ITX*/
14868         { 0x3185, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14869         { 0x3184, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14870 };
14871
14872 static void intel_init_quirks(struct drm_device *dev)
14873 {
14874         struct pci_dev *d = dev->pdev;
14875         int i;
14876
14877         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14878                 struct intel_quirk *q = &intel_quirks[i];
14879
14880                 if (d->device == q->device &&
14881                     (d->subsystem_vendor == q->subsystem_vendor ||
14882                      q->subsystem_vendor == PCI_ANY_ID) &&
14883                     (d->subsystem_device == q->subsystem_device ||
14884                      q->subsystem_device == PCI_ANY_ID))
14885                         q->hook(dev);
14886         }
14887         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14888                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14889                         intel_dmi_quirks[i].hook(dev);
14890         }
14891 }
14892
14893 /* Disable the VGA plane that we never use */
14894 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14895 {
14896         struct pci_dev *pdev = dev_priv->drm.pdev;
14897         u8 sr1;
14898         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14899
14900         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14901         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14902         outb(SR01, VGA_SR_INDEX);
14903         sr1 = inb(VGA_SR_DATA);
14904         outb(sr1 | 1<<5, VGA_SR_DATA);
14905         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14906         udelay(300);
14907
14908         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14909         POSTING_READ(vga_reg);
14910 }
14911
14912 void intel_modeset_init_hw(struct drm_device *dev)
14913 {
14914         struct drm_i915_private *dev_priv = to_i915(dev);
14915
14916         intel_update_cdclk(dev_priv);
14917         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
14918         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14919 }
14920
14921 /*
14922  * Calculate what we think the watermarks should be for the state we've read
14923  * out of the hardware and then immediately program those watermarks so that
14924  * we ensure the hardware settings match our internal state.
14925  *
14926  * We can calculate what we think WM's should be by creating a duplicate of the
14927  * current state (which was constructed during hardware readout) and running it
14928  * through the atomic check code to calculate new watermark values in the
14929  * state object.
14930  */
14931 static void sanitize_watermarks(struct drm_device *dev)
14932 {
14933         struct drm_i915_private *dev_priv = to_i915(dev);
14934         struct drm_atomic_state *state;
14935         struct intel_atomic_state *intel_state;
14936         struct drm_crtc *crtc;
14937         struct drm_crtc_state *cstate;
14938         struct drm_modeset_acquire_ctx ctx;
14939         int ret;
14940         int i;
14941
14942         /* Only supported on platforms that use atomic watermark design */
14943         if (!dev_priv->display.optimize_watermarks)
14944                 return;
14945
14946         /*
14947          * We need to hold connection_mutex before calling duplicate_state so
14948          * that the connector loop is protected.
14949          */
14950         drm_modeset_acquire_init(&ctx, 0);
14951 retry:
14952         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14953         if (ret == -EDEADLK) {
14954                 drm_modeset_backoff(&ctx);
14955                 goto retry;
14956         } else if (WARN_ON(ret)) {
14957                 goto fail;
14958         }
14959
14960         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14961         if (WARN_ON(IS_ERR(state)))
14962                 goto fail;
14963
14964         intel_state = to_intel_atomic_state(state);
14965
14966         /*
14967          * Hardware readout is the only time we don't want to calculate
14968          * intermediate watermarks (since we don't trust the current
14969          * watermarks).
14970          */
14971         if (!HAS_GMCH_DISPLAY(dev_priv))
14972                 intel_state->skip_intermediate_wm = true;
14973
14974         ret = intel_atomic_check(dev, state);
14975         if (ret) {
14976                 /*
14977                  * If we fail here, it means that the hardware appears to be
14978                  * programmed in a way that shouldn't be possible, given our
14979                  * understanding of watermark requirements.  This might mean a
14980                  * mistake in the hardware readout code or a mistake in the
14981                  * watermark calculations for a given platform.  Raise a WARN
14982                  * so that this is noticeable.
14983                  *
14984                  * If this actually happens, we'll have to just leave the
14985                  * BIOS-programmed watermarks untouched and hope for the best.
14986                  */
14987                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14988                 goto put_state;
14989         }
14990
14991         /* Write calculated watermark values back */
14992         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14993                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14994
14995                 cs->wm.need_postvbl_update = true;
14996                 dev_priv->display.optimize_watermarks(intel_state, cs);
14997
14998                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
14999         }
15000
15001 put_state:
15002         drm_atomic_state_put(state);
15003 fail:
15004         drm_modeset_drop_locks(&ctx);
15005         drm_modeset_acquire_fini(&ctx);
15006 }
15007
15008 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
15009 {
15010         if (IS_GEN5(dev_priv)) {
15011                 u32 fdi_pll_clk =
15012                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
15013
15014                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
15015         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
15016                 dev_priv->fdi_pll_freq = 270000;
15017         } else {
15018                 return;
15019         }
15020
15021         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
15022 }
15023
15024 static int intel_initial_commit(struct drm_device *dev)
15025 {
15026         struct drm_atomic_state *state = NULL;
15027         struct drm_modeset_acquire_ctx ctx;
15028         struct drm_crtc *crtc;
15029         struct drm_crtc_state *crtc_state;
15030         int ret = 0;
15031
15032         state = drm_atomic_state_alloc(dev);
15033         if (!state)
15034                 return -ENOMEM;
15035
15036         drm_modeset_acquire_init(&ctx, 0);
15037
15038 retry:
15039         state->acquire_ctx = &ctx;
15040
15041         drm_for_each_crtc(crtc, dev) {
15042                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
15043                 if (IS_ERR(crtc_state)) {
15044                         ret = PTR_ERR(crtc_state);
15045                         goto out;
15046                 }
15047
15048                 if (crtc_state->active) {
15049                         ret = drm_atomic_add_affected_planes(state, crtc);
15050                         if (ret)
15051                                 goto out;
15052                 }
15053         }
15054
15055         ret = drm_atomic_commit(state);
15056
15057 out:
15058         if (ret == -EDEADLK) {
15059                 drm_atomic_state_clear(state);
15060                 drm_modeset_backoff(&ctx);
15061                 goto retry;
15062         }
15063
15064         drm_atomic_state_put(state);
15065
15066         drm_modeset_drop_locks(&ctx);
15067         drm_modeset_acquire_fini(&ctx);
15068
15069         return ret;
15070 }
15071
15072 int intel_modeset_init(struct drm_device *dev)
15073 {
15074         struct drm_i915_private *dev_priv = to_i915(dev);
15075         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15076         enum pipe pipe;
15077         struct intel_crtc *crtc;
15078         int ret;
15079
15080         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15081
15082         drm_mode_config_init(dev);
15083
15084         dev->mode_config.min_width = 0;
15085         dev->mode_config.min_height = 0;
15086
15087         dev->mode_config.preferred_depth = 24;
15088         dev->mode_config.prefer_shadow = 1;
15089
15090         dev->mode_config.allow_fb_modifiers = true;
15091
15092         dev->mode_config.funcs = &intel_mode_funcs;
15093
15094         init_llist_head(&dev_priv->atomic_helper.free_list);
15095         INIT_WORK(&dev_priv->atomic_helper.free_work,
15096                   intel_atomic_helper_free_state_worker);
15097
15098         intel_init_quirks(dev);
15099
15100         intel_init_pm(dev_priv);
15101
15102         /*
15103          * There may be no VBT; and if the BIOS enabled SSC we can
15104          * just keep using it to avoid unnecessary flicker.  Whereas if the
15105          * BIOS isn't using it, don't assume it will work even if the VBT
15106          * indicates as much.
15107          */
15108         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15109                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15110                                             DREF_SSC1_ENABLE);
15111
15112                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15113                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15114                                      bios_lvds_use_ssc ? "en" : "dis",
15115                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15116                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15117                 }
15118         }
15119
15120         /* maximum framebuffer dimensions */
15121         if (IS_GEN2(dev_priv)) {
15122                 dev->mode_config.max_width = 2048;
15123                 dev->mode_config.max_height = 2048;
15124         } else if (IS_GEN3(dev_priv)) {
15125                 dev->mode_config.max_width = 4096;
15126                 dev->mode_config.max_height = 4096;
15127         } else {
15128                 dev->mode_config.max_width = 8192;
15129                 dev->mode_config.max_height = 8192;
15130         }
15131
15132         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15133                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15134                 dev->mode_config.cursor_height = 1023;
15135         } else if (IS_GEN2(dev_priv)) {
15136                 dev->mode_config.cursor_width = 64;
15137                 dev->mode_config.cursor_height = 64;
15138         } else {
15139                 dev->mode_config.cursor_width = 256;
15140                 dev->mode_config.cursor_height = 256;
15141         }
15142
15143         dev->mode_config.fb_base = ggtt->gmadr.start;
15144
15145         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15146                       INTEL_INFO(dev_priv)->num_pipes,
15147                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15148
15149         for_each_pipe(dev_priv, pipe) {
15150                 ret = intel_crtc_init(dev_priv, pipe);
15151                 if (ret) {
15152                         drm_mode_config_cleanup(dev);
15153                         return ret;
15154                 }
15155         }
15156
15157         intel_shared_dpll_init(dev);
15158         intel_update_fdi_pll_freq(dev_priv);
15159
15160         intel_update_czclk(dev_priv);
15161         intel_modeset_init_hw(dev);
15162
15163         if (dev_priv->max_cdclk_freq == 0)
15164                 intel_update_max_cdclk(dev_priv);
15165
15166         /* Just disable it once at startup */
15167         i915_disable_vga(dev_priv);
15168         intel_setup_outputs(dev_priv);
15169
15170         drm_modeset_lock_all(dev);
15171         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15172         drm_modeset_unlock_all(dev);
15173
15174         for_each_intel_crtc(dev, crtc) {
15175                 struct intel_initial_plane_config plane_config = {};
15176
15177                 if (!crtc->active)
15178                         continue;
15179
15180                 /*
15181                  * Note that reserving the BIOS fb up front prevents us
15182                  * from stuffing other stolen allocations like the ring
15183                  * on top.  This prevents some ugliness at boot time, and
15184                  * can even allow for smooth boot transitions if the BIOS
15185                  * fb is large enough for the active pipe configuration.
15186                  */
15187                 dev_priv->display.get_initial_plane_config(crtc,
15188                                                            &plane_config);
15189
15190                 /*
15191                  * If the fb is shared between multiple heads, we'll
15192                  * just get the first one.
15193                  */
15194                 intel_find_initial_plane_obj(crtc, &plane_config);
15195         }
15196
15197         /*
15198          * Make sure hardware watermarks really match the state we read out.
15199          * Note that we need to do this after reconstructing the BIOS fb's
15200          * since the watermark calculation done here will use pstate->fb.
15201          */
15202         if (!HAS_GMCH_DISPLAY(dev_priv))
15203                 sanitize_watermarks(dev);
15204
15205         /*
15206          * Force all active planes to recompute their states. So that on
15207          * mode_setcrtc after probe, all the intel_plane_state variables
15208          * are already calculated and there is no assert_plane warnings
15209          * during bootup.
15210          */
15211         ret = intel_initial_commit(dev);
15212         if (ret)
15213                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15214
15215         return 0;
15216 }
15217
15218 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15219 {
15220         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15221         /* 640x480@60Hz, ~25175 kHz */
15222         struct dpll clock = {
15223                 .m1 = 18,
15224                 .m2 = 7,
15225                 .p1 = 13,
15226                 .p2 = 4,
15227                 .n = 2,
15228         };
15229         u32 dpll, fp;
15230         int i;
15231
15232         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15233
15234         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15235                       pipe_name(pipe), clock.vco, clock.dot);
15236
15237         fp = i9xx_dpll_compute_fp(&clock);
15238         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
15239                 DPLL_VGA_MODE_DIS |
15240                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15241                 PLL_P2_DIVIDE_BY_4 |
15242                 PLL_REF_INPUT_DREFCLK |
15243                 DPLL_VCO_ENABLE;
15244
15245         I915_WRITE(FP0(pipe), fp);
15246         I915_WRITE(FP1(pipe), fp);
15247
15248         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15249         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15250         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15251         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15252         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15253         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15254         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15255
15256         /*
15257          * Apparently we need to have VGA mode enabled prior to changing
15258          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15259          * dividers, even though the register value does change.
15260          */
15261         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15262         I915_WRITE(DPLL(pipe), dpll);
15263
15264         /* Wait for the clocks to stabilize. */
15265         POSTING_READ(DPLL(pipe));
15266         udelay(150);
15267
15268         /* The pixel multiplier can only be updated once the
15269          * DPLL is enabled and the clocks are stable.
15270          *
15271          * So write it again.
15272          */
15273         I915_WRITE(DPLL(pipe), dpll);
15274
15275         /* We do this three times for luck */
15276         for (i = 0; i < 3 ; i++) {
15277                 I915_WRITE(DPLL(pipe), dpll);
15278                 POSTING_READ(DPLL(pipe));
15279                 udelay(150); /* wait for warmup */
15280         }
15281
15282         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15283         POSTING_READ(PIPECONF(pipe));
15284
15285         intel_wait_for_pipe_scanline_moving(crtc);
15286 }
15287
15288 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15289 {
15290         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15291
15292         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15293                       pipe_name(pipe));
15294
15295         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15296         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15297         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15298         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15299         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
15300
15301         I915_WRITE(PIPECONF(pipe), 0);
15302         POSTING_READ(PIPECONF(pipe));
15303
15304         intel_wait_for_pipe_scanline_stopped(crtc);
15305
15306         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15307         POSTING_READ(DPLL(pipe));
15308 }
15309
15310 static void
15311 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15312 {
15313         struct intel_crtc *crtc;
15314
15315         if (INTEL_GEN(dev_priv) >= 4)
15316                 return;
15317
15318         for_each_intel_crtc(&dev_priv->drm, crtc) {
15319                 struct intel_plane *plane =
15320                         to_intel_plane(crtc->base.primary);
15321                 struct intel_crtc *plane_crtc;
15322                 enum pipe pipe;
15323
15324                 if (!plane->get_hw_state(plane, &pipe))
15325                         continue;
15326
15327                 if (pipe == crtc->pipe)
15328                         continue;
15329
15330                 DRM_DEBUG_KMS("[PLANE:%d:%s] attached to the wrong pipe, disabling plane\n",
15331                               plane->base.base.id, plane->base.name);
15332
15333                 plane_crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15334                 intel_plane_disable_noatomic(plane_crtc, plane);
15335         }
15336 }
15337
15338 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15339 {
15340         struct drm_device *dev = crtc->base.dev;
15341         struct intel_encoder *encoder;
15342
15343         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15344                 return true;
15345
15346         return false;
15347 }
15348
15349 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15350 {
15351         struct drm_device *dev = encoder->base.dev;
15352         struct intel_connector *connector;
15353
15354         for_each_connector_on_encoder(dev, &encoder->base, connector)
15355                 return connector;
15356
15357         return NULL;
15358 }
15359
15360 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15361                               enum pipe pch_transcoder)
15362 {
15363         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15364                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15365 }
15366
15367 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15368                                 struct drm_modeset_acquire_ctx *ctx)
15369 {
15370         struct drm_device *dev = crtc->base.dev;
15371         struct drm_i915_private *dev_priv = to_i915(dev);
15372         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15373
15374         /* Clear any frame start delays used for debugging left by the BIOS */
15375         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15376                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15377
15378                 I915_WRITE(reg,
15379                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15380         }
15381
15382         if (crtc->active) {
15383                 struct intel_plane *plane;
15384
15385                 /* Disable everything but the primary plane */
15386                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15387                         const struct intel_plane_state *plane_state =
15388                                 to_intel_plane_state(plane->base.state);
15389
15390                         if (plane_state->base.visible &&
15391                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15392                                 intel_plane_disable_noatomic(crtc, plane);
15393                 }
15394         }
15395
15396         /* Adjust the state of the output pipe according to whether we
15397          * have active connectors/encoders. */
15398         if (crtc->active && !intel_crtc_has_encoders(crtc))
15399                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15400
15401         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15402                 /*
15403                  * We start out with underrun reporting disabled to avoid races.
15404                  * For correct bookkeeping mark this on active crtcs.
15405                  *
15406                  * Also on gmch platforms we dont have any hardware bits to
15407                  * disable the underrun reporting. Which means we need to start
15408                  * out with underrun reporting disabled also on inactive pipes,
15409                  * since otherwise we'll complain about the garbage we read when
15410                  * e.g. coming up after runtime pm.
15411                  *
15412                  * No protection against concurrent access is required - at
15413                  * worst a fifo underrun happens which also sets this to false.
15414                  */
15415                 crtc->cpu_fifo_underrun_disabled = true;
15416                 /*
15417                  * We track the PCH trancoder underrun reporting state
15418                  * within the crtc. With crtc for pipe A housing the underrun
15419                  * reporting state for PCH transcoder A, crtc for pipe B housing
15420                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15421                  * and marking underrun reporting as disabled for the non-existing
15422                  * PCH transcoders B and C would prevent enabling the south
15423                  * error interrupt (see cpt_can_enable_serr_int()).
15424                  */
15425                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15426                         crtc->pch_fifo_underrun_disabled = true;
15427         }
15428 }
15429
15430 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15431 {
15432         struct intel_connector *connector;
15433
15434         /* We need to check both for a crtc link (meaning that the
15435          * encoder is active and trying to read from a pipe) and the
15436          * pipe itself being active. */
15437         bool has_active_crtc = encoder->base.crtc &&
15438                 to_intel_crtc(encoder->base.crtc)->active;
15439
15440         connector = intel_encoder_find_connector(encoder);
15441         if (connector && !has_active_crtc) {
15442                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15443                               encoder->base.base.id,
15444                               encoder->base.name);
15445
15446                 /* Connector is active, but has no active pipe. This is
15447                  * fallout from our resume register restoring. Disable
15448                  * the encoder manually again. */
15449                 if (encoder->base.crtc) {
15450                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15451
15452                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15453                                       encoder->base.base.id,
15454                                       encoder->base.name);
15455                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15456                         if (encoder->post_disable)
15457                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15458                 }
15459                 encoder->base.crtc = NULL;
15460
15461                 /* Inconsistent output/port/pipe state happens presumably due to
15462                  * a bug in one of the get_hw_state functions. Or someplace else
15463                  * in our code, like the register restore mess on resume. Clamp
15464                  * things to off as a safer default. */
15465
15466                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15467                 connector->base.encoder = NULL;
15468         }
15469
15470         /* notify opregion of the sanitized encoder state */
15471         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
15472 }
15473
15474 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15475 {
15476         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15477
15478         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15479                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15480                 i915_disable_vga(dev_priv);
15481         }
15482 }
15483
15484 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15485 {
15486         /* This function can be called both from intel_modeset_setup_hw_state or
15487          * at a very early point in our resume sequence, where the power well
15488          * structures are not yet restored. Since this function is at a very
15489          * paranoid "someone might have enabled VGA while we were not looking"
15490          * level, just check if the power well is enabled instead of trying to
15491          * follow the "don't touch the power well if we don't need it" policy
15492          * the rest of the driver uses. */
15493         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15494                 return;
15495
15496         i915_redisable_vga_power_on(dev_priv);
15497
15498         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15499 }
15500
15501 /* FIXME read out full plane state for all planes */
15502 static void readout_plane_state(struct drm_i915_private *dev_priv)
15503 {
15504         struct intel_plane *plane;
15505         struct intel_crtc *crtc;
15506
15507         for_each_intel_plane(&dev_priv->drm, plane) {
15508                 struct intel_plane_state *plane_state =
15509                         to_intel_plane_state(plane->base.state);
15510                 struct intel_crtc_state *crtc_state;
15511                 enum pipe pipe = PIPE_A;
15512                 bool visible;
15513
15514                 visible = plane->get_hw_state(plane, &pipe);
15515
15516                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15517                 crtc_state = to_intel_crtc_state(crtc->base.state);
15518
15519                 intel_set_plane_visible(crtc_state, plane_state, visible);
15520
15521                 DRM_DEBUG_KMS("[PLANE:%d:%s] hw state readout: %s, pipe %c\n",
15522                               plane->base.base.id, plane->base.name,
15523                               enableddisabled(visible), pipe_name(pipe));
15524         }
15525
15526         for_each_intel_crtc(&dev_priv->drm, crtc) {
15527                 struct intel_crtc_state *crtc_state =
15528                         to_intel_crtc_state(crtc->base.state);
15529
15530                 fixup_active_planes(crtc_state);
15531         }
15532 }
15533
15534 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15535 {
15536         struct drm_i915_private *dev_priv = to_i915(dev);
15537         enum pipe pipe;
15538         struct intel_crtc *crtc;
15539         struct intel_encoder *encoder;
15540         struct intel_connector *connector;
15541         struct drm_connector_list_iter conn_iter;
15542         int i;
15543
15544         dev_priv->active_crtcs = 0;
15545
15546         for_each_intel_crtc(dev, crtc) {
15547                 struct intel_crtc_state *crtc_state =
15548                         to_intel_crtc_state(crtc->base.state);
15549
15550                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15551                 memset(crtc_state, 0, sizeof(*crtc_state));
15552                 crtc_state->base.crtc = &crtc->base;
15553
15554                 crtc_state->base.active = crtc_state->base.enable =
15555                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15556
15557                 crtc->base.enabled = crtc_state->base.enable;
15558                 crtc->active = crtc_state->base.active;
15559
15560                 if (crtc_state->base.active)
15561                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15562
15563                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15564                               crtc->base.base.id, crtc->base.name,
15565                               enableddisabled(crtc_state->base.active));
15566         }
15567
15568         readout_plane_state(dev_priv);
15569
15570         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15571                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15572
15573                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15574                                                         &pll->state.hw_state);
15575                 pll->state.crtc_mask = 0;
15576                 for_each_intel_crtc(dev, crtc) {
15577                         struct intel_crtc_state *crtc_state =
15578                                 to_intel_crtc_state(crtc->base.state);
15579
15580                         if (crtc_state->base.active &&
15581                             crtc_state->shared_dpll == pll)
15582                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15583                 }
15584                 pll->active_mask = pll->state.crtc_mask;
15585
15586                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15587                               pll->info->name, pll->state.crtc_mask, pll->on);
15588         }
15589
15590         for_each_intel_encoder(dev, encoder) {
15591                 pipe = 0;
15592
15593                 if (encoder->get_hw_state(encoder, &pipe)) {
15594                         struct intel_crtc_state *crtc_state;
15595
15596                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15597                         crtc_state = to_intel_crtc_state(crtc->base.state);
15598
15599                         encoder->base.crtc = &crtc->base;
15600                         encoder->get_config(encoder, crtc_state);
15601                 } else {
15602                         encoder->base.crtc = NULL;
15603                 }
15604
15605                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15606                               encoder->base.base.id, encoder->base.name,
15607                               enableddisabled(encoder->base.crtc),
15608                               pipe_name(pipe));
15609         }
15610
15611         drm_connector_list_iter_begin(dev, &conn_iter);
15612         for_each_intel_connector_iter(connector, &conn_iter) {
15613                 if (connector->get_hw_state(connector)) {
15614                         connector->base.dpms = DRM_MODE_DPMS_ON;
15615
15616                         encoder = connector->encoder;
15617                         connector->base.encoder = &encoder->base;
15618
15619                         if (encoder->base.crtc &&
15620                             encoder->base.crtc->state->active) {
15621                                 /*
15622                                  * This has to be done during hardware readout
15623                                  * because anything calling .crtc_disable may
15624                                  * rely on the connector_mask being accurate.
15625                                  */
15626                                 encoder->base.crtc->state->connector_mask |=
15627                                         drm_connector_mask(&connector->base);
15628                                 encoder->base.crtc->state->encoder_mask |=
15629                                         drm_encoder_mask(&encoder->base);
15630                         }
15631
15632                 } else {
15633                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15634                         connector->base.encoder = NULL;
15635                 }
15636                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15637                               connector->base.base.id, connector->base.name,
15638                               enableddisabled(connector->base.encoder));
15639         }
15640         drm_connector_list_iter_end(&conn_iter);
15641
15642         for_each_intel_crtc(dev, crtc) {
15643                 struct intel_crtc_state *crtc_state =
15644                         to_intel_crtc_state(crtc->base.state);
15645                 int min_cdclk = 0;
15646
15647                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15648                 if (crtc_state->base.active) {
15649                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15650                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
15651                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
15652                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15653                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15654
15655                         /*
15656                          * The initial mode needs to be set in order to keep
15657                          * the atomic core happy. It wants a valid mode if the
15658                          * crtc's enabled, so we do the above call.
15659                          *
15660                          * But we don't set all the derived state fully, hence
15661                          * set a flag to indicate that a full recalculation is
15662                          * needed on the next commit.
15663                          */
15664                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15665
15666                         intel_crtc_compute_pixel_rate(crtc_state);
15667
15668                         if (dev_priv->display.modeset_calc_cdclk) {
15669                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15670                                 if (WARN_ON(min_cdclk < 0))
15671                                         min_cdclk = 0;
15672                         }
15673
15674                         drm_calc_timestamping_constants(&crtc->base,
15675                                                         &crtc_state->base.adjusted_mode);
15676                         update_scanline_offset(crtc);
15677                 }
15678
15679                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15680                 dev_priv->min_voltage_level[crtc->pipe] =
15681                         crtc_state->min_voltage_level;
15682
15683                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15684         }
15685 }
15686
15687 static void
15688 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15689 {
15690         struct intel_encoder *encoder;
15691
15692         for_each_intel_encoder(&dev_priv->drm, encoder) {
15693                 u64 get_domains;
15694                 enum intel_display_power_domain domain;
15695                 struct intel_crtc_state *crtc_state;
15696
15697                 if (!encoder->get_power_domains)
15698                         continue;
15699
15700                 /*
15701                  * MST-primary and inactive encoders don't have a crtc state
15702                  * and neither of these require any power domain references.
15703                  */
15704                 if (!encoder->base.crtc)
15705                         continue;
15706
15707                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
15708                 get_domains = encoder->get_power_domains(encoder, crtc_state);
15709                 for_each_power_domain(domain, get_domains)
15710                         intel_display_power_get(dev_priv, domain);
15711         }
15712 }
15713
15714 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15715 {
15716         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15717         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15718                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15719                            DARBF_GATING_DIS);
15720
15721         if (IS_HASWELL(dev_priv)) {
15722                 /*
15723                  * WaRsPkgCStateDisplayPMReq:hsw
15724                  * System hang if this isn't done before disabling all planes!
15725                  */
15726                 I915_WRITE(CHICKEN_PAR1_1,
15727                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15728         }
15729 }
15730
15731 /* Scan out the current hw modeset state,
15732  * and sanitizes it to the current state
15733  */
15734 static void
15735 intel_modeset_setup_hw_state(struct drm_device *dev,
15736                              struct drm_modeset_acquire_ctx *ctx)
15737 {
15738         struct drm_i915_private *dev_priv = to_i915(dev);
15739         struct intel_crtc *crtc;
15740         struct intel_encoder *encoder;
15741         int i;
15742
15743         intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
15744
15745         intel_early_display_was(dev_priv);
15746         intel_modeset_readout_hw_state(dev);
15747
15748         /* HW state is read out, now we need to sanitize this mess. */
15749         get_encoder_power_domains(dev_priv);
15750
15751         /*
15752          * intel_sanitize_plane_mapping() may need to do vblank
15753          * waits, so we need vblank interrupts restored beforehand.
15754          */
15755         for_each_intel_crtc(&dev_priv->drm, crtc) {
15756                 drm_crtc_vblank_reset(&crtc->base);
15757
15758                 if (crtc->active)
15759                         drm_crtc_vblank_on(&crtc->base);
15760         }
15761
15762         intel_sanitize_plane_mapping(dev_priv);
15763
15764         for_each_intel_encoder(dev, encoder)
15765                 intel_sanitize_encoder(encoder);
15766
15767         for_each_intel_crtc(&dev_priv->drm, crtc) {
15768                 intel_sanitize_crtc(crtc, ctx);
15769                 intel_dump_pipe_config(crtc, crtc->config,
15770                                        "[setup_hw_state]");
15771         }
15772
15773         intel_modeset_update_connector_atomic_state(dev);
15774
15775         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15776                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15777
15778                 if (!pll->on || pll->active_mask)
15779                         continue;
15780
15781                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
15782                               pll->info->name);
15783
15784                 pll->info->funcs->disable(dev_priv, pll);
15785                 pll->on = false;
15786         }
15787
15788         if (IS_G4X(dev_priv)) {
15789                 g4x_wm_get_hw_state(dev);
15790                 g4x_wm_sanitize(dev_priv);
15791         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15792                 vlv_wm_get_hw_state(dev);
15793                 vlv_wm_sanitize(dev_priv);
15794         } else if (INTEL_GEN(dev_priv) >= 9) {
15795                 skl_wm_get_hw_state(dev);
15796         } else if (HAS_PCH_SPLIT(dev_priv)) {
15797                 ilk_wm_get_hw_state(dev);
15798         }
15799
15800         for_each_intel_crtc(dev, crtc) {
15801                 u64 put_domains;
15802
15803                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15804                 if (WARN_ON(put_domains))
15805                         modeset_put_power_domains(dev_priv, put_domains);
15806         }
15807
15808         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT);
15809
15810         intel_fbc_init_pipe_state(dev_priv);
15811 }
15812
15813 void intel_display_resume(struct drm_device *dev)
15814 {
15815         struct drm_i915_private *dev_priv = to_i915(dev);
15816         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15817         struct drm_modeset_acquire_ctx ctx;
15818         int ret;
15819
15820         dev_priv->modeset_restore_state = NULL;
15821         if (state)
15822                 state->acquire_ctx = &ctx;
15823
15824         drm_modeset_acquire_init(&ctx, 0);
15825
15826         while (1) {
15827                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15828                 if (ret != -EDEADLK)
15829                         break;
15830
15831                 drm_modeset_backoff(&ctx);
15832         }
15833
15834         if (!ret)
15835                 ret = __intel_display_resume(dev, state, &ctx);
15836
15837         intel_enable_ipc(dev_priv);
15838         drm_modeset_drop_locks(&ctx);
15839         drm_modeset_acquire_fini(&ctx);
15840
15841         if (ret)
15842                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15843         if (state)
15844                 drm_atomic_state_put(state);
15845 }
15846
15847 static void intel_hpd_poll_fini(struct drm_device *dev)
15848 {
15849         struct intel_connector *connector;
15850         struct drm_connector_list_iter conn_iter;
15851
15852         /* Kill all the work that may have been queued by hpd. */
15853         drm_connector_list_iter_begin(dev, &conn_iter);
15854         for_each_intel_connector_iter(connector, &conn_iter) {
15855                 if (connector->modeset_retry_work.func)
15856                         cancel_work_sync(&connector->modeset_retry_work);
15857                 if (connector->hdcp_shim) {
15858                         cancel_delayed_work_sync(&connector->hdcp_check_work);
15859                         cancel_work_sync(&connector->hdcp_prop_work);
15860                 }
15861         }
15862         drm_connector_list_iter_end(&conn_iter);
15863 }
15864
15865 void intel_modeset_cleanup(struct drm_device *dev)
15866 {
15867         struct drm_i915_private *dev_priv = to_i915(dev);
15868
15869         flush_workqueue(dev_priv->modeset_wq);
15870
15871         flush_work(&dev_priv->atomic_helper.free_work);
15872         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15873
15874         /*
15875          * Interrupts and polling as the first thing to avoid creating havoc.
15876          * Too much stuff here (turning of connectors, ...) would
15877          * experience fancy races otherwise.
15878          */
15879         intel_irq_uninstall(dev_priv);
15880
15881         /*
15882          * Due to the hpd irq storm handling the hotplug work can re-arm the
15883          * poll handlers. Hence disable polling after hpd handling is shut down.
15884          */
15885         intel_hpd_poll_fini(dev);
15886
15887         /* poll work can call into fbdev, hence clean that up afterwards */
15888         intel_fbdev_fini(dev_priv);
15889
15890         intel_unregister_dsm_handler();
15891
15892         intel_fbc_global_disable(dev_priv);
15893
15894         /* flush any delayed tasks or pending work */
15895         flush_scheduled_work();
15896
15897         drm_mode_config_cleanup(dev);
15898
15899         intel_cleanup_overlay(dev_priv);
15900
15901         intel_teardown_gmbus(dev_priv);
15902
15903         destroy_workqueue(dev_priv->modeset_wq);
15904 }
15905
15906 /*
15907  * set vga decode state - true == enable VGA decode
15908  */
15909 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15910 {
15911         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15912         u16 gmch_ctrl;
15913
15914         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15915                 DRM_ERROR("failed to read control word\n");
15916                 return -EIO;
15917         }
15918
15919         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15920                 return 0;
15921
15922         if (state)
15923                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15924         else
15925                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15926
15927         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15928                 DRM_ERROR("failed to write control word\n");
15929                 return -EIO;
15930         }
15931
15932         return 0;
15933 }
15934
15935 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15936
15937 struct intel_display_error_state {
15938
15939         u32 power_well_driver;
15940
15941         int num_transcoders;
15942
15943         struct intel_cursor_error_state {
15944                 u32 control;
15945                 u32 position;
15946                 u32 base;
15947                 u32 size;
15948         } cursor[I915_MAX_PIPES];
15949
15950         struct intel_pipe_error_state {
15951                 bool power_domain_on;
15952                 u32 source;
15953                 u32 stat;
15954         } pipe[I915_MAX_PIPES];
15955
15956         struct intel_plane_error_state {
15957                 u32 control;
15958                 u32 stride;
15959                 u32 size;
15960                 u32 pos;
15961                 u32 addr;
15962                 u32 surface;
15963                 u32 tile_offset;
15964         } plane[I915_MAX_PIPES];
15965
15966         struct intel_transcoder_error_state {
15967                 bool power_domain_on;
15968                 enum transcoder cpu_transcoder;
15969
15970                 u32 conf;
15971
15972                 u32 htotal;
15973                 u32 hblank;
15974                 u32 hsync;
15975                 u32 vtotal;
15976                 u32 vblank;
15977                 u32 vsync;
15978         } transcoder[4];
15979 };
15980
15981 struct intel_display_error_state *
15982 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15983 {
15984         struct intel_display_error_state *error;
15985         int transcoders[] = {
15986                 TRANSCODER_A,
15987                 TRANSCODER_B,
15988                 TRANSCODER_C,
15989                 TRANSCODER_EDP,
15990         };
15991         int i;
15992
15993         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15994                 return NULL;
15995
15996         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15997         if (error == NULL)
15998                 return NULL;
15999
16000         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16001                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
16002
16003         for_each_pipe(dev_priv, i) {
16004                 error->pipe[i].power_domain_on =
16005                         __intel_display_power_is_enabled(dev_priv,
16006                                                          POWER_DOMAIN_PIPE(i));
16007                 if (!error->pipe[i].power_domain_on)
16008                         continue;
16009
16010                 error->cursor[i].control = I915_READ(CURCNTR(i));
16011                 error->cursor[i].position = I915_READ(CURPOS(i));
16012                 error->cursor[i].base = I915_READ(CURBASE(i));
16013
16014                 error->plane[i].control = I915_READ(DSPCNTR(i));
16015                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16016                 if (INTEL_GEN(dev_priv) <= 3) {
16017                         error->plane[i].size = I915_READ(DSPSIZE(i));
16018                         error->plane[i].pos = I915_READ(DSPPOS(i));
16019                 }
16020                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16021                         error->plane[i].addr = I915_READ(DSPADDR(i));
16022                 if (INTEL_GEN(dev_priv) >= 4) {
16023                         error->plane[i].surface = I915_READ(DSPSURF(i));
16024                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16025                 }
16026
16027                 error->pipe[i].source = I915_READ(PIPESRC(i));
16028
16029                 if (HAS_GMCH_DISPLAY(dev_priv))
16030                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16031         }
16032
16033         /* Note: this does not include DSI transcoders. */
16034         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16035         if (HAS_DDI(dev_priv))
16036                 error->num_transcoders++; /* Account for eDP. */
16037
16038         for (i = 0; i < error->num_transcoders; i++) {
16039                 enum transcoder cpu_transcoder = transcoders[i];
16040
16041                 error->transcoder[i].power_domain_on =
16042                         __intel_display_power_is_enabled(dev_priv,
16043                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16044                 if (!error->transcoder[i].power_domain_on)
16045                         continue;
16046
16047                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16048
16049                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16050                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16051                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16052                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16053                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16054                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16055                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16056         }
16057
16058         return error;
16059 }
16060
16061 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16062
16063 void
16064 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16065                                 struct intel_display_error_state *error)
16066 {
16067         struct drm_i915_private *dev_priv = m->i915;
16068         int i;
16069
16070         if (!error)
16071                 return;
16072
16073         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16074         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16075                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16076                            error->power_well_driver);
16077         for_each_pipe(dev_priv, i) {
16078                 err_printf(m, "Pipe [%d]:\n", i);
16079                 err_printf(m, "  Power: %s\n",
16080                            onoff(error->pipe[i].power_domain_on));
16081                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16082                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16083
16084                 err_printf(m, "Plane [%d]:\n", i);
16085                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16086                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16087                 if (INTEL_GEN(dev_priv) <= 3) {
16088                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16089                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16090                 }
16091                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16092                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16093                 if (INTEL_GEN(dev_priv) >= 4) {
16094                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16095                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16096                 }
16097
16098                 err_printf(m, "Cursor [%d]:\n", i);
16099                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16100                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16101                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16102         }
16103
16104         for (i = 0; i < error->num_transcoders; i++) {
16105                 err_printf(m, "CPU transcoder: %s\n",
16106                            transcoder_name(error->transcoder[i].cpu_transcoder));
16107                 err_printf(m, "  Power: %s\n",
16108                            onoff(error->transcoder[i].power_domain_on));
16109                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16110                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16111                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16112                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16113                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16114                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16115                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16116         }
16117 }
16118
16119 #endif