]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/gpu/drm/i915/intel_display.c
ce88c86d0813f480233fdfd6707cfcec07ede8a4
[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(const struct intel_crtc_state *crtc_state)
12106 {
12107         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
12108         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12109
12110         /*
12111          * The scanline counter increments at the leading edge of hsync.
12112          *
12113          * On most platforms it starts counting from vtotal-1 on the
12114          * first active line. That means the scanline counter value is
12115          * always one less than what we would expect. Ie. just after
12116          * start of vblank, which also occurs at start of hsync (on the
12117          * last active line), the scanline counter will read vblank_start-1.
12118          *
12119          * On gen2 the scanline counter starts counting from 1 instead
12120          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12121          * to keep the value positive), instead of adding one.
12122          *
12123          * On HSW+ the behaviour of the scanline counter depends on the output
12124          * type. For DP ports it behaves like most other platforms, but on HDMI
12125          * there's an extra 1 line difference. So we need to add two instead of
12126          * one to the value.
12127          *
12128          * On VLV/CHV DSI the scanline counter would appear to increment
12129          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12130          * that means we can't tell whether we're in vblank or not while
12131          * we're on that particular line. We must still set scanline_offset
12132          * to 1 so that the vblank timestamps come out correct when we query
12133          * the scanline counter from within the vblank interrupt handler.
12134          * However if queried just before the start of vblank we'll get an
12135          * answer that's slightly in the future.
12136          */
12137         if (IS_GEN2(dev_priv)) {
12138                 const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
12139                 int vtotal;
12140
12141                 vtotal = adjusted_mode->crtc_vtotal;
12142                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12143                         vtotal /= 2;
12144
12145                 crtc->scanline_offset = vtotal - 1;
12146         } else if (HAS_DDI(dev_priv) &&
12147                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI)) {
12148                 crtc->scanline_offset = 2;
12149         } else
12150                 crtc->scanline_offset = 1;
12151 }
12152
12153 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12154 {
12155         struct drm_device *dev = state->dev;
12156         struct drm_i915_private *dev_priv = to_i915(dev);
12157         struct drm_crtc *crtc;
12158         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12159         int i;
12160
12161         if (!dev_priv->display.crtc_compute_clock)
12162                 return;
12163
12164         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12165                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12166                 struct intel_shared_dpll *old_dpll =
12167                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12168
12169                 if (!needs_modeset(new_crtc_state))
12170                         continue;
12171
12172                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12173
12174                 if (!old_dpll)
12175                         continue;
12176
12177                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12178         }
12179 }
12180
12181 /*
12182  * This implements the workaround described in the "notes" section of the mode
12183  * set sequence documentation. When going from no pipes or single pipe to
12184  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12185  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12186  */
12187 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12188 {
12189         struct drm_crtc_state *crtc_state;
12190         struct intel_crtc *intel_crtc;
12191         struct drm_crtc *crtc;
12192         struct intel_crtc_state *first_crtc_state = NULL;
12193         struct intel_crtc_state *other_crtc_state = NULL;
12194         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12195         int i;
12196
12197         /* look at all crtc's that are going to be enabled in during modeset */
12198         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12199                 intel_crtc = to_intel_crtc(crtc);
12200
12201                 if (!crtc_state->active || !needs_modeset(crtc_state))
12202                         continue;
12203
12204                 if (first_crtc_state) {
12205                         other_crtc_state = to_intel_crtc_state(crtc_state);
12206                         break;
12207                 } else {
12208                         first_crtc_state = to_intel_crtc_state(crtc_state);
12209                         first_pipe = intel_crtc->pipe;
12210                 }
12211         }
12212
12213         /* No workaround needed? */
12214         if (!first_crtc_state)
12215                 return 0;
12216
12217         /* w/a possibly needed, check how many crtc's are already enabled. */
12218         for_each_intel_crtc(state->dev, intel_crtc) {
12219                 struct intel_crtc_state *pipe_config;
12220
12221                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12222                 if (IS_ERR(pipe_config))
12223                         return PTR_ERR(pipe_config);
12224
12225                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12226
12227                 if (!pipe_config->base.active ||
12228                     needs_modeset(&pipe_config->base))
12229                         continue;
12230
12231                 /* 2 or more enabled crtcs means no need for w/a */
12232                 if (enabled_pipe != INVALID_PIPE)
12233                         return 0;
12234
12235                 enabled_pipe = intel_crtc->pipe;
12236         }
12237
12238         if (enabled_pipe != INVALID_PIPE)
12239                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12240         else if (other_crtc_state)
12241                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12242
12243         return 0;
12244 }
12245
12246 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12247 {
12248         struct drm_crtc *crtc;
12249
12250         /* Add all pipes to the state */
12251         for_each_crtc(state->dev, crtc) {
12252                 struct drm_crtc_state *crtc_state;
12253
12254                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12255                 if (IS_ERR(crtc_state))
12256                         return PTR_ERR(crtc_state);
12257         }
12258
12259         return 0;
12260 }
12261
12262 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12263 {
12264         struct drm_crtc *crtc;
12265
12266         /*
12267          * Add all pipes to the state, and force
12268          * a modeset on all the active ones.
12269          */
12270         for_each_crtc(state->dev, crtc) {
12271                 struct drm_crtc_state *crtc_state;
12272                 int ret;
12273
12274                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12275                 if (IS_ERR(crtc_state))
12276                         return PTR_ERR(crtc_state);
12277
12278                 if (!crtc_state->active || needs_modeset(crtc_state))
12279                         continue;
12280
12281                 crtc_state->mode_changed = true;
12282
12283                 ret = drm_atomic_add_affected_connectors(state, crtc);
12284                 if (ret)
12285                         return ret;
12286
12287                 ret = drm_atomic_add_affected_planes(state, crtc);
12288                 if (ret)
12289                         return ret;
12290         }
12291
12292         return 0;
12293 }
12294
12295 static int intel_modeset_checks(struct drm_atomic_state *state)
12296 {
12297         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12298         struct drm_i915_private *dev_priv = to_i915(state->dev);
12299         struct drm_crtc *crtc;
12300         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12301         int ret = 0, i;
12302
12303         if (!check_digital_port_conflicts(state)) {
12304                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12305                 return -EINVAL;
12306         }
12307
12308         intel_state->modeset = true;
12309         intel_state->active_crtcs = dev_priv->active_crtcs;
12310         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12311         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12312
12313         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12314                 if (new_crtc_state->active)
12315                         intel_state->active_crtcs |= 1 << i;
12316                 else
12317                         intel_state->active_crtcs &= ~(1 << i);
12318
12319                 if (old_crtc_state->active != new_crtc_state->active)
12320                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12321         }
12322
12323         /*
12324          * See if the config requires any additional preparation, e.g.
12325          * to adjust global state with pipes off.  We need to do this
12326          * here so we can get the modeset_pipe updated config for the new
12327          * mode set on this crtc.  For other crtcs we need to use the
12328          * adjusted_mode bits in the crtc directly.
12329          */
12330         if (dev_priv->display.modeset_calc_cdclk) {
12331                 ret = dev_priv->display.modeset_calc_cdclk(state);
12332                 if (ret < 0)
12333                         return ret;
12334
12335                 /*
12336                  * Writes to dev_priv->cdclk.logical must protected by
12337                  * holding all the crtc locks, even if we don't end up
12338                  * touching the hardware
12339                  */
12340                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12341                                         &intel_state->cdclk.logical)) {
12342                         ret = intel_lock_all_pipes(state);
12343                         if (ret < 0)
12344                                 return ret;
12345                 }
12346
12347                 /* All pipes must be switched off while we change the cdclk. */
12348                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12349                                               &intel_state->cdclk.actual)) {
12350                         ret = intel_modeset_all_pipes(state);
12351                         if (ret < 0)
12352                                 return ret;
12353                 }
12354
12355                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12356                               intel_state->cdclk.logical.cdclk,
12357                               intel_state->cdclk.actual.cdclk);
12358                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12359                               intel_state->cdclk.logical.voltage_level,
12360                               intel_state->cdclk.actual.voltage_level);
12361         } else {
12362                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12363         }
12364
12365         intel_modeset_clear_plls(state);
12366
12367         if (IS_HASWELL(dev_priv))
12368                 return haswell_mode_set_planes_workaround(state);
12369
12370         return 0;
12371 }
12372
12373 /*
12374  * Handle calculation of various watermark data at the end of the atomic check
12375  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12376  * handlers to ensure that all derived state has been updated.
12377  */
12378 static int calc_watermark_data(struct drm_atomic_state *state)
12379 {
12380         struct drm_device *dev = state->dev;
12381         struct drm_i915_private *dev_priv = to_i915(dev);
12382
12383         /* Is there platform-specific watermark information to calculate? */
12384         if (dev_priv->display.compute_global_watermarks)
12385                 return dev_priv->display.compute_global_watermarks(state);
12386
12387         return 0;
12388 }
12389
12390 /**
12391  * intel_atomic_check - validate state object
12392  * @dev: drm device
12393  * @state: state to validate
12394  */
12395 static int intel_atomic_check(struct drm_device *dev,
12396                               struct drm_atomic_state *state)
12397 {
12398         struct drm_i915_private *dev_priv = to_i915(dev);
12399         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12400         struct drm_crtc *crtc;
12401         struct drm_crtc_state *old_crtc_state, *crtc_state;
12402         int ret, i;
12403         bool any_ms = false;
12404
12405         /* Catch I915_MODE_FLAG_INHERITED */
12406         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12407                                       crtc_state, i) {
12408                 if (crtc_state->mode.private_flags !=
12409                     old_crtc_state->mode.private_flags)
12410                         crtc_state->mode_changed = true;
12411         }
12412
12413         ret = drm_atomic_helper_check_modeset(dev, state);
12414         if (ret)
12415                 return ret;
12416
12417         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12418                 struct intel_crtc_state *pipe_config =
12419                         to_intel_crtc_state(crtc_state);
12420
12421                 if (!needs_modeset(crtc_state))
12422                         continue;
12423
12424                 if (!crtc_state->enable) {
12425                         any_ms = true;
12426                         continue;
12427                 }
12428
12429                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12430                 if (ret) {
12431                         intel_dump_pipe_config(to_intel_crtc(crtc),
12432                                                pipe_config, "[failed]");
12433                         return ret;
12434                 }
12435
12436                 if (i915_modparams.fastboot &&
12437                     intel_pipe_config_compare(dev_priv,
12438                                         to_intel_crtc_state(old_crtc_state),
12439                                         pipe_config, true)) {
12440                         crtc_state->mode_changed = false;
12441                         pipe_config->update_pipe = true;
12442                 }
12443
12444                 if (needs_modeset(crtc_state))
12445                         any_ms = true;
12446
12447                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12448                                        needs_modeset(crtc_state) ?
12449                                        "[modeset]" : "[fastset]");
12450         }
12451
12452         if (any_ms) {
12453                 ret = intel_modeset_checks(state);
12454
12455                 if (ret)
12456                         return ret;
12457         } else {
12458                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12459         }
12460
12461         ret = drm_atomic_helper_check_planes(dev, state);
12462         if (ret)
12463                 return ret;
12464
12465         intel_fbc_choose_crtc(dev_priv, intel_state);
12466         return calc_watermark_data(state);
12467 }
12468
12469 static int intel_atomic_prepare_commit(struct drm_device *dev,
12470                                        struct drm_atomic_state *state)
12471 {
12472         return drm_atomic_helper_prepare_planes(dev, state);
12473 }
12474
12475 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12476 {
12477         struct drm_device *dev = crtc->base.dev;
12478
12479         if (!dev->max_vblank_count)
12480                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12481
12482         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12483 }
12484
12485 static void intel_update_crtc(struct drm_crtc *crtc,
12486                               struct drm_atomic_state *state,
12487                               struct drm_crtc_state *old_crtc_state,
12488                               struct drm_crtc_state *new_crtc_state)
12489 {
12490         struct drm_device *dev = crtc->dev;
12491         struct drm_i915_private *dev_priv = to_i915(dev);
12492         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12493         struct intel_crtc_state *old_intel_cstate = to_intel_crtc_state(old_crtc_state);
12494         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12495         bool modeset = needs_modeset(new_crtc_state);
12496         struct intel_plane_state *new_plane_state =
12497                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
12498                                                  to_intel_plane(crtc->primary));
12499
12500         if (modeset) {
12501                 update_scanline_offset(pipe_config);
12502                 dev_priv->display.crtc_enable(pipe_config, state);
12503
12504                 /* vblanks work again, re-enable pipe CRC. */
12505                 intel_crtc_enable_pipe_crc(intel_crtc);
12506         } else {
12507                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12508                                        pipe_config);
12509         }
12510
12511         if (new_plane_state)
12512                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
12513
12514         intel_begin_crtc_commit(crtc, old_crtc_state);
12515
12516         intel_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc,
12517                                     old_intel_cstate, pipe_config);
12518
12519         intel_finish_crtc_commit(crtc, old_crtc_state);
12520 }
12521
12522 static void intel_update_crtcs(struct drm_atomic_state *state)
12523 {
12524         struct drm_crtc *crtc;
12525         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12526         int i;
12527
12528         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12529                 if (!new_crtc_state->active)
12530                         continue;
12531
12532                 intel_update_crtc(crtc, state, old_crtc_state,
12533                                   new_crtc_state);
12534         }
12535 }
12536
12537 static void skl_update_crtcs(struct drm_atomic_state *state)
12538 {
12539         struct drm_i915_private *dev_priv = to_i915(state->dev);
12540         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12541         struct drm_crtc *crtc;
12542         struct intel_crtc *intel_crtc;
12543         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12544         struct intel_crtc_state *cstate;
12545         unsigned int updated = 0;
12546         bool progress;
12547         enum pipe pipe;
12548         int i;
12549         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
12550         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
12551
12552         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12553
12554         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12555                 /* ignore allocations for crtc's that have been turned off. */
12556                 if (new_crtc_state->active)
12557                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12558
12559         /* If 2nd DBuf slice required, enable it here */
12560         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
12561                 icl_dbuf_slices_update(dev_priv, required_slices);
12562
12563         /*
12564          * Whenever the number of active pipes changes, we need to make sure we
12565          * update the pipes in the right order so that their ddb allocations
12566          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12567          * cause pipe underruns and other bad stuff.
12568          */
12569         do {
12570                 progress = false;
12571
12572                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12573                         bool vbl_wait = false;
12574                         unsigned int cmask = drm_crtc_mask(crtc);
12575
12576                         intel_crtc = to_intel_crtc(crtc);
12577                         cstate = to_intel_crtc_state(new_crtc_state);
12578                         pipe = intel_crtc->pipe;
12579
12580                         if (updated & cmask || !cstate->base.active)
12581                                 continue;
12582
12583                         if (skl_ddb_allocation_overlaps(dev_priv,
12584                                                         entries,
12585                                                         &cstate->wm.skl.ddb,
12586                                                         i))
12587                                 continue;
12588
12589                         updated |= cmask;
12590                         entries[i] = &cstate->wm.skl.ddb;
12591
12592                         /*
12593                          * If this is an already active pipe, it's DDB changed,
12594                          * and this isn't the last pipe that needs updating
12595                          * then we need to wait for a vblank to pass for the
12596                          * new ddb allocation to take effect.
12597                          */
12598                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12599                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12600                             !new_crtc_state->active_changed &&
12601                             intel_state->wm_results.dirty_pipes != updated)
12602                                 vbl_wait = true;
12603
12604                         intel_update_crtc(crtc, state, old_crtc_state,
12605                                           new_crtc_state);
12606
12607                         if (vbl_wait)
12608                                 intel_wait_for_vblank(dev_priv, pipe);
12609
12610                         progress = true;
12611                 }
12612         } while (progress);
12613
12614         /* If 2nd DBuf slice is no more required disable it */
12615         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
12616                 icl_dbuf_slices_update(dev_priv, required_slices);
12617 }
12618
12619 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12620 {
12621         struct intel_atomic_state *state, *next;
12622         struct llist_node *freed;
12623
12624         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12625         llist_for_each_entry_safe(state, next, freed, freed)
12626                 drm_atomic_state_put(&state->base);
12627 }
12628
12629 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12630 {
12631         struct drm_i915_private *dev_priv =
12632                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12633
12634         intel_atomic_helper_free_state(dev_priv);
12635 }
12636
12637 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12638 {
12639         struct wait_queue_entry wait_fence, wait_reset;
12640         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12641
12642         init_wait_entry(&wait_fence, 0);
12643         init_wait_entry(&wait_reset, 0);
12644         for (;;) {
12645                 prepare_to_wait(&intel_state->commit_ready.wait,
12646                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12647                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12648                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12649
12650
12651                 if (i915_sw_fence_done(&intel_state->commit_ready)
12652                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12653                         break;
12654
12655                 schedule();
12656         }
12657         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12658         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12659 }
12660
12661 static void intel_atomic_cleanup_work(struct work_struct *work)
12662 {
12663         struct drm_atomic_state *state =
12664                 container_of(work, struct drm_atomic_state, commit_work);
12665         struct drm_i915_private *i915 = to_i915(state->dev);
12666
12667         drm_atomic_helper_cleanup_planes(&i915->drm, state);
12668         drm_atomic_helper_commit_cleanup_done(state);
12669         drm_atomic_state_put(state);
12670
12671         intel_atomic_helper_free_state(i915);
12672 }
12673
12674 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12675 {
12676         struct drm_device *dev = state->dev;
12677         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12678         struct drm_i915_private *dev_priv = to_i915(dev);
12679         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12680         struct intel_crtc_state *new_intel_crtc_state, *old_intel_crtc_state;
12681         struct drm_crtc *crtc;
12682         struct intel_crtc *intel_crtc;
12683         u64 put_domains[I915_MAX_PIPES] = {};
12684         int i;
12685
12686         intel_atomic_commit_fence_wait(intel_state);
12687
12688         drm_atomic_helper_wait_for_dependencies(state);
12689
12690         if (intel_state->modeset)
12691                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12692
12693         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12694                 old_intel_crtc_state = to_intel_crtc_state(old_crtc_state);
12695                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
12696                 intel_crtc = to_intel_crtc(crtc);
12697
12698                 if (needs_modeset(new_crtc_state) ||
12699                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12700
12701                         put_domains[intel_crtc->pipe] =
12702                                 modeset_get_crtc_power_domains(crtc,
12703                                         new_intel_crtc_state);
12704                 }
12705
12706                 if (!needs_modeset(new_crtc_state))
12707                         continue;
12708
12709                 intel_pre_plane_update(old_intel_crtc_state, new_intel_crtc_state);
12710
12711                 if (old_crtc_state->active) {
12712                         intel_crtc_disable_planes(intel_crtc, old_intel_crtc_state->active_planes);
12713
12714                         /*
12715                          * We need to disable pipe CRC before disabling the pipe,
12716                          * or we race against vblank off.
12717                          */
12718                         intel_crtc_disable_pipe_crc(intel_crtc);
12719
12720                         dev_priv->display.crtc_disable(old_intel_crtc_state, state);
12721                         intel_crtc->active = false;
12722                         intel_fbc_disable(intel_crtc);
12723                         intel_disable_shared_dpll(old_intel_crtc_state);
12724
12725                         /*
12726                          * Underruns don't always raise
12727                          * interrupts, so check manually.
12728                          */
12729                         intel_check_cpu_fifo_underruns(dev_priv);
12730                         intel_check_pch_fifo_underruns(dev_priv);
12731
12732                         if (!new_crtc_state->active) {
12733                                 /*
12734                                  * Make sure we don't call initial_watermarks
12735                                  * for ILK-style watermark updates.
12736                                  *
12737                                  * No clue what this is supposed to achieve.
12738                                  */
12739                                 if (INTEL_GEN(dev_priv) >= 9)
12740                                         dev_priv->display.initial_watermarks(intel_state,
12741                                                                              new_intel_crtc_state);
12742                         }
12743                 }
12744         }
12745
12746         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12747         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12748                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12749
12750         if (intel_state->modeset) {
12751                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12752
12753                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12754
12755                 /*
12756                  * SKL workaround: bspec recommends we disable the SAGV when we
12757                  * have more then one pipe enabled
12758                  */
12759                 if (!intel_can_enable_sagv(state))
12760                         intel_disable_sagv(dev_priv);
12761
12762                 intel_modeset_verify_disabled(dev, state);
12763         }
12764
12765         /* Complete the events for pipes that have now been disabled */
12766         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12767                 bool modeset = needs_modeset(new_crtc_state);
12768
12769                 /* Complete events for now disable pipes here. */
12770                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12771                         spin_lock_irq(&dev->event_lock);
12772                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12773                         spin_unlock_irq(&dev->event_lock);
12774
12775                         new_crtc_state->event = NULL;
12776                 }
12777         }
12778
12779         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12780         dev_priv->display.update_crtcs(state);
12781
12782         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12783          * already, but still need the state for the delayed optimization. To
12784          * fix this:
12785          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12786          * - schedule that vblank worker _before_ calling hw_done
12787          * - at the start of commit_tail, cancel it _synchrously
12788          * - switch over to the vblank wait helper in the core after that since
12789          *   we don't need out special handling any more.
12790          */
12791         drm_atomic_helper_wait_for_flip_done(dev, state);
12792
12793         /*
12794          * Now that the vblank has passed, we can go ahead and program the
12795          * optimal watermarks on platforms that need two-step watermark
12796          * programming.
12797          *
12798          * TODO: Move this (and other cleanup) to an async worker eventually.
12799          */
12800         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12801                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
12802
12803                 if (dev_priv->display.optimize_watermarks)
12804                         dev_priv->display.optimize_watermarks(intel_state,
12805                                                               new_intel_crtc_state);
12806         }
12807
12808         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12809                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12810
12811                 if (put_domains[i])
12812                         modeset_put_power_domains(dev_priv, put_domains[i]);
12813
12814                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12815         }
12816
12817         if (intel_state->modeset)
12818                 intel_verify_planes(intel_state);
12819
12820         if (intel_state->modeset && intel_can_enable_sagv(state))
12821                 intel_enable_sagv(dev_priv);
12822
12823         drm_atomic_helper_commit_hw_done(state);
12824
12825         if (intel_state->modeset) {
12826                 /* As one of the primary mmio accessors, KMS has a high
12827                  * likelihood of triggering bugs in unclaimed access. After we
12828                  * finish modesetting, see if an error has been flagged, and if
12829                  * so enable debugging for the next modeset - and hope we catch
12830                  * the culprit.
12831                  */
12832                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12833                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12834         }
12835
12836         /*
12837          * Defer the cleanup of the old state to a separate worker to not
12838          * impede the current task (userspace for blocking modesets) that
12839          * are executed inline. For out-of-line asynchronous modesets/flips,
12840          * deferring to a new worker seems overkill, but we would place a
12841          * schedule point (cond_resched()) here anyway to keep latencies
12842          * down.
12843          */
12844         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
12845         queue_work(system_highpri_wq, &state->commit_work);
12846 }
12847
12848 static void intel_atomic_commit_work(struct work_struct *work)
12849 {
12850         struct drm_atomic_state *state =
12851                 container_of(work, struct drm_atomic_state, commit_work);
12852
12853         intel_atomic_commit_tail(state);
12854 }
12855
12856 static int __i915_sw_fence_call
12857 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12858                           enum i915_sw_fence_notify notify)
12859 {
12860         struct intel_atomic_state *state =
12861                 container_of(fence, struct intel_atomic_state, commit_ready);
12862
12863         switch (notify) {
12864         case FENCE_COMPLETE:
12865                 /* we do blocking waits in the worker, nothing to do here */
12866                 break;
12867         case FENCE_FREE:
12868                 {
12869                         struct intel_atomic_helper *helper =
12870                                 &to_i915(state->base.dev)->atomic_helper;
12871
12872                         if (llist_add(&state->freed, &helper->free_list))
12873                                 schedule_work(&helper->free_work);
12874                         break;
12875                 }
12876         }
12877
12878         return NOTIFY_DONE;
12879 }
12880
12881 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12882 {
12883         struct drm_plane_state *old_plane_state, *new_plane_state;
12884         struct drm_plane *plane;
12885         int i;
12886
12887         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12888                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12889                                   intel_fb_obj(new_plane_state->fb),
12890                                   to_intel_plane(plane)->frontbuffer_bit);
12891 }
12892
12893 /**
12894  * intel_atomic_commit - commit validated state object
12895  * @dev: DRM device
12896  * @state: the top-level driver state object
12897  * @nonblock: nonblocking commit
12898  *
12899  * This function commits a top-level state object that has been validated
12900  * with drm_atomic_helper_check().
12901  *
12902  * RETURNS
12903  * Zero for success or -errno.
12904  */
12905 static int intel_atomic_commit(struct drm_device *dev,
12906                                struct drm_atomic_state *state,
12907                                bool nonblock)
12908 {
12909         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12910         struct drm_i915_private *dev_priv = to_i915(dev);
12911         int ret = 0;
12912
12913         drm_atomic_state_get(state);
12914         i915_sw_fence_init(&intel_state->commit_ready,
12915                            intel_atomic_commit_ready);
12916
12917         /*
12918          * The intel_legacy_cursor_update() fast path takes care
12919          * of avoiding the vblank waits for simple cursor
12920          * movement and flips. For cursor on/off and size changes,
12921          * we want to perform the vblank waits so that watermark
12922          * updates happen during the correct frames. Gen9+ have
12923          * double buffered watermarks and so shouldn't need this.
12924          *
12925          * Unset state->legacy_cursor_update before the call to
12926          * drm_atomic_helper_setup_commit() because otherwise
12927          * drm_atomic_helper_wait_for_flip_done() is a noop and
12928          * we get FIFO underruns because we didn't wait
12929          * for vblank.
12930          *
12931          * FIXME doing watermarks and fb cleanup from a vblank worker
12932          * (assuming we had any) would solve these problems.
12933          */
12934         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12935                 struct intel_crtc_state *new_crtc_state;
12936                 struct intel_crtc *crtc;
12937                 int i;
12938
12939                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12940                         if (new_crtc_state->wm.need_postvbl_update ||
12941                             new_crtc_state->update_wm_post)
12942                                 state->legacy_cursor_update = false;
12943         }
12944
12945         ret = intel_atomic_prepare_commit(dev, state);
12946         if (ret) {
12947                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12948                 i915_sw_fence_commit(&intel_state->commit_ready);
12949                 return ret;
12950         }
12951
12952         ret = drm_atomic_helper_setup_commit(state, nonblock);
12953         if (!ret)
12954                 ret = drm_atomic_helper_swap_state(state, true);
12955
12956         if (ret) {
12957                 i915_sw_fence_commit(&intel_state->commit_ready);
12958
12959                 drm_atomic_helper_cleanup_planes(dev, state);
12960                 return ret;
12961         }
12962         dev_priv->wm.distrust_bios_wm = false;
12963         intel_shared_dpll_swap_state(state);
12964         intel_atomic_track_fbs(state);
12965
12966         if (intel_state->modeset) {
12967                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12968                        sizeof(intel_state->min_cdclk));
12969                 memcpy(dev_priv->min_voltage_level,
12970                        intel_state->min_voltage_level,
12971                        sizeof(intel_state->min_voltage_level));
12972                 dev_priv->active_crtcs = intel_state->active_crtcs;
12973                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12974                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12975         }
12976
12977         drm_atomic_state_get(state);
12978         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12979
12980         i915_sw_fence_commit(&intel_state->commit_ready);
12981         if (nonblock && intel_state->modeset) {
12982                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12983         } else if (nonblock) {
12984                 queue_work(system_unbound_wq, &state->commit_work);
12985         } else {
12986                 if (intel_state->modeset)
12987                         flush_workqueue(dev_priv->modeset_wq);
12988                 intel_atomic_commit_tail(state);
12989         }
12990
12991         return 0;
12992 }
12993
12994 static const struct drm_crtc_funcs intel_crtc_funcs = {
12995         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12996         .set_config = drm_atomic_helper_set_config,
12997         .destroy = intel_crtc_destroy,
12998         .page_flip = drm_atomic_helper_page_flip,
12999         .atomic_duplicate_state = intel_crtc_duplicate_state,
13000         .atomic_destroy_state = intel_crtc_destroy_state,
13001         .set_crc_source = intel_crtc_set_crc_source,
13002         .verify_crc_source = intel_crtc_verify_crc_source,
13003         .get_crc_sources = intel_crtc_get_crc_sources,
13004 };
13005
13006 struct wait_rps_boost {
13007         struct wait_queue_entry wait;
13008
13009         struct drm_crtc *crtc;
13010         struct i915_request *request;
13011 };
13012
13013 static int do_rps_boost(struct wait_queue_entry *_wait,
13014                         unsigned mode, int sync, void *key)
13015 {
13016         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
13017         struct i915_request *rq = wait->request;
13018
13019         /*
13020          * If we missed the vblank, but the request is already running it
13021          * is reasonable to assume that it will complete before the next
13022          * vblank without our intervention, so leave RPS alone.
13023          */
13024         if (!i915_request_started(rq))
13025                 gen6_rps_boost(rq, NULL);
13026         i915_request_put(rq);
13027
13028         drm_crtc_vblank_put(wait->crtc);
13029
13030         list_del(&wait->wait.entry);
13031         kfree(wait);
13032         return 1;
13033 }
13034
13035 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
13036                                        struct dma_fence *fence)
13037 {
13038         struct wait_rps_boost *wait;
13039
13040         if (!dma_fence_is_i915(fence))
13041                 return;
13042
13043         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
13044                 return;
13045
13046         if (drm_crtc_vblank_get(crtc))
13047                 return;
13048
13049         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
13050         if (!wait) {
13051                 drm_crtc_vblank_put(crtc);
13052                 return;
13053         }
13054
13055         wait->request = to_request(dma_fence_get(fence));
13056         wait->crtc = crtc;
13057
13058         wait->wait.func = do_rps_boost;
13059         wait->wait.flags = 0;
13060
13061         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
13062 }
13063
13064 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
13065 {
13066         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
13067         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13068         struct drm_framebuffer *fb = plane_state->base.fb;
13069         struct i915_vma *vma;
13070
13071         if (plane->id == PLANE_CURSOR &&
13072             INTEL_INFO(dev_priv)->cursor_needs_physical) {
13073                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13074                 const int align = intel_cursor_alignment(dev_priv);
13075                 int err;
13076
13077                 err = i915_gem_object_attach_phys(obj, align);
13078                 if (err)
13079                         return err;
13080         }
13081
13082         vma = intel_pin_and_fence_fb_obj(fb,
13083                                          &plane_state->view,
13084                                          intel_plane_uses_fence(plane_state),
13085                                          &plane_state->flags);
13086         if (IS_ERR(vma))
13087                 return PTR_ERR(vma);
13088
13089         plane_state->vma = vma;
13090
13091         return 0;
13092 }
13093
13094 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
13095 {
13096         struct i915_vma *vma;
13097
13098         vma = fetch_and_zero(&old_plane_state->vma);
13099         if (vma)
13100                 intel_unpin_fb_vma(vma, old_plane_state->flags);
13101 }
13102
13103 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
13104 {
13105         struct i915_sched_attr attr = {
13106                 .priority = I915_PRIORITY_DISPLAY,
13107         };
13108
13109         i915_gem_object_wait_priority(obj, 0, &attr);
13110 }
13111
13112 /**
13113  * intel_prepare_plane_fb - Prepare fb for usage on plane
13114  * @plane: drm plane to prepare for
13115  * @new_state: the plane state being prepared
13116  *
13117  * Prepares a framebuffer for usage on a display plane.  Generally this
13118  * involves pinning the underlying object and updating the frontbuffer tracking
13119  * bits.  Some older platforms need special physical address handling for
13120  * cursor planes.
13121  *
13122  * Must be called with struct_mutex held.
13123  *
13124  * Returns 0 on success, negative error code on failure.
13125  */
13126 int
13127 intel_prepare_plane_fb(struct drm_plane *plane,
13128                        struct drm_plane_state *new_state)
13129 {
13130         struct intel_atomic_state *intel_state =
13131                 to_intel_atomic_state(new_state->state);
13132         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13133         struct drm_framebuffer *fb = new_state->fb;
13134         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13135         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13136         int ret;
13137
13138         if (old_obj) {
13139                 struct drm_crtc_state *crtc_state =
13140                         drm_atomic_get_new_crtc_state(new_state->state,
13141                                                       plane->state->crtc);
13142
13143                 /* Big Hammer, we also need to ensure that any pending
13144                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13145                  * current scanout is retired before unpinning the old
13146                  * framebuffer. Note that we rely on userspace rendering
13147                  * into the buffer attached to the pipe they are waiting
13148                  * on. If not, userspace generates a GPU hang with IPEHR
13149                  * point to the MI_WAIT_FOR_EVENT.
13150                  *
13151                  * This should only fail upon a hung GPU, in which case we
13152                  * can safely continue.
13153                  */
13154                 if (needs_modeset(crtc_state)) {
13155                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13156                                                               old_obj->resv, NULL,
13157                                                               false, 0,
13158                                                               GFP_KERNEL);
13159                         if (ret < 0)
13160                                 return ret;
13161                 }
13162         }
13163
13164         if (new_state->fence) { /* explicit fencing */
13165                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13166                                                     new_state->fence,
13167                                                     I915_FENCE_TIMEOUT,
13168                                                     GFP_KERNEL);
13169                 if (ret < 0)
13170                         return ret;
13171         }
13172
13173         if (!obj)
13174                 return 0;
13175
13176         ret = i915_gem_object_pin_pages(obj);
13177         if (ret)
13178                 return ret;
13179
13180         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13181         if (ret) {
13182                 i915_gem_object_unpin_pages(obj);
13183                 return ret;
13184         }
13185
13186         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
13187
13188         mutex_unlock(&dev_priv->drm.struct_mutex);
13189         i915_gem_object_unpin_pages(obj);
13190         if (ret)
13191                 return ret;
13192
13193         fb_obj_bump_render_priority(obj);
13194         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13195
13196         if (!new_state->fence) { /* implicit fencing */
13197                 struct dma_fence *fence;
13198
13199                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13200                                                       obj->resv, NULL,
13201                                                       false, I915_FENCE_TIMEOUT,
13202                                                       GFP_KERNEL);
13203                 if (ret < 0)
13204                         return ret;
13205
13206                 fence = reservation_object_get_excl_rcu(obj->resv);
13207                 if (fence) {
13208                         add_rps_boost_after_vblank(new_state->crtc, fence);
13209                         dma_fence_put(fence);
13210                 }
13211         } else {
13212                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
13213         }
13214
13215         /*
13216          * We declare pageflips to be interactive and so merit a small bias
13217          * towards upclocking to deliver the frame on time. By only changing
13218          * the RPS thresholds to sample more regularly and aim for higher
13219          * clocks we can hopefully deliver low power workloads (like kodi)
13220          * that are not quite steady state without resorting to forcing
13221          * maximum clocks following a vblank miss (see do_rps_boost()).
13222          */
13223         if (!intel_state->rps_interactive) {
13224                 intel_rps_mark_interactive(dev_priv, true);
13225                 intel_state->rps_interactive = true;
13226         }
13227
13228         return 0;
13229 }
13230
13231 /**
13232  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13233  * @plane: drm plane to clean up for
13234  * @old_state: the state from the previous modeset
13235  *
13236  * Cleans up a framebuffer that has just been removed from a plane.
13237  *
13238  * Must be called with struct_mutex held.
13239  */
13240 void
13241 intel_cleanup_plane_fb(struct drm_plane *plane,
13242                        struct drm_plane_state *old_state)
13243 {
13244         struct intel_atomic_state *intel_state =
13245                 to_intel_atomic_state(old_state->state);
13246         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13247
13248         if (intel_state->rps_interactive) {
13249                 intel_rps_mark_interactive(dev_priv, false);
13250                 intel_state->rps_interactive = false;
13251         }
13252
13253         /* Should only be called after a successful intel_prepare_plane_fb()! */
13254         mutex_lock(&dev_priv->drm.struct_mutex);
13255         intel_plane_unpin_fb(to_intel_plane_state(old_state));
13256         mutex_unlock(&dev_priv->drm.struct_mutex);
13257 }
13258
13259 int
13260 skl_max_scale(const struct intel_crtc_state *crtc_state,
13261               u32 pixel_format)
13262 {
13263         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
13264         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13265         int max_scale, mult;
13266         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
13267
13268         if (!crtc_state->base.enable)
13269                 return DRM_PLANE_HELPER_NO_SCALING;
13270
13271         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13272         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13273
13274         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
13275                 max_dotclk *= 2;
13276
13277         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13278                 return DRM_PLANE_HELPER_NO_SCALING;
13279
13280         /*
13281          * skl max scale is lower of:
13282          *    close to 3 but not 3, -1 is for that purpose
13283          *            or
13284          *    cdclk/crtc_clock
13285          */
13286         mult = pixel_format == DRM_FORMAT_NV12 ? 2 : 3;
13287         tmpclk1 = (1 << 16) * mult - 1;
13288         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
13289         max_scale = min(tmpclk1, tmpclk2);
13290
13291         return max_scale;
13292 }
13293
13294 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13295                                     struct drm_crtc_state *old_crtc_state)
13296 {
13297         struct drm_device *dev = crtc->dev;
13298         struct drm_i915_private *dev_priv = to_i915(dev);
13299         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13300         struct intel_crtc_state *old_intel_cstate =
13301                 to_intel_crtc_state(old_crtc_state);
13302         struct intel_atomic_state *old_intel_state =
13303                 to_intel_atomic_state(old_crtc_state->state);
13304         struct intel_crtc_state *intel_cstate =
13305                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13306         bool modeset = needs_modeset(&intel_cstate->base);
13307
13308         if (!modeset &&
13309             (intel_cstate->base.color_mgmt_changed ||
13310              intel_cstate->update_pipe)) {
13311                 intel_color_set_csc(&intel_cstate->base);
13312                 intel_color_load_luts(&intel_cstate->base);
13313         }
13314
13315         /* Perform vblank evasion around commit operation */
13316         intel_pipe_update_start(intel_cstate);
13317
13318         if (modeset)
13319                 goto out;
13320
13321         if (intel_cstate->update_pipe)
13322                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
13323         else if (INTEL_GEN(dev_priv) >= 9)
13324                 skl_detach_scalers(intel_cstate);
13325
13326 out:
13327         if (dev_priv->display.atomic_update_watermarks)
13328                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13329                                                            intel_cstate);
13330 }
13331
13332 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
13333                                   struct intel_crtc_state *crtc_state)
13334 {
13335         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13336
13337         if (!IS_GEN2(dev_priv))
13338                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
13339
13340         if (crtc_state->has_pch_encoder) {
13341                 enum pipe pch_transcoder =
13342                         intel_crtc_pch_transcoder(crtc);
13343
13344                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13345         }
13346 }
13347
13348 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13349                                      struct drm_crtc_state *old_crtc_state)
13350 {
13351         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13352         struct intel_atomic_state *old_intel_state =
13353                 to_intel_atomic_state(old_crtc_state->state);
13354         struct intel_crtc_state *new_crtc_state =
13355                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13356
13357         intel_pipe_update_end(new_crtc_state);
13358
13359         if (new_crtc_state->update_pipe &&
13360             !needs_modeset(&new_crtc_state->base) &&
13361             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED)
13362                 intel_crtc_arm_fifo_underrun(intel_crtc, new_crtc_state);
13363 }
13364
13365 /**
13366  * intel_plane_destroy - destroy a plane
13367  * @plane: plane to destroy
13368  *
13369  * Common destruction function for all types of planes (primary, cursor,
13370  * sprite).
13371  */
13372 void intel_plane_destroy(struct drm_plane *plane)
13373 {
13374         drm_plane_cleanup(plane);
13375         kfree(to_intel_plane(plane));
13376 }
13377
13378 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
13379                                             u32 format, u64 modifier)
13380 {
13381         switch (modifier) {
13382         case DRM_FORMAT_MOD_LINEAR:
13383         case I915_FORMAT_MOD_X_TILED:
13384                 break;
13385         default:
13386                 return false;
13387         }
13388
13389         switch (format) {
13390         case DRM_FORMAT_C8:
13391         case DRM_FORMAT_RGB565:
13392         case DRM_FORMAT_XRGB1555:
13393         case DRM_FORMAT_XRGB8888:
13394                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13395                         modifier == I915_FORMAT_MOD_X_TILED;
13396         default:
13397                 return false;
13398         }
13399 }
13400
13401 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
13402                                             u32 format, u64 modifier)
13403 {
13404         switch (modifier) {
13405         case DRM_FORMAT_MOD_LINEAR:
13406         case I915_FORMAT_MOD_X_TILED:
13407                 break;
13408         default:
13409                 return false;
13410         }
13411
13412         switch (format) {
13413         case DRM_FORMAT_C8:
13414         case DRM_FORMAT_RGB565:
13415         case DRM_FORMAT_XRGB8888:
13416         case DRM_FORMAT_XBGR8888:
13417         case DRM_FORMAT_XRGB2101010:
13418         case DRM_FORMAT_XBGR2101010:
13419                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13420                         modifier == I915_FORMAT_MOD_X_TILED;
13421         default:
13422                 return false;
13423         }
13424 }
13425
13426 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
13427                                               u32 format, u64 modifier)
13428 {
13429         return modifier == DRM_FORMAT_MOD_LINEAR &&
13430                 format == DRM_FORMAT_ARGB8888;
13431 }
13432
13433 static const struct drm_plane_funcs i965_plane_funcs = {
13434         .update_plane = drm_atomic_helper_update_plane,
13435         .disable_plane = drm_atomic_helper_disable_plane,
13436         .destroy = intel_plane_destroy,
13437         .atomic_get_property = intel_plane_atomic_get_property,
13438         .atomic_set_property = intel_plane_atomic_set_property,
13439         .atomic_duplicate_state = intel_plane_duplicate_state,
13440         .atomic_destroy_state = intel_plane_destroy_state,
13441         .format_mod_supported = i965_plane_format_mod_supported,
13442 };
13443
13444 static const struct drm_plane_funcs i8xx_plane_funcs = {
13445         .update_plane = drm_atomic_helper_update_plane,
13446         .disable_plane = drm_atomic_helper_disable_plane,
13447         .destroy = intel_plane_destroy,
13448         .atomic_get_property = intel_plane_atomic_get_property,
13449         .atomic_set_property = intel_plane_atomic_set_property,
13450         .atomic_duplicate_state = intel_plane_duplicate_state,
13451         .atomic_destroy_state = intel_plane_destroy_state,
13452         .format_mod_supported = i8xx_plane_format_mod_supported,
13453 };
13454
13455 static int
13456 intel_legacy_cursor_update(struct drm_plane *plane,
13457                            struct drm_crtc *crtc,
13458                            struct drm_framebuffer *fb,
13459                            int crtc_x, int crtc_y,
13460                            unsigned int crtc_w, unsigned int crtc_h,
13461                            uint32_t src_x, uint32_t src_y,
13462                            uint32_t src_w, uint32_t src_h,
13463                            struct drm_modeset_acquire_ctx *ctx)
13464 {
13465         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13466         int ret;
13467         struct drm_plane_state *old_plane_state, *new_plane_state;
13468         struct intel_plane *intel_plane = to_intel_plane(plane);
13469         struct drm_framebuffer *old_fb;
13470         struct intel_crtc_state *crtc_state =
13471                 to_intel_crtc_state(crtc->state);
13472         struct intel_crtc_state *new_crtc_state;
13473
13474         /*
13475          * When crtc is inactive or there is a modeset pending,
13476          * wait for it to complete in the slowpath
13477          */
13478         if (!crtc_state->base.active || needs_modeset(&crtc_state->base) ||
13479             crtc_state->update_pipe)
13480                 goto slow;
13481
13482         old_plane_state = plane->state;
13483         /*
13484          * Don't do an async update if there is an outstanding commit modifying
13485          * the plane.  This prevents our async update's changes from getting
13486          * overridden by a previous synchronous update's state.
13487          */
13488         if (old_plane_state->commit &&
13489             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13490                 goto slow;
13491
13492         /*
13493          * If any parameters change that may affect watermarks,
13494          * take the slowpath. Only changing fb or position should be
13495          * in the fastpath.
13496          */
13497         if (old_plane_state->crtc != crtc ||
13498             old_plane_state->src_w != src_w ||
13499             old_plane_state->src_h != src_h ||
13500             old_plane_state->crtc_w != crtc_w ||
13501             old_plane_state->crtc_h != crtc_h ||
13502             !old_plane_state->fb != !fb)
13503                 goto slow;
13504
13505         new_plane_state = intel_plane_duplicate_state(plane);
13506         if (!new_plane_state)
13507                 return -ENOMEM;
13508
13509         new_crtc_state = to_intel_crtc_state(intel_crtc_duplicate_state(crtc));
13510         if (!new_crtc_state) {
13511                 ret = -ENOMEM;
13512                 goto out_free;
13513         }
13514
13515         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13516
13517         new_plane_state->src_x = src_x;
13518         new_plane_state->src_y = src_y;
13519         new_plane_state->src_w = src_w;
13520         new_plane_state->src_h = src_h;
13521         new_plane_state->crtc_x = crtc_x;
13522         new_plane_state->crtc_y = crtc_y;
13523         new_plane_state->crtc_w = crtc_w;
13524         new_plane_state->crtc_h = crtc_h;
13525
13526         ret = intel_plane_atomic_check_with_state(crtc_state, new_crtc_state,
13527                                                   to_intel_plane_state(old_plane_state),
13528                                                   to_intel_plane_state(new_plane_state));
13529         if (ret)
13530                 goto out_free;
13531
13532         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13533         if (ret)
13534                 goto out_free;
13535
13536         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13537         if (ret)
13538                 goto out_unlock;
13539
13540         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13541
13542         old_fb = old_plane_state->fb;
13543         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13544                           intel_plane->frontbuffer_bit);
13545
13546         /* Swap plane state */
13547         plane->state = new_plane_state;
13548
13549         /*
13550          * We cannot swap crtc_state as it may be in use by an atomic commit or
13551          * page flip that's running simultaneously. If we swap crtc_state and
13552          * destroy the old state, we will cause a use-after-free there.
13553          *
13554          * Only update active_planes, which is needed for our internal
13555          * bookkeeping. Either value will do the right thing when updating
13556          * planes atomically. If the cursor was part of the atomic update then
13557          * we would have taken the slowpath.
13558          */
13559         crtc_state->active_planes = new_crtc_state->active_planes;
13560
13561         if (plane->state->visible) {
13562                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13563                 intel_plane->update_plane(intel_plane, crtc_state,
13564                                           to_intel_plane_state(plane->state));
13565         } else {
13566                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13567                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13568         }
13569
13570         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13571
13572 out_unlock:
13573         mutex_unlock(&dev_priv->drm.struct_mutex);
13574 out_free:
13575         if (new_crtc_state)
13576                 intel_crtc_destroy_state(crtc, &new_crtc_state->base);
13577         if (ret)
13578                 intel_plane_destroy_state(plane, new_plane_state);
13579         else
13580                 intel_plane_destroy_state(plane, old_plane_state);
13581         return ret;
13582
13583 slow:
13584         return drm_atomic_helper_update_plane(plane, crtc, fb,
13585                                               crtc_x, crtc_y, crtc_w, crtc_h,
13586                                               src_x, src_y, src_w, src_h, ctx);
13587 }
13588
13589 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13590         .update_plane = intel_legacy_cursor_update,
13591         .disable_plane = drm_atomic_helper_disable_plane,
13592         .destroy = intel_plane_destroy,
13593         .atomic_get_property = intel_plane_atomic_get_property,
13594         .atomic_set_property = intel_plane_atomic_set_property,
13595         .atomic_duplicate_state = intel_plane_duplicate_state,
13596         .atomic_destroy_state = intel_plane_destroy_state,
13597         .format_mod_supported = intel_cursor_format_mod_supported,
13598 };
13599
13600 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13601                                enum i9xx_plane_id i9xx_plane)
13602 {
13603         if (!HAS_FBC(dev_priv))
13604                 return false;
13605
13606         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13607                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13608         else if (IS_IVYBRIDGE(dev_priv))
13609                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13610                         i9xx_plane == PLANE_C;
13611         else if (INTEL_GEN(dev_priv) >= 4)
13612                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13613         else
13614                 return i9xx_plane == PLANE_A;
13615 }
13616
13617 static struct intel_plane *
13618 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13619 {
13620         struct intel_plane *plane;
13621         const struct drm_plane_funcs *plane_funcs;
13622         unsigned int supported_rotations;
13623         unsigned int possible_crtcs;
13624         const u64 *modifiers;
13625         const u32 *formats;
13626         int num_formats;
13627         int ret;
13628
13629         if (INTEL_GEN(dev_priv) >= 9)
13630                 return skl_universal_plane_create(dev_priv, pipe,
13631                                                   PLANE_PRIMARY);
13632
13633         plane = intel_plane_alloc();
13634         if (IS_ERR(plane))
13635                 return plane;
13636
13637         plane->pipe = pipe;
13638         /*
13639          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13640          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13641          */
13642         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13643                 plane->i9xx_plane = (enum i9xx_plane_id) !pipe;
13644         else
13645                 plane->i9xx_plane = (enum i9xx_plane_id) pipe;
13646         plane->id = PLANE_PRIMARY;
13647         plane->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, plane->id);
13648
13649         plane->has_fbc = i9xx_plane_has_fbc(dev_priv, plane->i9xx_plane);
13650         if (plane->has_fbc) {
13651                 struct intel_fbc *fbc = &dev_priv->fbc;
13652
13653                 fbc->possible_framebuffer_bits |= plane->frontbuffer_bit;
13654         }
13655
13656         if (INTEL_GEN(dev_priv) >= 4) {
13657                 formats = i965_primary_formats;
13658                 num_formats = ARRAY_SIZE(i965_primary_formats);
13659                 modifiers = i9xx_format_modifiers;
13660
13661                 plane->max_stride = i9xx_plane_max_stride;
13662                 plane->update_plane = i9xx_update_plane;
13663                 plane->disable_plane = i9xx_disable_plane;
13664                 plane->get_hw_state = i9xx_plane_get_hw_state;
13665                 plane->check_plane = i9xx_plane_check;
13666
13667                 plane_funcs = &i965_plane_funcs;
13668         } else {
13669                 formats = i8xx_primary_formats;
13670                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13671                 modifiers = i9xx_format_modifiers;
13672
13673                 plane->max_stride = i9xx_plane_max_stride;
13674                 plane->update_plane = i9xx_update_plane;
13675                 plane->disable_plane = i9xx_disable_plane;
13676                 plane->get_hw_state = i9xx_plane_get_hw_state;
13677                 plane->check_plane = i9xx_plane_check;
13678
13679                 plane_funcs = &i8xx_plane_funcs;
13680         }
13681
13682         possible_crtcs = BIT(pipe);
13683
13684         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13685                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
13686                                                possible_crtcs, plane_funcs,
13687                                                formats, num_formats, modifiers,
13688                                                DRM_PLANE_TYPE_PRIMARY,
13689                                                "primary %c", pipe_name(pipe));
13690         else
13691                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
13692                                                possible_crtcs, plane_funcs,
13693                                                formats, num_formats, modifiers,
13694                                                DRM_PLANE_TYPE_PRIMARY,
13695                                                "plane %c",
13696                                                plane_name(plane->i9xx_plane));
13697         if (ret)
13698                 goto fail;
13699
13700         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13701                 supported_rotations =
13702                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13703                         DRM_MODE_REFLECT_X;
13704         } else if (INTEL_GEN(dev_priv) >= 4) {
13705                 supported_rotations =
13706                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13707         } else {
13708                 supported_rotations = DRM_MODE_ROTATE_0;
13709         }
13710
13711         if (INTEL_GEN(dev_priv) >= 4)
13712                 drm_plane_create_rotation_property(&plane->base,
13713                                                    DRM_MODE_ROTATE_0,
13714                                                    supported_rotations);
13715
13716         drm_plane_helper_add(&plane->base, &intel_plane_helper_funcs);
13717
13718         return plane;
13719
13720 fail:
13721         intel_plane_free(plane);
13722
13723         return ERR_PTR(ret);
13724 }
13725
13726 static struct intel_plane *
13727 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13728                           enum pipe pipe)
13729 {
13730         unsigned int possible_crtcs;
13731         struct intel_plane *cursor;
13732         int ret;
13733
13734         cursor = intel_plane_alloc();
13735         if (IS_ERR(cursor))
13736                 return cursor;
13737
13738         cursor->pipe = pipe;
13739         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13740         cursor->id = PLANE_CURSOR;
13741         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13742
13743         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13744                 cursor->max_stride = i845_cursor_max_stride;
13745                 cursor->update_plane = i845_update_cursor;
13746                 cursor->disable_plane = i845_disable_cursor;
13747                 cursor->get_hw_state = i845_cursor_get_hw_state;
13748                 cursor->check_plane = i845_check_cursor;
13749         } else {
13750                 cursor->max_stride = i9xx_cursor_max_stride;
13751                 cursor->update_plane = i9xx_update_cursor;
13752                 cursor->disable_plane = i9xx_disable_cursor;
13753                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13754                 cursor->check_plane = i9xx_check_cursor;
13755         }
13756
13757         cursor->cursor.base = ~0;
13758         cursor->cursor.cntl = ~0;
13759
13760         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13761                 cursor->cursor.size = ~0;
13762
13763         possible_crtcs = BIT(pipe);
13764
13765         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13766                                        possible_crtcs, &intel_cursor_plane_funcs,
13767                                        intel_cursor_formats,
13768                                        ARRAY_SIZE(intel_cursor_formats),
13769                                        cursor_format_modifiers,
13770                                        DRM_PLANE_TYPE_CURSOR,
13771                                        "cursor %c", pipe_name(pipe));
13772         if (ret)
13773                 goto fail;
13774
13775         if (INTEL_GEN(dev_priv) >= 4)
13776                 drm_plane_create_rotation_property(&cursor->base,
13777                                                    DRM_MODE_ROTATE_0,
13778                                                    DRM_MODE_ROTATE_0 |
13779                                                    DRM_MODE_ROTATE_180);
13780
13781         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13782
13783         return cursor;
13784
13785 fail:
13786         intel_plane_free(cursor);
13787
13788         return ERR_PTR(ret);
13789 }
13790
13791 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13792                                     struct intel_crtc_state *crtc_state)
13793 {
13794         struct intel_crtc_scaler_state *scaler_state =
13795                 &crtc_state->scaler_state;
13796         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13797         int i;
13798
13799         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13800         if (!crtc->num_scalers)
13801                 return;
13802
13803         for (i = 0; i < crtc->num_scalers; i++) {
13804                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13805
13806                 scaler->in_use = 0;
13807                 scaler->mode = 0;
13808         }
13809
13810         scaler_state->scaler_id = -1;
13811 }
13812
13813 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13814 {
13815         struct intel_crtc *intel_crtc;
13816         struct intel_crtc_state *crtc_state = NULL;
13817         struct intel_plane *primary = NULL;
13818         struct intel_plane *cursor = NULL;
13819         int sprite, ret;
13820
13821         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13822         if (!intel_crtc)
13823                 return -ENOMEM;
13824
13825         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13826         if (!crtc_state) {
13827                 ret = -ENOMEM;
13828                 goto fail;
13829         }
13830         intel_crtc->config = crtc_state;
13831         intel_crtc->base.state = &crtc_state->base;
13832         crtc_state->base.crtc = &intel_crtc->base;
13833
13834         primary = intel_primary_plane_create(dev_priv, pipe);
13835         if (IS_ERR(primary)) {
13836                 ret = PTR_ERR(primary);
13837                 goto fail;
13838         }
13839         intel_crtc->plane_ids_mask |= BIT(primary->id);
13840
13841         for_each_sprite(dev_priv, pipe, sprite) {
13842                 struct intel_plane *plane;
13843
13844                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13845                 if (IS_ERR(plane)) {
13846                         ret = PTR_ERR(plane);
13847                         goto fail;
13848                 }
13849                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13850         }
13851
13852         cursor = intel_cursor_plane_create(dev_priv, pipe);
13853         if (IS_ERR(cursor)) {
13854                 ret = PTR_ERR(cursor);
13855                 goto fail;
13856         }
13857         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13858
13859         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13860                                         &primary->base, &cursor->base,
13861                                         &intel_crtc_funcs,
13862                                         "pipe %c", pipe_name(pipe));
13863         if (ret)
13864                 goto fail;
13865
13866         intel_crtc->pipe = pipe;
13867
13868         /* initialize shared scalers */
13869         intel_crtc_init_scalers(intel_crtc, crtc_state);
13870
13871         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
13872                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
13873         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
13874
13875         if (INTEL_GEN(dev_priv) < 9) {
13876                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
13877
13878                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13879                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
13880                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
13881         }
13882
13883         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13884
13885         intel_color_init(&intel_crtc->base);
13886
13887         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13888
13889         return 0;
13890
13891 fail:
13892         /*
13893          * drm_mode_config_cleanup() will free up any
13894          * crtcs/planes already initialized.
13895          */
13896         kfree(crtc_state);
13897         kfree(intel_crtc);
13898
13899         return ret;
13900 }
13901
13902 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13903 {
13904         struct drm_device *dev = connector->base.dev;
13905
13906         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13907
13908         if (!connector->base.state->crtc)
13909                 return INVALID_PIPE;
13910
13911         return to_intel_crtc(connector->base.state->crtc)->pipe;
13912 }
13913
13914 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
13915                                       struct drm_file *file)
13916 {
13917         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13918         struct drm_crtc *drmmode_crtc;
13919         struct intel_crtc *crtc;
13920
13921         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
13922         if (!drmmode_crtc)
13923                 return -ENOENT;
13924
13925         crtc = to_intel_crtc(drmmode_crtc);
13926         pipe_from_crtc_id->pipe = crtc->pipe;
13927
13928         return 0;
13929 }
13930
13931 static int intel_encoder_clones(struct intel_encoder *encoder)
13932 {
13933         struct drm_device *dev = encoder->base.dev;
13934         struct intel_encoder *source_encoder;
13935         int index_mask = 0;
13936         int entry = 0;
13937
13938         for_each_intel_encoder(dev, source_encoder) {
13939                 if (encoders_cloneable(encoder, source_encoder))
13940                         index_mask |= (1 << entry);
13941
13942                 entry++;
13943         }
13944
13945         return index_mask;
13946 }
13947
13948 static bool has_edp_a(struct drm_i915_private *dev_priv)
13949 {
13950         if (!IS_MOBILE(dev_priv))
13951                 return false;
13952
13953         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13954                 return false;
13955
13956         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13957                 return false;
13958
13959         return true;
13960 }
13961
13962 static bool intel_crt_present(struct drm_i915_private *dev_priv)
13963 {
13964         if (INTEL_GEN(dev_priv) >= 9)
13965                 return false;
13966
13967         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
13968                 return false;
13969
13970         if (IS_CHERRYVIEW(dev_priv))
13971                 return false;
13972
13973         if (HAS_PCH_LPT_H(dev_priv) &&
13974             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
13975                 return false;
13976
13977         /* DDI E can't be used if DDI A requires 4 lanes */
13978         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
13979                 return false;
13980
13981         if (!dev_priv->vbt.int_crt_support)
13982                 return false;
13983
13984         return true;
13985 }
13986
13987 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
13988 {
13989         int pps_num;
13990         int pps_idx;
13991
13992         if (HAS_DDI(dev_priv))
13993                 return;
13994         /*
13995          * This w/a is needed at least on CPT/PPT, but to be sure apply it
13996          * everywhere where registers can be write protected.
13997          */
13998         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13999                 pps_num = 2;
14000         else
14001                 pps_num = 1;
14002
14003         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14004                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14005
14006                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14007                 I915_WRITE(PP_CONTROL(pps_idx), val);
14008         }
14009 }
14010
14011 static void intel_pps_init(struct drm_i915_private *dev_priv)
14012 {
14013         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14014                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14015         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14016                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14017         else
14018                 dev_priv->pps_mmio_base = PPS_BASE;
14019
14020         intel_pps_unlock_regs_wa(dev_priv);
14021 }
14022
14023 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14024 {
14025         struct intel_encoder *encoder;
14026         bool dpd_is_edp = false;
14027
14028         intel_pps_init(dev_priv);
14029
14030         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14031                 return;
14032
14033         /*
14034          * intel_edp_init_connector() depends on this completing first, to
14035          * prevent the registeration of both eDP and LVDS and the incorrect
14036          * sharing of the PPS.
14037          */
14038         intel_lvds_init(dev_priv);
14039
14040         if (intel_crt_present(dev_priv))
14041                 intel_crt_init(dev_priv);
14042
14043         if (IS_ICELAKE(dev_priv)) {
14044                 intel_ddi_init(dev_priv, PORT_A);
14045                 intel_ddi_init(dev_priv, PORT_B);
14046                 intel_ddi_init(dev_priv, PORT_C);
14047                 intel_ddi_init(dev_priv, PORT_D);
14048                 intel_ddi_init(dev_priv, PORT_E);
14049                 intel_ddi_init(dev_priv, PORT_F);
14050         } else if (IS_GEN9_LP(dev_priv)) {
14051                 /*
14052                  * FIXME: Broxton doesn't support port detection via the
14053                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14054                  * detect the ports.
14055                  */
14056                 intel_ddi_init(dev_priv, PORT_A);
14057                 intel_ddi_init(dev_priv, PORT_B);
14058                 intel_ddi_init(dev_priv, PORT_C);
14059
14060                 vlv_dsi_init(dev_priv);
14061         } else if (HAS_DDI(dev_priv)) {
14062                 int found;
14063
14064                 /*
14065                  * Haswell uses DDI functions to detect digital outputs.
14066                  * On SKL pre-D0 the strap isn't connected, so we assume
14067                  * it's there.
14068                  */
14069                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14070                 /* WaIgnoreDDIAStrap: skl */
14071                 if (found || IS_GEN9_BC(dev_priv))
14072                         intel_ddi_init(dev_priv, PORT_A);
14073
14074                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
14075                  * register */
14076                 found = I915_READ(SFUSE_STRAP);
14077
14078                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14079                         intel_ddi_init(dev_priv, PORT_B);
14080                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14081                         intel_ddi_init(dev_priv, PORT_C);
14082                 if (found & SFUSE_STRAP_DDID_DETECTED)
14083                         intel_ddi_init(dev_priv, PORT_D);
14084                 if (found & SFUSE_STRAP_DDIF_DETECTED)
14085                         intel_ddi_init(dev_priv, PORT_F);
14086                 /*
14087                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14088                  */
14089                 if (IS_GEN9_BC(dev_priv) &&
14090                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14091                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14092                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14093                         intel_ddi_init(dev_priv, PORT_E);
14094
14095         } else if (HAS_PCH_SPLIT(dev_priv)) {
14096                 int found;
14097                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14098
14099                 if (has_edp_a(dev_priv))
14100                         intel_dp_init(dev_priv, DP_A, PORT_A);
14101
14102                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14103                         /* PCH SDVOB multiplex with HDMIB */
14104                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14105                         if (!found)
14106                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14107                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14108                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14109                 }
14110
14111                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14112                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14113
14114                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14115                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14116
14117                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14118                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14119
14120                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14121                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14122         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14123                 bool has_edp, has_port;
14124
14125                 /*
14126                  * The DP_DETECTED bit is the latched state of the DDC
14127                  * SDA pin at boot. However since eDP doesn't require DDC
14128                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14129                  * eDP ports may have been muxed to an alternate function.
14130                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14131                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14132                  * detect eDP ports.
14133                  *
14134                  * Sadly the straps seem to be missing sometimes even for HDMI
14135                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14136                  * and VBT for the presence of the port. Additionally we can't
14137                  * trust the port type the VBT declares as we've seen at least
14138                  * HDMI ports that the VBT claim are DP or eDP.
14139                  */
14140                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14141                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14142                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14143                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14144                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14145                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14146
14147                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14148                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14149                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14150                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14151                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14152                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14153
14154                 if (IS_CHERRYVIEW(dev_priv)) {
14155                         /*
14156                          * eDP not supported on port D,
14157                          * so no need to worry about it
14158                          */
14159                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14160                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14161                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14162                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14163                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14164                 }
14165
14166                 vlv_dsi_init(dev_priv);
14167         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
14168                 bool found = false;
14169
14170                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14171                         DRM_DEBUG_KMS("probing SDVOB\n");
14172                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14173                         if (!found && IS_G4X(dev_priv)) {
14174                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14175                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14176                         }
14177
14178                         if (!found && IS_G4X(dev_priv))
14179                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14180                 }
14181
14182                 /* Before G4X SDVOC doesn't have its own detect register */
14183
14184                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14185                         DRM_DEBUG_KMS("probing SDVOC\n");
14186                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14187                 }
14188
14189                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14190
14191                         if (IS_G4X(dev_priv)) {
14192                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14193                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14194                         }
14195                         if (IS_G4X(dev_priv))
14196                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14197                 }
14198
14199                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14200                         intel_dp_init(dev_priv, DP_D, PORT_D);
14201         } else if (IS_GEN2(dev_priv))
14202                 intel_dvo_init(dev_priv);
14203
14204         if (SUPPORTS_TV(dev_priv))
14205                 intel_tv_init(dev_priv);
14206
14207         intel_psr_init(dev_priv);
14208
14209         for_each_intel_encoder(&dev_priv->drm, encoder) {
14210                 encoder->base.possible_crtcs = encoder->crtc_mask;
14211                 encoder->base.possible_clones =
14212                         intel_encoder_clones(encoder);
14213         }
14214
14215         intel_init_pch_refclk(dev_priv);
14216
14217         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14218 }
14219
14220 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14221 {
14222         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14223         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14224
14225         drm_framebuffer_cleanup(fb);
14226
14227         i915_gem_object_lock(obj);
14228         WARN_ON(!obj->framebuffer_references--);
14229         i915_gem_object_unlock(obj);
14230
14231         i915_gem_object_put(obj);
14232
14233         kfree(intel_fb);
14234 }
14235
14236 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14237                                                 struct drm_file *file,
14238                                                 unsigned int *handle)
14239 {
14240         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14241
14242         if (obj->userptr.mm) {
14243                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14244                 return -EINVAL;
14245         }
14246
14247         return drm_gem_handle_create(file, &obj->base, handle);
14248 }
14249
14250 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14251                                         struct drm_file *file,
14252                                         unsigned flags, unsigned color,
14253                                         struct drm_clip_rect *clips,
14254                                         unsigned num_clips)
14255 {
14256         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14257
14258         i915_gem_object_flush_if_display(obj);
14259         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14260
14261         return 0;
14262 }
14263
14264 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14265         .destroy = intel_user_framebuffer_destroy,
14266         .create_handle = intel_user_framebuffer_create_handle,
14267         .dirty = intel_user_framebuffer_dirty,
14268 };
14269
14270 static
14271 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14272                          uint64_t fb_modifier, uint32_t pixel_format)
14273 {
14274         struct intel_crtc *crtc;
14275         struct intel_plane *plane;
14276
14277         /*
14278          * We assume the primary plane for pipe A has
14279          * the highest stride limits of them all.
14280          */
14281         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
14282         plane = to_intel_plane(crtc->base.primary);
14283
14284         return plane->max_stride(plane, pixel_format, fb_modifier,
14285                                  DRM_MODE_ROTATE_0);
14286 }
14287
14288 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14289                                   struct drm_i915_gem_object *obj,
14290                                   struct drm_mode_fb_cmd2 *mode_cmd)
14291 {
14292         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14293         struct drm_framebuffer *fb = &intel_fb->base;
14294         struct drm_format_name_buf format_name;
14295         u32 pitch_limit;
14296         unsigned int tiling, stride;
14297         int ret = -EINVAL;
14298         int i;
14299
14300         i915_gem_object_lock(obj);
14301         obj->framebuffer_references++;
14302         tiling = i915_gem_object_get_tiling(obj);
14303         stride = i915_gem_object_get_stride(obj);
14304         i915_gem_object_unlock(obj);
14305
14306         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14307                 /*
14308                  * If there's a fence, enforce that
14309                  * the fb modifier and tiling mode match.
14310                  */
14311                 if (tiling != I915_TILING_NONE &&
14312                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14313                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14314                         goto err;
14315                 }
14316         } else {
14317                 if (tiling == I915_TILING_X) {
14318                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14319                 } else if (tiling == I915_TILING_Y) {
14320                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14321                         goto err;
14322                 }
14323         }
14324
14325         /* Passed in modifier sanity checking. */
14326         switch (mode_cmd->modifier[0]) {
14327         case I915_FORMAT_MOD_Y_TILED_CCS:
14328         case I915_FORMAT_MOD_Yf_TILED_CCS:
14329                 switch (mode_cmd->pixel_format) {
14330                 case DRM_FORMAT_XBGR8888:
14331                 case DRM_FORMAT_ABGR8888:
14332                 case DRM_FORMAT_XRGB8888:
14333                 case DRM_FORMAT_ARGB8888:
14334                         break;
14335                 default:
14336                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
14337                         goto err;
14338                 }
14339                 /* fall through */
14340         case I915_FORMAT_MOD_Yf_TILED:
14341                 if (mode_cmd->pixel_format == DRM_FORMAT_C8) {
14342                         DRM_DEBUG_KMS("Indexed format does not support Yf tiling\n");
14343                         goto err;
14344                 }
14345                 /* fall through */
14346         case I915_FORMAT_MOD_Y_TILED:
14347                 if (INTEL_GEN(dev_priv) < 9) {
14348                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14349                                       mode_cmd->modifier[0]);
14350                         goto err;
14351                 }
14352                 break;
14353         case DRM_FORMAT_MOD_LINEAR:
14354         case I915_FORMAT_MOD_X_TILED:
14355                 break;
14356         default:
14357                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14358                               mode_cmd->modifier[0]);
14359                 goto err;
14360         }
14361
14362         /*
14363          * gen2/3 display engine uses the fence if present,
14364          * so the tiling mode must match the fb modifier exactly.
14365          */
14366         if (INTEL_GEN(dev_priv) < 4 &&
14367             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14368                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14369                 goto err;
14370         }
14371
14372         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14373                                            mode_cmd->pixel_format);
14374         if (mode_cmd->pitches[0] > pitch_limit) {
14375                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14376                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14377                               "tiled" : "linear",
14378                               mode_cmd->pitches[0], pitch_limit);
14379                 goto err;
14380         }
14381
14382         /*
14383          * If there's a fence, enforce that
14384          * the fb pitch and fence stride match.
14385          */
14386         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14387                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14388                               mode_cmd->pitches[0], stride);
14389                 goto err;
14390         }
14391
14392         /* Reject formats not supported by any plane early. */
14393         switch (mode_cmd->pixel_format) {
14394         case DRM_FORMAT_C8:
14395         case DRM_FORMAT_RGB565:
14396         case DRM_FORMAT_XRGB8888:
14397         case DRM_FORMAT_ARGB8888:
14398                 break;
14399         case DRM_FORMAT_XRGB1555:
14400                 if (INTEL_GEN(dev_priv) > 3) {
14401                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14402                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14403                         goto err;
14404                 }
14405                 break;
14406         case DRM_FORMAT_ABGR8888:
14407                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14408                     INTEL_GEN(dev_priv) < 9) {
14409                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14410                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14411                         goto err;
14412                 }
14413                 break;
14414         case DRM_FORMAT_XBGR8888:
14415         case DRM_FORMAT_XRGB2101010:
14416         case DRM_FORMAT_XBGR2101010:
14417                 if (INTEL_GEN(dev_priv) < 4) {
14418                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14419                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14420                         goto err;
14421                 }
14422                 break;
14423         case DRM_FORMAT_ABGR2101010:
14424                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14425                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14426                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14427                         goto err;
14428                 }
14429                 break;
14430         case DRM_FORMAT_YUYV:
14431         case DRM_FORMAT_UYVY:
14432         case DRM_FORMAT_YVYU:
14433         case DRM_FORMAT_VYUY:
14434                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14435                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14436                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14437                         goto err;
14438                 }
14439                 break;
14440         case DRM_FORMAT_NV12:
14441                 if (INTEL_GEN(dev_priv) < 9 || IS_SKYLAKE(dev_priv) ||
14442                     IS_BROXTON(dev_priv) || INTEL_GEN(dev_priv) >= 11) {
14443                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14444                                       drm_get_format_name(mode_cmd->pixel_format,
14445                                                           &format_name));
14446                         goto err;
14447                 }
14448                 break;
14449         default:
14450                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14451                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14452                 goto err;
14453         }
14454
14455         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14456         if (mode_cmd->offsets[0] != 0)
14457                 goto err;
14458
14459         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14460
14461         if (fb->format->format == DRM_FORMAT_NV12 &&
14462             (fb->width < SKL_MIN_YUV_420_SRC_W ||
14463              fb->height < SKL_MIN_YUV_420_SRC_H ||
14464              (fb->width % 4) != 0 || (fb->height % 4) != 0)) {
14465                 DRM_DEBUG_KMS("src dimensions not correct for NV12\n");
14466                 return -EINVAL;
14467         }
14468
14469         for (i = 0; i < fb->format->num_planes; i++) {
14470                 u32 stride_alignment;
14471
14472                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14473                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14474                         goto err;
14475                 }
14476
14477                 stride_alignment = intel_fb_stride_alignment(fb, i);
14478
14479                 /*
14480                  * Display WA #0531: skl,bxt,kbl,glk
14481                  *
14482                  * Render decompression and plane width > 3840
14483                  * combined with horizontal panning requires the
14484                  * plane stride to be a multiple of 4. We'll just
14485                  * require the entire fb to accommodate that to avoid
14486                  * potential runtime errors at plane configuration time.
14487                  */
14488                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14489                     is_ccs_modifier(fb->modifier))
14490                         stride_alignment *= 4;
14491
14492                 if (fb->pitches[i] & (stride_alignment - 1)) {
14493                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14494                                       i, fb->pitches[i], stride_alignment);
14495                         goto err;
14496                 }
14497
14498                 fb->obj[i] = &obj->base;
14499         }
14500
14501         ret = intel_fill_fb_info(dev_priv, fb);
14502         if (ret)
14503                 goto err;
14504
14505         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14506         if (ret) {
14507                 DRM_ERROR("framebuffer init failed %d\n", ret);
14508                 goto err;
14509         }
14510
14511         return 0;
14512
14513 err:
14514         i915_gem_object_lock(obj);
14515         obj->framebuffer_references--;
14516         i915_gem_object_unlock(obj);
14517         return ret;
14518 }
14519
14520 static struct drm_framebuffer *
14521 intel_user_framebuffer_create(struct drm_device *dev,
14522                               struct drm_file *filp,
14523                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14524 {
14525         struct drm_framebuffer *fb;
14526         struct drm_i915_gem_object *obj;
14527         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14528
14529         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14530         if (!obj)
14531                 return ERR_PTR(-ENOENT);
14532
14533         fb = intel_framebuffer_create(obj, &mode_cmd);
14534         if (IS_ERR(fb))
14535                 i915_gem_object_put(obj);
14536
14537         return fb;
14538 }
14539
14540 static void intel_atomic_state_free(struct drm_atomic_state *state)
14541 {
14542         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14543
14544         drm_atomic_state_default_release(state);
14545
14546         i915_sw_fence_fini(&intel_state->commit_ready);
14547
14548         kfree(state);
14549 }
14550
14551 static enum drm_mode_status
14552 intel_mode_valid(struct drm_device *dev,
14553                  const struct drm_display_mode *mode)
14554 {
14555         struct drm_i915_private *dev_priv = to_i915(dev);
14556         int hdisplay_max, htotal_max;
14557         int vdisplay_max, vtotal_max;
14558
14559         /*
14560          * Can't reject DBLSCAN here because Xorg ddxen can add piles
14561          * of DBLSCAN modes to the output's mode list when they detect
14562          * the scaling mode property on the connector. And they don't
14563          * ask the kernel to validate those modes in any way until
14564          * modeset time at which point the client gets a protocol error.
14565          * So in order to not upset those clients we silently ignore the
14566          * DBLSCAN flag on such connectors. For other connectors we will
14567          * reject modes with the DBLSCAN flag in encoder->compute_config().
14568          * And we always reject DBLSCAN modes in connector->mode_valid()
14569          * as we never want such modes on the connector's mode list.
14570          */
14571
14572         if (mode->vscan > 1)
14573                 return MODE_NO_VSCAN;
14574
14575         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14576                 return MODE_H_ILLEGAL;
14577
14578         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14579                            DRM_MODE_FLAG_NCSYNC |
14580                            DRM_MODE_FLAG_PCSYNC))
14581                 return MODE_HSYNC;
14582
14583         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14584                            DRM_MODE_FLAG_PIXMUX |
14585                            DRM_MODE_FLAG_CLKDIV2))
14586                 return MODE_BAD;
14587
14588         if (INTEL_GEN(dev_priv) >= 9 ||
14589             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
14590                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
14591                 vdisplay_max = 4096;
14592                 htotal_max = 8192;
14593                 vtotal_max = 8192;
14594         } else if (INTEL_GEN(dev_priv) >= 3) {
14595                 hdisplay_max = 4096;
14596                 vdisplay_max = 4096;
14597                 htotal_max = 8192;
14598                 vtotal_max = 8192;
14599         } else {
14600                 hdisplay_max = 2048;
14601                 vdisplay_max = 2048;
14602                 htotal_max = 4096;
14603                 vtotal_max = 4096;
14604         }
14605
14606         if (mode->hdisplay > hdisplay_max ||
14607             mode->hsync_start > htotal_max ||
14608             mode->hsync_end > htotal_max ||
14609             mode->htotal > htotal_max)
14610                 return MODE_H_ILLEGAL;
14611
14612         if (mode->vdisplay > vdisplay_max ||
14613             mode->vsync_start > vtotal_max ||
14614             mode->vsync_end > vtotal_max ||
14615             mode->vtotal > vtotal_max)
14616                 return MODE_V_ILLEGAL;
14617
14618         return MODE_OK;
14619 }
14620
14621 static const struct drm_mode_config_funcs intel_mode_funcs = {
14622         .fb_create = intel_user_framebuffer_create,
14623         .get_format_info = intel_get_format_info,
14624         .output_poll_changed = intel_fbdev_output_poll_changed,
14625         .mode_valid = intel_mode_valid,
14626         .atomic_check = intel_atomic_check,
14627         .atomic_commit = intel_atomic_commit,
14628         .atomic_state_alloc = intel_atomic_state_alloc,
14629         .atomic_state_clear = intel_atomic_state_clear,
14630         .atomic_state_free = intel_atomic_state_free,
14631 };
14632
14633 /**
14634  * intel_init_display_hooks - initialize the display modesetting hooks
14635  * @dev_priv: device private
14636  */
14637 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14638 {
14639         intel_init_cdclk_hooks(dev_priv);
14640
14641         if (INTEL_GEN(dev_priv) >= 9) {
14642                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14643                 dev_priv->display.get_initial_plane_config =
14644                         skylake_get_initial_plane_config;
14645                 dev_priv->display.crtc_compute_clock =
14646                         haswell_crtc_compute_clock;
14647                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14648                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14649         } else if (HAS_DDI(dev_priv)) {
14650                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14651                 dev_priv->display.get_initial_plane_config =
14652                         i9xx_get_initial_plane_config;
14653                 dev_priv->display.crtc_compute_clock =
14654                         haswell_crtc_compute_clock;
14655                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14656                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14657         } else if (HAS_PCH_SPLIT(dev_priv)) {
14658                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14659                 dev_priv->display.get_initial_plane_config =
14660                         i9xx_get_initial_plane_config;
14661                 dev_priv->display.crtc_compute_clock =
14662                         ironlake_crtc_compute_clock;
14663                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14664                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14665         } else if (IS_CHERRYVIEW(dev_priv)) {
14666                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14667                 dev_priv->display.get_initial_plane_config =
14668                         i9xx_get_initial_plane_config;
14669                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14670                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14671                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14672         } else if (IS_VALLEYVIEW(dev_priv)) {
14673                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14674                 dev_priv->display.get_initial_plane_config =
14675                         i9xx_get_initial_plane_config;
14676                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14677                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14678                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14679         } else if (IS_G4X(dev_priv)) {
14680                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14681                 dev_priv->display.get_initial_plane_config =
14682                         i9xx_get_initial_plane_config;
14683                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14684                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14685                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14686         } else if (IS_PINEVIEW(dev_priv)) {
14687                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14688                 dev_priv->display.get_initial_plane_config =
14689                         i9xx_get_initial_plane_config;
14690                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14691                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14692                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14693         } else if (!IS_GEN2(dev_priv)) {
14694                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14695                 dev_priv->display.get_initial_plane_config =
14696                         i9xx_get_initial_plane_config;
14697                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14698                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14699                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14700         } else {
14701                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14702                 dev_priv->display.get_initial_plane_config =
14703                         i9xx_get_initial_plane_config;
14704                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14705                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14706                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14707         }
14708
14709         if (IS_GEN5(dev_priv)) {
14710                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14711         } else if (IS_GEN6(dev_priv)) {
14712                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14713         } else if (IS_IVYBRIDGE(dev_priv)) {
14714                 /* FIXME: detect B0+ stepping and use auto training */
14715                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14716         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14717                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14718         }
14719
14720         if (INTEL_GEN(dev_priv) >= 9)
14721                 dev_priv->display.update_crtcs = skl_update_crtcs;
14722         else
14723                 dev_priv->display.update_crtcs = intel_update_crtcs;
14724 }
14725
14726 /*
14727  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14728  */
14729 static void quirk_ssc_force_disable(struct drm_device *dev)
14730 {
14731         struct drm_i915_private *dev_priv = to_i915(dev);
14732         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14733         DRM_INFO("applying lvds SSC disable quirk\n");
14734 }
14735
14736 /*
14737  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14738  * brightness value
14739  */
14740 static void quirk_invert_brightness(struct drm_device *dev)
14741 {
14742         struct drm_i915_private *dev_priv = to_i915(dev);
14743         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14744         DRM_INFO("applying inverted panel brightness quirk\n");
14745 }
14746
14747 /* Some VBT's incorrectly indicate no backlight is present */
14748 static void quirk_backlight_present(struct drm_device *dev)
14749 {
14750         struct drm_i915_private *dev_priv = to_i915(dev);
14751         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14752         DRM_INFO("applying backlight present quirk\n");
14753 }
14754
14755 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14756  * which is 300 ms greater than eDP spec T12 min.
14757  */
14758 static void quirk_increase_t12_delay(struct drm_device *dev)
14759 {
14760         struct drm_i915_private *dev_priv = to_i915(dev);
14761
14762         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14763         DRM_INFO("Applying T12 delay quirk\n");
14764 }
14765
14766 /*
14767  * GeminiLake NUC HDMI outputs require additional off time
14768  * this allows the onboard retimer to correctly sync to signal
14769  */
14770 static void quirk_increase_ddi_disabled_time(struct drm_device *dev)
14771 {
14772         struct drm_i915_private *dev_priv = to_i915(dev);
14773
14774         dev_priv->quirks |= QUIRK_INCREASE_DDI_DISABLED_TIME;
14775         DRM_INFO("Applying Increase DDI Disabled quirk\n");
14776 }
14777
14778 struct intel_quirk {
14779         int device;
14780         int subsystem_vendor;
14781         int subsystem_device;
14782         void (*hook)(struct drm_device *dev);
14783 };
14784
14785 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14786 struct intel_dmi_quirk {
14787         void (*hook)(struct drm_device *dev);
14788         const struct dmi_system_id (*dmi_id_list)[];
14789 };
14790
14791 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14792 {
14793         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14794         return 1;
14795 }
14796
14797 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14798         {
14799                 .dmi_id_list = &(const struct dmi_system_id[]) {
14800                         {
14801                                 .callback = intel_dmi_reverse_brightness,
14802                                 .ident = "NCR Corporation",
14803                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14804                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14805                                 },
14806                         },
14807                         { }  /* terminating entry */
14808                 },
14809                 .hook = quirk_invert_brightness,
14810         },
14811 };
14812
14813 static struct intel_quirk intel_quirks[] = {
14814         /* Lenovo U160 cannot use SSC on LVDS */
14815         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14816
14817         /* Sony Vaio Y cannot use SSC on LVDS */
14818         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14819
14820         /* Acer Aspire 5734Z must invert backlight brightness */
14821         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14822
14823         /* Acer/eMachines G725 */
14824         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14825
14826         /* Acer/eMachines e725 */
14827         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14828
14829         /* Acer/Packard Bell NCL20 */
14830         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14831
14832         /* Acer Aspire 4736Z */
14833         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14834
14835         /* Acer Aspire 5336 */
14836         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14837
14838         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14839         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14840
14841         /* Acer C720 Chromebook (Core i3 4005U) */
14842         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14843
14844         /* Apple Macbook 2,1 (Core 2 T7400) */
14845         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14846
14847         /* Apple Macbook 4,1 */
14848         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14849
14850         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14851         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14852
14853         /* HP Chromebook 14 (Celeron 2955U) */
14854         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14855
14856         /* Dell Chromebook 11 */
14857         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14858
14859         /* Dell Chromebook 11 (2015 version) */
14860         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14861
14862         /* Toshiba Satellite P50-C-18C */
14863         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14864
14865         /* GeminiLake NUC */
14866         { 0x3185, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14867         { 0x3184, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14868         /* ASRock ITX*/
14869         { 0x3185, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14870         { 0x3184, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14871 };
14872
14873 static void intel_init_quirks(struct drm_device *dev)
14874 {
14875         struct pci_dev *d = dev->pdev;
14876         int i;
14877
14878         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14879                 struct intel_quirk *q = &intel_quirks[i];
14880
14881                 if (d->device == q->device &&
14882                     (d->subsystem_vendor == q->subsystem_vendor ||
14883                      q->subsystem_vendor == PCI_ANY_ID) &&
14884                     (d->subsystem_device == q->subsystem_device ||
14885                      q->subsystem_device == PCI_ANY_ID))
14886                         q->hook(dev);
14887         }
14888         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14889                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14890                         intel_dmi_quirks[i].hook(dev);
14891         }
14892 }
14893
14894 /* Disable the VGA plane that we never use */
14895 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14896 {
14897         struct pci_dev *pdev = dev_priv->drm.pdev;
14898         u8 sr1;
14899         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14900
14901         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14902         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14903         outb(SR01, VGA_SR_INDEX);
14904         sr1 = inb(VGA_SR_DATA);
14905         outb(sr1 | 1<<5, VGA_SR_DATA);
14906         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14907         udelay(300);
14908
14909         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14910         POSTING_READ(vga_reg);
14911 }
14912
14913 void intel_modeset_init_hw(struct drm_device *dev)
14914 {
14915         struct drm_i915_private *dev_priv = to_i915(dev);
14916
14917         intel_update_cdclk(dev_priv);
14918         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
14919         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14920 }
14921
14922 /*
14923  * Calculate what we think the watermarks should be for the state we've read
14924  * out of the hardware and then immediately program those watermarks so that
14925  * we ensure the hardware settings match our internal state.
14926  *
14927  * We can calculate what we think WM's should be by creating a duplicate of the
14928  * current state (which was constructed during hardware readout) and running it
14929  * through the atomic check code to calculate new watermark values in the
14930  * state object.
14931  */
14932 static void sanitize_watermarks(struct drm_device *dev)
14933 {
14934         struct drm_i915_private *dev_priv = to_i915(dev);
14935         struct drm_atomic_state *state;
14936         struct intel_atomic_state *intel_state;
14937         struct drm_crtc *crtc;
14938         struct drm_crtc_state *cstate;
14939         struct drm_modeset_acquire_ctx ctx;
14940         int ret;
14941         int i;
14942
14943         /* Only supported on platforms that use atomic watermark design */
14944         if (!dev_priv->display.optimize_watermarks)
14945                 return;
14946
14947         /*
14948          * We need to hold connection_mutex before calling duplicate_state so
14949          * that the connector loop is protected.
14950          */
14951         drm_modeset_acquire_init(&ctx, 0);
14952 retry:
14953         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14954         if (ret == -EDEADLK) {
14955                 drm_modeset_backoff(&ctx);
14956                 goto retry;
14957         } else if (WARN_ON(ret)) {
14958                 goto fail;
14959         }
14960
14961         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14962         if (WARN_ON(IS_ERR(state)))
14963                 goto fail;
14964
14965         intel_state = to_intel_atomic_state(state);
14966
14967         /*
14968          * Hardware readout is the only time we don't want to calculate
14969          * intermediate watermarks (since we don't trust the current
14970          * watermarks).
14971          */
14972         if (!HAS_GMCH_DISPLAY(dev_priv))
14973                 intel_state->skip_intermediate_wm = true;
14974
14975         ret = intel_atomic_check(dev, state);
14976         if (ret) {
14977                 /*
14978                  * If we fail here, it means that the hardware appears to be
14979                  * programmed in a way that shouldn't be possible, given our
14980                  * understanding of watermark requirements.  This might mean a
14981                  * mistake in the hardware readout code or a mistake in the
14982                  * watermark calculations for a given platform.  Raise a WARN
14983                  * so that this is noticeable.
14984                  *
14985                  * If this actually happens, we'll have to just leave the
14986                  * BIOS-programmed watermarks untouched and hope for the best.
14987                  */
14988                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14989                 goto put_state;
14990         }
14991
14992         /* Write calculated watermark values back */
14993         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14994                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14995
14996                 cs->wm.need_postvbl_update = true;
14997                 dev_priv->display.optimize_watermarks(intel_state, cs);
14998
14999                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
15000         }
15001
15002 put_state:
15003         drm_atomic_state_put(state);
15004 fail:
15005         drm_modeset_drop_locks(&ctx);
15006         drm_modeset_acquire_fini(&ctx);
15007 }
15008
15009 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
15010 {
15011         if (IS_GEN5(dev_priv)) {
15012                 u32 fdi_pll_clk =
15013                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
15014
15015                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
15016         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
15017                 dev_priv->fdi_pll_freq = 270000;
15018         } else {
15019                 return;
15020         }
15021
15022         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
15023 }
15024
15025 static int intel_initial_commit(struct drm_device *dev)
15026 {
15027         struct drm_atomic_state *state = NULL;
15028         struct drm_modeset_acquire_ctx ctx;
15029         struct drm_crtc *crtc;
15030         struct drm_crtc_state *crtc_state;
15031         int ret = 0;
15032
15033         state = drm_atomic_state_alloc(dev);
15034         if (!state)
15035                 return -ENOMEM;
15036
15037         drm_modeset_acquire_init(&ctx, 0);
15038
15039 retry:
15040         state->acquire_ctx = &ctx;
15041
15042         drm_for_each_crtc(crtc, dev) {
15043                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
15044                 if (IS_ERR(crtc_state)) {
15045                         ret = PTR_ERR(crtc_state);
15046                         goto out;
15047                 }
15048
15049                 if (crtc_state->active) {
15050                         ret = drm_atomic_add_affected_planes(state, crtc);
15051                         if (ret)
15052                                 goto out;
15053                 }
15054         }
15055
15056         ret = drm_atomic_commit(state);
15057
15058 out:
15059         if (ret == -EDEADLK) {
15060                 drm_atomic_state_clear(state);
15061                 drm_modeset_backoff(&ctx);
15062                 goto retry;
15063         }
15064
15065         drm_atomic_state_put(state);
15066
15067         drm_modeset_drop_locks(&ctx);
15068         drm_modeset_acquire_fini(&ctx);
15069
15070         return ret;
15071 }
15072
15073 int intel_modeset_init(struct drm_device *dev)
15074 {
15075         struct drm_i915_private *dev_priv = to_i915(dev);
15076         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15077         enum pipe pipe;
15078         struct intel_crtc *crtc;
15079         int ret;
15080
15081         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15082
15083         drm_mode_config_init(dev);
15084
15085         dev->mode_config.min_width = 0;
15086         dev->mode_config.min_height = 0;
15087
15088         dev->mode_config.preferred_depth = 24;
15089         dev->mode_config.prefer_shadow = 1;
15090
15091         dev->mode_config.allow_fb_modifiers = true;
15092
15093         dev->mode_config.funcs = &intel_mode_funcs;
15094
15095         init_llist_head(&dev_priv->atomic_helper.free_list);
15096         INIT_WORK(&dev_priv->atomic_helper.free_work,
15097                   intel_atomic_helper_free_state_worker);
15098
15099         intel_init_quirks(dev);
15100
15101         intel_init_pm(dev_priv);
15102
15103         /*
15104          * There may be no VBT; and if the BIOS enabled SSC we can
15105          * just keep using it to avoid unnecessary flicker.  Whereas if the
15106          * BIOS isn't using it, don't assume it will work even if the VBT
15107          * indicates as much.
15108          */
15109         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15110                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15111                                             DREF_SSC1_ENABLE);
15112
15113                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15114                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15115                                      bios_lvds_use_ssc ? "en" : "dis",
15116                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15117                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15118                 }
15119         }
15120
15121         /* maximum framebuffer dimensions */
15122         if (IS_GEN2(dev_priv)) {
15123                 dev->mode_config.max_width = 2048;
15124                 dev->mode_config.max_height = 2048;
15125         } else if (IS_GEN3(dev_priv)) {
15126                 dev->mode_config.max_width = 4096;
15127                 dev->mode_config.max_height = 4096;
15128         } else {
15129                 dev->mode_config.max_width = 8192;
15130                 dev->mode_config.max_height = 8192;
15131         }
15132
15133         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15134                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15135                 dev->mode_config.cursor_height = 1023;
15136         } else if (IS_GEN2(dev_priv)) {
15137                 dev->mode_config.cursor_width = 64;
15138                 dev->mode_config.cursor_height = 64;
15139         } else {
15140                 dev->mode_config.cursor_width = 256;
15141                 dev->mode_config.cursor_height = 256;
15142         }
15143
15144         dev->mode_config.fb_base = ggtt->gmadr.start;
15145
15146         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15147                       INTEL_INFO(dev_priv)->num_pipes,
15148                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15149
15150         for_each_pipe(dev_priv, pipe) {
15151                 ret = intel_crtc_init(dev_priv, pipe);
15152                 if (ret) {
15153                         drm_mode_config_cleanup(dev);
15154                         return ret;
15155                 }
15156         }
15157
15158         intel_shared_dpll_init(dev);
15159         intel_update_fdi_pll_freq(dev_priv);
15160
15161         intel_update_czclk(dev_priv);
15162         intel_modeset_init_hw(dev);
15163
15164         if (dev_priv->max_cdclk_freq == 0)
15165                 intel_update_max_cdclk(dev_priv);
15166
15167         /* Just disable it once at startup */
15168         i915_disable_vga(dev_priv);
15169         intel_setup_outputs(dev_priv);
15170
15171         drm_modeset_lock_all(dev);
15172         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15173         drm_modeset_unlock_all(dev);
15174
15175         for_each_intel_crtc(dev, crtc) {
15176                 struct intel_initial_plane_config plane_config = {};
15177
15178                 if (!crtc->active)
15179                         continue;
15180
15181                 /*
15182                  * Note that reserving the BIOS fb up front prevents us
15183                  * from stuffing other stolen allocations like the ring
15184                  * on top.  This prevents some ugliness at boot time, and
15185                  * can even allow for smooth boot transitions if the BIOS
15186                  * fb is large enough for the active pipe configuration.
15187                  */
15188                 dev_priv->display.get_initial_plane_config(crtc,
15189                                                            &plane_config);
15190
15191                 /*
15192                  * If the fb is shared between multiple heads, we'll
15193                  * just get the first one.
15194                  */
15195                 intel_find_initial_plane_obj(crtc, &plane_config);
15196         }
15197
15198         /*
15199          * Make sure hardware watermarks really match the state we read out.
15200          * Note that we need to do this after reconstructing the BIOS fb's
15201          * since the watermark calculation done here will use pstate->fb.
15202          */
15203         if (!HAS_GMCH_DISPLAY(dev_priv))
15204                 sanitize_watermarks(dev);
15205
15206         /*
15207          * Force all active planes to recompute their states. So that on
15208          * mode_setcrtc after probe, all the intel_plane_state variables
15209          * are already calculated and there is no assert_plane warnings
15210          * during bootup.
15211          */
15212         ret = intel_initial_commit(dev);
15213         if (ret)
15214                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15215
15216         return 0;
15217 }
15218
15219 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15220 {
15221         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15222         /* 640x480@60Hz, ~25175 kHz */
15223         struct dpll clock = {
15224                 .m1 = 18,
15225                 .m2 = 7,
15226                 .p1 = 13,
15227                 .p2 = 4,
15228                 .n = 2,
15229         };
15230         u32 dpll, fp;
15231         int i;
15232
15233         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15234
15235         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15236                       pipe_name(pipe), clock.vco, clock.dot);
15237
15238         fp = i9xx_dpll_compute_fp(&clock);
15239         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
15240                 DPLL_VGA_MODE_DIS |
15241                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15242                 PLL_P2_DIVIDE_BY_4 |
15243                 PLL_REF_INPUT_DREFCLK |
15244                 DPLL_VCO_ENABLE;
15245
15246         I915_WRITE(FP0(pipe), fp);
15247         I915_WRITE(FP1(pipe), fp);
15248
15249         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15250         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15251         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15252         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15253         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15254         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15255         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15256
15257         /*
15258          * Apparently we need to have VGA mode enabled prior to changing
15259          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15260          * dividers, even though the register value does change.
15261          */
15262         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15263         I915_WRITE(DPLL(pipe), dpll);
15264
15265         /* Wait for the clocks to stabilize. */
15266         POSTING_READ(DPLL(pipe));
15267         udelay(150);
15268
15269         /* The pixel multiplier can only be updated once the
15270          * DPLL is enabled and the clocks are stable.
15271          *
15272          * So write it again.
15273          */
15274         I915_WRITE(DPLL(pipe), dpll);
15275
15276         /* We do this three times for luck */
15277         for (i = 0; i < 3 ; i++) {
15278                 I915_WRITE(DPLL(pipe), dpll);
15279                 POSTING_READ(DPLL(pipe));
15280                 udelay(150); /* wait for warmup */
15281         }
15282
15283         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15284         POSTING_READ(PIPECONF(pipe));
15285
15286         intel_wait_for_pipe_scanline_moving(crtc);
15287 }
15288
15289 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15290 {
15291         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15292
15293         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15294                       pipe_name(pipe));
15295
15296         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15297         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15298         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15299         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15300         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
15301
15302         I915_WRITE(PIPECONF(pipe), 0);
15303         POSTING_READ(PIPECONF(pipe));
15304
15305         intel_wait_for_pipe_scanline_stopped(crtc);
15306
15307         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15308         POSTING_READ(DPLL(pipe));
15309 }
15310
15311 static void
15312 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15313 {
15314         struct intel_crtc *crtc;
15315
15316         if (INTEL_GEN(dev_priv) >= 4)
15317                 return;
15318
15319         for_each_intel_crtc(&dev_priv->drm, crtc) {
15320                 struct intel_plane *plane =
15321                         to_intel_plane(crtc->base.primary);
15322                 struct intel_crtc *plane_crtc;
15323                 enum pipe pipe;
15324
15325                 if (!plane->get_hw_state(plane, &pipe))
15326                         continue;
15327
15328                 if (pipe == crtc->pipe)
15329                         continue;
15330
15331                 DRM_DEBUG_KMS("[PLANE:%d:%s] attached to the wrong pipe, disabling plane\n",
15332                               plane->base.base.id, plane->base.name);
15333
15334                 plane_crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15335                 intel_plane_disable_noatomic(plane_crtc, plane);
15336         }
15337 }
15338
15339 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15340 {
15341         struct drm_device *dev = crtc->base.dev;
15342         struct intel_encoder *encoder;
15343
15344         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15345                 return true;
15346
15347         return false;
15348 }
15349
15350 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15351 {
15352         struct drm_device *dev = encoder->base.dev;
15353         struct intel_connector *connector;
15354
15355         for_each_connector_on_encoder(dev, &encoder->base, connector)
15356                 return connector;
15357
15358         return NULL;
15359 }
15360
15361 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15362                               enum pipe pch_transcoder)
15363 {
15364         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15365                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15366 }
15367
15368 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15369                                 struct drm_modeset_acquire_ctx *ctx)
15370 {
15371         struct drm_device *dev = crtc->base.dev;
15372         struct drm_i915_private *dev_priv = to_i915(dev);
15373         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15374
15375         /* Clear any frame start delays used for debugging left by the BIOS */
15376         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15377                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15378
15379                 I915_WRITE(reg,
15380                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15381         }
15382
15383         if (crtc->active) {
15384                 struct intel_plane *plane;
15385
15386                 /* Disable everything but the primary plane */
15387                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15388                         const struct intel_plane_state *plane_state =
15389                                 to_intel_plane_state(plane->base.state);
15390
15391                         if (plane_state->base.visible &&
15392                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15393                                 intel_plane_disable_noatomic(crtc, plane);
15394                 }
15395         }
15396
15397         /* Adjust the state of the output pipe according to whether we
15398          * have active connectors/encoders. */
15399         if (crtc->active && !intel_crtc_has_encoders(crtc))
15400                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15401
15402         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15403                 /*
15404                  * We start out with underrun reporting disabled to avoid races.
15405                  * For correct bookkeeping mark this on active crtcs.
15406                  *
15407                  * Also on gmch platforms we dont have any hardware bits to
15408                  * disable the underrun reporting. Which means we need to start
15409                  * out with underrun reporting disabled also on inactive pipes,
15410                  * since otherwise we'll complain about the garbage we read when
15411                  * e.g. coming up after runtime pm.
15412                  *
15413                  * No protection against concurrent access is required - at
15414                  * worst a fifo underrun happens which also sets this to false.
15415                  */
15416                 crtc->cpu_fifo_underrun_disabled = true;
15417                 /*
15418                  * We track the PCH trancoder underrun reporting state
15419                  * within the crtc. With crtc for pipe A housing the underrun
15420                  * reporting state for PCH transcoder A, crtc for pipe B housing
15421                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15422                  * and marking underrun reporting as disabled for the non-existing
15423                  * PCH transcoders B and C would prevent enabling the south
15424                  * error interrupt (see cpt_can_enable_serr_int()).
15425                  */
15426                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15427                         crtc->pch_fifo_underrun_disabled = true;
15428         }
15429 }
15430
15431 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15432 {
15433         struct intel_connector *connector;
15434
15435         /* We need to check both for a crtc link (meaning that the
15436          * encoder is active and trying to read from a pipe) and the
15437          * pipe itself being active. */
15438         bool has_active_crtc = encoder->base.crtc &&
15439                 to_intel_crtc(encoder->base.crtc)->active;
15440
15441         connector = intel_encoder_find_connector(encoder);
15442         if (connector && !has_active_crtc) {
15443                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15444                               encoder->base.base.id,
15445                               encoder->base.name);
15446
15447                 /* Connector is active, but has no active pipe. This is
15448                  * fallout from our resume register restoring. Disable
15449                  * the encoder manually again. */
15450                 if (encoder->base.crtc) {
15451                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15452
15453                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15454                                       encoder->base.base.id,
15455                                       encoder->base.name);
15456                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15457                         if (encoder->post_disable)
15458                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15459                 }
15460                 encoder->base.crtc = NULL;
15461
15462                 /* Inconsistent output/port/pipe state happens presumably due to
15463                  * a bug in one of the get_hw_state functions. Or someplace else
15464                  * in our code, like the register restore mess on resume. Clamp
15465                  * things to off as a safer default. */
15466
15467                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15468                 connector->base.encoder = NULL;
15469         }
15470
15471         /* notify opregion of the sanitized encoder state */
15472         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
15473 }
15474
15475 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15476 {
15477         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15478
15479         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15480                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15481                 i915_disable_vga(dev_priv);
15482         }
15483 }
15484
15485 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15486 {
15487         /* This function can be called both from intel_modeset_setup_hw_state or
15488          * at a very early point in our resume sequence, where the power well
15489          * structures are not yet restored. Since this function is at a very
15490          * paranoid "someone might have enabled VGA while we were not looking"
15491          * level, just check if the power well is enabled instead of trying to
15492          * follow the "don't touch the power well if we don't need it" policy
15493          * the rest of the driver uses. */
15494         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15495                 return;
15496
15497         i915_redisable_vga_power_on(dev_priv);
15498
15499         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15500 }
15501
15502 /* FIXME read out full plane state for all planes */
15503 static void readout_plane_state(struct drm_i915_private *dev_priv)
15504 {
15505         struct intel_plane *plane;
15506         struct intel_crtc *crtc;
15507
15508         for_each_intel_plane(&dev_priv->drm, plane) {
15509                 struct intel_plane_state *plane_state =
15510                         to_intel_plane_state(plane->base.state);
15511                 struct intel_crtc_state *crtc_state;
15512                 enum pipe pipe = PIPE_A;
15513                 bool visible;
15514
15515                 visible = plane->get_hw_state(plane, &pipe);
15516
15517                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15518                 crtc_state = to_intel_crtc_state(crtc->base.state);
15519
15520                 intel_set_plane_visible(crtc_state, plane_state, visible);
15521
15522                 DRM_DEBUG_KMS("[PLANE:%d:%s] hw state readout: %s, pipe %c\n",
15523                               plane->base.base.id, plane->base.name,
15524                               enableddisabled(visible), pipe_name(pipe));
15525         }
15526
15527         for_each_intel_crtc(&dev_priv->drm, crtc) {
15528                 struct intel_crtc_state *crtc_state =
15529                         to_intel_crtc_state(crtc->base.state);
15530
15531                 fixup_active_planes(crtc_state);
15532         }
15533 }
15534
15535 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15536 {
15537         struct drm_i915_private *dev_priv = to_i915(dev);
15538         enum pipe pipe;
15539         struct intel_crtc *crtc;
15540         struct intel_encoder *encoder;
15541         struct intel_connector *connector;
15542         struct drm_connector_list_iter conn_iter;
15543         int i;
15544
15545         dev_priv->active_crtcs = 0;
15546
15547         for_each_intel_crtc(dev, crtc) {
15548                 struct intel_crtc_state *crtc_state =
15549                         to_intel_crtc_state(crtc->base.state);
15550
15551                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15552                 memset(crtc_state, 0, sizeof(*crtc_state));
15553                 crtc_state->base.crtc = &crtc->base;
15554
15555                 crtc_state->base.active = crtc_state->base.enable =
15556                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15557
15558                 crtc->base.enabled = crtc_state->base.enable;
15559                 crtc->active = crtc_state->base.active;
15560
15561                 if (crtc_state->base.active)
15562                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15563
15564                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15565                               crtc->base.base.id, crtc->base.name,
15566                               enableddisabled(crtc_state->base.active));
15567         }
15568
15569         readout_plane_state(dev_priv);
15570
15571         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15572                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15573
15574                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15575                                                         &pll->state.hw_state);
15576                 pll->state.crtc_mask = 0;
15577                 for_each_intel_crtc(dev, crtc) {
15578                         struct intel_crtc_state *crtc_state =
15579                                 to_intel_crtc_state(crtc->base.state);
15580
15581                         if (crtc_state->base.active &&
15582                             crtc_state->shared_dpll == pll)
15583                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15584                 }
15585                 pll->active_mask = pll->state.crtc_mask;
15586
15587                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15588                               pll->info->name, pll->state.crtc_mask, pll->on);
15589         }
15590
15591         for_each_intel_encoder(dev, encoder) {
15592                 pipe = 0;
15593
15594                 if (encoder->get_hw_state(encoder, &pipe)) {
15595                         struct intel_crtc_state *crtc_state;
15596
15597                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15598                         crtc_state = to_intel_crtc_state(crtc->base.state);
15599
15600                         encoder->base.crtc = &crtc->base;
15601                         encoder->get_config(encoder, crtc_state);
15602                 } else {
15603                         encoder->base.crtc = NULL;
15604                 }
15605
15606                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15607                               encoder->base.base.id, encoder->base.name,
15608                               enableddisabled(encoder->base.crtc),
15609                               pipe_name(pipe));
15610         }
15611
15612         drm_connector_list_iter_begin(dev, &conn_iter);
15613         for_each_intel_connector_iter(connector, &conn_iter) {
15614                 if (connector->get_hw_state(connector)) {
15615                         connector->base.dpms = DRM_MODE_DPMS_ON;
15616
15617                         encoder = connector->encoder;
15618                         connector->base.encoder = &encoder->base;
15619
15620                         if (encoder->base.crtc &&
15621                             encoder->base.crtc->state->active) {
15622                                 /*
15623                                  * This has to be done during hardware readout
15624                                  * because anything calling .crtc_disable may
15625                                  * rely on the connector_mask being accurate.
15626                                  */
15627                                 encoder->base.crtc->state->connector_mask |=
15628                                         drm_connector_mask(&connector->base);
15629                                 encoder->base.crtc->state->encoder_mask |=
15630                                         drm_encoder_mask(&encoder->base);
15631                         }
15632
15633                 } else {
15634                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15635                         connector->base.encoder = NULL;
15636                 }
15637                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15638                               connector->base.base.id, connector->base.name,
15639                               enableddisabled(connector->base.encoder));
15640         }
15641         drm_connector_list_iter_end(&conn_iter);
15642
15643         for_each_intel_crtc(dev, crtc) {
15644                 struct intel_crtc_state *crtc_state =
15645                         to_intel_crtc_state(crtc->base.state);
15646                 int min_cdclk = 0;
15647
15648                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15649                 if (crtc_state->base.active) {
15650                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15651                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
15652                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
15653                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15654                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15655
15656                         /*
15657                          * The initial mode needs to be set in order to keep
15658                          * the atomic core happy. It wants a valid mode if the
15659                          * crtc's enabled, so we do the above call.
15660                          *
15661                          * But we don't set all the derived state fully, hence
15662                          * set a flag to indicate that a full recalculation is
15663                          * needed on the next commit.
15664                          */
15665                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15666
15667                         intel_crtc_compute_pixel_rate(crtc_state);
15668
15669                         if (dev_priv->display.modeset_calc_cdclk) {
15670                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15671                                 if (WARN_ON(min_cdclk < 0))
15672                                         min_cdclk = 0;
15673                         }
15674
15675                         drm_calc_timestamping_constants(&crtc->base,
15676                                                         &crtc_state->base.adjusted_mode);
15677                         update_scanline_offset(crtc_state);
15678                 }
15679
15680                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15681                 dev_priv->min_voltage_level[crtc->pipe] =
15682                         crtc_state->min_voltage_level;
15683
15684                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15685         }
15686 }
15687
15688 static void
15689 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15690 {
15691         struct intel_encoder *encoder;
15692
15693         for_each_intel_encoder(&dev_priv->drm, encoder) {
15694                 u64 get_domains;
15695                 enum intel_display_power_domain domain;
15696                 struct intel_crtc_state *crtc_state;
15697
15698                 if (!encoder->get_power_domains)
15699                         continue;
15700
15701                 /*
15702                  * MST-primary and inactive encoders don't have a crtc state
15703                  * and neither of these require any power domain references.
15704                  */
15705                 if (!encoder->base.crtc)
15706                         continue;
15707
15708                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
15709                 get_domains = encoder->get_power_domains(encoder, crtc_state);
15710                 for_each_power_domain(domain, get_domains)
15711                         intel_display_power_get(dev_priv, domain);
15712         }
15713 }
15714
15715 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15716 {
15717         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15718         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15719                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15720                            DARBF_GATING_DIS);
15721
15722         if (IS_HASWELL(dev_priv)) {
15723                 /*
15724                  * WaRsPkgCStateDisplayPMReq:hsw
15725                  * System hang if this isn't done before disabling all planes!
15726                  */
15727                 I915_WRITE(CHICKEN_PAR1_1,
15728                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15729         }
15730 }
15731
15732 /* Scan out the current hw modeset state,
15733  * and sanitizes it to the current state
15734  */
15735 static void
15736 intel_modeset_setup_hw_state(struct drm_device *dev,
15737                              struct drm_modeset_acquire_ctx *ctx)
15738 {
15739         struct drm_i915_private *dev_priv = to_i915(dev);
15740         struct intel_crtc *crtc;
15741         struct intel_encoder *encoder;
15742         int i;
15743
15744         intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
15745
15746         intel_early_display_was(dev_priv);
15747         intel_modeset_readout_hw_state(dev);
15748
15749         /* HW state is read out, now we need to sanitize this mess. */
15750         get_encoder_power_domains(dev_priv);
15751
15752         /*
15753          * intel_sanitize_plane_mapping() may need to do vblank
15754          * waits, so we need vblank interrupts restored beforehand.
15755          */
15756         for_each_intel_crtc(&dev_priv->drm, crtc) {
15757                 drm_crtc_vblank_reset(&crtc->base);
15758
15759                 if (crtc->active)
15760                         drm_crtc_vblank_on(&crtc->base);
15761         }
15762
15763         intel_sanitize_plane_mapping(dev_priv);
15764
15765         for_each_intel_encoder(dev, encoder)
15766                 intel_sanitize_encoder(encoder);
15767
15768         for_each_intel_crtc(&dev_priv->drm, crtc) {
15769                 intel_sanitize_crtc(crtc, ctx);
15770                 intel_dump_pipe_config(crtc, crtc->config,
15771                                        "[setup_hw_state]");
15772         }
15773
15774         intel_modeset_update_connector_atomic_state(dev);
15775
15776         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15777                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15778
15779                 if (!pll->on || pll->active_mask)
15780                         continue;
15781
15782                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
15783                               pll->info->name);
15784
15785                 pll->info->funcs->disable(dev_priv, pll);
15786                 pll->on = false;
15787         }
15788
15789         if (IS_G4X(dev_priv)) {
15790                 g4x_wm_get_hw_state(dev);
15791                 g4x_wm_sanitize(dev_priv);
15792         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15793                 vlv_wm_get_hw_state(dev);
15794                 vlv_wm_sanitize(dev_priv);
15795         } else if (INTEL_GEN(dev_priv) >= 9) {
15796                 skl_wm_get_hw_state(dev);
15797         } else if (HAS_PCH_SPLIT(dev_priv)) {
15798                 ilk_wm_get_hw_state(dev);
15799         }
15800
15801         for_each_intel_crtc(dev, crtc) {
15802                 u64 put_domains;
15803
15804                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15805                 if (WARN_ON(put_domains))
15806                         modeset_put_power_domains(dev_priv, put_domains);
15807         }
15808
15809         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT);
15810
15811         intel_fbc_init_pipe_state(dev_priv);
15812 }
15813
15814 void intel_display_resume(struct drm_device *dev)
15815 {
15816         struct drm_i915_private *dev_priv = to_i915(dev);
15817         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15818         struct drm_modeset_acquire_ctx ctx;
15819         int ret;
15820
15821         dev_priv->modeset_restore_state = NULL;
15822         if (state)
15823                 state->acquire_ctx = &ctx;
15824
15825         drm_modeset_acquire_init(&ctx, 0);
15826
15827         while (1) {
15828                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15829                 if (ret != -EDEADLK)
15830                         break;
15831
15832                 drm_modeset_backoff(&ctx);
15833         }
15834
15835         if (!ret)
15836                 ret = __intel_display_resume(dev, state, &ctx);
15837
15838         intel_enable_ipc(dev_priv);
15839         drm_modeset_drop_locks(&ctx);
15840         drm_modeset_acquire_fini(&ctx);
15841
15842         if (ret)
15843                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15844         if (state)
15845                 drm_atomic_state_put(state);
15846 }
15847
15848 static void intel_hpd_poll_fini(struct drm_device *dev)
15849 {
15850         struct intel_connector *connector;
15851         struct drm_connector_list_iter conn_iter;
15852
15853         /* Kill all the work that may have been queued by hpd. */
15854         drm_connector_list_iter_begin(dev, &conn_iter);
15855         for_each_intel_connector_iter(connector, &conn_iter) {
15856                 if (connector->modeset_retry_work.func)
15857                         cancel_work_sync(&connector->modeset_retry_work);
15858                 if (connector->hdcp_shim) {
15859                         cancel_delayed_work_sync(&connector->hdcp_check_work);
15860                         cancel_work_sync(&connector->hdcp_prop_work);
15861                 }
15862         }
15863         drm_connector_list_iter_end(&conn_iter);
15864 }
15865
15866 void intel_modeset_cleanup(struct drm_device *dev)
15867 {
15868         struct drm_i915_private *dev_priv = to_i915(dev);
15869
15870         flush_workqueue(dev_priv->modeset_wq);
15871
15872         flush_work(&dev_priv->atomic_helper.free_work);
15873         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15874
15875         /*
15876          * Interrupts and polling as the first thing to avoid creating havoc.
15877          * Too much stuff here (turning of connectors, ...) would
15878          * experience fancy races otherwise.
15879          */
15880         intel_irq_uninstall(dev_priv);
15881
15882         /*
15883          * Due to the hpd irq storm handling the hotplug work can re-arm the
15884          * poll handlers. Hence disable polling after hpd handling is shut down.
15885          */
15886         intel_hpd_poll_fini(dev);
15887
15888         /* poll work can call into fbdev, hence clean that up afterwards */
15889         intel_fbdev_fini(dev_priv);
15890
15891         intel_unregister_dsm_handler();
15892
15893         intel_fbc_global_disable(dev_priv);
15894
15895         /* flush any delayed tasks or pending work */
15896         flush_scheduled_work();
15897
15898         drm_mode_config_cleanup(dev);
15899
15900         intel_cleanup_overlay(dev_priv);
15901
15902         intel_teardown_gmbus(dev_priv);
15903
15904         destroy_workqueue(dev_priv->modeset_wq);
15905 }
15906
15907 /*
15908  * set vga decode state - true == enable VGA decode
15909  */
15910 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15911 {
15912         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15913         u16 gmch_ctrl;
15914
15915         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15916                 DRM_ERROR("failed to read control word\n");
15917                 return -EIO;
15918         }
15919
15920         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15921                 return 0;
15922
15923         if (state)
15924                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15925         else
15926                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15927
15928         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15929                 DRM_ERROR("failed to write control word\n");
15930                 return -EIO;
15931         }
15932
15933         return 0;
15934 }
15935
15936 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15937
15938 struct intel_display_error_state {
15939
15940         u32 power_well_driver;
15941
15942         int num_transcoders;
15943
15944         struct intel_cursor_error_state {
15945                 u32 control;
15946                 u32 position;
15947                 u32 base;
15948                 u32 size;
15949         } cursor[I915_MAX_PIPES];
15950
15951         struct intel_pipe_error_state {
15952                 bool power_domain_on;
15953                 u32 source;
15954                 u32 stat;
15955         } pipe[I915_MAX_PIPES];
15956
15957         struct intel_plane_error_state {
15958                 u32 control;
15959                 u32 stride;
15960                 u32 size;
15961                 u32 pos;
15962                 u32 addr;
15963                 u32 surface;
15964                 u32 tile_offset;
15965         } plane[I915_MAX_PIPES];
15966
15967         struct intel_transcoder_error_state {
15968                 bool power_domain_on;
15969                 enum transcoder cpu_transcoder;
15970
15971                 u32 conf;
15972
15973                 u32 htotal;
15974                 u32 hblank;
15975                 u32 hsync;
15976                 u32 vtotal;
15977                 u32 vblank;
15978                 u32 vsync;
15979         } transcoder[4];
15980 };
15981
15982 struct intel_display_error_state *
15983 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15984 {
15985         struct intel_display_error_state *error;
15986         int transcoders[] = {
15987                 TRANSCODER_A,
15988                 TRANSCODER_B,
15989                 TRANSCODER_C,
15990                 TRANSCODER_EDP,
15991         };
15992         int i;
15993
15994         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15995                 return NULL;
15996
15997         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15998         if (error == NULL)
15999                 return NULL;
16000
16001         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16002                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
16003
16004         for_each_pipe(dev_priv, i) {
16005                 error->pipe[i].power_domain_on =
16006                         __intel_display_power_is_enabled(dev_priv,
16007                                                          POWER_DOMAIN_PIPE(i));
16008                 if (!error->pipe[i].power_domain_on)
16009                         continue;
16010
16011                 error->cursor[i].control = I915_READ(CURCNTR(i));
16012                 error->cursor[i].position = I915_READ(CURPOS(i));
16013                 error->cursor[i].base = I915_READ(CURBASE(i));
16014
16015                 error->plane[i].control = I915_READ(DSPCNTR(i));
16016                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16017                 if (INTEL_GEN(dev_priv) <= 3) {
16018                         error->plane[i].size = I915_READ(DSPSIZE(i));
16019                         error->plane[i].pos = I915_READ(DSPPOS(i));
16020                 }
16021                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16022                         error->plane[i].addr = I915_READ(DSPADDR(i));
16023                 if (INTEL_GEN(dev_priv) >= 4) {
16024                         error->plane[i].surface = I915_READ(DSPSURF(i));
16025                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16026                 }
16027
16028                 error->pipe[i].source = I915_READ(PIPESRC(i));
16029
16030                 if (HAS_GMCH_DISPLAY(dev_priv))
16031                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16032         }
16033
16034         /* Note: this does not include DSI transcoders. */
16035         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16036         if (HAS_DDI(dev_priv))
16037                 error->num_transcoders++; /* Account for eDP. */
16038
16039         for (i = 0; i < error->num_transcoders; i++) {
16040                 enum transcoder cpu_transcoder = transcoders[i];
16041
16042                 error->transcoder[i].power_domain_on =
16043                         __intel_display_power_is_enabled(dev_priv,
16044                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16045                 if (!error->transcoder[i].power_domain_on)
16046                         continue;
16047
16048                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16049
16050                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16051                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16052                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16053                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16054                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16055                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16056                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16057         }
16058
16059         return error;
16060 }
16061
16062 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16063
16064 void
16065 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16066                                 struct intel_display_error_state *error)
16067 {
16068         struct drm_i915_private *dev_priv = m->i915;
16069         int i;
16070
16071         if (!error)
16072                 return;
16073
16074         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16075         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16076                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16077                            error->power_well_driver);
16078         for_each_pipe(dev_priv, i) {
16079                 err_printf(m, "Pipe [%d]:\n", i);
16080                 err_printf(m, "  Power: %s\n",
16081                            onoff(error->pipe[i].power_domain_on));
16082                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16083                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16084
16085                 err_printf(m, "Plane [%d]:\n", i);
16086                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16087                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16088                 if (INTEL_GEN(dev_priv) <= 3) {
16089                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16090                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16091                 }
16092                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16093                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16094                 if (INTEL_GEN(dev_priv) >= 4) {
16095                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16096                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16097                 }
16098
16099                 err_printf(m, "Cursor [%d]:\n", i);
16100                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16101                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16102                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16103         }
16104
16105         for (i = 0; i < error->num_transcoders; i++) {
16106                 err_printf(m, "CPU transcoder: %s\n",
16107                            transcoder_name(error->transcoder[i].cpu_transcoder));
16108                 err_printf(m, "  Power: %s\n",
16109                            onoff(error->transcoder[i].power_domain_on));
16110                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16111                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16112                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16113                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16114                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16115                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16116                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16117         }
16118 }
16119
16120 #endif