drm/i915: move intel connector specific functions to intel_connector.c
[sfrench/cifs-2.6.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(struct intel_crtc *crtc,
98                                          struct intel_link_m_n *m_n,
99                                          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->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4843                 need_scaling = true;
4844
4845         /*
4846          * Scaling/fitting not supported in IF-ID mode in GEN9+
4847          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4848          * Once NV12 is enabled, handle it here while allocating scaler
4849          * for NV12.
4850          */
4851         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4852             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4853                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4854                 return -EINVAL;
4855         }
4856
4857         /*
4858          * if plane is being disabled or scaler is no more required or force detach
4859          *  - free scaler binded to this plane/crtc
4860          *  - in order to do this, update crtc->scaler_usage
4861          *
4862          * Here scaler state in crtc_state is set free so that
4863          * scaler can be assigned to other user. Actual register
4864          * update to free the scaler is done in plane/panel-fit programming.
4865          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4866          */
4867         if (force_detach || !need_scaling) {
4868                 if (*scaler_id >= 0) {
4869                         scaler_state->scaler_users &= ~(1 << scaler_user);
4870                         scaler_state->scalers[*scaler_id].in_use = 0;
4871
4872                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4873                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4874                                 intel_crtc->pipe, scaler_user, *scaler_id,
4875                                 scaler_state->scaler_users);
4876                         *scaler_id = -1;
4877                 }
4878                 return 0;
4879         }
4880
4881         if (plane_scaler_check && pixel_format == DRM_FORMAT_NV12 &&
4882             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
4883                 DRM_DEBUG_KMS("NV12: src dimensions not met\n");
4884                 return -EINVAL;
4885         }
4886
4887         /* range checks */
4888         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4889             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4890             (IS_GEN11(dev_priv) &&
4891              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
4892               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
4893             (!IS_GEN11(dev_priv) &&
4894              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4895               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
4896                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4897                         "size is out of scaler range\n",
4898                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4899                 return -EINVAL;
4900         }
4901
4902         /* mark this plane as a scaler user in crtc_state */
4903         scaler_state->scaler_users |= (1 << scaler_user);
4904         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4905                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4906                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4907                 scaler_state->scaler_users);
4908
4909         return 0;
4910 }
4911
4912 /**
4913  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4914  *
4915  * @state: crtc's scaler state
4916  *
4917  * Return
4918  *     0 - scaler_usage updated successfully
4919  *    error - requested scaling cannot be supported or other error condition
4920  */
4921 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4922 {
4923         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4924
4925         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4926                                  &state->scaler_state.scaler_id,
4927                                  state->pipe_src_w, state->pipe_src_h,
4928                                  adjusted_mode->crtc_hdisplay,
4929                                  adjusted_mode->crtc_vdisplay, false, 0);
4930 }
4931
4932 /**
4933  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4934  * @crtc_state: crtc's scaler state
4935  * @plane_state: atomic plane state to update
4936  *
4937  * Return
4938  *     0 - scaler_usage updated successfully
4939  *    error - requested scaling cannot be supported or other error condition
4940  */
4941 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4942                                    struct intel_plane_state *plane_state)
4943 {
4944
4945         struct intel_plane *intel_plane =
4946                 to_intel_plane(plane_state->base.plane);
4947         struct drm_framebuffer *fb = plane_state->base.fb;
4948         int ret;
4949
4950         bool force_detach = !fb || !plane_state->base.visible;
4951
4952         ret = skl_update_scaler(crtc_state, force_detach,
4953                                 drm_plane_index(&intel_plane->base),
4954                                 &plane_state->scaler_id,
4955                                 drm_rect_width(&plane_state->base.src) >> 16,
4956                                 drm_rect_height(&plane_state->base.src) >> 16,
4957                                 drm_rect_width(&plane_state->base.dst),
4958                                 drm_rect_height(&plane_state->base.dst),
4959                                 fb ? true : false, fb ? fb->format->format : 0);
4960
4961         if (ret || plane_state->scaler_id < 0)
4962                 return ret;
4963
4964         /* check colorkey */
4965         if (plane_state->ckey.flags) {
4966                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4967                               intel_plane->base.base.id,
4968                               intel_plane->base.name);
4969                 return -EINVAL;
4970         }
4971
4972         /* Check src format */
4973         switch (fb->format->format) {
4974         case DRM_FORMAT_RGB565:
4975         case DRM_FORMAT_XBGR8888:
4976         case DRM_FORMAT_XRGB8888:
4977         case DRM_FORMAT_ABGR8888:
4978         case DRM_FORMAT_ARGB8888:
4979         case DRM_FORMAT_XRGB2101010:
4980         case DRM_FORMAT_XBGR2101010:
4981         case DRM_FORMAT_YUYV:
4982         case DRM_FORMAT_YVYU:
4983         case DRM_FORMAT_UYVY:
4984         case DRM_FORMAT_VYUY:
4985         case DRM_FORMAT_NV12:
4986                 break;
4987         default:
4988                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4989                               intel_plane->base.base.id, intel_plane->base.name,
4990                               fb->base.id, fb->format->format);
4991                 return -EINVAL;
4992         }
4993
4994         return 0;
4995 }
4996
4997 static void skylake_scaler_disable(struct intel_crtc *crtc)
4998 {
4999         int i;
5000
5001         for (i = 0; i < crtc->num_scalers; i++)
5002                 skl_detach_scaler(crtc, i);
5003 }
5004
5005 static void skylake_pfit_enable(const struct intel_crtc_state *crtc_state)
5006 {
5007         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5008         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5009         enum pipe pipe = crtc->pipe;
5010         const struct intel_crtc_scaler_state *scaler_state =
5011                 &crtc_state->scaler_state;
5012
5013         if (crtc_state->pch_pfit.enabled) {
5014                 u16 uv_rgb_hphase, uv_rgb_vphase;
5015                 int id;
5016
5017                 if (WARN_ON(crtc_state->scaler_state.scaler_id < 0))
5018                         return;
5019
5020                 uv_rgb_hphase = skl_scaler_calc_phase(1, false);
5021                 uv_rgb_vphase = skl_scaler_calc_phase(1, false);
5022
5023                 id = scaler_state->scaler_id;
5024                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5025                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5026                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5027                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5028                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5029                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5030                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc_state->pch_pfit.pos);
5031                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc_state->pch_pfit.size);
5032         }
5033 }
5034
5035 static void ironlake_pfit_enable(const struct intel_crtc_state *crtc_state)
5036 {
5037         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5038         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5039         int pipe = crtc->pipe;
5040
5041         if (crtc_state->pch_pfit.enabled) {
5042                 /* Force use of hard-coded filter coefficients
5043                  * as some pre-programmed values are broken,
5044                  * e.g. x201.
5045                  */
5046                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5047                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5048                                                  PF_PIPE_SEL_IVB(pipe));
5049                 else
5050                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5051                 I915_WRITE(PF_WIN_POS(pipe), crtc_state->pch_pfit.pos);
5052                 I915_WRITE(PF_WIN_SZ(pipe), crtc_state->pch_pfit.size);
5053         }
5054 }
5055
5056 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5057 {
5058         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5059         struct drm_device *dev = crtc->base.dev;
5060         struct drm_i915_private *dev_priv = to_i915(dev);
5061
5062         if (!crtc_state->ips_enabled)
5063                 return;
5064
5065         /*
5066          * We can only enable IPS after we enable a plane and wait for a vblank
5067          * This function is called from post_plane_update, which is run after
5068          * a vblank wait.
5069          */
5070         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5071
5072         if (IS_BROADWELL(dev_priv)) {
5073                 mutex_lock(&dev_priv->pcu_lock);
5074                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5075                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5076                 mutex_unlock(&dev_priv->pcu_lock);
5077                 /* Quoting Art Runyan: "its not safe to expect any particular
5078                  * value in IPS_CTL bit 31 after enabling IPS through the
5079                  * mailbox." Moreover, the mailbox may return a bogus state,
5080                  * so we need to just enable it and continue on.
5081                  */
5082         } else {
5083                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5084                 /* The bit only becomes 1 in the next vblank, so this wait here
5085                  * is essentially intel_wait_for_vblank. If we don't have this
5086                  * and don't wait for vblanks until the end of crtc_enable, then
5087                  * the HW state readout code will complain that the expected
5088                  * IPS_CTL value is not the one we read. */
5089                 if (intel_wait_for_register(dev_priv,
5090                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5091                                             50))
5092                         DRM_ERROR("Timed out waiting for IPS enable\n");
5093         }
5094 }
5095
5096 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5097 {
5098         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5099         struct drm_device *dev = crtc->base.dev;
5100         struct drm_i915_private *dev_priv = to_i915(dev);
5101
5102         if (!crtc_state->ips_enabled)
5103                 return;
5104
5105         if (IS_BROADWELL(dev_priv)) {
5106                 mutex_lock(&dev_priv->pcu_lock);
5107                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5108                 mutex_unlock(&dev_priv->pcu_lock);
5109                 /*
5110                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5111                  * 42ms timeout value leads to occasional timeouts so use 100ms
5112                  * instead.
5113                  */
5114                 if (intel_wait_for_register(dev_priv,
5115                                             IPS_CTL, IPS_ENABLE, 0,
5116                                             100))
5117                         DRM_ERROR("Timed out waiting for IPS disable\n");
5118         } else {
5119                 I915_WRITE(IPS_CTL, 0);
5120                 POSTING_READ(IPS_CTL);
5121         }
5122
5123         /* We need to wait for a vblank before we can disable the plane. */
5124         intel_wait_for_vblank(dev_priv, crtc->pipe);
5125 }
5126
5127 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5128 {
5129         if (intel_crtc->overlay) {
5130                 struct drm_device *dev = intel_crtc->base.dev;
5131
5132                 mutex_lock(&dev->struct_mutex);
5133                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5134                 mutex_unlock(&dev->struct_mutex);
5135         }
5136
5137         /* Let userspace switch the overlay on again. In most cases userspace
5138          * has to recompute where to put it anyway.
5139          */
5140 }
5141
5142 /**
5143  * intel_post_enable_primary - Perform operations after enabling primary plane
5144  * @crtc: the CRTC whose primary plane was just enabled
5145  * @new_crtc_state: the enabling state
5146  *
5147  * Performs potentially sleeping operations that must be done after the primary
5148  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5149  * called due to an explicit primary plane update, or due to an implicit
5150  * re-enable that is caused when a sprite plane is updated to no longer
5151  * completely hide the primary plane.
5152  */
5153 static void
5154 intel_post_enable_primary(struct drm_crtc *crtc,
5155                           const struct intel_crtc_state *new_crtc_state)
5156 {
5157         struct drm_device *dev = crtc->dev;
5158         struct drm_i915_private *dev_priv = to_i915(dev);
5159         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5160         int pipe = intel_crtc->pipe;
5161
5162         /*
5163          * Gen2 reports pipe underruns whenever all planes are disabled.
5164          * So don't enable underrun reporting before at least some planes
5165          * are enabled.
5166          * FIXME: Need to fix the logic to work when we turn off all planes
5167          * but leave the pipe running.
5168          */
5169         if (IS_GEN2(dev_priv))
5170                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5171
5172         /* Underruns don't always raise interrupts, so check manually. */
5173         intel_check_cpu_fifo_underruns(dev_priv);
5174         intel_check_pch_fifo_underruns(dev_priv);
5175 }
5176
5177 /* FIXME get rid of this and use pre_plane_update */
5178 static void
5179 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5180 {
5181         struct drm_device *dev = crtc->dev;
5182         struct drm_i915_private *dev_priv = to_i915(dev);
5183         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5184         int pipe = intel_crtc->pipe;
5185
5186         /*
5187          * Gen2 reports pipe underruns whenever all planes are disabled.
5188          * So disable underrun reporting before all the planes get disabled.
5189          */
5190         if (IS_GEN2(dev_priv))
5191                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5192
5193         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5194
5195         /*
5196          * Vblank time updates from the shadow to live plane control register
5197          * are blocked if the memory self-refresh mode is active at that
5198          * moment. So to make sure the plane gets truly disabled, disable
5199          * first the self-refresh mode. The self-refresh enable bit in turn
5200          * will be checked/applied by the HW only at the next frame start
5201          * event which is after the vblank start event, so we need to have a
5202          * wait-for-vblank between disabling the plane and the pipe.
5203          */
5204         if (HAS_GMCH_DISPLAY(dev_priv) &&
5205             intel_set_memory_cxsr(dev_priv, false))
5206                 intel_wait_for_vblank(dev_priv, pipe);
5207 }
5208
5209 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5210                                        const struct intel_crtc_state *new_crtc_state)
5211 {
5212         if (!old_crtc_state->ips_enabled)
5213                 return false;
5214
5215         if (needs_modeset(&new_crtc_state->base))
5216                 return true;
5217
5218         return !new_crtc_state->ips_enabled;
5219 }
5220
5221 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5222                                        const struct intel_crtc_state *new_crtc_state)
5223 {
5224         if (!new_crtc_state->ips_enabled)
5225                 return false;
5226
5227         if (needs_modeset(&new_crtc_state->base))
5228                 return true;
5229
5230         /*
5231          * We can't read out IPS on broadwell, assume the worst and
5232          * forcibly enable IPS on the first fastset.
5233          */
5234         if (new_crtc_state->update_pipe &&
5235             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5236                 return true;
5237
5238         return !old_crtc_state->ips_enabled;
5239 }
5240
5241 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5242                           const struct intel_crtc_state *crtc_state)
5243 {
5244         if (!crtc_state->nv12_planes)
5245                 return false;
5246
5247         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
5248                 return false;
5249
5250         if ((INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv)) ||
5251             IS_CANNONLAKE(dev_priv))
5252                 return true;
5253
5254         return false;
5255 }
5256
5257 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5258 {
5259         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5260         struct drm_device *dev = crtc->base.dev;
5261         struct drm_i915_private *dev_priv = to_i915(dev);
5262         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5263         struct intel_crtc_state *pipe_config =
5264                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5265                                                 crtc);
5266         struct drm_plane *primary = crtc->base.primary;
5267         struct drm_plane_state *old_primary_state =
5268                 drm_atomic_get_old_plane_state(old_state, primary);
5269
5270         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5271
5272         if (pipe_config->update_wm_post && pipe_config->base.active)
5273                 intel_update_watermarks(crtc);
5274
5275         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5276                 hsw_enable_ips(pipe_config);
5277
5278         if (old_primary_state) {
5279                 struct drm_plane_state *new_primary_state =
5280                         drm_atomic_get_new_plane_state(old_state, primary);
5281
5282                 intel_fbc_post_update(crtc);
5283
5284                 if (new_primary_state->visible &&
5285                     (needs_modeset(&pipe_config->base) ||
5286                      !old_primary_state->visible))
5287                         intel_post_enable_primary(&crtc->base, pipe_config);
5288         }
5289
5290         /* Display WA 827 */
5291         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5292             !needs_nv12_wa(dev_priv, pipe_config)) {
5293                 skl_wa_clkgate(dev_priv, crtc->pipe, false);
5294                 skl_wa_528(dev_priv, crtc->pipe, false);
5295         }
5296 }
5297
5298 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5299                                    struct intel_crtc_state *pipe_config)
5300 {
5301         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5302         struct drm_device *dev = crtc->base.dev;
5303         struct drm_i915_private *dev_priv = to_i915(dev);
5304         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5305         struct drm_plane *primary = crtc->base.primary;
5306         struct drm_plane_state *old_primary_state =
5307                 drm_atomic_get_old_plane_state(old_state, primary);
5308         bool modeset = needs_modeset(&pipe_config->base);
5309         struct intel_atomic_state *old_intel_state =
5310                 to_intel_atomic_state(old_state);
5311
5312         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5313                 hsw_disable_ips(old_crtc_state);
5314
5315         if (old_primary_state) {
5316                 struct intel_plane_state *new_primary_state =
5317                         intel_atomic_get_new_plane_state(old_intel_state,
5318                                                          to_intel_plane(primary));
5319
5320                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5321                 /*
5322                  * Gen2 reports pipe underruns whenever all planes are disabled.
5323                  * So disable underrun reporting before all the planes get disabled.
5324                  */
5325                 if (IS_GEN2(dev_priv) && old_primary_state->visible &&
5326                     (modeset || !new_primary_state->base.visible))
5327                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5328         }
5329
5330         /* Display WA 827 */
5331         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5332             needs_nv12_wa(dev_priv, pipe_config)) {
5333                 skl_wa_clkgate(dev_priv, crtc->pipe, true);
5334                 skl_wa_528(dev_priv, crtc->pipe, true);
5335         }
5336
5337         /*
5338          * Vblank time updates from the shadow to live plane control register
5339          * are blocked if the memory self-refresh mode is active at that
5340          * moment. So to make sure the plane gets truly disabled, disable
5341          * first the self-refresh mode. The self-refresh enable bit in turn
5342          * will be checked/applied by the HW only at the next frame start
5343          * event which is after the vblank start event, so we need to have a
5344          * wait-for-vblank between disabling the plane and the pipe.
5345          */
5346         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5347             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5348                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5349
5350         /*
5351          * IVB workaround: must disable low power watermarks for at least
5352          * one frame before enabling scaling.  LP watermarks can be re-enabled
5353          * when scaling is disabled.
5354          *
5355          * WaCxSRDisabledForSpriteScaling:ivb
5356          */
5357         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev) &&
5358             old_crtc_state->base.active)
5359                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5360
5361         /*
5362          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5363          * watermark programming here.
5364          */
5365         if (needs_modeset(&pipe_config->base))
5366                 return;
5367
5368         /*
5369          * For platforms that support atomic watermarks, program the
5370          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5371          * will be the intermediate values that are safe for both pre- and
5372          * post- vblank; when vblank happens, the 'active' values will be set
5373          * to the final 'target' values and we'll do this again to get the
5374          * optimal watermarks.  For gen9+ platforms, the values we program here
5375          * will be the final target values which will get automatically latched
5376          * at vblank time; no further programming will be necessary.
5377          *
5378          * If a platform hasn't been transitioned to atomic watermarks yet,
5379          * we'll continue to update watermarks the old way, if flags tell
5380          * us to.
5381          */
5382         if (dev_priv->display.initial_watermarks != NULL)
5383                 dev_priv->display.initial_watermarks(old_intel_state,
5384                                                      pipe_config);
5385         else if (pipe_config->update_wm_pre)
5386                 intel_update_watermarks(crtc);
5387 }
5388
5389 static void intel_crtc_disable_planes(struct intel_crtc *crtc, unsigned plane_mask)
5390 {
5391         struct drm_device *dev = crtc->base.dev;
5392         struct intel_plane *plane;
5393         unsigned fb_bits = 0;
5394
5395         intel_crtc_dpms_overlay_disable(crtc);
5396
5397         for_each_intel_plane_on_crtc(dev, crtc, plane) {
5398                 if (plane_mask & BIT(plane->id)) {
5399                         plane->disable_plane(plane, crtc);
5400
5401                         fb_bits |= plane->frontbuffer_bit;
5402                 }
5403         }
5404
5405         intel_frontbuffer_flip(to_i915(dev), fb_bits);
5406 }
5407
5408 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5409                                           struct intel_crtc_state *crtc_state,
5410                                           struct drm_atomic_state *old_state)
5411 {
5412         struct drm_connector_state *conn_state;
5413         struct drm_connector *conn;
5414         int i;
5415
5416         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5417                 struct intel_encoder *encoder =
5418                         to_intel_encoder(conn_state->best_encoder);
5419
5420                 if (conn_state->crtc != crtc)
5421                         continue;
5422
5423                 if (encoder->pre_pll_enable)
5424                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5425         }
5426 }
5427
5428 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5429                                       struct intel_crtc_state *crtc_state,
5430                                       struct drm_atomic_state *old_state)
5431 {
5432         struct drm_connector_state *conn_state;
5433         struct drm_connector *conn;
5434         int i;
5435
5436         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5437                 struct intel_encoder *encoder =
5438                         to_intel_encoder(conn_state->best_encoder);
5439
5440                 if (conn_state->crtc != crtc)
5441                         continue;
5442
5443                 if (encoder->pre_enable)
5444                         encoder->pre_enable(encoder, crtc_state, conn_state);
5445         }
5446 }
5447
5448 static void intel_encoders_enable(struct drm_crtc *crtc,
5449                                   struct intel_crtc_state *crtc_state,
5450                                   struct drm_atomic_state *old_state)
5451 {
5452         struct drm_connector_state *conn_state;
5453         struct drm_connector *conn;
5454         int i;
5455
5456         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5457                 struct intel_encoder *encoder =
5458                         to_intel_encoder(conn_state->best_encoder);
5459
5460                 if (conn_state->crtc != crtc)
5461                         continue;
5462
5463                 encoder->enable(encoder, crtc_state, conn_state);
5464                 intel_opregion_notify_encoder(encoder, true);
5465         }
5466 }
5467
5468 static void intel_encoders_disable(struct drm_crtc *crtc,
5469                                    struct intel_crtc_state *old_crtc_state,
5470                                    struct drm_atomic_state *old_state)
5471 {
5472         struct drm_connector_state *old_conn_state;
5473         struct drm_connector *conn;
5474         int i;
5475
5476         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5477                 struct intel_encoder *encoder =
5478                         to_intel_encoder(old_conn_state->best_encoder);
5479
5480                 if (old_conn_state->crtc != crtc)
5481                         continue;
5482
5483                 intel_opregion_notify_encoder(encoder, false);
5484                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5485         }
5486 }
5487
5488 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5489                                         struct intel_crtc_state *old_crtc_state,
5490                                         struct drm_atomic_state *old_state)
5491 {
5492         struct drm_connector_state *old_conn_state;
5493         struct drm_connector *conn;
5494         int i;
5495
5496         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5497                 struct intel_encoder *encoder =
5498                         to_intel_encoder(old_conn_state->best_encoder);
5499
5500                 if (old_conn_state->crtc != crtc)
5501                         continue;
5502
5503                 if (encoder->post_disable)
5504                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5505         }
5506 }
5507
5508 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5509                                             struct intel_crtc_state *old_crtc_state,
5510                                             struct drm_atomic_state *old_state)
5511 {
5512         struct drm_connector_state *old_conn_state;
5513         struct drm_connector *conn;
5514         int i;
5515
5516         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5517                 struct intel_encoder *encoder =
5518                         to_intel_encoder(old_conn_state->best_encoder);
5519
5520                 if (old_conn_state->crtc != crtc)
5521                         continue;
5522
5523                 if (encoder->post_pll_disable)
5524                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5525         }
5526 }
5527
5528 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5529                                  struct drm_atomic_state *old_state)
5530 {
5531         struct drm_crtc *crtc = pipe_config->base.crtc;
5532         struct drm_device *dev = crtc->dev;
5533         struct drm_i915_private *dev_priv = to_i915(dev);
5534         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5535         int pipe = intel_crtc->pipe;
5536         struct intel_atomic_state *old_intel_state =
5537                 to_intel_atomic_state(old_state);
5538
5539         if (WARN_ON(intel_crtc->active))
5540                 return;
5541
5542         /*
5543          * Sometimes spurious CPU pipe underruns happen during FDI
5544          * training, at least with VGA+HDMI cloning. Suppress them.
5545          *
5546          * On ILK we get an occasional spurious CPU pipe underruns
5547          * between eDP port A enable and vdd enable. Also PCH port
5548          * enable seems to result in the occasional CPU pipe underrun.
5549          *
5550          * Spurious PCH underruns also occur during PCH enabling.
5551          */
5552         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5553         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5554
5555         if (pipe_config->has_pch_encoder)
5556                 intel_prepare_shared_dpll(pipe_config);
5557
5558         if (intel_crtc_has_dp_encoder(pipe_config))
5559                 intel_dp_set_m_n(intel_crtc, M1_N1);
5560
5561         intel_set_pipe_timings(pipe_config);
5562         intel_set_pipe_src_size(pipe_config);
5563
5564         if (pipe_config->has_pch_encoder) {
5565                 intel_cpu_transcoder_set_m_n(intel_crtc,
5566                                      &pipe_config->fdi_m_n, NULL);
5567         }
5568
5569         ironlake_set_pipeconf(pipe_config);
5570
5571         intel_crtc->active = true;
5572
5573         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5574
5575         if (pipe_config->has_pch_encoder) {
5576                 /* Note: FDI PLL enabling _must_ be done before we enable the
5577                  * cpu pipes, hence this is separate from all the other fdi/pch
5578                  * enabling. */
5579                 ironlake_fdi_pll_enable(pipe_config);
5580         } else {
5581                 assert_fdi_tx_disabled(dev_priv, pipe);
5582                 assert_fdi_rx_disabled(dev_priv, pipe);
5583         }
5584
5585         ironlake_pfit_enable(pipe_config);
5586
5587         /*
5588          * On ILK+ LUT must be loaded before the pipe is running but with
5589          * clocks enabled
5590          */
5591         intel_color_load_luts(&pipe_config->base);
5592
5593         if (dev_priv->display.initial_watermarks != NULL)
5594                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5595         intel_enable_pipe(pipe_config);
5596
5597         if (pipe_config->has_pch_encoder)
5598                 ironlake_pch_enable(old_intel_state, pipe_config);
5599
5600         assert_vblank_disabled(crtc);
5601         drm_crtc_vblank_on(crtc);
5602
5603         intel_encoders_enable(crtc, pipe_config, old_state);
5604
5605         if (HAS_PCH_CPT(dev_priv))
5606                 cpt_verify_modeset(dev, intel_crtc->pipe);
5607
5608         /*
5609          * Must wait for vblank to avoid spurious PCH FIFO underruns.
5610          * And a second vblank wait is needed at least on ILK with
5611          * some interlaced HDMI modes. Let's do the double wait always
5612          * in case there are more corner cases we don't know about.
5613          */
5614         if (pipe_config->has_pch_encoder) {
5615                 intel_wait_for_vblank(dev_priv, pipe);
5616                 intel_wait_for_vblank(dev_priv, pipe);
5617         }
5618         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5619         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5620 }
5621
5622 /* IPS only exists on ULT machines and is tied to pipe A. */
5623 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5624 {
5625         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5626 }
5627
5628 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5629                                             enum pipe pipe, bool apply)
5630 {
5631         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5632         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5633
5634         if (apply)
5635                 val |= mask;
5636         else
5637                 val &= ~mask;
5638
5639         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5640 }
5641
5642 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5643 {
5644         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5645         enum pipe pipe = crtc->pipe;
5646         uint32_t val;
5647
5648         val = MBUS_DBOX_A_CREDIT(2);
5649         val |= MBUS_DBOX_BW_CREDIT(1);
5650         val |= MBUS_DBOX_B_CREDIT(8);
5651
5652         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5653 }
5654
5655 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5656                                 struct drm_atomic_state *old_state)
5657 {
5658         struct drm_crtc *crtc = pipe_config->base.crtc;
5659         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5660         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5661         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5662         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
5663         struct intel_atomic_state *old_intel_state =
5664                 to_intel_atomic_state(old_state);
5665         bool psl_clkgate_wa;
5666         u32 pipe_chicken;
5667
5668         if (WARN_ON(intel_crtc->active))
5669                 return;
5670
5671         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5672
5673         if (pipe_config->shared_dpll)
5674                 intel_enable_shared_dpll(pipe_config);
5675
5676         if (INTEL_GEN(dev_priv) >= 11)
5677                 icl_map_plls_to_ports(crtc, pipe_config, old_state);
5678
5679         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5680
5681         if (intel_crtc_has_dp_encoder(pipe_config))
5682                 intel_dp_set_m_n(intel_crtc, M1_N1);
5683
5684         if (!transcoder_is_dsi(cpu_transcoder))
5685                 intel_set_pipe_timings(pipe_config);
5686
5687         intel_set_pipe_src_size(pipe_config);
5688
5689         if (cpu_transcoder != TRANSCODER_EDP &&
5690             !transcoder_is_dsi(cpu_transcoder)) {
5691                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5692                            pipe_config->pixel_multiplier - 1);
5693         }
5694
5695         if (pipe_config->has_pch_encoder) {
5696                 intel_cpu_transcoder_set_m_n(intel_crtc,
5697                                      &pipe_config->fdi_m_n, NULL);
5698         }
5699
5700         if (!transcoder_is_dsi(cpu_transcoder))
5701                 haswell_set_pipeconf(pipe_config);
5702
5703         haswell_set_pipemisc(pipe_config);
5704
5705         intel_color_set_csc(&pipe_config->base);
5706
5707         intel_crtc->active = true;
5708
5709         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5710         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5711                          pipe_config->pch_pfit.enabled;
5712         if (psl_clkgate_wa)
5713                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5714
5715         if (INTEL_GEN(dev_priv) >= 9)
5716                 skylake_pfit_enable(pipe_config);
5717         else
5718                 ironlake_pfit_enable(pipe_config);
5719
5720         /*
5721          * On ILK+ LUT must be loaded before the pipe is running but with
5722          * clocks enabled
5723          */
5724         intel_color_load_luts(&pipe_config->base);
5725
5726         /*
5727          * Display WA #1153: enable hardware to bypass the alpha math
5728          * and rounding for per-pixel values 00 and 0xff
5729          */
5730         if (INTEL_GEN(dev_priv) >= 11) {
5731                 pipe_chicken = I915_READ(PIPE_CHICKEN(pipe));
5732                 if (!(pipe_chicken & PER_PIXEL_ALPHA_BYPASS_EN))
5733                         I915_WRITE_FW(PIPE_CHICKEN(pipe),
5734                                       pipe_chicken | PER_PIXEL_ALPHA_BYPASS_EN);
5735         }
5736
5737         intel_ddi_set_pipe_settings(pipe_config);
5738         if (!transcoder_is_dsi(cpu_transcoder))
5739                 intel_ddi_enable_transcoder_func(pipe_config);
5740
5741         if (dev_priv->display.initial_watermarks != NULL)
5742                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5743
5744         if (INTEL_GEN(dev_priv) >= 11)
5745                 icl_pipe_mbus_enable(intel_crtc);
5746
5747         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5748         if (!transcoder_is_dsi(cpu_transcoder))
5749                 intel_enable_pipe(pipe_config);
5750
5751         if (pipe_config->has_pch_encoder)
5752                 lpt_pch_enable(old_intel_state, pipe_config);
5753
5754         if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DP_MST))
5755                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5756
5757         assert_vblank_disabled(crtc);
5758         drm_crtc_vblank_on(crtc);
5759
5760         intel_encoders_enable(crtc, pipe_config, old_state);
5761
5762         if (psl_clkgate_wa) {
5763                 intel_wait_for_vblank(dev_priv, pipe);
5764                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5765         }
5766
5767         /* If we change the relative order between pipe/planes enabling, we need
5768          * to change the workaround. */
5769         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5770         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5771                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5772                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5773         }
5774 }
5775
5776 static void ironlake_pfit_disable(const struct intel_crtc_state *old_crtc_state)
5777 {
5778         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5779         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5780         enum pipe pipe = crtc->pipe;
5781
5782         /* To avoid upsetting the power well on haswell only disable the pfit if
5783          * it's in use. The hw state code will make sure we get this right. */
5784         if (old_crtc_state->pch_pfit.enabled) {
5785                 I915_WRITE(PF_CTL(pipe), 0);
5786                 I915_WRITE(PF_WIN_POS(pipe), 0);
5787                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5788         }
5789 }
5790
5791 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5792                                   struct drm_atomic_state *old_state)
5793 {
5794         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5795         struct drm_device *dev = crtc->dev;
5796         struct drm_i915_private *dev_priv = to_i915(dev);
5797         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5798         int pipe = intel_crtc->pipe;
5799
5800         /*
5801          * Sometimes spurious CPU pipe underruns happen when the
5802          * pipe is already disabled, but FDI RX/TX is still enabled.
5803          * Happens at least with VGA+HDMI cloning. Suppress them.
5804          */
5805         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5806         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5807
5808         intel_encoders_disable(crtc, old_crtc_state, old_state);
5809
5810         drm_crtc_vblank_off(crtc);
5811         assert_vblank_disabled(crtc);
5812
5813         intel_disable_pipe(old_crtc_state);
5814
5815         ironlake_pfit_disable(old_crtc_state);
5816
5817         if (old_crtc_state->has_pch_encoder)
5818                 ironlake_fdi_disable(crtc);
5819
5820         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5821
5822         if (old_crtc_state->has_pch_encoder) {
5823                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5824
5825                 if (HAS_PCH_CPT(dev_priv)) {
5826                         i915_reg_t reg;
5827                         u32 temp;
5828
5829                         /* disable TRANS_DP_CTL */
5830                         reg = TRANS_DP_CTL(pipe);
5831                         temp = I915_READ(reg);
5832                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5833                                   TRANS_DP_PORT_SEL_MASK);
5834                         temp |= TRANS_DP_PORT_SEL_NONE;
5835                         I915_WRITE(reg, temp);
5836
5837                         /* disable DPLL_SEL */
5838                         temp = I915_READ(PCH_DPLL_SEL);
5839                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5840                         I915_WRITE(PCH_DPLL_SEL, temp);
5841                 }
5842
5843                 ironlake_fdi_pll_disable(intel_crtc);
5844         }
5845
5846         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5847         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5848 }
5849
5850 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5851                                  struct drm_atomic_state *old_state)
5852 {
5853         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5854         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5855         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5856         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
5857
5858         intel_encoders_disable(crtc, old_crtc_state, old_state);
5859
5860         drm_crtc_vblank_off(crtc);
5861         assert_vblank_disabled(crtc);
5862
5863         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5864         if (!transcoder_is_dsi(cpu_transcoder))
5865                 intel_disable_pipe(old_crtc_state);
5866
5867         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
5868                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
5869
5870         if (!transcoder_is_dsi(cpu_transcoder))
5871                 intel_ddi_disable_transcoder_func(old_crtc_state);
5872
5873         if (INTEL_GEN(dev_priv) >= 9)
5874                 skylake_scaler_disable(intel_crtc);
5875         else
5876                 ironlake_pfit_disable(old_crtc_state);
5877
5878         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5879
5880         if (INTEL_GEN(dev_priv) >= 11)
5881                 icl_unmap_plls_to_ports(crtc, old_crtc_state, old_state);
5882 }
5883
5884 static void i9xx_pfit_enable(const struct intel_crtc_state *crtc_state)
5885 {
5886         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5887         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5888
5889         if (!crtc_state->gmch_pfit.control)
5890                 return;
5891
5892         /*
5893          * The panel fitter should only be adjusted whilst the pipe is disabled,
5894          * according to register description and PRM.
5895          */
5896         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5897         assert_pipe_disabled(dev_priv, crtc->pipe);
5898
5899         I915_WRITE(PFIT_PGM_RATIOS, crtc_state->gmch_pfit.pgm_ratios);
5900         I915_WRITE(PFIT_CONTROL, crtc_state->gmch_pfit.control);
5901
5902         /* Border color in case we don't scale up to the full screen. Black by
5903          * default, change to something else for debugging. */
5904         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5905 }
5906
5907 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
5908 {
5909         if (IS_ICELAKE(dev_priv))
5910                 return port >= PORT_C && port <= PORT_F;
5911
5912         return false;
5913 }
5914
5915 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
5916 {
5917         if (!intel_port_is_tc(dev_priv, port))
5918                 return PORT_TC_NONE;
5919
5920         return port - PORT_C;
5921 }
5922
5923 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5924 {
5925         switch (port) {
5926         case PORT_A:
5927                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5928         case PORT_B:
5929                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5930         case PORT_C:
5931                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5932         case PORT_D:
5933                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5934         case PORT_E:
5935                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5936         case PORT_F:
5937                 return POWER_DOMAIN_PORT_DDI_F_LANES;
5938         default:
5939                 MISSING_CASE(port);
5940                 return POWER_DOMAIN_PORT_OTHER;
5941         }
5942 }
5943
5944 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5945                                   struct intel_crtc_state *crtc_state)
5946 {
5947         struct drm_device *dev = crtc->dev;
5948         struct drm_i915_private *dev_priv = to_i915(dev);
5949         struct drm_encoder *encoder;
5950         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5951         enum pipe pipe = intel_crtc->pipe;
5952         u64 mask;
5953         enum transcoder transcoder = crtc_state->cpu_transcoder;
5954
5955         if (!crtc_state->base.active)
5956                 return 0;
5957
5958         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
5959         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
5960         if (crtc_state->pch_pfit.enabled ||
5961             crtc_state->pch_pfit.force_thru)
5962                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5963
5964         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5965                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5966
5967                 mask |= BIT_ULL(intel_encoder->power_domain);
5968         }
5969
5970         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5971                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
5972
5973         if (crtc_state->shared_dpll)
5974                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5975
5976         return mask;
5977 }
5978
5979 static u64
5980 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5981                                struct intel_crtc_state *crtc_state)
5982 {
5983         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5984         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5985         enum intel_display_power_domain domain;
5986         u64 domains, new_domains, old_domains;
5987
5988         old_domains = intel_crtc->enabled_power_domains;
5989         intel_crtc->enabled_power_domains = new_domains =
5990                 get_crtc_power_domains(crtc, crtc_state);
5991
5992         domains = new_domains & ~old_domains;
5993
5994         for_each_power_domain(domain, domains)
5995                 intel_display_power_get(dev_priv, domain);
5996
5997         return old_domains & ~new_domains;
5998 }
5999
6000 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
6001                                       u64 domains)
6002 {
6003         enum intel_display_power_domain domain;
6004
6005         for_each_power_domain(domain, domains)
6006                 intel_display_power_put(dev_priv, domain);
6007 }
6008
6009 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6010                                    struct drm_atomic_state *old_state)
6011 {
6012         struct intel_atomic_state *old_intel_state =
6013                 to_intel_atomic_state(old_state);
6014         struct drm_crtc *crtc = pipe_config->base.crtc;
6015         struct drm_device *dev = crtc->dev;
6016         struct drm_i915_private *dev_priv = to_i915(dev);
6017         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6018         int pipe = intel_crtc->pipe;
6019
6020         if (WARN_ON(intel_crtc->active))
6021                 return;
6022
6023         if (intel_crtc_has_dp_encoder(pipe_config))
6024                 intel_dp_set_m_n(intel_crtc, M1_N1);
6025
6026         intel_set_pipe_timings(pipe_config);
6027         intel_set_pipe_src_size(pipe_config);
6028
6029         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6030                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6031                 I915_WRITE(CHV_CANVAS(pipe), 0);
6032         }
6033
6034         i9xx_set_pipeconf(pipe_config);
6035
6036         intel_color_set_csc(&pipe_config->base);
6037
6038         intel_crtc->active = true;
6039
6040         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6041
6042         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6043
6044         if (IS_CHERRYVIEW(dev_priv)) {
6045                 chv_prepare_pll(intel_crtc, pipe_config);
6046                 chv_enable_pll(intel_crtc, pipe_config);
6047         } else {
6048                 vlv_prepare_pll(intel_crtc, pipe_config);
6049                 vlv_enable_pll(intel_crtc, pipe_config);
6050         }
6051
6052         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6053
6054         i9xx_pfit_enable(pipe_config);
6055
6056         intel_color_load_luts(&pipe_config->base);
6057
6058         dev_priv->display.initial_watermarks(old_intel_state,
6059                                              pipe_config);
6060         intel_enable_pipe(pipe_config);
6061
6062         assert_vblank_disabled(crtc);
6063         drm_crtc_vblank_on(crtc);
6064
6065         intel_encoders_enable(crtc, pipe_config, old_state);
6066 }
6067
6068 static void i9xx_set_pll_dividers(const struct intel_crtc_state *crtc_state)
6069 {
6070         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6071         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6072
6073         I915_WRITE(FP0(crtc->pipe), crtc_state->dpll_hw_state.fp0);
6074         I915_WRITE(FP1(crtc->pipe), crtc_state->dpll_hw_state.fp1);
6075 }
6076
6077 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6078                              struct drm_atomic_state *old_state)
6079 {
6080         struct intel_atomic_state *old_intel_state =
6081                 to_intel_atomic_state(old_state);
6082         struct drm_crtc *crtc = pipe_config->base.crtc;
6083         struct drm_device *dev = crtc->dev;
6084         struct drm_i915_private *dev_priv = to_i915(dev);
6085         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6086         enum pipe pipe = intel_crtc->pipe;
6087
6088         if (WARN_ON(intel_crtc->active))
6089                 return;
6090
6091         i9xx_set_pll_dividers(pipe_config);
6092
6093         if (intel_crtc_has_dp_encoder(pipe_config))
6094                 intel_dp_set_m_n(intel_crtc, M1_N1);
6095
6096         intel_set_pipe_timings(pipe_config);
6097         intel_set_pipe_src_size(pipe_config);
6098
6099         i9xx_set_pipeconf(pipe_config);
6100
6101         intel_crtc->active = true;
6102
6103         if (!IS_GEN2(dev_priv))
6104                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6105
6106         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6107
6108         i9xx_enable_pll(intel_crtc, pipe_config);
6109
6110         i9xx_pfit_enable(pipe_config);
6111
6112         intel_color_load_luts(&pipe_config->base);
6113
6114         if (dev_priv->display.initial_watermarks != NULL)
6115                 dev_priv->display.initial_watermarks(old_intel_state,
6116                                                      pipe_config);
6117         else
6118                 intel_update_watermarks(intel_crtc);
6119         intel_enable_pipe(pipe_config);
6120
6121         assert_vblank_disabled(crtc);
6122         drm_crtc_vblank_on(crtc);
6123
6124         intel_encoders_enable(crtc, pipe_config, old_state);
6125 }
6126
6127 static void i9xx_pfit_disable(const struct intel_crtc_state *old_crtc_state)
6128 {
6129         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
6130         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6131
6132         if (!old_crtc_state->gmch_pfit.control)
6133                 return;
6134
6135         assert_pipe_disabled(dev_priv, crtc->pipe);
6136
6137         DRM_DEBUG_KMS("disabling pfit, current: 0x%08x\n",
6138                       I915_READ(PFIT_CONTROL));
6139         I915_WRITE(PFIT_CONTROL, 0);
6140 }
6141
6142 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6143                               struct drm_atomic_state *old_state)
6144 {
6145         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6146         struct drm_device *dev = crtc->dev;
6147         struct drm_i915_private *dev_priv = to_i915(dev);
6148         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6149         int pipe = intel_crtc->pipe;
6150
6151         /*
6152          * On gen2 planes are double buffered but the pipe isn't, so we must
6153          * wait for planes to fully turn off before disabling the pipe.
6154          */
6155         if (IS_GEN2(dev_priv))
6156                 intel_wait_for_vblank(dev_priv, pipe);
6157
6158         intel_encoders_disable(crtc, old_crtc_state, old_state);
6159
6160         drm_crtc_vblank_off(crtc);
6161         assert_vblank_disabled(crtc);
6162
6163         intel_disable_pipe(old_crtc_state);
6164
6165         i9xx_pfit_disable(old_crtc_state);
6166
6167         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6168
6169         if (!intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DSI)) {
6170                 if (IS_CHERRYVIEW(dev_priv))
6171                         chv_disable_pll(dev_priv, pipe);
6172                 else if (IS_VALLEYVIEW(dev_priv))
6173                         vlv_disable_pll(dev_priv, pipe);
6174                 else
6175                         i9xx_disable_pll(old_crtc_state);
6176         }
6177
6178         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6179
6180         if (!IS_GEN2(dev_priv))
6181                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6182
6183         if (!dev_priv->display.initial_watermarks)
6184                 intel_update_watermarks(intel_crtc);
6185
6186         /* clock the pipe down to 640x480@60 to potentially save power */
6187         if (IS_I830(dev_priv))
6188                 i830_enable_pipe(dev_priv, pipe);
6189 }
6190
6191 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6192                                         struct drm_modeset_acquire_ctx *ctx)
6193 {
6194         struct intel_encoder *encoder;
6195         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6196         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6197         enum intel_display_power_domain domain;
6198         struct intel_plane *plane;
6199         u64 domains;
6200         struct drm_atomic_state *state;
6201         struct intel_crtc_state *crtc_state;
6202         int ret;
6203
6204         if (!intel_crtc->active)
6205                 return;
6206
6207         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6208                 const struct intel_plane_state *plane_state =
6209                         to_intel_plane_state(plane->base.state);
6210
6211                 if (plane_state->base.visible)
6212                         intel_plane_disable_noatomic(intel_crtc, plane);
6213         }
6214
6215         state = drm_atomic_state_alloc(crtc->dev);
6216         if (!state) {
6217                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6218                               crtc->base.id, crtc->name);
6219                 return;
6220         }
6221
6222         state->acquire_ctx = ctx;
6223
6224         /* Everything's already locked, -EDEADLK can't happen. */
6225         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6226         ret = drm_atomic_add_affected_connectors(state, crtc);
6227
6228         WARN_ON(IS_ERR(crtc_state) || ret);
6229
6230         dev_priv->display.crtc_disable(crtc_state, state);
6231
6232         drm_atomic_state_put(state);
6233
6234         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6235                       crtc->base.id, crtc->name);
6236
6237         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6238         crtc->state->active = false;
6239         intel_crtc->active = false;
6240         crtc->enabled = false;
6241         crtc->state->connector_mask = 0;
6242         crtc->state->encoder_mask = 0;
6243
6244         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6245                 encoder->base.crtc = NULL;
6246
6247         intel_fbc_disable(intel_crtc);
6248         intel_update_watermarks(intel_crtc);
6249         intel_disable_shared_dpll(to_intel_crtc_state(crtc->state));
6250
6251         domains = intel_crtc->enabled_power_domains;
6252         for_each_power_domain(domain, domains)
6253                 intel_display_power_put(dev_priv, domain);
6254         intel_crtc->enabled_power_domains = 0;
6255
6256         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6257         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6258         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6259 }
6260
6261 /*
6262  * turn all crtc's off, but do not adjust state
6263  * This has to be paired with a call to intel_modeset_setup_hw_state.
6264  */
6265 int intel_display_suspend(struct drm_device *dev)
6266 {
6267         struct drm_i915_private *dev_priv = to_i915(dev);
6268         struct drm_atomic_state *state;
6269         int ret;
6270
6271         state = drm_atomic_helper_suspend(dev);
6272         ret = PTR_ERR_OR_ZERO(state);
6273         if (ret)
6274                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6275         else
6276                 dev_priv->modeset_restore_state = state;
6277         return ret;
6278 }
6279
6280 void intel_encoder_destroy(struct drm_encoder *encoder)
6281 {
6282         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6283
6284         drm_encoder_cleanup(encoder);
6285         kfree(intel_encoder);
6286 }
6287
6288 /* Cross check the actual hw state with our own modeset state tracking (and it's
6289  * internal consistency). */
6290 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6291                                          struct drm_connector_state *conn_state)
6292 {
6293         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6294
6295         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6296                       connector->base.base.id,
6297                       connector->base.name);
6298
6299         if (connector->get_hw_state(connector)) {
6300                 struct intel_encoder *encoder = connector->encoder;
6301
6302                 I915_STATE_WARN(!crtc_state,
6303                          "connector enabled without attached crtc\n");
6304
6305                 if (!crtc_state)
6306                         return;
6307
6308                 I915_STATE_WARN(!crtc_state->active,
6309                       "connector is active, but attached crtc isn't\n");
6310
6311                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6312                         return;
6313
6314                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6315                         "atomic encoder doesn't match attached encoder\n");
6316
6317                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6318                         "attached encoder crtc differs from connector crtc\n");
6319         } else {
6320                 I915_STATE_WARN(crtc_state && crtc_state->active,
6321                         "attached crtc is active, but connector isn't\n");
6322                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6323                         "best encoder set without crtc!\n");
6324         }
6325 }
6326
6327 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6328 {
6329         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6330                 return crtc_state->fdi_lanes;
6331
6332         return 0;
6333 }
6334
6335 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6336                                      struct intel_crtc_state *pipe_config)
6337 {
6338         struct drm_i915_private *dev_priv = to_i915(dev);
6339         struct drm_atomic_state *state = pipe_config->base.state;
6340         struct intel_crtc *other_crtc;
6341         struct intel_crtc_state *other_crtc_state;
6342
6343         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6344                       pipe_name(pipe), pipe_config->fdi_lanes);
6345         if (pipe_config->fdi_lanes > 4) {
6346                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6347                               pipe_name(pipe), pipe_config->fdi_lanes);
6348                 return -EINVAL;
6349         }
6350
6351         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6352                 if (pipe_config->fdi_lanes > 2) {
6353                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6354                                       pipe_config->fdi_lanes);
6355                         return -EINVAL;
6356                 } else {
6357                         return 0;
6358                 }
6359         }
6360
6361         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6362                 return 0;
6363
6364         /* Ivybridge 3 pipe is really complicated */
6365         switch (pipe) {
6366         case PIPE_A:
6367                 return 0;
6368         case PIPE_B:
6369                 if (pipe_config->fdi_lanes <= 2)
6370                         return 0;
6371
6372                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6373                 other_crtc_state =
6374                         intel_atomic_get_crtc_state(state, other_crtc);
6375                 if (IS_ERR(other_crtc_state))
6376                         return PTR_ERR(other_crtc_state);
6377
6378                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6379                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6380                                       pipe_name(pipe), pipe_config->fdi_lanes);
6381                         return -EINVAL;
6382                 }
6383                 return 0;
6384         case PIPE_C:
6385                 if (pipe_config->fdi_lanes > 2) {
6386                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6387                                       pipe_name(pipe), pipe_config->fdi_lanes);
6388                         return -EINVAL;
6389                 }
6390
6391                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6392                 other_crtc_state =
6393                         intel_atomic_get_crtc_state(state, other_crtc);
6394                 if (IS_ERR(other_crtc_state))
6395                         return PTR_ERR(other_crtc_state);
6396
6397                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6398                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6399                         return -EINVAL;
6400                 }
6401                 return 0;
6402         default:
6403                 BUG();
6404         }
6405 }
6406
6407 #define RETRY 1
6408 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6409                                        struct intel_crtc_state *pipe_config)
6410 {
6411         struct drm_device *dev = intel_crtc->base.dev;
6412         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6413         int lane, link_bw, fdi_dotclock, ret;
6414         bool needs_recompute = false;
6415
6416 retry:
6417         /* FDI is a binary signal running at ~2.7GHz, encoding
6418          * each output octet as 10 bits. The actual frequency
6419          * is stored as a divider into a 100MHz clock, and the
6420          * mode pixel clock is stored in units of 1KHz.
6421          * Hence the bw of each lane in terms of the mode signal
6422          * is:
6423          */
6424         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6425
6426         fdi_dotclock = adjusted_mode->crtc_clock;
6427
6428         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6429                                            pipe_config->pipe_bpp);
6430
6431         pipe_config->fdi_lanes = lane;
6432
6433         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6434                                link_bw, &pipe_config->fdi_m_n, false);
6435
6436         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6437         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6438                 pipe_config->pipe_bpp -= 2*3;
6439                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6440                               pipe_config->pipe_bpp);
6441                 needs_recompute = true;
6442                 pipe_config->bw_constrained = true;
6443
6444                 goto retry;
6445         }
6446
6447         if (needs_recompute)
6448                 return RETRY;
6449
6450         return ret;
6451 }
6452
6453 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6454 {
6455         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6456         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6457
6458         /* IPS only exists on ULT machines and is tied to pipe A. */
6459         if (!hsw_crtc_supports_ips(crtc))
6460                 return false;
6461
6462         if (!i915_modparams.enable_ips)
6463                 return false;
6464
6465         if (crtc_state->pipe_bpp > 24)
6466                 return false;
6467
6468         /*
6469          * We compare against max which means we must take
6470          * the increased cdclk requirement into account when
6471          * calculating the new cdclk.
6472          *
6473          * Should measure whether using a lower cdclk w/o IPS
6474          */
6475         if (IS_BROADWELL(dev_priv) &&
6476             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6477                 return false;
6478
6479         return true;
6480 }
6481
6482 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6483 {
6484         struct drm_i915_private *dev_priv =
6485                 to_i915(crtc_state->base.crtc->dev);
6486         struct intel_atomic_state *intel_state =
6487                 to_intel_atomic_state(crtc_state->base.state);
6488
6489         if (!hsw_crtc_state_ips_capable(crtc_state))
6490                 return false;
6491
6492         if (crtc_state->ips_force_disable)
6493                 return false;
6494
6495         /* IPS should be fine as long as at least one plane is enabled. */
6496         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6497                 return false;
6498
6499         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6500         if (IS_BROADWELL(dev_priv) &&
6501             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6502                 return false;
6503
6504         return true;
6505 }
6506
6507 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6508 {
6509         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6510
6511         /* GDG double wide on either pipe, otherwise pipe A only */
6512         return INTEL_GEN(dev_priv) < 4 &&
6513                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6514 }
6515
6516 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6517 {
6518         uint32_t pixel_rate;
6519
6520         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6521
6522         /*
6523          * We only use IF-ID interlacing. If we ever use
6524          * PF-ID we'll need to adjust the pixel_rate here.
6525          */
6526
6527         if (pipe_config->pch_pfit.enabled) {
6528                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6529                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6530
6531                 pipe_w = pipe_config->pipe_src_w;
6532                 pipe_h = pipe_config->pipe_src_h;
6533
6534                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6535                 pfit_h = pfit_size & 0xFFFF;
6536                 if (pipe_w < pfit_w)
6537                         pipe_w = pfit_w;
6538                 if (pipe_h < pfit_h)
6539                         pipe_h = pfit_h;
6540
6541                 if (WARN_ON(!pfit_w || !pfit_h))
6542                         return pixel_rate;
6543
6544                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6545                                      pfit_w * pfit_h);
6546         }
6547
6548         return pixel_rate;
6549 }
6550
6551 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6552 {
6553         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6554
6555         if (HAS_GMCH_DISPLAY(dev_priv))
6556                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6557                 crtc_state->pixel_rate =
6558                         crtc_state->base.adjusted_mode.crtc_clock;
6559         else
6560                 crtc_state->pixel_rate =
6561                         ilk_pipe_pixel_rate(crtc_state);
6562 }
6563
6564 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6565                                      struct intel_crtc_state *pipe_config)
6566 {
6567         struct drm_device *dev = crtc->base.dev;
6568         struct drm_i915_private *dev_priv = to_i915(dev);
6569         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6570         int clock_limit = dev_priv->max_dotclk_freq;
6571
6572         if (INTEL_GEN(dev_priv) < 4) {
6573                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6574
6575                 /*
6576                  * Enable double wide mode when the dot clock
6577                  * is > 90% of the (display) core speed.
6578                  */
6579                 if (intel_crtc_supports_double_wide(crtc) &&
6580                     adjusted_mode->crtc_clock > clock_limit) {
6581                         clock_limit = dev_priv->max_dotclk_freq;
6582                         pipe_config->double_wide = true;
6583                 }
6584         }
6585
6586         if (adjusted_mode->crtc_clock > clock_limit) {
6587                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6588                               adjusted_mode->crtc_clock, clock_limit,
6589                               yesno(pipe_config->double_wide));
6590                 return -EINVAL;
6591         }
6592
6593         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6594                 /*
6595                  * There is only one pipe CSC unit per pipe, and we need that
6596                  * for output conversion from RGB->YCBCR. So if CTM is already
6597                  * applied we can't support YCBCR420 output.
6598                  */
6599                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6600                 return -EINVAL;
6601         }
6602
6603         /*
6604          * Pipe horizontal size must be even in:
6605          * - DVO ganged mode
6606          * - LVDS dual channel mode
6607          * - Double wide pipe
6608          */
6609         if (pipe_config->pipe_src_w & 1) {
6610                 if (pipe_config->double_wide) {
6611                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6612                         return -EINVAL;
6613                 }
6614
6615                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6616                     intel_is_dual_link_lvds(dev)) {
6617                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6618                         return -EINVAL;
6619                 }
6620         }
6621
6622         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6623          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6624          */
6625         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6626                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6627                 return -EINVAL;
6628
6629         intel_crtc_compute_pixel_rate(pipe_config);
6630
6631         if (pipe_config->has_pch_encoder)
6632                 return ironlake_fdi_compute_config(crtc, pipe_config);
6633
6634         return 0;
6635 }
6636
6637 static void
6638 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6639 {
6640         while (*num > DATA_LINK_M_N_MASK ||
6641                *den > DATA_LINK_M_N_MASK) {
6642                 *num >>= 1;
6643                 *den >>= 1;
6644         }
6645 }
6646
6647 static void compute_m_n(unsigned int m, unsigned int n,
6648                         uint32_t *ret_m, uint32_t *ret_n,
6649                         bool constant_n)
6650 {
6651         /*
6652          * Several DP dongles in particular seem to be fussy about
6653          * too large link M/N values. Give N value as 0x8000 that
6654          * should be acceptable by specific devices. 0x8000 is the
6655          * specified fixed N value for asynchronous clock mode,
6656          * which the devices expect also in synchronous clock mode.
6657          */
6658         if (constant_n)
6659                 *ret_n = 0x8000;
6660         else
6661                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6662
6663         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6664         intel_reduce_m_n_ratio(ret_m, ret_n);
6665 }
6666
6667 void
6668 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6669                        int pixel_clock, int link_clock,
6670                        struct intel_link_m_n *m_n,
6671                        bool constant_n)
6672 {
6673         m_n->tu = 64;
6674
6675         compute_m_n(bits_per_pixel * pixel_clock,
6676                     link_clock * nlanes * 8,
6677                     &m_n->gmch_m, &m_n->gmch_n,
6678                     constant_n);
6679
6680         compute_m_n(pixel_clock, link_clock,
6681                     &m_n->link_m, &m_n->link_n,
6682                     constant_n);
6683 }
6684
6685 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6686 {
6687         if (i915_modparams.panel_use_ssc >= 0)
6688                 return i915_modparams.panel_use_ssc != 0;
6689         return dev_priv->vbt.lvds_use_ssc
6690                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6691 }
6692
6693 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6694 {
6695         return (1 << dpll->n) << 16 | dpll->m2;
6696 }
6697
6698 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6699 {
6700         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6701 }
6702
6703 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6704                                      struct intel_crtc_state *crtc_state,
6705                                      struct dpll *reduced_clock)
6706 {
6707         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6708         u32 fp, fp2 = 0;
6709
6710         if (IS_PINEVIEW(dev_priv)) {
6711                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6712                 if (reduced_clock)
6713                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6714         } else {
6715                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6716                 if (reduced_clock)
6717                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6718         }
6719
6720         crtc_state->dpll_hw_state.fp0 = fp;
6721
6722         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6723             reduced_clock) {
6724                 crtc_state->dpll_hw_state.fp1 = fp2;
6725         } else {
6726                 crtc_state->dpll_hw_state.fp1 = fp;
6727         }
6728 }
6729
6730 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6731                 pipe)
6732 {
6733         u32 reg_val;
6734
6735         /*
6736          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6737          * and set it to a reasonable value instead.
6738          */
6739         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6740         reg_val &= 0xffffff00;
6741         reg_val |= 0x00000030;
6742         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6743
6744         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6745         reg_val &= 0x00ffffff;
6746         reg_val |= 0x8c000000;
6747         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6748
6749         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6750         reg_val &= 0xffffff00;
6751         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6752
6753         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6754         reg_val &= 0x00ffffff;
6755         reg_val |= 0xb0000000;
6756         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6757 }
6758
6759 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6760                                          struct intel_link_m_n *m_n)
6761 {
6762         struct drm_device *dev = crtc->base.dev;
6763         struct drm_i915_private *dev_priv = to_i915(dev);
6764         int pipe = crtc->pipe;
6765
6766         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6767         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6768         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6769         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6770 }
6771
6772 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6773                                          struct intel_link_m_n *m_n,
6774                                          struct intel_link_m_n *m2_n2)
6775 {
6776         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6777         int pipe = crtc->pipe;
6778         enum transcoder transcoder = crtc->config->cpu_transcoder;
6779
6780         if (INTEL_GEN(dev_priv) >= 5) {
6781                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6782                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6783                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6784                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6785                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6786                  * for gen < 8) and if DRRS is supported (to make sure the
6787                  * registers are not unnecessarily accessed).
6788                  */
6789                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6790                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6791                         I915_WRITE(PIPE_DATA_M2(transcoder),
6792                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6793                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6794                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6795                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6796                 }
6797         } else {
6798                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6799                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6800                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6801                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6802         }
6803 }
6804
6805 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6806 {
6807         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6808
6809         if (m_n == M1_N1) {
6810                 dp_m_n = &crtc->config->dp_m_n;
6811                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6812         } else if (m_n == M2_N2) {
6813
6814                 /*
6815                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6816                  * needs to be programmed into M1_N1.
6817                  */
6818                 dp_m_n = &crtc->config->dp_m2_n2;
6819         } else {
6820                 DRM_ERROR("Unsupported divider value\n");
6821                 return;
6822         }
6823
6824         if (crtc->config->has_pch_encoder)
6825                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6826         else
6827                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6828 }
6829
6830 static void vlv_compute_dpll(struct intel_crtc *crtc,
6831                              struct intel_crtc_state *pipe_config)
6832 {
6833         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6834                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6835         if (crtc->pipe != PIPE_A)
6836                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6837
6838         /* DPLL not used with DSI, but still need the rest set up */
6839         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6840                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6841                         DPLL_EXT_BUFFER_ENABLE_VLV;
6842
6843         pipe_config->dpll_hw_state.dpll_md =
6844                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6845 }
6846
6847 static void chv_compute_dpll(struct intel_crtc *crtc,
6848                              struct intel_crtc_state *pipe_config)
6849 {
6850         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
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
6859         pipe_config->dpll_hw_state.dpll_md =
6860                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6861 }
6862
6863 static void vlv_prepare_pll(struct intel_crtc *crtc,
6864                             const struct intel_crtc_state *pipe_config)
6865 {
6866         struct drm_device *dev = crtc->base.dev;
6867         struct drm_i915_private *dev_priv = to_i915(dev);
6868         enum pipe pipe = crtc->pipe;
6869         u32 mdiv;
6870         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6871         u32 coreclk, reg_val;
6872
6873         /* Enable Refclk */
6874         I915_WRITE(DPLL(pipe),
6875                    pipe_config->dpll_hw_state.dpll &
6876                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6877
6878         /* No need to actually set up the DPLL with DSI */
6879         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6880                 return;
6881
6882         mutex_lock(&dev_priv->sb_lock);
6883
6884         bestn = pipe_config->dpll.n;
6885         bestm1 = pipe_config->dpll.m1;
6886         bestm2 = pipe_config->dpll.m2;
6887         bestp1 = pipe_config->dpll.p1;
6888         bestp2 = pipe_config->dpll.p2;
6889
6890         /* See eDP HDMI DPIO driver vbios notes doc */
6891
6892         /* PLL B needs special handling */
6893         if (pipe == PIPE_B)
6894                 vlv_pllb_recal_opamp(dev_priv, pipe);
6895
6896         /* Set up Tx target for periodic Rcomp update */
6897         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6898
6899         /* Disable target IRef on PLL */
6900         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6901         reg_val &= 0x00ffffff;
6902         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6903
6904         /* Disable fast lock */
6905         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6906
6907         /* Set idtafcrecal before PLL is enabled */
6908         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6909         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6910         mdiv |= ((bestn << DPIO_N_SHIFT));
6911         mdiv |= (1 << DPIO_K_SHIFT);
6912
6913         /*
6914          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6915          * but we don't support that).
6916          * Note: don't use the DAC post divider as it seems unstable.
6917          */
6918         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6919         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6920
6921         mdiv |= DPIO_ENABLE_CALIBRATION;
6922         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6923
6924         /* Set HBR and RBR LPF coefficients */
6925         if (pipe_config->port_clock == 162000 ||
6926             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6927             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6928                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6929                                  0x009f0003);
6930         else
6931                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6932                                  0x00d0000f);
6933
6934         if (intel_crtc_has_dp_encoder(pipe_config)) {
6935                 /* Use SSC source */
6936                 if (pipe == PIPE_A)
6937                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6938                                          0x0df40000);
6939                 else
6940                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6941                                          0x0df70000);
6942         } else { /* HDMI or VGA */
6943                 /* Use bend source */
6944                 if (pipe == PIPE_A)
6945                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6946                                          0x0df70000);
6947                 else
6948                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6949                                          0x0df40000);
6950         }
6951
6952         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6953         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6954         if (intel_crtc_has_dp_encoder(crtc->config))
6955                 coreclk |= 0x01000000;
6956         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6957
6958         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6959         mutex_unlock(&dev_priv->sb_lock);
6960 }
6961
6962 static void chv_prepare_pll(struct intel_crtc *crtc,
6963                             const struct intel_crtc_state *pipe_config)
6964 {
6965         struct drm_device *dev = crtc->base.dev;
6966         struct drm_i915_private *dev_priv = to_i915(dev);
6967         enum pipe pipe = crtc->pipe;
6968         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6969         u32 loopfilter, tribuf_calcntr;
6970         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6971         u32 dpio_val;
6972         int vco;
6973
6974         /* Enable Refclk and SSC */
6975         I915_WRITE(DPLL(pipe),
6976                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6977
6978         /* No need to actually set up the DPLL with DSI */
6979         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6980                 return;
6981
6982         bestn = pipe_config->dpll.n;
6983         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6984         bestm1 = pipe_config->dpll.m1;
6985         bestm2 = pipe_config->dpll.m2 >> 22;
6986         bestp1 = pipe_config->dpll.p1;
6987         bestp2 = pipe_config->dpll.p2;
6988         vco = pipe_config->dpll.vco;
6989         dpio_val = 0;
6990         loopfilter = 0;
6991
6992         mutex_lock(&dev_priv->sb_lock);
6993
6994         /* p1 and p2 divider */
6995         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6996                         5 << DPIO_CHV_S1_DIV_SHIFT |
6997                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6998                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6999                         1 << DPIO_CHV_K_DIV_SHIFT);
7000
7001         /* Feedback post-divider - m2 */
7002         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7003
7004         /* Feedback refclk divider - n and m1 */
7005         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7006                         DPIO_CHV_M1_DIV_BY_2 |
7007                         1 << DPIO_CHV_N_DIV_SHIFT);
7008
7009         /* M2 fraction division */
7010         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7011
7012         /* M2 fraction division enable */
7013         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7014         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7015         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7016         if (bestm2_frac)
7017                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7018         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7019
7020         /* Program digital lock detect threshold */
7021         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7022         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7023                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7024         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7025         if (!bestm2_frac)
7026                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7027         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7028
7029         /* Loop filter */
7030         if (vco == 5400000) {
7031                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7032                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7033                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7034                 tribuf_calcntr = 0x9;
7035         } else if (vco <= 6200000) {
7036                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7037                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7038                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7039                 tribuf_calcntr = 0x9;
7040         } else if (vco <= 6480000) {
7041                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7042                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7043                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7044                 tribuf_calcntr = 0x8;
7045         } else {
7046                 /* Not supported. Apply the same limits as in the max case */
7047                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7048                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7049                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7050                 tribuf_calcntr = 0;
7051         }
7052         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7053
7054         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7055         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7056         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7057         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7058
7059         /* AFC Recal */
7060         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7061                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7062                         DPIO_AFC_RECAL);
7063
7064         mutex_unlock(&dev_priv->sb_lock);
7065 }
7066
7067 /**
7068  * vlv_force_pll_on - forcibly enable just the PLL
7069  * @dev_priv: i915 private structure
7070  * @pipe: pipe PLL to enable
7071  * @dpll: PLL configuration
7072  *
7073  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7074  * in cases where we need the PLL enabled even when @pipe is not going to
7075  * be enabled.
7076  */
7077 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7078                      const struct dpll *dpll)
7079 {
7080         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7081         struct intel_crtc_state *pipe_config;
7082
7083         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7084         if (!pipe_config)
7085                 return -ENOMEM;
7086
7087         pipe_config->base.crtc = &crtc->base;
7088         pipe_config->pixel_multiplier = 1;
7089         pipe_config->dpll = *dpll;
7090
7091         if (IS_CHERRYVIEW(dev_priv)) {
7092                 chv_compute_dpll(crtc, pipe_config);
7093                 chv_prepare_pll(crtc, pipe_config);
7094                 chv_enable_pll(crtc, pipe_config);
7095         } else {
7096                 vlv_compute_dpll(crtc, pipe_config);
7097                 vlv_prepare_pll(crtc, pipe_config);
7098                 vlv_enable_pll(crtc, pipe_config);
7099         }
7100
7101         kfree(pipe_config);
7102
7103         return 0;
7104 }
7105
7106 /**
7107  * vlv_force_pll_off - forcibly disable just the PLL
7108  * @dev_priv: i915 private structure
7109  * @pipe: pipe PLL to disable
7110  *
7111  * Disable the PLL for @pipe. To be used in cases where we need
7112  * the PLL enabled even when @pipe is not going to be enabled.
7113  */
7114 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7115 {
7116         if (IS_CHERRYVIEW(dev_priv))
7117                 chv_disable_pll(dev_priv, pipe);
7118         else
7119                 vlv_disable_pll(dev_priv, pipe);
7120 }
7121
7122 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7123                               struct intel_crtc_state *crtc_state,
7124                               struct dpll *reduced_clock)
7125 {
7126         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7127         u32 dpll;
7128         struct dpll *clock = &crtc_state->dpll;
7129
7130         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7131
7132         dpll = DPLL_VGA_MODE_DIS;
7133
7134         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7135                 dpll |= DPLLB_MODE_LVDS;
7136         else
7137                 dpll |= DPLLB_MODE_DAC_SERIAL;
7138
7139         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7140             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7141                 dpll |= (crtc_state->pixel_multiplier - 1)
7142                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7143         }
7144
7145         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7146             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7147                 dpll |= DPLL_SDVO_HIGH_SPEED;
7148
7149         if (intel_crtc_has_dp_encoder(crtc_state))
7150                 dpll |= DPLL_SDVO_HIGH_SPEED;
7151
7152         /* compute bitmask from p1 value */
7153         if (IS_PINEVIEW(dev_priv))
7154                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7155         else {
7156                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7157                 if (IS_G4X(dev_priv) && reduced_clock)
7158                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7159         }
7160         switch (clock->p2) {
7161         case 5:
7162                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7163                 break;
7164         case 7:
7165                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7166                 break;
7167         case 10:
7168                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7169                 break;
7170         case 14:
7171                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7172                 break;
7173         }
7174         if (INTEL_GEN(dev_priv) >= 4)
7175                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7176
7177         if (crtc_state->sdvo_tv_clock)
7178                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7179         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7180                  intel_panel_use_ssc(dev_priv))
7181                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7182         else
7183                 dpll |= PLL_REF_INPUT_DREFCLK;
7184
7185         dpll |= DPLL_VCO_ENABLE;
7186         crtc_state->dpll_hw_state.dpll = dpll;
7187
7188         if (INTEL_GEN(dev_priv) >= 4) {
7189                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7190                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7191                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7192         }
7193 }
7194
7195 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7196                               struct intel_crtc_state *crtc_state,
7197                               struct dpll *reduced_clock)
7198 {
7199         struct drm_device *dev = crtc->base.dev;
7200         struct drm_i915_private *dev_priv = to_i915(dev);
7201         u32 dpll;
7202         struct dpll *clock = &crtc_state->dpll;
7203
7204         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7205
7206         dpll = DPLL_VGA_MODE_DIS;
7207
7208         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7209                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7210         } else {
7211                 if (clock->p1 == 2)
7212                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7213                 else
7214                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7215                 if (clock->p2 == 4)
7216                         dpll |= PLL_P2_DIVIDE_BY_4;
7217         }
7218
7219         if (!IS_I830(dev_priv) &&
7220             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7221                 dpll |= DPLL_DVO_2X_MODE;
7222
7223         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7224             intel_panel_use_ssc(dev_priv))
7225                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7226         else
7227                 dpll |= PLL_REF_INPUT_DREFCLK;
7228
7229         dpll |= DPLL_VCO_ENABLE;
7230         crtc_state->dpll_hw_state.dpll = dpll;
7231 }
7232
7233 static void intel_set_pipe_timings(const struct intel_crtc_state *crtc_state)
7234 {
7235         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7236         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7237         enum pipe pipe = crtc->pipe;
7238         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
7239         const struct drm_display_mode *adjusted_mode = &crtc_state->base.adjusted_mode;
7240         uint32_t crtc_vtotal, crtc_vblank_end;
7241         int vsyncshift = 0;
7242
7243         /* We need to be careful not to changed the adjusted mode, for otherwise
7244          * the hw state checker will get angry at the mismatch. */
7245         crtc_vtotal = adjusted_mode->crtc_vtotal;
7246         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7247
7248         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7249                 /* the chip adds 2 halflines automatically */
7250                 crtc_vtotal -= 1;
7251                 crtc_vblank_end -= 1;
7252
7253                 if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7254                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7255                 else
7256                         vsyncshift = adjusted_mode->crtc_hsync_start -
7257                                 adjusted_mode->crtc_htotal / 2;
7258                 if (vsyncshift < 0)
7259                         vsyncshift += adjusted_mode->crtc_htotal;
7260         }
7261
7262         if (INTEL_GEN(dev_priv) > 3)
7263                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7264
7265         I915_WRITE(HTOTAL(cpu_transcoder),
7266                    (adjusted_mode->crtc_hdisplay - 1) |
7267                    ((adjusted_mode->crtc_htotal - 1) << 16));
7268         I915_WRITE(HBLANK(cpu_transcoder),
7269                    (adjusted_mode->crtc_hblank_start - 1) |
7270                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7271         I915_WRITE(HSYNC(cpu_transcoder),
7272                    (adjusted_mode->crtc_hsync_start - 1) |
7273                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7274
7275         I915_WRITE(VTOTAL(cpu_transcoder),
7276                    (adjusted_mode->crtc_vdisplay - 1) |
7277                    ((crtc_vtotal - 1) << 16));
7278         I915_WRITE(VBLANK(cpu_transcoder),
7279                    (adjusted_mode->crtc_vblank_start - 1) |
7280                    ((crtc_vblank_end - 1) << 16));
7281         I915_WRITE(VSYNC(cpu_transcoder),
7282                    (adjusted_mode->crtc_vsync_start - 1) |
7283                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7284
7285         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7286          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7287          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7288          * bits. */
7289         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7290             (pipe == PIPE_B || pipe == PIPE_C))
7291                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7292
7293 }
7294
7295 static void intel_set_pipe_src_size(const struct intel_crtc_state *crtc_state)
7296 {
7297         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7298         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7299         enum pipe pipe = crtc->pipe;
7300
7301         /* pipesrc controls the size that is scaled from, which should
7302          * always be the user's requested size.
7303          */
7304         I915_WRITE(PIPESRC(pipe),
7305                    ((crtc_state->pipe_src_w - 1) << 16) |
7306                    (crtc_state->pipe_src_h - 1));
7307 }
7308
7309 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7310                                    struct intel_crtc_state *pipe_config)
7311 {
7312         struct drm_device *dev = crtc->base.dev;
7313         struct drm_i915_private *dev_priv = to_i915(dev);
7314         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7315         uint32_t tmp;
7316
7317         tmp = I915_READ(HTOTAL(cpu_transcoder));
7318         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7319         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7320         tmp = I915_READ(HBLANK(cpu_transcoder));
7321         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7322         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7323         tmp = I915_READ(HSYNC(cpu_transcoder));
7324         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7325         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7326
7327         tmp = I915_READ(VTOTAL(cpu_transcoder));
7328         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7329         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7330         tmp = I915_READ(VBLANK(cpu_transcoder));
7331         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7332         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7333         tmp = I915_READ(VSYNC(cpu_transcoder));
7334         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7335         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7336
7337         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7338                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7339                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7340                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7341         }
7342 }
7343
7344 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7345                                     struct intel_crtc_state *pipe_config)
7346 {
7347         struct drm_device *dev = crtc->base.dev;
7348         struct drm_i915_private *dev_priv = to_i915(dev);
7349         u32 tmp;
7350
7351         tmp = I915_READ(PIPESRC(crtc->pipe));
7352         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7353         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7354
7355         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7356         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7357 }
7358
7359 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7360                                  struct intel_crtc_state *pipe_config)
7361 {
7362         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7363         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7364         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7365         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7366
7367         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7368         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7369         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7370         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7371
7372         mode->flags = pipe_config->base.adjusted_mode.flags;
7373         mode->type = DRM_MODE_TYPE_DRIVER;
7374
7375         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7376
7377         mode->hsync = drm_mode_hsync(mode);
7378         mode->vrefresh = drm_mode_vrefresh(mode);
7379         drm_mode_set_name(mode);
7380 }
7381
7382 static void i9xx_set_pipeconf(const struct intel_crtc_state *crtc_state)
7383 {
7384         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
7385         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7386         uint32_t pipeconf;
7387
7388         pipeconf = 0;
7389
7390         /* we keep both pipes enabled on 830 */
7391         if (IS_I830(dev_priv))
7392                 pipeconf |= I915_READ(PIPECONF(crtc->pipe)) & PIPECONF_ENABLE;
7393
7394         if (crtc_state->double_wide)
7395                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7396
7397         /* only g4x and later have fancy bpc/dither controls */
7398         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7399             IS_CHERRYVIEW(dev_priv)) {
7400                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7401                 if (crtc_state->dither && crtc_state->pipe_bpp != 30)
7402                         pipeconf |= PIPECONF_DITHER_EN |
7403                                     PIPECONF_DITHER_TYPE_SP;
7404
7405                 switch (crtc_state->pipe_bpp) {
7406                 case 18:
7407                         pipeconf |= PIPECONF_6BPC;
7408                         break;
7409                 case 24:
7410                         pipeconf |= PIPECONF_8BPC;
7411                         break;
7412                 case 30:
7413                         pipeconf |= PIPECONF_10BPC;
7414                         break;
7415                 default:
7416                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7417                         BUG();
7418                 }
7419         }
7420
7421         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7422                 if (INTEL_GEN(dev_priv) < 4 ||
7423                     intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO))
7424                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7425                 else
7426                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7427         } else
7428                 pipeconf |= PIPECONF_PROGRESSIVE;
7429
7430         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7431              crtc_state->limited_color_range)
7432                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7433
7434         I915_WRITE(PIPECONF(crtc->pipe), pipeconf);
7435         POSTING_READ(PIPECONF(crtc->pipe));
7436 }
7437
7438 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7439                                    struct intel_crtc_state *crtc_state)
7440 {
7441         struct drm_device *dev = crtc->base.dev;
7442         struct drm_i915_private *dev_priv = to_i915(dev);
7443         const struct intel_limit *limit;
7444         int refclk = 48000;
7445
7446         memset(&crtc_state->dpll_hw_state, 0,
7447                sizeof(crtc_state->dpll_hw_state));
7448
7449         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7450                 if (intel_panel_use_ssc(dev_priv)) {
7451                         refclk = dev_priv->vbt.lvds_ssc_freq;
7452                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7453                 }
7454
7455                 limit = &intel_limits_i8xx_lvds;
7456         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7457                 limit = &intel_limits_i8xx_dvo;
7458         } else {
7459                 limit = &intel_limits_i8xx_dac;
7460         }
7461
7462         if (!crtc_state->clock_set &&
7463             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7464                                  refclk, NULL, &crtc_state->dpll)) {
7465                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7466                 return -EINVAL;
7467         }
7468
7469         i8xx_compute_dpll(crtc, crtc_state, NULL);
7470
7471         return 0;
7472 }
7473
7474 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7475                                   struct intel_crtc_state *crtc_state)
7476 {
7477         struct drm_device *dev = crtc->base.dev;
7478         struct drm_i915_private *dev_priv = to_i915(dev);
7479         const struct intel_limit *limit;
7480         int refclk = 96000;
7481
7482         memset(&crtc_state->dpll_hw_state, 0,
7483                sizeof(crtc_state->dpll_hw_state));
7484
7485         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7486                 if (intel_panel_use_ssc(dev_priv)) {
7487                         refclk = dev_priv->vbt.lvds_ssc_freq;
7488                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7489                 }
7490
7491                 if (intel_is_dual_link_lvds(dev))
7492                         limit = &intel_limits_g4x_dual_channel_lvds;
7493                 else
7494                         limit = &intel_limits_g4x_single_channel_lvds;
7495         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7496                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7497                 limit = &intel_limits_g4x_hdmi;
7498         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7499                 limit = &intel_limits_g4x_sdvo;
7500         } else {
7501                 /* The option is for other outputs */
7502                 limit = &intel_limits_i9xx_sdvo;
7503         }
7504
7505         if (!crtc_state->clock_set &&
7506             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7507                                 refclk, NULL, &crtc_state->dpll)) {
7508                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7509                 return -EINVAL;
7510         }
7511
7512         i9xx_compute_dpll(crtc, crtc_state, NULL);
7513
7514         return 0;
7515 }
7516
7517 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7518                                   struct intel_crtc_state *crtc_state)
7519 {
7520         struct drm_device *dev = crtc->base.dev;
7521         struct drm_i915_private *dev_priv = to_i915(dev);
7522         const struct intel_limit *limit;
7523         int refclk = 96000;
7524
7525         memset(&crtc_state->dpll_hw_state, 0,
7526                sizeof(crtc_state->dpll_hw_state));
7527
7528         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7529                 if (intel_panel_use_ssc(dev_priv)) {
7530                         refclk = dev_priv->vbt.lvds_ssc_freq;
7531                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7532                 }
7533
7534                 limit = &intel_limits_pineview_lvds;
7535         } else {
7536                 limit = &intel_limits_pineview_sdvo;
7537         }
7538
7539         if (!crtc_state->clock_set &&
7540             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7541                                 refclk, NULL, &crtc_state->dpll)) {
7542                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7543                 return -EINVAL;
7544         }
7545
7546         i9xx_compute_dpll(crtc, crtc_state, NULL);
7547
7548         return 0;
7549 }
7550
7551 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7552                                    struct intel_crtc_state *crtc_state)
7553 {
7554         struct drm_device *dev = crtc->base.dev;
7555         struct drm_i915_private *dev_priv = to_i915(dev);
7556         const struct intel_limit *limit;
7557         int refclk = 96000;
7558
7559         memset(&crtc_state->dpll_hw_state, 0,
7560                sizeof(crtc_state->dpll_hw_state));
7561
7562         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7563                 if (intel_panel_use_ssc(dev_priv)) {
7564                         refclk = dev_priv->vbt.lvds_ssc_freq;
7565                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7566                 }
7567
7568                 limit = &intel_limits_i9xx_lvds;
7569         } else {
7570                 limit = &intel_limits_i9xx_sdvo;
7571         }
7572
7573         if (!crtc_state->clock_set &&
7574             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7575                                  refclk, NULL, &crtc_state->dpll)) {
7576                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7577                 return -EINVAL;
7578         }
7579
7580         i9xx_compute_dpll(crtc, crtc_state, NULL);
7581
7582         return 0;
7583 }
7584
7585 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7586                                   struct intel_crtc_state *crtc_state)
7587 {
7588         int refclk = 100000;
7589         const struct intel_limit *limit = &intel_limits_chv;
7590
7591         memset(&crtc_state->dpll_hw_state, 0,
7592                sizeof(crtc_state->dpll_hw_state));
7593
7594         if (!crtc_state->clock_set &&
7595             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7596                                 refclk, NULL, &crtc_state->dpll)) {
7597                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7598                 return -EINVAL;
7599         }
7600
7601         chv_compute_dpll(crtc, crtc_state);
7602
7603         return 0;
7604 }
7605
7606 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7607                                   struct intel_crtc_state *crtc_state)
7608 {
7609         int refclk = 100000;
7610         const struct intel_limit *limit = &intel_limits_vlv;
7611
7612         memset(&crtc_state->dpll_hw_state, 0,
7613                sizeof(crtc_state->dpll_hw_state));
7614
7615         if (!crtc_state->clock_set &&
7616             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7617                                 refclk, NULL, &crtc_state->dpll)) {
7618                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7619                 return -EINVAL;
7620         }
7621
7622         vlv_compute_dpll(crtc, crtc_state);
7623
7624         return 0;
7625 }
7626
7627 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7628                                  struct intel_crtc_state *pipe_config)
7629 {
7630         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7631         uint32_t tmp;
7632
7633         if (INTEL_GEN(dev_priv) <= 3 &&
7634             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7635                 return;
7636
7637         tmp = I915_READ(PFIT_CONTROL);
7638         if (!(tmp & PFIT_ENABLE))
7639                 return;
7640
7641         /* Check whether the pfit is attached to our pipe. */
7642         if (INTEL_GEN(dev_priv) < 4) {
7643                 if (crtc->pipe != PIPE_B)
7644                         return;
7645         } else {
7646                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7647                         return;
7648         }
7649
7650         pipe_config->gmch_pfit.control = tmp;
7651         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7652 }
7653
7654 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7655                                struct intel_crtc_state *pipe_config)
7656 {
7657         struct drm_device *dev = crtc->base.dev;
7658         struct drm_i915_private *dev_priv = to_i915(dev);
7659         int pipe = pipe_config->cpu_transcoder;
7660         struct dpll clock;
7661         u32 mdiv;
7662         int refclk = 100000;
7663
7664         /* In case of DSI, DPLL will not be used */
7665         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7666                 return;
7667
7668         mutex_lock(&dev_priv->sb_lock);
7669         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7670         mutex_unlock(&dev_priv->sb_lock);
7671
7672         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7673         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7674         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7675         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7676         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7677
7678         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7679 }
7680
7681 static void
7682 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7683                               struct intel_initial_plane_config *plane_config)
7684 {
7685         struct drm_device *dev = crtc->base.dev;
7686         struct drm_i915_private *dev_priv = to_i915(dev);
7687         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7688         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7689         enum pipe pipe;
7690         u32 val, base, offset;
7691         int fourcc, pixel_format;
7692         unsigned int aligned_height;
7693         struct drm_framebuffer *fb;
7694         struct intel_framebuffer *intel_fb;
7695
7696         if (!plane->get_hw_state(plane, &pipe))
7697                 return;
7698
7699         WARN_ON(pipe != crtc->pipe);
7700
7701         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7702         if (!intel_fb) {
7703                 DRM_DEBUG_KMS("failed to alloc fb\n");
7704                 return;
7705         }
7706
7707         fb = &intel_fb->base;
7708
7709         fb->dev = dev;
7710
7711         val = I915_READ(DSPCNTR(i9xx_plane));
7712
7713         if (INTEL_GEN(dev_priv) >= 4) {
7714                 if (val & DISPPLANE_TILED) {
7715                         plane_config->tiling = I915_TILING_X;
7716                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7717                 }
7718         }
7719
7720         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7721         fourcc = i9xx_format_to_fourcc(pixel_format);
7722         fb->format = drm_format_info(fourcc);
7723
7724         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7725                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7726                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7727         } else if (INTEL_GEN(dev_priv) >= 4) {
7728                 if (plane_config->tiling)
7729                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7730                 else
7731                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7732                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7733         } else {
7734                 base = I915_READ(DSPADDR(i9xx_plane));
7735         }
7736         plane_config->base = base;
7737
7738         val = I915_READ(PIPESRC(pipe));
7739         fb->width = ((val >> 16) & 0xfff) + 1;
7740         fb->height = ((val >> 0) & 0xfff) + 1;
7741
7742         val = I915_READ(DSPSTRIDE(i9xx_plane));
7743         fb->pitches[0] = val & 0xffffffc0;
7744
7745         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7746
7747         plane_config->size = fb->pitches[0] * aligned_height;
7748
7749         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7750                       crtc->base.name, plane->base.name, fb->width, fb->height,
7751                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7752                       plane_config->size);
7753
7754         plane_config->fb = intel_fb;
7755 }
7756
7757 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7758                                struct intel_crtc_state *pipe_config)
7759 {
7760         struct drm_device *dev = crtc->base.dev;
7761         struct drm_i915_private *dev_priv = to_i915(dev);
7762         int pipe = pipe_config->cpu_transcoder;
7763         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7764         struct dpll clock;
7765         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7766         int refclk = 100000;
7767
7768         /* In case of DSI, DPLL will not be used */
7769         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7770                 return;
7771
7772         mutex_lock(&dev_priv->sb_lock);
7773         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7774         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7775         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7776         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7777         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7778         mutex_unlock(&dev_priv->sb_lock);
7779
7780         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7781         clock.m2 = (pll_dw0 & 0xff) << 22;
7782         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7783                 clock.m2 |= pll_dw2 & 0x3fffff;
7784         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7785         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7786         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7787
7788         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7789 }
7790
7791 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7792                                  struct intel_crtc_state *pipe_config)
7793 {
7794         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7795         enum intel_display_power_domain power_domain;
7796         uint32_t tmp;
7797         bool ret;
7798
7799         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7800         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7801                 return false;
7802
7803         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7804         pipe_config->shared_dpll = NULL;
7805
7806         ret = false;
7807
7808         tmp = I915_READ(PIPECONF(crtc->pipe));
7809         if (!(tmp & PIPECONF_ENABLE))
7810                 goto out;
7811
7812         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7813             IS_CHERRYVIEW(dev_priv)) {
7814                 switch (tmp & PIPECONF_BPC_MASK) {
7815                 case PIPECONF_6BPC:
7816                         pipe_config->pipe_bpp = 18;
7817                         break;
7818                 case PIPECONF_8BPC:
7819                         pipe_config->pipe_bpp = 24;
7820                         break;
7821                 case PIPECONF_10BPC:
7822                         pipe_config->pipe_bpp = 30;
7823                         break;
7824                 default:
7825                         break;
7826                 }
7827         }
7828
7829         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7830             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7831                 pipe_config->limited_color_range = true;
7832
7833         if (INTEL_GEN(dev_priv) < 4)
7834                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7835
7836         intel_get_pipe_timings(crtc, pipe_config);
7837         intel_get_pipe_src_size(crtc, pipe_config);
7838
7839         i9xx_get_pfit_config(crtc, pipe_config);
7840
7841         if (INTEL_GEN(dev_priv) >= 4) {
7842                 /* No way to read it out on pipes B and C */
7843                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7844                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7845                 else
7846                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7847                 pipe_config->pixel_multiplier =
7848                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7849                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7850                 pipe_config->dpll_hw_state.dpll_md = tmp;
7851         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7852                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7853                 tmp = I915_READ(DPLL(crtc->pipe));
7854                 pipe_config->pixel_multiplier =
7855                         ((tmp & SDVO_MULTIPLIER_MASK)
7856                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7857         } else {
7858                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7859                  * port and will be fixed up in the encoder->get_config
7860                  * function. */
7861                 pipe_config->pixel_multiplier = 1;
7862         }
7863         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7864         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7865                 /*
7866                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7867                  * on 830. Filter it out here so that we don't
7868                  * report errors due to that.
7869                  */
7870                 if (IS_I830(dev_priv))
7871                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7872
7873                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7874                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7875         } else {
7876                 /* Mask out read-only status bits. */
7877                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7878                                                      DPLL_PORTC_READY_MASK |
7879                                                      DPLL_PORTB_READY_MASK);
7880         }
7881
7882         if (IS_CHERRYVIEW(dev_priv))
7883                 chv_crtc_clock_get(crtc, pipe_config);
7884         else if (IS_VALLEYVIEW(dev_priv))
7885                 vlv_crtc_clock_get(crtc, pipe_config);
7886         else
7887                 i9xx_crtc_clock_get(crtc, pipe_config);
7888
7889         /*
7890          * Normally the dotclock is filled in by the encoder .get_config()
7891          * but in case the pipe is enabled w/o any ports we need a sane
7892          * default.
7893          */
7894         pipe_config->base.adjusted_mode.crtc_clock =
7895                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7896
7897         ret = true;
7898
7899 out:
7900         intel_display_power_put(dev_priv, power_domain);
7901
7902         return ret;
7903 }
7904
7905 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7906 {
7907         struct intel_encoder *encoder;
7908         int i;
7909         u32 val, final;
7910         bool has_lvds = false;
7911         bool has_cpu_edp = false;
7912         bool has_panel = false;
7913         bool has_ck505 = false;
7914         bool can_ssc = false;
7915         bool using_ssc_source = false;
7916
7917         /* We need to take the global config into account */
7918         for_each_intel_encoder(&dev_priv->drm, encoder) {
7919                 switch (encoder->type) {
7920                 case INTEL_OUTPUT_LVDS:
7921                         has_panel = true;
7922                         has_lvds = true;
7923                         break;
7924                 case INTEL_OUTPUT_EDP:
7925                         has_panel = true;
7926                         if (encoder->port == PORT_A)
7927                                 has_cpu_edp = true;
7928                         break;
7929                 default:
7930                         break;
7931                 }
7932         }
7933
7934         if (HAS_PCH_IBX(dev_priv)) {
7935                 has_ck505 = dev_priv->vbt.display_clock_mode;
7936                 can_ssc = has_ck505;
7937         } else {
7938                 has_ck505 = false;
7939                 can_ssc = true;
7940         }
7941
7942         /* Check if any DPLLs are using the SSC source */
7943         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7944                 u32 temp = I915_READ(PCH_DPLL(i));
7945
7946                 if (!(temp & DPLL_VCO_ENABLE))
7947                         continue;
7948
7949                 if ((temp & PLL_REF_INPUT_MASK) ==
7950                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7951                         using_ssc_source = true;
7952                         break;
7953                 }
7954         }
7955
7956         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7957                       has_panel, has_lvds, has_ck505, using_ssc_source);
7958
7959         /* Ironlake: try to setup display ref clock before DPLL
7960          * enabling. This is only under driver's control after
7961          * PCH B stepping, previous chipset stepping should be
7962          * ignoring this setting.
7963          */
7964         val = I915_READ(PCH_DREF_CONTROL);
7965
7966         /* As we must carefully and slowly disable/enable each source in turn,
7967          * compute the final state we want first and check if we need to
7968          * make any changes at all.
7969          */
7970         final = val;
7971         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7972         if (has_ck505)
7973                 final |= DREF_NONSPREAD_CK505_ENABLE;
7974         else
7975                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7976
7977         final &= ~DREF_SSC_SOURCE_MASK;
7978         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7979         final &= ~DREF_SSC1_ENABLE;
7980
7981         if (has_panel) {
7982                 final |= DREF_SSC_SOURCE_ENABLE;
7983
7984                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7985                         final |= DREF_SSC1_ENABLE;
7986
7987                 if (has_cpu_edp) {
7988                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7989                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7990                         else
7991                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7992                 } else
7993                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7994         } else if (using_ssc_source) {
7995                 final |= DREF_SSC_SOURCE_ENABLE;
7996                 final |= DREF_SSC1_ENABLE;
7997         }
7998
7999         if (final == val)
8000                 return;
8001
8002         /* Always enable nonspread source */
8003         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8004
8005         if (has_ck505)
8006                 val |= DREF_NONSPREAD_CK505_ENABLE;
8007         else
8008                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8009
8010         if (has_panel) {
8011                 val &= ~DREF_SSC_SOURCE_MASK;
8012                 val |= DREF_SSC_SOURCE_ENABLE;
8013
8014                 /* SSC must be turned on before enabling the CPU output  */
8015                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8016                         DRM_DEBUG_KMS("Using SSC on panel\n");
8017                         val |= DREF_SSC1_ENABLE;
8018                 } else
8019                         val &= ~DREF_SSC1_ENABLE;
8020
8021                 /* Get SSC going before enabling the outputs */
8022                 I915_WRITE(PCH_DREF_CONTROL, val);
8023                 POSTING_READ(PCH_DREF_CONTROL);
8024                 udelay(200);
8025
8026                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8027
8028                 /* Enable CPU source on CPU attached eDP */
8029                 if (has_cpu_edp) {
8030                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8031                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8032                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8033                         } else
8034                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8035                 } else
8036                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8037
8038                 I915_WRITE(PCH_DREF_CONTROL, val);
8039                 POSTING_READ(PCH_DREF_CONTROL);
8040                 udelay(200);
8041         } else {
8042                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8043
8044                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8045
8046                 /* Turn off CPU output */
8047                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8048
8049                 I915_WRITE(PCH_DREF_CONTROL, val);
8050                 POSTING_READ(PCH_DREF_CONTROL);
8051                 udelay(200);
8052
8053                 if (!using_ssc_source) {
8054                         DRM_DEBUG_KMS("Disabling SSC source\n");
8055
8056                         /* Turn off the SSC source */
8057                         val &= ~DREF_SSC_SOURCE_MASK;
8058                         val |= DREF_SSC_SOURCE_DISABLE;
8059
8060                         /* Turn off SSC1 */
8061                         val &= ~DREF_SSC1_ENABLE;
8062
8063                         I915_WRITE(PCH_DREF_CONTROL, val);
8064                         POSTING_READ(PCH_DREF_CONTROL);
8065                         udelay(200);
8066                 }
8067         }
8068
8069         BUG_ON(val != final);
8070 }
8071
8072 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8073 {
8074         uint32_t tmp;
8075
8076         tmp = I915_READ(SOUTH_CHICKEN2);
8077         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8078         I915_WRITE(SOUTH_CHICKEN2, tmp);
8079
8080         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8081                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8082                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8083
8084         tmp = I915_READ(SOUTH_CHICKEN2);
8085         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8086         I915_WRITE(SOUTH_CHICKEN2, tmp);
8087
8088         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8089                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8090                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8091 }
8092
8093 /* WaMPhyProgramming:hsw */
8094 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8095 {
8096         uint32_t tmp;
8097
8098         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8099         tmp &= ~(0xFF << 24);
8100         tmp |= (0x12 << 24);
8101         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8102
8103         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8104         tmp |= (1 << 11);
8105         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8106
8107         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8108         tmp |= (1 << 11);
8109         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8110
8111         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8112         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8113         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8114
8115         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8116         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8117         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8118
8119         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8120         tmp &= ~(7 << 13);
8121         tmp |= (5 << 13);
8122         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8123
8124         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8125         tmp &= ~(7 << 13);
8126         tmp |= (5 << 13);
8127         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8128
8129         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8130         tmp &= ~0xFF;
8131         tmp |= 0x1C;
8132         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8133
8134         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8135         tmp &= ~0xFF;
8136         tmp |= 0x1C;
8137         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8138
8139         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8140         tmp &= ~(0xFF << 16);
8141         tmp |= (0x1C << 16);
8142         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8143
8144         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8145         tmp &= ~(0xFF << 16);
8146         tmp |= (0x1C << 16);
8147         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8148
8149         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8150         tmp |= (1 << 27);
8151         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8152
8153         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8154         tmp |= (1 << 27);
8155         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8156
8157         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8158         tmp &= ~(0xF << 28);
8159         tmp |= (4 << 28);
8160         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8161
8162         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8163         tmp &= ~(0xF << 28);
8164         tmp |= (4 << 28);
8165         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8166 }
8167
8168 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8169  * Programming" based on the parameters passed:
8170  * - Sequence to enable CLKOUT_DP
8171  * - Sequence to enable CLKOUT_DP without spread
8172  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8173  */
8174 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8175                                  bool with_spread, bool with_fdi)
8176 {
8177         uint32_t reg, tmp;
8178
8179         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8180                 with_spread = true;
8181         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8182             with_fdi, "LP PCH doesn't have FDI\n"))
8183                 with_fdi = false;
8184
8185         mutex_lock(&dev_priv->sb_lock);
8186
8187         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8188         tmp &= ~SBI_SSCCTL_DISABLE;
8189         tmp |= SBI_SSCCTL_PATHALT;
8190         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8191
8192         udelay(24);
8193
8194         if (with_spread) {
8195                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8196                 tmp &= ~SBI_SSCCTL_PATHALT;
8197                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8198
8199                 if (with_fdi) {
8200                         lpt_reset_fdi_mphy(dev_priv);
8201                         lpt_program_fdi_mphy(dev_priv);
8202                 }
8203         }
8204
8205         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8206         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8207         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8208         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8209
8210         mutex_unlock(&dev_priv->sb_lock);
8211 }
8212
8213 /* Sequence to disable CLKOUT_DP */
8214 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8215 {
8216         uint32_t reg, tmp;
8217
8218         mutex_lock(&dev_priv->sb_lock);
8219
8220         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8221         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8222         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8223         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8224
8225         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8226         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8227                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8228                         tmp |= SBI_SSCCTL_PATHALT;
8229                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8230                         udelay(32);
8231                 }
8232                 tmp |= SBI_SSCCTL_DISABLE;
8233                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8234         }
8235
8236         mutex_unlock(&dev_priv->sb_lock);
8237 }
8238
8239 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8240
8241 static const uint16_t sscdivintphase[] = {
8242         [BEND_IDX( 50)] = 0x3B23,
8243         [BEND_IDX( 45)] = 0x3B23,
8244         [BEND_IDX( 40)] = 0x3C23,
8245         [BEND_IDX( 35)] = 0x3C23,
8246         [BEND_IDX( 30)] = 0x3D23,
8247         [BEND_IDX( 25)] = 0x3D23,
8248         [BEND_IDX( 20)] = 0x3E23,
8249         [BEND_IDX( 15)] = 0x3E23,
8250         [BEND_IDX( 10)] = 0x3F23,
8251         [BEND_IDX(  5)] = 0x3F23,
8252         [BEND_IDX(  0)] = 0x0025,
8253         [BEND_IDX( -5)] = 0x0025,
8254         [BEND_IDX(-10)] = 0x0125,
8255         [BEND_IDX(-15)] = 0x0125,
8256         [BEND_IDX(-20)] = 0x0225,
8257         [BEND_IDX(-25)] = 0x0225,
8258         [BEND_IDX(-30)] = 0x0325,
8259         [BEND_IDX(-35)] = 0x0325,
8260         [BEND_IDX(-40)] = 0x0425,
8261         [BEND_IDX(-45)] = 0x0425,
8262         [BEND_IDX(-50)] = 0x0525,
8263 };
8264
8265 /*
8266  * Bend CLKOUT_DP
8267  * steps -50 to 50 inclusive, in steps of 5
8268  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8269  * change in clock period = -(steps / 10) * 5.787 ps
8270  */
8271 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8272 {
8273         uint32_t tmp;
8274         int idx = BEND_IDX(steps);
8275
8276         if (WARN_ON(steps % 5 != 0))
8277                 return;
8278
8279         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8280                 return;
8281
8282         mutex_lock(&dev_priv->sb_lock);
8283
8284         if (steps % 10 != 0)
8285                 tmp = 0xAAAAAAAB;
8286         else
8287                 tmp = 0x00000000;
8288         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8289
8290         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8291         tmp &= 0xffff0000;
8292         tmp |= sscdivintphase[idx];
8293         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8294
8295         mutex_unlock(&dev_priv->sb_lock);
8296 }
8297
8298 #undef BEND_IDX
8299
8300 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8301 {
8302         struct intel_encoder *encoder;
8303         bool has_vga = false;
8304
8305         for_each_intel_encoder(&dev_priv->drm, encoder) {
8306                 switch (encoder->type) {
8307                 case INTEL_OUTPUT_ANALOG:
8308                         has_vga = true;
8309                         break;
8310                 default:
8311                         break;
8312                 }
8313         }
8314
8315         if (has_vga) {
8316                 lpt_bend_clkout_dp(dev_priv, 0);
8317                 lpt_enable_clkout_dp(dev_priv, true, true);
8318         } else {
8319                 lpt_disable_clkout_dp(dev_priv);
8320         }
8321 }
8322
8323 /*
8324  * Initialize reference clocks when the driver loads
8325  */
8326 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8327 {
8328         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8329                 ironlake_init_pch_refclk(dev_priv);
8330         else if (HAS_PCH_LPT(dev_priv))
8331                 lpt_init_pch_refclk(dev_priv);
8332 }
8333
8334 static void ironlake_set_pipeconf(const struct intel_crtc_state *crtc_state)
8335 {
8336         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8337         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8338         enum pipe pipe = crtc->pipe;
8339         uint32_t val;
8340
8341         val = 0;
8342
8343         switch (crtc_state->pipe_bpp) {
8344         case 18:
8345                 val |= PIPECONF_6BPC;
8346                 break;
8347         case 24:
8348                 val |= PIPECONF_8BPC;
8349                 break;
8350         case 30:
8351                 val |= PIPECONF_10BPC;
8352                 break;
8353         case 36:
8354                 val |= PIPECONF_12BPC;
8355                 break;
8356         default:
8357                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8358                 BUG();
8359         }
8360
8361         if (crtc_state->dither)
8362                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8363
8364         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8365                 val |= PIPECONF_INTERLACED_ILK;
8366         else
8367                 val |= PIPECONF_PROGRESSIVE;
8368
8369         if (crtc_state->limited_color_range)
8370                 val |= PIPECONF_COLOR_RANGE_SELECT;
8371
8372         I915_WRITE(PIPECONF(pipe), val);
8373         POSTING_READ(PIPECONF(pipe));
8374 }
8375
8376 static void haswell_set_pipeconf(const struct intel_crtc_state *crtc_state)
8377 {
8378         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
8379         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8380         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
8381         u32 val = 0;
8382
8383         if (IS_HASWELL(dev_priv) && crtc_state->dither)
8384                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8385
8386         if (crtc_state->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8387                 val |= PIPECONF_INTERLACED_ILK;
8388         else
8389                 val |= PIPECONF_PROGRESSIVE;
8390
8391         I915_WRITE(PIPECONF(cpu_transcoder), val);
8392         POSTING_READ(PIPECONF(cpu_transcoder));
8393 }
8394
8395 static void haswell_set_pipemisc(const struct intel_crtc_state *crtc_state)
8396 {
8397         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->base.crtc);
8398         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
8399
8400         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8401                 u32 val = 0;
8402
8403                 switch (crtc_state->pipe_bpp) {
8404                 case 18:
8405                         val |= PIPEMISC_DITHER_6_BPC;
8406                         break;
8407                 case 24:
8408                         val |= PIPEMISC_DITHER_8_BPC;
8409                         break;
8410                 case 30:
8411                         val |= PIPEMISC_DITHER_10_BPC;
8412                         break;
8413                 case 36:
8414                         val |= PIPEMISC_DITHER_12_BPC;
8415                         break;
8416                 default:
8417                         /* Case prevented by pipe_config_set_bpp. */
8418                         BUG();
8419                 }
8420
8421                 if (crtc_state->dither)
8422                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8423
8424                 if (crtc_state->ycbcr420) {
8425                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8426                                 PIPEMISC_YUV420_ENABLE |
8427                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8428                 }
8429
8430                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8431         }
8432 }
8433
8434 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8435 {
8436         /*
8437          * Account for spread spectrum to avoid
8438          * oversubscribing the link. Max center spread
8439          * is 2.5%; use 5% for safety's sake.
8440          */
8441         u32 bps = target_clock * bpp * 21 / 20;
8442         return DIV_ROUND_UP(bps, link_bw * 8);
8443 }
8444
8445 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8446 {
8447         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8448 }
8449
8450 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8451                                   struct intel_crtc_state *crtc_state,
8452                                   struct dpll *reduced_clock)
8453 {
8454         struct drm_crtc *crtc = &intel_crtc->base;
8455         struct drm_device *dev = crtc->dev;
8456         struct drm_i915_private *dev_priv = to_i915(dev);
8457         u32 dpll, fp, fp2;
8458         int factor;
8459
8460         /* Enable autotuning of the PLL clock (if permissible) */
8461         factor = 21;
8462         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8463                 if ((intel_panel_use_ssc(dev_priv) &&
8464                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8465                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8466                         factor = 25;
8467         } else if (crtc_state->sdvo_tv_clock)
8468                 factor = 20;
8469
8470         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8471
8472         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8473                 fp |= FP_CB_TUNE;
8474
8475         if (reduced_clock) {
8476                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8477
8478                 if (reduced_clock->m < factor * reduced_clock->n)
8479                         fp2 |= FP_CB_TUNE;
8480         } else {
8481                 fp2 = fp;
8482         }
8483
8484         dpll = 0;
8485
8486         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8487                 dpll |= DPLLB_MODE_LVDS;
8488         else
8489                 dpll |= DPLLB_MODE_DAC_SERIAL;
8490
8491         dpll |= (crtc_state->pixel_multiplier - 1)
8492                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8493
8494         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8495             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8496                 dpll |= DPLL_SDVO_HIGH_SPEED;
8497
8498         if (intel_crtc_has_dp_encoder(crtc_state))
8499                 dpll |= DPLL_SDVO_HIGH_SPEED;
8500
8501         /*
8502          * The high speed IO clock is only really required for
8503          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8504          * possible to share the DPLL between CRT and HDMI. Enabling
8505          * the clock needlessly does no real harm, except use up a
8506          * bit of power potentially.
8507          *
8508          * We'll limit this to IVB with 3 pipes, since it has only two
8509          * DPLLs and so DPLL sharing is the only way to get three pipes
8510          * driving PCH ports at the same time. On SNB we could do this,
8511          * and potentially avoid enabling the second DPLL, but it's not
8512          * clear if it''s a win or loss power wise. No point in doing
8513          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8514          */
8515         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8516             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8517                 dpll |= DPLL_SDVO_HIGH_SPEED;
8518
8519         /* compute bitmask from p1 value */
8520         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8521         /* also FPA1 */
8522         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8523
8524         switch (crtc_state->dpll.p2) {
8525         case 5:
8526                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8527                 break;
8528         case 7:
8529                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8530                 break;
8531         case 10:
8532                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8533                 break;
8534         case 14:
8535                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8536                 break;
8537         }
8538
8539         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8540             intel_panel_use_ssc(dev_priv))
8541                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8542         else
8543                 dpll |= PLL_REF_INPUT_DREFCLK;
8544
8545         dpll |= DPLL_VCO_ENABLE;
8546
8547         crtc_state->dpll_hw_state.dpll = dpll;
8548         crtc_state->dpll_hw_state.fp0 = fp;
8549         crtc_state->dpll_hw_state.fp1 = fp2;
8550 }
8551
8552 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8553                                        struct intel_crtc_state *crtc_state)
8554 {
8555         struct drm_device *dev = crtc->base.dev;
8556         struct drm_i915_private *dev_priv = to_i915(dev);
8557         const struct intel_limit *limit;
8558         int refclk = 120000;
8559
8560         memset(&crtc_state->dpll_hw_state, 0,
8561                sizeof(crtc_state->dpll_hw_state));
8562
8563         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8564         if (!crtc_state->has_pch_encoder)
8565                 return 0;
8566
8567         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8568                 if (intel_panel_use_ssc(dev_priv)) {
8569                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8570                                       dev_priv->vbt.lvds_ssc_freq);
8571                         refclk = dev_priv->vbt.lvds_ssc_freq;
8572                 }
8573
8574                 if (intel_is_dual_link_lvds(dev)) {
8575                         if (refclk == 100000)
8576                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8577                         else
8578                                 limit = &intel_limits_ironlake_dual_lvds;
8579                 } else {
8580                         if (refclk == 100000)
8581                                 limit = &intel_limits_ironlake_single_lvds_100m;
8582                         else
8583                                 limit = &intel_limits_ironlake_single_lvds;
8584                 }
8585         } else {
8586                 limit = &intel_limits_ironlake_dac;
8587         }
8588
8589         if (!crtc_state->clock_set &&
8590             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8591                                 refclk, NULL, &crtc_state->dpll)) {
8592                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8593                 return -EINVAL;
8594         }
8595
8596         ironlake_compute_dpll(crtc, crtc_state, NULL);
8597
8598         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8599                 DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
8600                               pipe_name(crtc->pipe));
8601                 return -EINVAL;
8602         }
8603
8604         return 0;
8605 }
8606
8607 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8608                                          struct intel_link_m_n *m_n)
8609 {
8610         struct drm_device *dev = crtc->base.dev;
8611         struct drm_i915_private *dev_priv = to_i915(dev);
8612         enum pipe pipe = crtc->pipe;
8613
8614         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8615         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8616         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8617                 & ~TU_SIZE_MASK;
8618         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8619         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8620                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8621 }
8622
8623 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8624                                          enum transcoder transcoder,
8625                                          struct intel_link_m_n *m_n,
8626                                          struct intel_link_m_n *m2_n2)
8627 {
8628         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8629         enum pipe pipe = crtc->pipe;
8630
8631         if (INTEL_GEN(dev_priv) >= 5) {
8632                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8633                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8634                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8635                         & ~TU_SIZE_MASK;
8636                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8637                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8638                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8639                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8640                  * gen < 8) and if DRRS is supported (to make sure the
8641                  * registers are not unnecessarily read).
8642                  */
8643                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8644                         crtc->config->has_drrs) {
8645                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8646                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8647                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8648                                         & ~TU_SIZE_MASK;
8649                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8650                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8651                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8652                 }
8653         } else {
8654                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8655                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8656                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8657                         & ~TU_SIZE_MASK;
8658                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8659                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8660                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8661         }
8662 }
8663
8664 void intel_dp_get_m_n(struct intel_crtc *crtc,
8665                       struct intel_crtc_state *pipe_config)
8666 {
8667         if (pipe_config->has_pch_encoder)
8668                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8669         else
8670                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8671                                              &pipe_config->dp_m_n,
8672                                              &pipe_config->dp_m2_n2);
8673 }
8674
8675 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8676                                         struct intel_crtc_state *pipe_config)
8677 {
8678         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8679                                      &pipe_config->fdi_m_n, NULL);
8680 }
8681
8682 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8683                                     struct intel_crtc_state *pipe_config)
8684 {
8685         struct drm_device *dev = crtc->base.dev;
8686         struct drm_i915_private *dev_priv = to_i915(dev);
8687         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8688         uint32_t ps_ctrl = 0;
8689         int id = -1;
8690         int i;
8691
8692         /* find scaler attached to this pipe */
8693         for (i = 0; i < crtc->num_scalers; i++) {
8694                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8695                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8696                         id = i;
8697                         pipe_config->pch_pfit.enabled = true;
8698                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8699                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8700                         break;
8701                 }
8702         }
8703
8704         scaler_state->scaler_id = id;
8705         if (id >= 0) {
8706                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8707         } else {
8708                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8709         }
8710 }
8711
8712 static void
8713 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8714                                  struct intel_initial_plane_config *plane_config)
8715 {
8716         struct drm_device *dev = crtc->base.dev;
8717         struct drm_i915_private *dev_priv = to_i915(dev);
8718         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8719         enum plane_id plane_id = plane->id;
8720         enum pipe pipe;
8721         u32 val, base, offset, stride_mult, tiling, alpha;
8722         int fourcc, pixel_format;
8723         unsigned int aligned_height;
8724         struct drm_framebuffer *fb;
8725         struct intel_framebuffer *intel_fb;
8726
8727         if (!plane->get_hw_state(plane, &pipe))
8728                 return;
8729
8730         WARN_ON(pipe != crtc->pipe);
8731
8732         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8733         if (!intel_fb) {
8734                 DRM_DEBUG_KMS("failed to alloc fb\n");
8735                 return;
8736         }
8737
8738         fb = &intel_fb->base;
8739
8740         fb->dev = dev;
8741
8742         val = I915_READ(PLANE_CTL(pipe, plane_id));
8743
8744         if (INTEL_GEN(dev_priv) >= 11)
8745                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8746         else
8747                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8748
8749         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8750                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8751                 alpha &= PLANE_COLOR_ALPHA_MASK;
8752         } else {
8753                 alpha = val & PLANE_CTL_ALPHA_MASK;
8754         }
8755
8756         fourcc = skl_format_to_fourcc(pixel_format,
8757                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8758         fb->format = drm_format_info(fourcc);
8759
8760         tiling = val & PLANE_CTL_TILED_MASK;
8761         switch (tiling) {
8762         case PLANE_CTL_TILED_LINEAR:
8763                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8764                 break;
8765         case PLANE_CTL_TILED_X:
8766                 plane_config->tiling = I915_TILING_X;
8767                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8768                 break;
8769         case PLANE_CTL_TILED_Y:
8770                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8771                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8772                 else
8773                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8774                 break;
8775         case PLANE_CTL_TILED_YF:
8776                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8777                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8778                 else
8779                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8780                 break;
8781         default:
8782                 MISSING_CASE(tiling);
8783                 goto error;
8784         }
8785
8786         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8787         plane_config->base = base;
8788
8789         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8790
8791         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8792         fb->height = ((val >> 16) & 0xfff) + 1;
8793         fb->width = ((val >> 0) & 0x1fff) + 1;
8794
8795         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8796         stride_mult = intel_fb_stride_alignment(fb, 0);
8797         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8798
8799         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8800
8801         plane_config->size = fb->pitches[0] * aligned_height;
8802
8803         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8804                       crtc->base.name, plane->base.name, fb->width, fb->height,
8805                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8806                       plane_config->size);
8807
8808         plane_config->fb = intel_fb;
8809         return;
8810
8811 error:
8812         kfree(intel_fb);
8813 }
8814
8815 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8816                                      struct intel_crtc_state *pipe_config)
8817 {
8818         struct drm_device *dev = crtc->base.dev;
8819         struct drm_i915_private *dev_priv = to_i915(dev);
8820         uint32_t tmp;
8821
8822         tmp = I915_READ(PF_CTL(crtc->pipe));
8823
8824         if (tmp & PF_ENABLE) {
8825                 pipe_config->pch_pfit.enabled = true;
8826                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8827                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8828
8829                 /* We currently do not free assignements of panel fitters on
8830                  * ivb/hsw (since we don't use the higher upscaling modes which
8831                  * differentiates them) so just WARN about this case for now. */
8832                 if (IS_GEN7(dev_priv)) {
8833                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8834                                 PF_PIPE_SEL_IVB(crtc->pipe));
8835                 }
8836         }
8837 }
8838
8839 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8840                                      struct intel_crtc_state *pipe_config)
8841 {
8842         struct drm_device *dev = crtc->base.dev;
8843         struct drm_i915_private *dev_priv = to_i915(dev);
8844         enum intel_display_power_domain power_domain;
8845         uint32_t tmp;
8846         bool ret;
8847
8848         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8849         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8850                 return false;
8851
8852         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8853         pipe_config->shared_dpll = NULL;
8854
8855         ret = false;
8856         tmp = I915_READ(PIPECONF(crtc->pipe));
8857         if (!(tmp & PIPECONF_ENABLE))
8858                 goto out;
8859
8860         switch (tmp & PIPECONF_BPC_MASK) {
8861         case PIPECONF_6BPC:
8862                 pipe_config->pipe_bpp = 18;
8863                 break;
8864         case PIPECONF_8BPC:
8865                 pipe_config->pipe_bpp = 24;
8866                 break;
8867         case PIPECONF_10BPC:
8868                 pipe_config->pipe_bpp = 30;
8869                 break;
8870         case PIPECONF_12BPC:
8871                 pipe_config->pipe_bpp = 36;
8872                 break;
8873         default:
8874                 break;
8875         }
8876
8877         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8878                 pipe_config->limited_color_range = true;
8879
8880         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8881                 struct intel_shared_dpll *pll;
8882                 enum intel_dpll_id pll_id;
8883
8884                 pipe_config->has_pch_encoder = true;
8885
8886                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8887                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8888                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8889
8890                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8891
8892                 if (HAS_PCH_IBX(dev_priv)) {
8893                         /*
8894                          * The pipe->pch transcoder and pch transcoder->pll
8895                          * mapping is fixed.
8896                          */
8897                         pll_id = (enum intel_dpll_id) crtc->pipe;
8898                 } else {
8899                         tmp = I915_READ(PCH_DPLL_SEL);
8900                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8901                                 pll_id = DPLL_ID_PCH_PLL_B;
8902                         else
8903                                 pll_id= DPLL_ID_PCH_PLL_A;
8904                 }
8905
8906                 pipe_config->shared_dpll =
8907                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8908                 pll = pipe_config->shared_dpll;
8909
8910                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
8911                                                 &pipe_config->dpll_hw_state));
8912
8913                 tmp = pipe_config->dpll_hw_state.dpll;
8914                 pipe_config->pixel_multiplier =
8915                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8916                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8917
8918                 ironlake_pch_clock_get(crtc, pipe_config);
8919         } else {
8920                 pipe_config->pixel_multiplier = 1;
8921         }
8922
8923         intel_get_pipe_timings(crtc, pipe_config);
8924         intel_get_pipe_src_size(crtc, pipe_config);
8925
8926         ironlake_get_pfit_config(crtc, pipe_config);
8927
8928         ret = true;
8929
8930 out:
8931         intel_display_power_put(dev_priv, power_domain);
8932
8933         return ret;
8934 }
8935
8936 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8937 {
8938         struct drm_device *dev = &dev_priv->drm;
8939         struct intel_crtc *crtc;
8940
8941         for_each_intel_crtc(dev, crtc)
8942                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8943                      pipe_name(crtc->pipe));
8944
8945         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL2),
8946                         "Display power well on\n");
8947         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8948         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8949         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8950         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8951         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8952              "CPU PWM1 enabled\n");
8953         if (IS_HASWELL(dev_priv))
8954                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8955                      "CPU PWM2 enabled\n");
8956         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8957              "PCH PWM1 enabled\n");
8958         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8959              "Utility pin enabled\n");
8960         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8961
8962         /*
8963          * In theory we can still leave IRQs enabled, as long as only the HPD
8964          * interrupts remain enabled. We used to check for that, but since it's
8965          * gen-specific and since we only disable LCPLL after we fully disable
8966          * the interrupts, the check below should be enough.
8967          */
8968         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8969 }
8970
8971 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8972 {
8973         if (IS_HASWELL(dev_priv))
8974                 return I915_READ(D_COMP_HSW);
8975         else
8976                 return I915_READ(D_COMP_BDW);
8977 }
8978
8979 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8980 {
8981         if (IS_HASWELL(dev_priv)) {
8982                 mutex_lock(&dev_priv->pcu_lock);
8983                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8984                                             val))
8985                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
8986                 mutex_unlock(&dev_priv->pcu_lock);
8987         } else {
8988                 I915_WRITE(D_COMP_BDW, val);
8989                 POSTING_READ(D_COMP_BDW);
8990         }
8991 }
8992
8993 /*
8994  * This function implements pieces of two sequences from BSpec:
8995  * - Sequence for display software to disable LCPLL
8996  * - Sequence for display software to allow package C8+
8997  * The steps implemented here are just the steps that actually touch the LCPLL
8998  * register. Callers should take care of disabling all the display engine
8999  * functions, doing the mode unset, fixing interrupts, etc.
9000  */
9001 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9002                               bool switch_to_fclk, bool allow_power_down)
9003 {
9004         uint32_t val;
9005
9006         assert_can_disable_lcpll(dev_priv);
9007
9008         val = I915_READ(LCPLL_CTL);
9009
9010         if (switch_to_fclk) {
9011                 val |= LCPLL_CD_SOURCE_FCLK;
9012                 I915_WRITE(LCPLL_CTL, val);
9013
9014                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9015                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9016                         DRM_ERROR("Switching to FCLK failed\n");
9017
9018                 val = I915_READ(LCPLL_CTL);
9019         }
9020
9021         val |= LCPLL_PLL_DISABLE;
9022         I915_WRITE(LCPLL_CTL, val);
9023         POSTING_READ(LCPLL_CTL);
9024
9025         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9026                 DRM_ERROR("LCPLL still locked\n");
9027
9028         val = hsw_read_dcomp(dev_priv);
9029         val |= D_COMP_COMP_DISABLE;
9030         hsw_write_dcomp(dev_priv, val);
9031         ndelay(100);
9032
9033         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9034                      1))
9035                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9036
9037         if (allow_power_down) {
9038                 val = I915_READ(LCPLL_CTL);
9039                 val |= LCPLL_POWER_DOWN_ALLOW;
9040                 I915_WRITE(LCPLL_CTL, val);
9041                 POSTING_READ(LCPLL_CTL);
9042         }
9043 }
9044
9045 /*
9046  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9047  * source.
9048  */
9049 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9050 {
9051         uint32_t val;
9052
9053         val = I915_READ(LCPLL_CTL);
9054
9055         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9056                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9057                 return;
9058
9059         /*
9060          * Make sure we're not on PC8 state before disabling PC8, otherwise
9061          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9062          */
9063         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9064
9065         if (val & LCPLL_POWER_DOWN_ALLOW) {
9066                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9067                 I915_WRITE(LCPLL_CTL, val);
9068                 POSTING_READ(LCPLL_CTL);
9069         }
9070
9071         val = hsw_read_dcomp(dev_priv);
9072         val |= D_COMP_COMP_FORCE;
9073         val &= ~D_COMP_COMP_DISABLE;
9074         hsw_write_dcomp(dev_priv, val);
9075
9076         val = I915_READ(LCPLL_CTL);
9077         val &= ~LCPLL_PLL_DISABLE;
9078         I915_WRITE(LCPLL_CTL, val);
9079
9080         if (intel_wait_for_register(dev_priv,
9081                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9082                                     5))
9083                 DRM_ERROR("LCPLL not locked yet\n");
9084
9085         if (val & LCPLL_CD_SOURCE_FCLK) {
9086                 val = I915_READ(LCPLL_CTL);
9087                 val &= ~LCPLL_CD_SOURCE_FCLK;
9088                 I915_WRITE(LCPLL_CTL, val);
9089
9090                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9091                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9092                         DRM_ERROR("Switching back to LCPLL failed\n");
9093         }
9094
9095         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9096
9097         intel_update_cdclk(dev_priv);
9098         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
9099 }
9100
9101 /*
9102  * Package states C8 and deeper are really deep PC states that can only be
9103  * reached when all the devices on the system allow it, so even if the graphics
9104  * device allows PC8+, it doesn't mean the system will actually get to these
9105  * states. Our driver only allows PC8+ when going into runtime PM.
9106  *
9107  * The requirements for PC8+ are that all the outputs are disabled, the power
9108  * well is disabled and most interrupts are disabled, and these are also
9109  * requirements for runtime PM. When these conditions are met, we manually do
9110  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9111  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9112  * hang the machine.
9113  *
9114  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9115  * the state of some registers, so when we come back from PC8+ we need to
9116  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9117  * need to take care of the registers kept by RC6. Notice that this happens even
9118  * if we don't put the device in PCI D3 state (which is what currently happens
9119  * because of the runtime PM support).
9120  *
9121  * For more, read "Display Sequences for Package C8" on the hardware
9122  * documentation.
9123  */
9124 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9125 {
9126         uint32_t val;
9127
9128         DRM_DEBUG_KMS("Enabling package C8+\n");
9129
9130         if (HAS_PCH_LPT_LP(dev_priv)) {
9131                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9132                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9133                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9134         }
9135
9136         lpt_disable_clkout_dp(dev_priv);
9137         hsw_disable_lcpll(dev_priv, true, true);
9138 }
9139
9140 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9141 {
9142         uint32_t val;
9143
9144         DRM_DEBUG_KMS("Disabling package C8+\n");
9145
9146         hsw_restore_lcpll(dev_priv);
9147         lpt_init_pch_refclk(dev_priv);
9148
9149         if (HAS_PCH_LPT_LP(dev_priv)) {
9150                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9151                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9152                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9153         }
9154 }
9155
9156 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9157                                       struct intel_crtc_state *crtc_state)
9158 {
9159         struct intel_atomic_state *state =
9160                 to_intel_atomic_state(crtc_state->base.state);
9161
9162         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9163                 struct intel_encoder *encoder =
9164                         intel_get_crtc_new_encoder(state, crtc_state);
9165
9166                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9167                         DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9168                                       pipe_name(crtc->pipe));
9169                         return -EINVAL;
9170                 }
9171         }
9172
9173         return 0;
9174 }
9175
9176 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9177                                    enum port port,
9178                                    struct intel_crtc_state *pipe_config)
9179 {
9180         enum intel_dpll_id id;
9181         u32 temp;
9182
9183         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9184         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9185
9186         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9187                 return;
9188
9189         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9190 }
9191
9192 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9193                                 enum port port,
9194                                 struct intel_crtc_state *pipe_config)
9195 {
9196         enum intel_dpll_id id;
9197         u32 temp;
9198
9199         /* TODO: TBT pll not implemented. */
9200         switch (port) {
9201         case PORT_A:
9202         case PORT_B:
9203                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9204                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9205                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9206
9207                 if (WARN_ON(id != DPLL_ID_ICL_DPLL0 && id != DPLL_ID_ICL_DPLL1))
9208                         return;
9209                 break;
9210         case PORT_C:
9211                 id = DPLL_ID_ICL_MGPLL1;
9212                 break;
9213         case PORT_D:
9214                 id = DPLL_ID_ICL_MGPLL2;
9215                 break;
9216         case PORT_E:
9217                 id = DPLL_ID_ICL_MGPLL3;
9218                 break;
9219         case PORT_F:
9220                 id = DPLL_ID_ICL_MGPLL4;
9221                 break;
9222         default:
9223                 MISSING_CASE(port);
9224                 return;
9225         }
9226
9227         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9228 }
9229
9230 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9231                                 enum port port,
9232                                 struct intel_crtc_state *pipe_config)
9233 {
9234         enum intel_dpll_id id;
9235
9236         switch (port) {
9237         case PORT_A:
9238                 id = DPLL_ID_SKL_DPLL0;
9239                 break;
9240         case PORT_B:
9241                 id = DPLL_ID_SKL_DPLL1;
9242                 break;
9243         case PORT_C:
9244                 id = DPLL_ID_SKL_DPLL2;
9245                 break;
9246         default:
9247                 DRM_ERROR("Incorrect port type\n");
9248                 return;
9249         }
9250
9251         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9252 }
9253
9254 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9255                                 enum port port,
9256                                 struct intel_crtc_state *pipe_config)
9257 {
9258         enum intel_dpll_id id;
9259         u32 temp;
9260
9261         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9262         id = temp >> (port * 3 + 1);
9263
9264         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9265                 return;
9266
9267         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9268 }
9269
9270 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9271                                 enum port port,
9272                                 struct intel_crtc_state *pipe_config)
9273 {
9274         enum intel_dpll_id id;
9275         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9276
9277         switch (ddi_pll_sel) {
9278         case PORT_CLK_SEL_WRPLL1:
9279                 id = DPLL_ID_WRPLL1;
9280                 break;
9281         case PORT_CLK_SEL_WRPLL2:
9282                 id = DPLL_ID_WRPLL2;
9283                 break;
9284         case PORT_CLK_SEL_SPLL:
9285                 id = DPLL_ID_SPLL;
9286                 break;
9287         case PORT_CLK_SEL_LCPLL_810:
9288                 id = DPLL_ID_LCPLL_810;
9289                 break;
9290         case PORT_CLK_SEL_LCPLL_1350:
9291                 id = DPLL_ID_LCPLL_1350;
9292                 break;
9293         case PORT_CLK_SEL_LCPLL_2700:
9294                 id = DPLL_ID_LCPLL_2700;
9295                 break;
9296         default:
9297                 MISSING_CASE(ddi_pll_sel);
9298                 /* fall through */
9299         case PORT_CLK_SEL_NONE:
9300                 return;
9301         }
9302
9303         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9304 }
9305
9306 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9307                                      struct intel_crtc_state *pipe_config,
9308                                      u64 *power_domain_mask)
9309 {
9310         struct drm_device *dev = crtc->base.dev;
9311         struct drm_i915_private *dev_priv = to_i915(dev);
9312         enum intel_display_power_domain power_domain;
9313         u32 tmp;
9314
9315         /*
9316          * The pipe->transcoder mapping is fixed with the exception of the eDP
9317          * transcoder handled below.
9318          */
9319         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9320
9321         /*
9322          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9323          * consistency and less surprising code; it's in always on power).
9324          */
9325         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9326         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9327                 enum pipe trans_edp_pipe;
9328                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9329                 default:
9330                         WARN(1, "unknown pipe linked to edp transcoder\n");
9331                         /* fall through */
9332                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9333                 case TRANS_DDI_EDP_INPUT_A_ON:
9334                         trans_edp_pipe = PIPE_A;
9335                         break;
9336                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9337                         trans_edp_pipe = PIPE_B;
9338                         break;
9339                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9340                         trans_edp_pipe = PIPE_C;
9341                         break;
9342                 }
9343
9344                 if (trans_edp_pipe == crtc->pipe)
9345                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9346         }
9347
9348         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9349         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9350                 return false;
9351         *power_domain_mask |= BIT_ULL(power_domain);
9352
9353         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9354
9355         return tmp & PIPECONF_ENABLE;
9356 }
9357
9358 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9359                                          struct intel_crtc_state *pipe_config,
9360                                          u64 *power_domain_mask)
9361 {
9362         struct drm_device *dev = crtc->base.dev;
9363         struct drm_i915_private *dev_priv = to_i915(dev);
9364         enum intel_display_power_domain power_domain;
9365         enum port port;
9366         enum transcoder cpu_transcoder;
9367         u32 tmp;
9368
9369         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9370                 if (port == PORT_A)
9371                         cpu_transcoder = TRANSCODER_DSI_A;
9372                 else
9373                         cpu_transcoder = TRANSCODER_DSI_C;
9374
9375                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9376                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9377                         continue;
9378                 *power_domain_mask |= BIT_ULL(power_domain);
9379
9380                 /*
9381                  * The PLL needs to be enabled with a valid divider
9382                  * configuration, otherwise accessing DSI registers will hang
9383                  * the machine. See BSpec North Display Engine
9384                  * registers/MIPI[BXT]. We can break out here early, since we
9385                  * need the same DSI PLL to be enabled for both DSI ports.
9386                  */
9387                 if (!bxt_dsi_pll_is_enabled(dev_priv))
9388                         break;
9389
9390                 /* XXX: this works for video mode only */
9391                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9392                 if (!(tmp & DPI_ENABLE))
9393                         continue;
9394
9395                 tmp = I915_READ(MIPI_CTRL(port));
9396                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9397                         continue;
9398
9399                 pipe_config->cpu_transcoder = cpu_transcoder;
9400                 break;
9401         }
9402
9403         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9404 }
9405
9406 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9407                                        struct intel_crtc_state *pipe_config)
9408 {
9409         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9410         struct intel_shared_dpll *pll;
9411         enum port port;
9412         uint32_t tmp;
9413
9414         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9415
9416         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9417
9418         if (IS_ICELAKE(dev_priv))
9419                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
9420         else if (IS_CANNONLAKE(dev_priv))
9421                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9422         else if (IS_GEN9_BC(dev_priv))
9423                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9424         else if (IS_GEN9_LP(dev_priv))
9425                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9426         else
9427                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9428
9429         pll = pipe_config->shared_dpll;
9430         if (pll) {
9431                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9432                                                 &pipe_config->dpll_hw_state));
9433         }
9434
9435         /*
9436          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9437          * DDI E. So just check whether this pipe is wired to DDI E and whether
9438          * the PCH transcoder is on.
9439          */
9440         if (INTEL_GEN(dev_priv) < 9 &&
9441             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9442                 pipe_config->has_pch_encoder = true;
9443
9444                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9445                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9446                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9447
9448                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9449         }
9450 }
9451
9452 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9453                                     struct intel_crtc_state *pipe_config)
9454 {
9455         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9456         enum intel_display_power_domain power_domain;
9457         u64 power_domain_mask;
9458         bool active;
9459
9460         intel_crtc_init_scalers(crtc, pipe_config);
9461
9462         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9463         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9464                 return false;
9465         power_domain_mask = BIT_ULL(power_domain);
9466
9467         pipe_config->shared_dpll = NULL;
9468
9469         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9470
9471         if (IS_GEN9_LP(dev_priv) &&
9472             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9473                 WARN_ON(active);
9474                 active = true;
9475         }
9476
9477         if (!active)
9478                 goto out;
9479
9480         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9481                 haswell_get_ddi_port_state(crtc, pipe_config);
9482                 intel_get_pipe_timings(crtc, pipe_config);
9483         }
9484
9485         intel_get_pipe_src_size(crtc, pipe_config);
9486
9487         pipe_config->gamma_mode =
9488                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9489
9490         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
9491                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9492                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9493
9494                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10) {
9495                         bool blend_mode_420 = tmp &
9496                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9497
9498                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9499                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9500                             pipe_config->ycbcr420 != blend_mode_420)
9501                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9502                 } else if (clrspace_yuv) {
9503                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9504                 }
9505         }
9506
9507         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9508         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9509                 power_domain_mask |= BIT_ULL(power_domain);
9510                 if (INTEL_GEN(dev_priv) >= 9)
9511                         skylake_get_pfit_config(crtc, pipe_config);
9512                 else
9513                         ironlake_get_pfit_config(crtc, pipe_config);
9514         }
9515
9516         if (hsw_crtc_supports_ips(crtc)) {
9517                 if (IS_HASWELL(dev_priv))
9518                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9519                 else {
9520                         /*
9521                          * We cannot readout IPS state on broadwell, set to
9522                          * true so we can set it to a defined state on first
9523                          * commit.
9524                          */
9525                         pipe_config->ips_enabled = true;
9526                 }
9527         }
9528
9529         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9530             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9531                 pipe_config->pixel_multiplier =
9532                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9533         } else {
9534                 pipe_config->pixel_multiplier = 1;
9535         }
9536
9537 out:
9538         for_each_power_domain(power_domain, power_domain_mask)
9539                 intel_display_power_put(dev_priv, power_domain);
9540
9541         return active;
9542 }
9543
9544 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9545 {
9546         struct drm_i915_private *dev_priv =
9547                 to_i915(plane_state->base.plane->dev);
9548         const struct drm_framebuffer *fb = plane_state->base.fb;
9549         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9550         u32 base;
9551
9552         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9553                 base = obj->phys_handle->busaddr;
9554         else
9555                 base = intel_plane_ggtt_offset(plane_state);
9556
9557         base += plane_state->color_plane[0].offset;
9558
9559         /* ILK+ do this automagically */
9560         if (HAS_GMCH_DISPLAY(dev_priv) &&
9561             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9562                 base += (plane_state->base.crtc_h *
9563                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9564
9565         return base;
9566 }
9567
9568 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9569 {
9570         int x = plane_state->base.crtc_x;
9571         int y = plane_state->base.crtc_y;
9572         u32 pos = 0;
9573
9574         if (x < 0) {
9575                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9576                 x = -x;
9577         }
9578         pos |= x << CURSOR_X_SHIFT;
9579
9580         if (y < 0) {
9581                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9582                 y = -y;
9583         }
9584         pos |= y << CURSOR_Y_SHIFT;
9585
9586         return pos;
9587 }
9588
9589 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9590 {
9591         const struct drm_mode_config *config =
9592                 &plane_state->base.plane->dev->mode_config;
9593         int width = plane_state->base.crtc_w;
9594         int height = plane_state->base.crtc_h;
9595
9596         return width > 0 && width <= config->cursor_width &&
9597                 height > 0 && height <= config->cursor_height;
9598 }
9599
9600 static int intel_cursor_check_surface(struct intel_plane_state *plane_state)
9601 {
9602         const struct drm_framebuffer *fb = plane_state->base.fb;
9603         unsigned int rotation = plane_state->base.rotation;
9604         int src_x, src_y;
9605         u32 offset;
9606         int ret;
9607
9608         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
9609         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
9610
9611         ret = intel_plane_check_stride(plane_state);
9612         if (ret)
9613                 return ret;
9614
9615         src_x = plane_state->base.src_x >> 16;
9616         src_y = plane_state->base.src_y >> 16;
9617
9618         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9619         offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
9620                                                     plane_state, 0);
9621
9622         if (src_x != 0 || src_y != 0) {
9623                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9624                 return -EINVAL;
9625         }
9626
9627         plane_state->color_plane[0].offset = offset;
9628
9629         return 0;
9630 }
9631
9632 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9633                               struct intel_plane_state *plane_state)
9634 {
9635         const struct drm_framebuffer *fb = plane_state->base.fb;
9636         int ret;
9637
9638         if (fb && fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9639                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9640                 return -EINVAL;
9641         }
9642
9643         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9644                                                   &crtc_state->base,
9645                                                   DRM_PLANE_HELPER_NO_SCALING,
9646                                                   DRM_PLANE_HELPER_NO_SCALING,
9647                                                   true, true);
9648         if (ret)
9649                 return ret;
9650
9651         if (!plane_state->base.visible)
9652                 return 0;
9653
9654         ret = intel_plane_check_src_coordinates(plane_state);
9655         if (ret)
9656                 return ret;
9657
9658         ret = intel_cursor_check_surface(plane_state);
9659         if (ret)
9660                 return ret;
9661
9662         return 0;
9663 }
9664
9665 static unsigned int
9666 i845_cursor_max_stride(struct intel_plane *plane,
9667                        u32 pixel_format, u64 modifier,
9668                        unsigned int rotation)
9669 {
9670         return 2048;
9671 }
9672
9673 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9674                            const struct intel_plane_state *plane_state)
9675 {
9676         return CURSOR_ENABLE |
9677                 CURSOR_GAMMA_ENABLE |
9678                 CURSOR_FORMAT_ARGB |
9679                 CURSOR_STRIDE(plane_state->color_plane[0].stride);
9680 }
9681
9682 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9683 {
9684         int width = plane_state->base.crtc_w;
9685
9686         /*
9687          * 845g/865g are only limited by the width of their cursors,
9688          * the height is arbitrary up to the precision of the register.
9689          */
9690         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9691 }
9692
9693 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
9694                              struct intel_plane_state *plane_state)
9695 {
9696         const struct drm_framebuffer *fb = plane_state->base.fb;
9697         int ret;
9698
9699         ret = intel_check_cursor(crtc_state, plane_state);
9700         if (ret)
9701                 return ret;
9702
9703         /* if we want to turn off the cursor ignore width and height */
9704         if (!fb)
9705                 return 0;
9706
9707         /* Check for which cursor types we support */
9708         if (!i845_cursor_size_ok(plane_state)) {
9709                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9710                           plane_state->base.crtc_w,
9711                           plane_state->base.crtc_h);
9712                 return -EINVAL;
9713         }
9714
9715         WARN_ON(plane_state->base.visible &&
9716                 plane_state->color_plane[0].stride != fb->pitches[0]);
9717
9718         switch (fb->pitches[0]) {
9719         case 256:
9720         case 512:
9721         case 1024:
9722         case 2048:
9723                 break;
9724         default:
9725                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9726                               fb->pitches[0]);
9727                 return -EINVAL;
9728         }
9729
9730         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9731
9732         return 0;
9733 }
9734
9735 static void i845_update_cursor(struct intel_plane *plane,
9736                                const struct intel_crtc_state *crtc_state,
9737                                const struct intel_plane_state *plane_state)
9738 {
9739         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9740         u32 cntl = 0, base = 0, pos = 0, size = 0;
9741         unsigned long irqflags;
9742
9743         if (plane_state && plane_state->base.visible) {
9744                 unsigned int width = plane_state->base.crtc_w;
9745                 unsigned int height = plane_state->base.crtc_h;
9746
9747                 cntl = plane_state->ctl;
9748                 size = (height << 12) | width;
9749
9750                 base = intel_cursor_base(plane_state);
9751                 pos = intel_cursor_position(plane_state);
9752         }
9753
9754         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9755
9756         /* On these chipsets we can only modify the base/size/stride
9757          * whilst the cursor is disabled.
9758          */
9759         if (plane->cursor.base != base ||
9760             plane->cursor.size != size ||
9761             plane->cursor.cntl != cntl) {
9762                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9763                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9764                 I915_WRITE_FW(CURSIZE, size);
9765                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9766                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9767
9768                 plane->cursor.base = base;
9769                 plane->cursor.size = size;
9770                 plane->cursor.cntl = cntl;
9771         } else {
9772                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9773         }
9774
9775         POSTING_READ_FW(CURCNTR(PIPE_A));
9776
9777         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9778 }
9779
9780 static void i845_disable_cursor(struct intel_plane *plane,
9781                                 struct intel_crtc *crtc)
9782 {
9783         i845_update_cursor(plane, NULL, NULL);
9784 }
9785
9786 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
9787                                      enum pipe *pipe)
9788 {
9789         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9790         enum intel_display_power_domain power_domain;
9791         bool ret;
9792
9793         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9794         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9795                 return false;
9796
9797         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9798
9799         *pipe = PIPE_A;
9800
9801         intel_display_power_put(dev_priv, power_domain);
9802
9803         return ret;
9804 }
9805
9806 static unsigned int
9807 i9xx_cursor_max_stride(struct intel_plane *plane,
9808                        u32 pixel_format, u64 modifier,
9809                        unsigned int rotation)
9810 {
9811         return plane->base.dev->mode_config.cursor_width * 4;
9812 }
9813
9814 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9815                            const struct intel_plane_state *plane_state)
9816 {
9817         struct drm_i915_private *dev_priv =
9818                 to_i915(plane_state->base.plane->dev);
9819         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9820         u32 cntl = 0;
9821
9822         if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
9823                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
9824
9825         if (INTEL_GEN(dev_priv) <= 10) {
9826                 cntl |= MCURSOR_GAMMA_ENABLE;
9827
9828                 if (HAS_DDI(dev_priv))
9829                         cntl |= MCURSOR_PIPE_CSC_ENABLE;
9830         }
9831
9832         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
9833                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9834
9835         switch (plane_state->base.crtc_w) {
9836         case 64:
9837                 cntl |= MCURSOR_MODE_64_ARGB_AX;
9838                 break;
9839         case 128:
9840                 cntl |= MCURSOR_MODE_128_ARGB_AX;
9841                 break;
9842         case 256:
9843                 cntl |= MCURSOR_MODE_256_ARGB_AX;
9844                 break;
9845         default:
9846                 MISSING_CASE(plane_state->base.crtc_w);
9847                 return 0;
9848         }
9849
9850         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9851                 cntl |= MCURSOR_ROTATE_180;
9852
9853         return cntl;
9854 }
9855
9856 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9857 {
9858         struct drm_i915_private *dev_priv =
9859                 to_i915(plane_state->base.plane->dev);
9860         int width = plane_state->base.crtc_w;
9861         int height = plane_state->base.crtc_h;
9862
9863         if (!intel_cursor_size_ok(plane_state))
9864                 return false;
9865
9866         /* Cursor width is limited to a few power-of-two sizes */
9867         switch (width) {
9868         case 256:
9869         case 128:
9870         case 64:
9871                 break;
9872         default:
9873                 return false;
9874         }
9875
9876         /*
9877          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9878          * height from 8 lines up to the cursor width, when the
9879          * cursor is not rotated. Everything else requires square
9880          * cursors.
9881          */
9882         if (HAS_CUR_FBC(dev_priv) &&
9883             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9884                 if (height < 8 || height > width)
9885                         return false;
9886         } else {
9887                 if (height != width)
9888                         return false;
9889         }
9890
9891         return true;
9892 }
9893
9894 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
9895                              struct intel_plane_state *plane_state)
9896 {
9897         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
9898         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9899         const struct drm_framebuffer *fb = plane_state->base.fb;
9900         enum pipe pipe = plane->pipe;
9901         int ret;
9902
9903         ret = intel_check_cursor(crtc_state, plane_state);
9904         if (ret)
9905                 return ret;
9906
9907         /* if we want to turn off the cursor ignore width and height */
9908         if (!fb)
9909                 return 0;
9910
9911         /* Check for which cursor types we support */
9912         if (!i9xx_cursor_size_ok(plane_state)) {
9913                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9914                           plane_state->base.crtc_w,
9915                           plane_state->base.crtc_h);
9916                 return -EINVAL;
9917         }
9918
9919         WARN_ON(plane_state->base.visible &&
9920                 plane_state->color_plane[0].stride != fb->pitches[0]);
9921
9922         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9923                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9924                               fb->pitches[0], plane_state->base.crtc_w);
9925                 return -EINVAL;
9926         }
9927
9928         /*
9929          * There's something wrong with the cursor on CHV pipe C.
9930          * If it straddles the left edge of the screen then
9931          * moving it away from the edge or disabling it often
9932          * results in a pipe underrun, and often that can lead to
9933          * dead pipe (constant underrun reported, and it scans
9934          * out just a solid color). To recover from that, the
9935          * display power well must be turned off and on again.
9936          * Refuse the put the cursor into that compromised position.
9937          */
9938         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9939             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9940                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9941                 return -EINVAL;
9942         }
9943
9944         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9945
9946         return 0;
9947 }
9948
9949 static void i9xx_update_cursor(struct intel_plane *plane,
9950                                const struct intel_crtc_state *crtc_state,
9951                                const struct intel_plane_state *plane_state)
9952 {
9953         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9954         enum pipe pipe = plane->pipe;
9955         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9956         unsigned long irqflags;
9957
9958         if (plane_state && plane_state->base.visible) {
9959                 cntl = plane_state->ctl;
9960
9961                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9962                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9963
9964                 base = intel_cursor_base(plane_state);
9965                 pos = intel_cursor_position(plane_state);
9966         }
9967
9968         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9969
9970         /*
9971          * On some platforms writing CURCNTR first will also
9972          * cause CURPOS to be armed by the CURBASE write.
9973          * Without the CURCNTR write the CURPOS write would
9974          * arm itself. Thus we always start the full update
9975          * with a CURCNTR write.
9976          *
9977          * On other platforms CURPOS always requires the
9978          * CURBASE write to arm the update. Additonally
9979          * a write to any of the cursor register will cancel
9980          * an already armed cursor update. Thus leaving out
9981          * the CURBASE write after CURPOS could lead to a
9982          * cursor that doesn't appear to move, or even change
9983          * shape. Thus we always write CURBASE.
9984          *
9985          * CURCNTR and CUR_FBC_CTL are always
9986          * armed by the CURBASE write only.
9987          */
9988         if (plane->cursor.base != base ||
9989             plane->cursor.size != fbc_ctl ||
9990             plane->cursor.cntl != cntl) {
9991                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9992                 if (HAS_CUR_FBC(dev_priv))
9993                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9994                 I915_WRITE_FW(CURPOS(pipe), pos);
9995                 I915_WRITE_FW(CURBASE(pipe), base);
9996
9997                 plane->cursor.base = base;
9998                 plane->cursor.size = fbc_ctl;
9999                 plane->cursor.cntl = cntl;
10000         } else {
10001                 I915_WRITE_FW(CURPOS(pipe), pos);
10002                 I915_WRITE_FW(CURBASE(pipe), base);
10003         }
10004
10005         POSTING_READ_FW(CURBASE(pipe));
10006
10007         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10008 }
10009
10010 static void i9xx_disable_cursor(struct intel_plane *plane,
10011                                 struct intel_crtc *crtc)
10012 {
10013         i9xx_update_cursor(plane, NULL, NULL);
10014 }
10015
10016 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10017                                      enum pipe *pipe)
10018 {
10019         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10020         enum intel_display_power_domain power_domain;
10021         bool ret;
10022         u32 val;
10023
10024         /*
10025          * Not 100% correct for planes that can move between pipes,
10026          * but that's only the case for gen2-3 which don't have any
10027          * display power wells.
10028          */
10029         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10030         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10031                 return false;
10032
10033         val = I915_READ(CURCNTR(plane->pipe));
10034
10035         ret = val & MCURSOR_MODE;
10036
10037         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10038                 *pipe = plane->pipe;
10039         else
10040                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10041                         MCURSOR_PIPE_SELECT_SHIFT;
10042
10043         intel_display_power_put(dev_priv, power_domain);
10044
10045         return ret;
10046 }
10047
10048 /* VESA 640x480x72Hz mode to set on the pipe */
10049 static const struct drm_display_mode load_detect_mode = {
10050         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10051                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10052 };
10053
10054 struct drm_framebuffer *
10055 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10056                          struct drm_mode_fb_cmd2 *mode_cmd)
10057 {
10058         struct intel_framebuffer *intel_fb;
10059         int ret;
10060
10061         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10062         if (!intel_fb)
10063                 return ERR_PTR(-ENOMEM);
10064
10065         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10066         if (ret)
10067                 goto err;
10068
10069         return &intel_fb->base;
10070
10071 err:
10072         kfree(intel_fb);
10073         return ERR_PTR(ret);
10074 }
10075
10076 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10077                                         struct drm_crtc *crtc)
10078 {
10079         struct drm_plane *plane;
10080         struct drm_plane_state *plane_state;
10081         int ret, i;
10082
10083         ret = drm_atomic_add_affected_planes(state, crtc);
10084         if (ret)
10085                 return ret;
10086
10087         for_each_new_plane_in_state(state, plane, plane_state, i) {
10088                 if (plane_state->crtc != crtc)
10089                         continue;
10090
10091                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10092                 if (ret)
10093                         return ret;
10094
10095                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10096         }
10097
10098         return 0;
10099 }
10100
10101 int intel_get_load_detect_pipe(struct drm_connector *connector,
10102                                const struct drm_display_mode *mode,
10103                                struct intel_load_detect_pipe *old,
10104                                struct drm_modeset_acquire_ctx *ctx)
10105 {
10106         struct intel_crtc *intel_crtc;
10107         struct intel_encoder *intel_encoder =
10108                 intel_attached_encoder(connector);
10109         struct drm_crtc *possible_crtc;
10110         struct drm_encoder *encoder = &intel_encoder->base;
10111         struct drm_crtc *crtc = NULL;
10112         struct drm_device *dev = encoder->dev;
10113         struct drm_i915_private *dev_priv = to_i915(dev);
10114         struct drm_mode_config *config = &dev->mode_config;
10115         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10116         struct drm_connector_state *connector_state;
10117         struct intel_crtc_state *crtc_state;
10118         int ret, i = -1;
10119
10120         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10121                       connector->base.id, connector->name,
10122                       encoder->base.id, encoder->name);
10123
10124         old->restore_state = NULL;
10125
10126         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10127
10128         /*
10129          * Algorithm gets a little messy:
10130          *
10131          *   - if the connector already has an assigned crtc, use it (but make
10132          *     sure it's on first)
10133          *
10134          *   - try to find the first unused crtc that can drive this connector,
10135          *     and use that if we find one
10136          */
10137
10138         /* See if we already have a CRTC for this connector */
10139         if (connector->state->crtc) {
10140                 crtc = connector->state->crtc;
10141
10142                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10143                 if (ret)
10144                         goto fail;
10145
10146                 /* Make sure the crtc and connector are running */
10147                 goto found;
10148         }
10149
10150         /* Find an unused one (if possible) */
10151         for_each_crtc(dev, possible_crtc) {
10152                 i++;
10153                 if (!(encoder->possible_crtcs & (1 << i)))
10154                         continue;
10155
10156                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10157                 if (ret)
10158                         goto fail;
10159
10160                 if (possible_crtc->state->enable) {
10161                         drm_modeset_unlock(&possible_crtc->mutex);
10162                         continue;
10163                 }
10164
10165                 crtc = possible_crtc;
10166                 break;
10167         }
10168
10169         /*
10170          * If we didn't find an unused CRTC, don't use any.
10171          */
10172         if (!crtc) {
10173                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10174                 ret = -ENODEV;
10175                 goto fail;
10176         }
10177
10178 found:
10179         intel_crtc = to_intel_crtc(crtc);
10180
10181         state = drm_atomic_state_alloc(dev);
10182         restore_state = drm_atomic_state_alloc(dev);
10183         if (!state || !restore_state) {
10184                 ret = -ENOMEM;
10185                 goto fail;
10186         }
10187
10188         state->acquire_ctx = ctx;
10189         restore_state->acquire_ctx = ctx;
10190
10191         connector_state = drm_atomic_get_connector_state(state, connector);
10192         if (IS_ERR(connector_state)) {
10193                 ret = PTR_ERR(connector_state);
10194                 goto fail;
10195         }
10196
10197         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10198         if (ret)
10199                 goto fail;
10200
10201         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10202         if (IS_ERR(crtc_state)) {
10203                 ret = PTR_ERR(crtc_state);
10204                 goto fail;
10205         }
10206
10207         crtc_state->base.active = crtc_state->base.enable = true;
10208
10209         if (!mode)
10210                 mode = &load_detect_mode;
10211
10212         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10213         if (ret)
10214                 goto fail;
10215
10216         ret = intel_modeset_disable_planes(state, crtc);
10217         if (ret)
10218                 goto fail;
10219
10220         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10221         if (!ret)
10222                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10223         if (!ret)
10224                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10225         if (ret) {
10226                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10227                 goto fail;
10228         }
10229
10230         ret = drm_atomic_commit(state);
10231         if (ret) {
10232                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10233                 goto fail;
10234         }
10235
10236         old->restore_state = restore_state;
10237         drm_atomic_state_put(state);
10238
10239         /* let the connector get through one full cycle before testing */
10240         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10241         return true;
10242
10243 fail:
10244         if (state) {
10245                 drm_atomic_state_put(state);
10246                 state = NULL;
10247         }
10248         if (restore_state) {
10249                 drm_atomic_state_put(restore_state);
10250                 restore_state = NULL;
10251         }
10252
10253         if (ret == -EDEADLK)
10254                 return ret;
10255
10256         return false;
10257 }
10258
10259 void intel_release_load_detect_pipe(struct drm_connector *connector,
10260                                     struct intel_load_detect_pipe *old,
10261                                     struct drm_modeset_acquire_ctx *ctx)
10262 {
10263         struct intel_encoder *intel_encoder =
10264                 intel_attached_encoder(connector);
10265         struct drm_encoder *encoder = &intel_encoder->base;
10266         struct drm_atomic_state *state = old->restore_state;
10267         int ret;
10268
10269         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10270                       connector->base.id, connector->name,
10271                       encoder->base.id, encoder->name);
10272
10273         if (!state)
10274                 return;
10275
10276         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10277         if (ret)
10278                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10279         drm_atomic_state_put(state);
10280 }
10281
10282 static int i9xx_pll_refclk(struct drm_device *dev,
10283                            const struct intel_crtc_state *pipe_config)
10284 {
10285         struct drm_i915_private *dev_priv = to_i915(dev);
10286         u32 dpll = pipe_config->dpll_hw_state.dpll;
10287
10288         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10289                 return dev_priv->vbt.lvds_ssc_freq;
10290         else if (HAS_PCH_SPLIT(dev_priv))
10291                 return 120000;
10292         else if (!IS_GEN2(dev_priv))
10293                 return 96000;
10294         else
10295                 return 48000;
10296 }
10297
10298 /* Returns the clock of the currently programmed mode of the given pipe. */
10299 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10300                                 struct intel_crtc_state *pipe_config)
10301 {
10302         struct drm_device *dev = crtc->base.dev;
10303         struct drm_i915_private *dev_priv = to_i915(dev);
10304         int pipe = pipe_config->cpu_transcoder;
10305         u32 dpll = pipe_config->dpll_hw_state.dpll;
10306         u32 fp;
10307         struct dpll clock;
10308         int port_clock;
10309         int refclk = i9xx_pll_refclk(dev, pipe_config);
10310
10311         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10312                 fp = pipe_config->dpll_hw_state.fp0;
10313         else
10314                 fp = pipe_config->dpll_hw_state.fp1;
10315
10316         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10317         if (IS_PINEVIEW(dev_priv)) {
10318                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10319                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10320         } else {
10321                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10322                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10323         }
10324
10325         if (!IS_GEN2(dev_priv)) {
10326                 if (IS_PINEVIEW(dev_priv))
10327                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10328                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10329                 else
10330                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10331                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10332
10333                 switch (dpll & DPLL_MODE_MASK) {
10334                 case DPLLB_MODE_DAC_SERIAL:
10335                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10336                                 5 : 10;
10337                         break;
10338                 case DPLLB_MODE_LVDS:
10339                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10340                                 7 : 14;
10341                         break;
10342                 default:
10343                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10344                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10345                         return;
10346                 }
10347
10348                 if (IS_PINEVIEW(dev_priv))
10349                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10350                 else
10351                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10352         } else {
10353                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10354                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10355
10356                 if (is_lvds) {
10357                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10358                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10359
10360                         if (lvds & LVDS_CLKB_POWER_UP)
10361                                 clock.p2 = 7;
10362                         else
10363                                 clock.p2 = 14;
10364                 } else {
10365                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10366                                 clock.p1 = 2;
10367                         else {
10368                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10369                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10370                         }
10371                         if (dpll & PLL_P2_DIVIDE_BY_4)
10372                                 clock.p2 = 4;
10373                         else
10374                                 clock.p2 = 2;
10375                 }
10376
10377                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10378         }
10379
10380         /*
10381          * This value includes pixel_multiplier. We will use
10382          * port_clock to compute adjusted_mode.crtc_clock in the
10383          * encoder's get_config() function.
10384          */
10385         pipe_config->port_clock = port_clock;
10386 }
10387
10388 int intel_dotclock_calculate(int link_freq,
10389                              const struct intel_link_m_n *m_n)
10390 {
10391         /*
10392          * The calculation for the data clock is:
10393          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10394          * But we want to avoid losing precison if possible, so:
10395          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10396          *
10397          * and the link clock is simpler:
10398          * link_clock = (m * link_clock) / n
10399          */
10400
10401         if (!m_n->link_n)
10402                 return 0;
10403
10404         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10405 }
10406
10407 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10408                                    struct intel_crtc_state *pipe_config)
10409 {
10410         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10411
10412         /* read out port_clock from the DPLL */
10413         i9xx_crtc_clock_get(crtc, pipe_config);
10414
10415         /*
10416          * In case there is an active pipe without active ports,
10417          * we may need some idea for the dotclock anyway.
10418          * Calculate one based on the FDI configuration.
10419          */
10420         pipe_config->base.adjusted_mode.crtc_clock =
10421                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10422                                          &pipe_config->fdi_m_n);
10423 }
10424
10425 /* Returns the currently programmed mode of the given encoder. */
10426 struct drm_display_mode *
10427 intel_encoder_current_mode(struct intel_encoder *encoder)
10428 {
10429         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10430         struct intel_crtc_state *crtc_state;
10431         struct drm_display_mode *mode;
10432         struct intel_crtc *crtc;
10433         enum pipe pipe;
10434
10435         if (!encoder->get_hw_state(encoder, &pipe))
10436                 return NULL;
10437
10438         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10439
10440         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10441         if (!mode)
10442                 return NULL;
10443
10444         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10445         if (!crtc_state) {
10446                 kfree(mode);
10447                 return NULL;
10448         }
10449
10450         crtc_state->base.crtc = &crtc->base;
10451
10452         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10453                 kfree(crtc_state);
10454                 kfree(mode);
10455                 return NULL;
10456         }
10457
10458         encoder->get_config(encoder, crtc_state);
10459
10460         intel_mode_from_pipe_config(mode, crtc_state);
10461
10462         kfree(crtc_state);
10463
10464         return mode;
10465 }
10466
10467 static void intel_crtc_destroy(struct drm_crtc *crtc)
10468 {
10469         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10470
10471         drm_crtc_cleanup(crtc);
10472         kfree(intel_crtc);
10473 }
10474
10475 /**
10476  * intel_wm_need_update - Check whether watermarks need updating
10477  * @plane: drm plane
10478  * @state: new plane state
10479  *
10480  * Check current plane state versus the new one to determine whether
10481  * watermarks need to be recalculated.
10482  *
10483  * Returns true or false.
10484  */
10485 static bool intel_wm_need_update(struct drm_plane *plane,
10486                                  struct drm_plane_state *state)
10487 {
10488         struct intel_plane_state *new = to_intel_plane_state(state);
10489         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10490
10491         /* Update watermarks on tiling or size changes. */
10492         if (new->base.visible != cur->base.visible)
10493                 return true;
10494
10495         if (!cur->base.fb || !new->base.fb)
10496                 return false;
10497
10498         if (cur->base.fb->modifier != new->base.fb->modifier ||
10499             cur->base.rotation != new->base.rotation ||
10500             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10501             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10502             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10503             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10504                 return true;
10505
10506         return false;
10507 }
10508
10509 static bool needs_scaling(const struct intel_plane_state *state)
10510 {
10511         int src_w = drm_rect_width(&state->base.src) >> 16;
10512         int src_h = drm_rect_height(&state->base.src) >> 16;
10513         int dst_w = drm_rect_width(&state->base.dst);
10514         int dst_h = drm_rect_height(&state->base.dst);
10515
10516         return (src_w != dst_w || src_h != dst_h);
10517 }
10518
10519 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10520                                     struct drm_crtc_state *crtc_state,
10521                                     const struct intel_plane_state *old_plane_state,
10522                                     struct drm_plane_state *plane_state)
10523 {
10524         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10525         struct drm_crtc *crtc = crtc_state->crtc;
10526         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10527         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10528         struct drm_device *dev = crtc->dev;
10529         struct drm_i915_private *dev_priv = to_i915(dev);
10530         bool mode_changed = needs_modeset(crtc_state);
10531         bool was_crtc_enabled = old_crtc_state->base.active;
10532         bool is_crtc_enabled = crtc_state->active;
10533         bool turn_off, turn_on, visible, was_visible;
10534         struct drm_framebuffer *fb = plane_state->fb;
10535         int ret;
10536
10537         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10538                 ret = skl_update_scaler_plane(
10539                         to_intel_crtc_state(crtc_state),
10540                         to_intel_plane_state(plane_state));
10541                 if (ret)
10542                         return ret;
10543         }
10544
10545         was_visible = old_plane_state->base.visible;
10546         visible = plane_state->visible;
10547
10548         if (!was_crtc_enabled && WARN_ON(was_visible))
10549                 was_visible = false;
10550
10551         /*
10552          * Visibility is calculated as if the crtc was on, but
10553          * after scaler setup everything depends on it being off
10554          * when the crtc isn't active.
10555          *
10556          * FIXME this is wrong for watermarks. Watermarks should also
10557          * be computed as if the pipe would be active. Perhaps move
10558          * per-plane wm computation to the .check_plane() hook, and
10559          * only combine the results from all planes in the current place?
10560          */
10561         if (!is_crtc_enabled) {
10562                 plane_state->visible = visible = false;
10563                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10564         }
10565
10566         if (!was_visible && !visible)
10567                 return 0;
10568
10569         if (fb != old_plane_state->base.fb)
10570                 pipe_config->fb_changed = true;
10571
10572         turn_off = was_visible && (!visible || mode_changed);
10573         turn_on = visible && (!was_visible || mode_changed);
10574
10575         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10576                          intel_crtc->base.base.id, intel_crtc->base.name,
10577                          plane->base.base.id, plane->base.name,
10578                          fb ? fb->base.id : -1);
10579
10580         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10581                          plane->base.base.id, plane->base.name,
10582                          was_visible, visible,
10583                          turn_off, turn_on, mode_changed);
10584
10585         if (turn_on) {
10586                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10587                         pipe_config->update_wm_pre = true;
10588
10589                 /* must disable cxsr around plane enable/disable */
10590                 if (plane->id != PLANE_CURSOR)
10591                         pipe_config->disable_cxsr = true;
10592         } else if (turn_off) {
10593                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10594                         pipe_config->update_wm_post = true;
10595
10596                 /* must disable cxsr around plane enable/disable */
10597                 if (plane->id != PLANE_CURSOR)
10598                         pipe_config->disable_cxsr = true;
10599         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10600                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10601                         /* FIXME bollocks */
10602                         pipe_config->update_wm_pre = true;
10603                         pipe_config->update_wm_post = true;
10604                 }
10605         }
10606
10607         if (visible || was_visible)
10608                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10609
10610         /*
10611          * ILK/SNB DVSACNTR/Sprite Enable
10612          * IVB SPR_CTL/Sprite Enable
10613          * "When in Self Refresh Big FIFO mode, a write to enable the
10614          *  plane will be internally buffered and delayed while Big FIFO
10615          *  mode is exiting."
10616          *
10617          * Which means that enabling the sprite can take an extra frame
10618          * when we start in big FIFO mode (LP1+). Thus we need to drop
10619          * down to LP0 and wait for vblank in order to make sure the
10620          * sprite gets enabled on the next vblank after the register write.
10621          * Doing otherwise would risk enabling the sprite one frame after
10622          * we've already signalled flip completion. We can resume LP1+
10623          * once the sprite has been enabled.
10624          *
10625          *
10626          * WaCxSRDisabledForSpriteScaling:ivb
10627          * IVB SPR_SCALE/Scaling Enable
10628          * "Low Power watermarks must be disabled for at least one
10629          *  frame before enabling sprite scaling, and kept disabled
10630          *  until sprite scaling is disabled."
10631          *
10632          * ILK/SNB DVSASCALE/Scaling Enable
10633          * "When in Self Refresh Big FIFO mode, scaling enable will be
10634          *  masked off while Big FIFO mode is exiting."
10635          *
10636          * Despite the w/a only being listed for IVB we assume that
10637          * the ILK/SNB note has similar ramifications, hence we apply
10638          * the w/a on all three platforms.
10639          */
10640         if (plane->id == PLANE_SPRITE0 &&
10641             (IS_GEN5(dev_priv) || IS_GEN6(dev_priv) ||
10642              IS_IVYBRIDGE(dev_priv)) &&
10643             (turn_on || (!needs_scaling(old_plane_state) &&
10644                          needs_scaling(to_intel_plane_state(plane_state)))))
10645                 pipe_config->disable_lp_wm = true;
10646
10647         return 0;
10648 }
10649
10650 static bool encoders_cloneable(const struct intel_encoder *a,
10651                                const struct intel_encoder *b)
10652 {
10653         /* masks could be asymmetric, so check both ways */
10654         return a == b || (a->cloneable & (1 << b->type) &&
10655                           b->cloneable & (1 << a->type));
10656 }
10657
10658 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10659                                          struct intel_crtc *crtc,
10660                                          struct intel_encoder *encoder)
10661 {
10662         struct intel_encoder *source_encoder;
10663         struct drm_connector *connector;
10664         struct drm_connector_state *connector_state;
10665         int i;
10666
10667         for_each_new_connector_in_state(state, connector, connector_state, i) {
10668                 if (connector_state->crtc != &crtc->base)
10669                         continue;
10670
10671                 source_encoder =
10672                         to_intel_encoder(connector_state->best_encoder);
10673                 if (!encoders_cloneable(encoder, source_encoder))
10674                         return false;
10675         }
10676
10677         return true;
10678 }
10679
10680 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10681                                    struct drm_crtc_state *crtc_state)
10682 {
10683         struct drm_device *dev = crtc->dev;
10684         struct drm_i915_private *dev_priv = to_i915(dev);
10685         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10686         struct intel_crtc_state *pipe_config =
10687                 to_intel_crtc_state(crtc_state);
10688         struct drm_atomic_state *state = crtc_state->state;
10689         int ret;
10690         bool mode_changed = needs_modeset(crtc_state);
10691
10692         if (mode_changed && !crtc_state->active)
10693                 pipe_config->update_wm_post = true;
10694
10695         if (mode_changed && crtc_state->enable &&
10696             dev_priv->display.crtc_compute_clock &&
10697             !WARN_ON(pipe_config->shared_dpll)) {
10698                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10699                                                            pipe_config);
10700                 if (ret)
10701                         return ret;
10702         }
10703
10704         if (crtc_state->color_mgmt_changed) {
10705                 ret = intel_color_check(crtc, crtc_state);
10706                 if (ret)
10707                         return ret;
10708
10709                 /*
10710                  * Changing color management on Intel hardware is
10711                  * handled as part of planes update.
10712                  */
10713                 crtc_state->planes_changed = true;
10714         }
10715
10716         ret = 0;
10717         if (dev_priv->display.compute_pipe_wm) {
10718                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10719                 if (ret) {
10720                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10721                         return ret;
10722                 }
10723         }
10724
10725         if (dev_priv->display.compute_intermediate_wm &&
10726             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10727                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10728                         return 0;
10729
10730                 /*
10731                  * Calculate 'intermediate' watermarks that satisfy both the
10732                  * old state and the new state.  We can program these
10733                  * immediately.
10734                  */
10735                 ret = dev_priv->display.compute_intermediate_wm(dev,
10736                                                                 intel_crtc,
10737                                                                 pipe_config);
10738                 if (ret) {
10739                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10740                         return ret;
10741                 }
10742         } else if (dev_priv->display.compute_intermediate_wm) {
10743                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10744                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10745         }
10746
10747         if (INTEL_GEN(dev_priv) >= 9) {
10748                 if (mode_changed)
10749                         ret = skl_update_scaler_crtc(pipe_config);
10750
10751                 if (!ret)
10752                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10753                                                             pipe_config);
10754                 if (!ret)
10755                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10756                                                          pipe_config);
10757         }
10758
10759         if (HAS_IPS(dev_priv))
10760                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10761
10762         return ret;
10763 }
10764
10765 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10766         .atomic_check = intel_crtc_atomic_check,
10767 };
10768
10769 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10770 {
10771         struct intel_connector *connector;
10772         struct drm_connector_list_iter conn_iter;
10773
10774         drm_connector_list_iter_begin(dev, &conn_iter);
10775         for_each_intel_connector_iter(connector, &conn_iter) {
10776                 if (connector->base.state->crtc)
10777                         drm_connector_put(&connector->base);
10778
10779                 if (connector->base.encoder) {
10780                         connector->base.state->best_encoder =
10781                                 connector->base.encoder;
10782                         connector->base.state->crtc =
10783                                 connector->base.encoder->crtc;
10784
10785                         drm_connector_get(&connector->base);
10786                 } else {
10787                         connector->base.state->best_encoder = NULL;
10788                         connector->base.state->crtc = NULL;
10789                 }
10790         }
10791         drm_connector_list_iter_end(&conn_iter);
10792 }
10793
10794 static void
10795 connected_sink_compute_bpp(struct intel_connector *connector,
10796                            struct intel_crtc_state *pipe_config)
10797 {
10798         const struct drm_display_info *info = &connector->base.display_info;
10799         int bpp = pipe_config->pipe_bpp;
10800
10801         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10802                       connector->base.base.id,
10803                       connector->base.name);
10804
10805         /* Don't use an invalid EDID bpc value */
10806         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10807                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10808                               bpp, info->bpc * 3);
10809                 pipe_config->pipe_bpp = info->bpc * 3;
10810         }
10811
10812         /* Clamp bpp to 8 on screens without EDID 1.4 */
10813         if (info->bpc == 0 && bpp > 24) {
10814                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10815                               bpp);
10816                 pipe_config->pipe_bpp = 24;
10817         }
10818 }
10819
10820 static int
10821 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10822                           struct intel_crtc_state *pipe_config)
10823 {
10824         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10825         struct drm_atomic_state *state;
10826         struct drm_connector *connector;
10827         struct drm_connector_state *connector_state;
10828         int bpp, i;
10829
10830         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10831             IS_CHERRYVIEW(dev_priv)))
10832                 bpp = 10*3;
10833         else if (INTEL_GEN(dev_priv) >= 5)
10834                 bpp = 12*3;
10835         else
10836                 bpp = 8*3;
10837
10838
10839         pipe_config->pipe_bpp = bpp;
10840
10841         state = pipe_config->base.state;
10842
10843         /* Clamp display bpp to EDID value */
10844         for_each_new_connector_in_state(state, connector, connector_state, i) {
10845                 if (connector_state->crtc != &crtc->base)
10846                         continue;
10847
10848                 connected_sink_compute_bpp(to_intel_connector(connector),
10849                                            pipe_config);
10850         }
10851
10852         return bpp;
10853 }
10854
10855 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10856 {
10857         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10858                         "type: 0x%x flags: 0x%x\n",
10859                 mode->crtc_clock,
10860                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10861                 mode->crtc_hsync_end, mode->crtc_htotal,
10862                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10863                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10864 }
10865
10866 static inline void
10867 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10868                       unsigned int lane_count, struct intel_link_m_n *m_n)
10869 {
10870         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10871                       id, lane_count,
10872                       m_n->gmch_m, m_n->gmch_n,
10873                       m_n->link_m, m_n->link_n, m_n->tu);
10874 }
10875
10876 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10877
10878 static const char * const output_type_str[] = {
10879         OUTPUT_TYPE(UNUSED),
10880         OUTPUT_TYPE(ANALOG),
10881         OUTPUT_TYPE(DVO),
10882         OUTPUT_TYPE(SDVO),
10883         OUTPUT_TYPE(LVDS),
10884         OUTPUT_TYPE(TVOUT),
10885         OUTPUT_TYPE(HDMI),
10886         OUTPUT_TYPE(DP),
10887         OUTPUT_TYPE(EDP),
10888         OUTPUT_TYPE(DSI),
10889         OUTPUT_TYPE(DDI),
10890         OUTPUT_TYPE(DP_MST),
10891 };
10892
10893 #undef OUTPUT_TYPE
10894
10895 static void snprintf_output_types(char *buf, size_t len,
10896                                   unsigned int output_types)
10897 {
10898         char *str = buf;
10899         int i;
10900
10901         str[0] = '\0';
10902
10903         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
10904                 int r;
10905
10906                 if ((output_types & BIT(i)) == 0)
10907                         continue;
10908
10909                 r = snprintf(str, len, "%s%s",
10910                              str != buf ? "," : "", output_type_str[i]);
10911                 if (r >= len)
10912                         break;
10913                 str += r;
10914                 len -= r;
10915
10916                 output_types &= ~BIT(i);
10917         }
10918
10919         WARN_ON_ONCE(output_types != 0);
10920 }
10921
10922 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10923                                    struct intel_crtc_state *pipe_config,
10924                                    const char *context)
10925 {
10926         struct drm_device *dev = crtc->base.dev;
10927         struct drm_i915_private *dev_priv = to_i915(dev);
10928         struct drm_plane *plane;
10929         struct intel_plane *intel_plane;
10930         struct intel_plane_state *state;
10931         struct drm_framebuffer *fb;
10932         char buf[64];
10933
10934         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10935                       crtc->base.base.id, crtc->base.name, context);
10936
10937         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
10938         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
10939                       buf, pipe_config->output_types);
10940
10941         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
10942                       transcoder_name(pipe_config->cpu_transcoder),
10943                       pipe_config->pipe_bpp, pipe_config->dither);
10944
10945         if (pipe_config->has_pch_encoder)
10946                 intel_dump_m_n_config(pipe_config, "fdi",
10947                                       pipe_config->fdi_lanes,
10948                                       &pipe_config->fdi_m_n);
10949
10950         if (pipe_config->ycbcr420)
10951                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
10952
10953         if (intel_crtc_has_dp_encoder(pipe_config)) {
10954                 intel_dump_m_n_config(pipe_config, "dp m_n",
10955                                 pipe_config->lane_count, &pipe_config->dp_m_n);
10956                 if (pipe_config->has_drrs)
10957                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
10958                                               pipe_config->lane_count,
10959                                               &pipe_config->dp_m2_n2);
10960         }
10961
10962         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10963                       pipe_config->has_audio, pipe_config->has_infoframe);
10964
10965         DRM_DEBUG_KMS("requested mode:\n");
10966         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10967         DRM_DEBUG_KMS("adjusted mode:\n");
10968         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10969         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10970         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
10971                       pipe_config->port_clock,
10972                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
10973                       pipe_config->pixel_rate);
10974
10975         if (INTEL_GEN(dev_priv) >= 9)
10976                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
10977                               crtc->num_scalers,
10978                               pipe_config->scaler_state.scaler_users,
10979                               pipe_config->scaler_state.scaler_id);
10980
10981         if (HAS_GMCH_DISPLAY(dev_priv))
10982                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10983                               pipe_config->gmch_pfit.control,
10984                               pipe_config->gmch_pfit.pgm_ratios,
10985                               pipe_config->gmch_pfit.lvds_border_bits);
10986         else
10987                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10988                               pipe_config->pch_pfit.pos,
10989                               pipe_config->pch_pfit.size,
10990                               enableddisabled(pipe_config->pch_pfit.enabled));
10991
10992         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
10993                       pipe_config->ips_enabled, pipe_config->double_wide);
10994
10995         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
10996
10997         DRM_DEBUG_KMS("planes on this crtc\n");
10998         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
10999                 struct drm_format_name_buf format_name;
11000                 intel_plane = to_intel_plane(plane);
11001                 if (intel_plane->pipe != crtc->pipe)
11002                         continue;
11003
11004                 state = to_intel_plane_state(plane->state);
11005                 fb = state->base.fb;
11006                 if (!fb) {
11007                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11008                                       plane->base.id, plane->name, state->scaler_id);
11009                         continue;
11010                 }
11011
11012                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11013                               plane->base.id, plane->name,
11014                               fb->base.id, fb->width, fb->height,
11015                               drm_get_format_name(fb->format->format, &format_name));
11016                 if (INTEL_GEN(dev_priv) >= 9)
11017                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11018                                       state->scaler_id,
11019                                       state->base.src.x1 >> 16,
11020                                       state->base.src.y1 >> 16,
11021                                       drm_rect_width(&state->base.src) >> 16,
11022                                       drm_rect_height(&state->base.src) >> 16,
11023                                       state->base.dst.x1, state->base.dst.y1,
11024                                       drm_rect_width(&state->base.dst),
11025                                       drm_rect_height(&state->base.dst));
11026         }
11027 }
11028
11029 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11030 {
11031         struct drm_device *dev = state->dev;
11032         struct drm_connector *connector;
11033         struct drm_connector_list_iter conn_iter;
11034         unsigned int used_ports = 0;
11035         unsigned int used_mst_ports = 0;
11036         bool ret = true;
11037
11038         /*
11039          * Walk the connector list instead of the encoder
11040          * list to detect the problem on ddi platforms
11041          * where there's just one encoder per digital port.
11042          */
11043         drm_connector_list_iter_begin(dev, &conn_iter);
11044         drm_for_each_connector_iter(connector, &conn_iter) {
11045                 struct drm_connector_state *connector_state;
11046                 struct intel_encoder *encoder;
11047
11048                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11049                 if (!connector_state)
11050                         connector_state = connector->state;
11051
11052                 if (!connector_state->best_encoder)
11053                         continue;
11054
11055                 encoder = to_intel_encoder(connector_state->best_encoder);
11056
11057                 WARN_ON(!connector_state->crtc);
11058
11059                 switch (encoder->type) {
11060                         unsigned int port_mask;
11061                 case INTEL_OUTPUT_DDI:
11062                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11063                                 break;
11064                         /* else: fall through */
11065                 case INTEL_OUTPUT_DP:
11066                 case INTEL_OUTPUT_HDMI:
11067                 case INTEL_OUTPUT_EDP:
11068                         port_mask = 1 << encoder->port;
11069
11070                         /* the same port mustn't appear more than once */
11071                         if (used_ports & port_mask)
11072                                 ret = false;
11073
11074                         used_ports |= port_mask;
11075                         break;
11076                 case INTEL_OUTPUT_DP_MST:
11077                         used_mst_ports |=
11078                                 1 << encoder->port;
11079                         break;
11080                 default:
11081                         break;
11082                 }
11083         }
11084         drm_connector_list_iter_end(&conn_iter);
11085
11086         /* can't mix MST and SST/HDMI on the same port */
11087         if (used_ports & used_mst_ports)
11088                 return false;
11089
11090         return ret;
11091 }
11092
11093 static void
11094 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11095 {
11096         struct drm_i915_private *dev_priv =
11097                 to_i915(crtc_state->base.crtc->dev);
11098         struct intel_crtc_scaler_state scaler_state;
11099         struct intel_dpll_hw_state dpll_hw_state;
11100         struct intel_shared_dpll *shared_dpll;
11101         struct intel_crtc_wm_state wm_state;
11102         bool force_thru, ips_force_disable;
11103
11104         /* FIXME: before the switch to atomic started, a new pipe_config was
11105          * kzalloc'd. Code that depends on any field being zero should be
11106          * fixed, so that the crtc_state can be safely duplicated. For now,
11107          * only fields that are know to not cause problems are preserved. */
11108
11109         scaler_state = crtc_state->scaler_state;
11110         shared_dpll = crtc_state->shared_dpll;
11111         dpll_hw_state = crtc_state->dpll_hw_state;
11112         force_thru = crtc_state->pch_pfit.force_thru;
11113         ips_force_disable = crtc_state->ips_force_disable;
11114         if (IS_G4X(dev_priv) ||
11115             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11116                 wm_state = crtc_state->wm;
11117
11118         /* Keep base drm_crtc_state intact, only clear our extended struct */
11119         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11120         memset(&crtc_state->base + 1, 0,
11121                sizeof(*crtc_state) - sizeof(crtc_state->base));
11122
11123         crtc_state->scaler_state = scaler_state;
11124         crtc_state->shared_dpll = shared_dpll;
11125         crtc_state->dpll_hw_state = dpll_hw_state;
11126         crtc_state->pch_pfit.force_thru = force_thru;
11127         crtc_state->ips_force_disable = ips_force_disable;
11128         if (IS_G4X(dev_priv) ||
11129             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11130                 crtc_state->wm = wm_state;
11131 }
11132
11133 static int
11134 intel_modeset_pipe_config(struct drm_crtc *crtc,
11135                           struct intel_crtc_state *pipe_config)
11136 {
11137         struct drm_atomic_state *state = pipe_config->base.state;
11138         struct intel_encoder *encoder;
11139         struct drm_connector *connector;
11140         struct drm_connector_state *connector_state;
11141         int base_bpp, ret = -EINVAL;
11142         int i;
11143         bool retry = true;
11144
11145         clear_intel_crtc_state(pipe_config);
11146
11147         pipe_config->cpu_transcoder =
11148                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11149
11150         /*
11151          * Sanitize sync polarity flags based on requested ones. If neither
11152          * positive or negative polarity is requested, treat this as meaning
11153          * negative polarity.
11154          */
11155         if (!(pipe_config->base.adjusted_mode.flags &
11156               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11157                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11158
11159         if (!(pipe_config->base.adjusted_mode.flags &
11160               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11161                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11162
11163         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11164                                              pipe_config);
11165         if (base_bpp < 0)
11166                 goto fail;
11167
11168         /*
11169          * Determine the real pipe dimensions. Note that stereo modes can
11170          * increase the actual pipe size due to the frame doubling and
11171          * insertion of additional space for blanks between the frame. This
11172          * is stored in the crtc timings. We use the requested mode to do this
11173          * computation to clearly distinguish it from the adjusted mode, which
11174          * can be changed by the connectors in the below retry loop.
11175          */
11176         drm_mode_get_hv_timing(&pipe_config->base.mode,
11177                                &pipe_config->pipe_src_w,
11178                                &pipe_config->pipe_src_h);
11179
11180         for_each_new_connector_in_state(state, connector, connector_state, i) {
11181                 if (connector_state->crtc != crtc)
11182                         continue;
11183
11184                 encoder = to_intel_encoder(connector_state->best_encoder);
11185
11186                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11187                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11188                         goto fail;
11189                 }
11190
11191                 /*
11192                  * Determine output_types before calling the .compute_config()
11193                  * hooks so that the hooks can use this information safely.
11194                  */
11195                 if (encoder->compute_output_type)
11196                         pipe_config->output_types |=
11197                                 BIT(encoder->compute_output_type(encoder, pipe_config,
11198                                                                  connector_state));
11199                 else
11200                         pipe_config->output_types |= BIT(encoder->type);
11201         }
11202
11203 encoder_retry:
11204         /* Ensure the port clock defaults are reset when retrying. */
11205         pipe_config->port_clock = 0;
11206         pipe_config->pixel_multiplier = 1;
11207
11208         /* Fill in default crtc timings, allow encoders to overwrite them. */
11209         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11210                               CRTC_STEREO_DOUBLE);
11211
11212         /* Pass our mode to the connectors and the CRTC to give them a chance to
11213          * adjust it according to limitations or connector properties, and also
11214          * a chance to reject the mode entirely.
11215          */
11216         for_each_new_connector_in_state(state, connector, connector_state, i) {
11217                 if (connector_state->crtc != crtc)
11218                         continue;
11219
11220                 encoder = to_intel_encoder(connector_state->best_encoder);
11221
11222                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
11223                         DRM_DEBUG_KMS("Encoder config failure\n");
11224                         goto fail;
11225                 }
11226         }
11227
11228         /* Set default port clock if not overwritten by the encoder. Needs to be
11229          * done afterwards in case the encoder adjusts the mode. */
11230         if (!pipe_config->port_clock)
11231                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11232                         * pipe_config->pixel_multiplier;
11233
11234         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11235         if (ret < 0) {
11236                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11237                 goto fail;
11238         }
11239
11240         if (ret == RETRY) {
11241                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11242                         ret = -EINVAL;
11243                         goto fail;
11244                 }
11245
11246                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11247                 retry = false;
11248                 goto encoder_retry;
11249         }
11250
11251         /* Dithering seems to not pass-through bits correctly when it should, so
11252          * only enable it on 6bpc panels and when its not a compliance
11253          * test requesting 6bpc video pattern.
11254          */
11255         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11256                 !pipe_config->dither_force_disable;
11257         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11258                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11259
11260 fail:
11261         return ret;
11262 }
11263
11264 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11265 {
11266         int diff;
11267
11268         if (clock1 == clock2)
11269                 return true;
11270
11271         if (!clock1 || !clock2)
11272                 return false;
11273
11274         diff = abs(clock1 - clock2);
11275
11276         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11277                 return true;
11278
11279         return false;
11280 }
11281
11282 static bool
11283 intel_compare_m_n(unsigned int m, unsigned int n,
11284                   unsigned int m2, unsigned int n2,
11285                   bool exact)
11286 {
11287         if (m == m2 && n == n2)
11288                 return true;
11289
11290         if (exact || !m || !n || !m2 || !n2)
11291                 return false;
11292
11293         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11294
11295         if (n > n2) {
11296                 while (n > n2) {
11297                         m2 <<= 1;
11298                         n2 <<= 1;
11299                 }
11300         } else if (n < n2) {
11301                 while (n < n2) {
11302                         m <<= 1;
11303                         n <<= 1;
11304                 }
11305         }
11306
11307         if (n != n2)
11308                 return false;
11309
11310         return intel_fuzzy_clock_check(m, m2);
11311 }
11312
11313 static bool
11314 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11315                        struct intel_link_m_n *m2_n2,
11316                        bool adjust)
11317 {
11318         if (m_n->tu == m2_n2->tu &&
11319             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11320                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11321             intel_compare_m_n(m_n->link_m, m_n->link_n,
11322                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11323                 if (adjust)
11324                         *m2_n2 = *m_n;
11325
11326                 return true;
11327         }
11328
11329         return false;
11330 }
11331
11332 static void __printf(3, 4)
11333 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11334 {
11335         struct va_format vaf;
11336         va_list args;
11337
11338         va_start(args, format);
11339         vaf.fmt = format;
11340         vaf.va = &args;
11341
11342         if (adjust)
11343                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11344         else
11345                 drm_err("mismatch in %s %pV", name, &vaf);
11346
11347         va_end(args);
11348 }
11349
11350 static bool
11351 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11352                           struct intel_crtc_state *current_config,
11353                           struct intel_crtc_state *pipe_config,
11354                           bool adjust)
11355 {
11356         bool ret = true;
11357         bool fixup_inherited = adjust &&
11358                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11359                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11360
11361 #define PIPE_CONF_CHECK_X(name) do { \
11362         if (current_config->name != pipe_config->name) { \
11363                 pipe_config_err(adjust, __stringify(name), \
11364                           "(expected 0x%08x, found 0x%08x)\n", \
11365                           current_config->name, \
11366                           pipe_config->name); \
11367                 ret = false; \
11368         } \
11369 } while (0)
11370
11371 #define PIPE_CONF_CHECK_I(name) do { \
11372         if (current_config->name != pipe_config->name) { \
11373                 pipe_config_err(adjust, __stringify(name), \
11374                           "(expected %i, found %i)\n", \
11375                           current_config->name, \
11376                           pipe_config->name); \
11377                 ret = false; \
11378         } \
11379 } while (0)
11380
11381 #define PIPE_CONF_CHECK_BOOL(name) do { \
11382         if (current_config->name != pipe_config->name) { \
11383                 pipe_config_err(adjust, __stringify(name), \
11384                           "(expected %s, found %s)\n", \
11385                           yesno(current_config->name), \
11386                           yesno(pipe_config->name)); \
11387                 ret = false; \
11388         } \
11389 } while (0)
11390
11391 /*
11392  * Checks state where we only read out the enabling, but not the entire
11393  * state itself (like full infoframes or ELD for audio). These states
11394  * require a full modeset on bootup to fix up.
11395  */
11396 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
11397         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11398                 PIPE_CONF_CHECK_BOOL(name); \
11399         } else { \
11400                 pipe_config_err(adjust, __stringify(name), \
11401                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11402                           yesno(current_config->name), \
11403                           yesno(pipe_config->name)); \
11404                 ret = false; \
11405         } \
11406 } while (0)
11407
11408 #define PIPE_CONF_CHECK_P(name) do { \
11409         if (current_config->name != pipe_config->name) { \
11410                 pipe_config_err(adjust, __stringify(name), \
11411                           "(expected %p, found %p)\n", \
11412                           current_config->name, \
11413                           pipe_config->name); \
11414                 ret = false; \
11415         } \
11416 } while (0)
11417
11418 #define PIPE_CONF_CHECK_M_N(name) do { \
11419         if (!intel_compare_link_m_n(&current_config->name, \
11420                                     &pipe_config->name,\
11421                                     adjust)) { \
11422                 pipe_config_err(adjust, __stringify(name), \
11423                           "(expected tu %i gmch %i/%i link %i/%i, " \
11424                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11425                           current_config->name.tu, \
11426                           current_config->name.gmch_m, \
11427                           current_config->name.gmch_n, \
11428                           current_config->name.link_m, \
11429                           current_config->name.link_n, \
11430                           pipe_config->name.tu, \
11431                           pipe_config->name.gmch_m, \
11432                           pipe_config->name.gmch_n, \
11433                           pipe_config->name.link_m, \
11434                           pipe_config->name.link_n); \
11435                 ret = false; \
11436         } \
11437 } while (0)
11438
11439 /* This is required for BDW+ where there is only one set of registers for
11440  * switching between high and low RR.
11441  * This macro can be used whenever a comparison has to be made between one
11442  * hw state and multiple sw state variables.
11443  */
11444 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
11445         if (!intel_compare_link_m_n(&current_config->name, \
11446                                     &pipe_config->name, adjust) && \
11447             !intel_compare_link_m_n(&current_config->alt_name, \
11448                                     &pipe_config->name, adjust)) { \
11449                 pipe_config_err(adjust, __stringify(name), \
11450                           "(expected tu %i gmch %i/%i link %i/%i, " \
11451                           "or tu %i gmch %i/%i link %i/%i, " \
11452                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11453                           current_config->name.tu, \
11454                           current_config->name.gmch_m, \
11455                           current_config->name.gmch_n, \
11456                           current_config->name.link_m, \
11457                           current_config->name.link_n, \
11458                           current_config->alt_name.tu, \
11459                           current_config->alt_name.gmch_m, \
11460                           current_config->alt_name.gmch_n, \
11461                           current_config->alt_name.link_m, \
11462                           current_config->alt_name.link_n, \
11463                           pipe_config->name.tu, \
11464                           pipe_config->name.gmch_m, \
11465                           pipe_config->name.gmch_n, \
11466                           pipe_config->name.link_m, \
11467                           pipe_config->name.link_n); \
11468                 ret = false; \
11469         } \
11470 } while (0)
11471
11472 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
11473         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11474                 pipe_config_err(adjust, __stringify(name), \
11475                           "(%x) (expected %i, found %i)\n", \
11476                           (mask), \
11477                           current_config->name & (mask), \
11478                           pipe_config->name & (mask)); \
11479                 ret = false; \
11480         } \
11481 } while (0)
11482
11483 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
11484         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11485                 pipe_config_err(adjust, __stringify(name), \
11486                           "(expected %i, found %i)\n", \
11487                           current_config->name, \
11488                           pipe_config->name); \
11489                 ret = false; \
11490         } \
11491 } while (0)
11492
11493 #define PIPE_CONF_QUIRK(quirk)  \
11494         ((current_config->quirks | pipe_config->quirks) & (quirk))
11495
11496         PIPE_CONF_CHECK_I(cpu_transcoder);
11497
11498         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11499         PIPE_CONF_CHECK_I(fdi_lanes);
11500         PIPE_CONF_CHECK_M_N(fdi_m_n);
11501
11502         PIPE_CONF_CHECK_I(lane_count);
11503         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11504
11505         if (INTEL_GEN(dev_priv) < 8) {
11506                 PIPE_CONF_CHECK_M_N(dp_m_n);
11507
11508                 if (current_config->has_drrs)
11509                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11510         } else
11511                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11512
11513         PIPE_CONF_CHECK_X(output_types);
11514
11515         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11516         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11517         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11518         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11519         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11520         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11521
11522         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11523         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11524         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11525         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11526         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11527         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11528
11529         PIPE_CONF_CHECK_I(pixel_multiplier);
11530         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11531         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11532             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11533                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11534
11535         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11536         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11537         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11538         PIPE_CONF_CHECK_BOOL(ycbcr420);
11539
11540         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11541
11542         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11543                               DRM_MODE_FLAG_INTERLACE);
11544
11545         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11546                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11547                                       DRM_MODE_FLAG_PHSYNC);
11548                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11549                                       DRM_MODE_FLAG_NHSYNC);
11550                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11551                                       DRM_MODE_FLAG_PVSYNC);
11552                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11553                                       DRM_MODE_FLAG_NVSYNC);
11554         }
11555
11556         PIPE_CONF_CHECK_X(gmch_pfit.control);
11557         /* pfit ratios are autocomputed by the hw on gen4+ */
11558         if (INTEL_GEN(dev_priv) < 4)
11559                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11560         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11561
11562         if (!adjust) {
11563                 PIPE_CONF_CHECK_I(pipe_src_w);
11564                 PIPE_CONF_CHECK_I(pipe_src_h);
11565
11566                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11567                 if (current_config->pch_pfit.enabled) {
11568                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11569                         PIPE_CONF_CHECK_X(pch_pfit.size);
11570                 }
11571
11572                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11573                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11574         }
11575
11576         PIPE_CONF_CHECK_BOOL(double_wide);
11577
11578         PIPE_CONF_CHECK_P(shared_dpll);
11579         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11580         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11581         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11582         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11583         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11584         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11585         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11586         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11587         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11588         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11589         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11590         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11591         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11592         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11593         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11594         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11595         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11596         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11597         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11598         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11599         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11600         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
11601         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
11602         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
11603         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
11604         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
11605         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
11606         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
11607         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
11608         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
11609         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
11610
11611         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11612         PIPE_CONF_CHECK_X(dsi_pll.div);
11613
11614         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11615                 PIPE_CONF_CHECK_I(pipe_bpp);
11616
11617         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11618         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11619
11620         PIPE_CONF_CHECK_I(min_voltage_level);
11621
11622 #undef PIPE_CONF_CHECK_X
11623 #undef PIPE_CONF_CHECK_I
11624 #undef PIPE_CONF_CHECK_BOOL
11625 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11626 #undef PIPE_CONF_CHECK_P
11627 #undef PIPE_CONF_CHECK_FLAGS
11628 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11629 #undef PIPE_CONF_QUIRK
11630
11631         return ret;
11632 }
11633
11634 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11635                                            const struct intel_crtc_state *pipe_config)
11636 {
11637         if (pipe_config->has_pch_encoder) {
11638                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11639                                                             &pipe_config->fdi_m_n);
11640                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11641
11642                 /*
11643                  * FDI already provided one idea for the dotclock.
11644                  * Yell if the encoder disagrees.
11645                  */
11646                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11647                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11648                      fdi_dotclock, dotclock);
11649         }
11650 }
11651
11652 static void verify_wm_state(struct drm_crtc *crtc,
11653                             struct drm_crtc_state *new_state)
11654 {
11655         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11656         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11657         struct skl_pipe_wm hw_wm, *sw_wm;
11658         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11659         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11660         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11661         const enum pipe pipe = intel_crtc->pipe;
11662         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11663
11664         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11665                 return;
11666
11667         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11668         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11669
11670         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11671         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11672
11673         if (INTEL_GEN(dev_priv) >= 11)
11674                 if (hw_ddb.enabled_slices != sw_ddb->enabled_slices)
11675                         DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
11676                                   sw_ddb->enabled_slices,
11677                                   hw_ddb.enabled_slices);
11678         /* planes */
11679         for_each_universal_plane(dev_priv, pipe, plane) {
11680                 hw_plane_wm = &hw_wm.planes[plane];
11681                 sw_plane_wm = &sw_wm->planes[plane];
11682
11683                 /* Watermarks */
11684                 for (level = 0; level <= max_level; level++) {
11685                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11686                                                 &sw_plane_wm->wm[level]))
11687                                 continue;
11688
11689                         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",
11690                                   pipe_name(pipe), plane + 1, level,
11691                                   sw_plane_wm->wm[level].plane_en,
11692                                   sw_plane_wm->wm[level].plane_res_b,
11693                                   sw_plane_wm->wm[level].plane_res_l,
11694                                   hw_plane_wm->wm[level].plane_en,
11695                                   hw_plane_wm->wm[level].plane_res_b,
11696                                   hw_plane_wm->wm[level].plane_res_l);
11697                 }
11698
11699                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11700                                          &sw_plane_wm->trans_wm)) {
11701                         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",
11702                                   pipe_name(pipe), plane + 1,
11703                                   sw_plane_wm->trans_wm.plane_en,
11704                                   sw_plane_wm->trans_wm.plane_res_b,
11705                                   sw_plane_wm->trans_wm.plane_res_l,
11706                                   hw_plane_wm->trans_wm.plane_en,
11707                                   hw_plane_wm->trans_wm.plane_res_b,
11708                                   hw_plane_wm->trans_wm.plane_res_l);
11709                 }
11710
11711                 /* DDB */
11712                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11713                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11714
11715                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11716                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11717                                   pipe_name(pipe), plane + 1,
11718                                   sw_ddb_entry->start, sw_ddb_entry->end,
11719                                   hw_ddb_entry->start, hw_ddb_entry->end);
11720                 }
11721         }
11722
11723         /*
11724          * cursor
11725          * If the cursor plane isn't active, we may not have updated it's ddb
11726          * allocation. In that case since the ddb allocation will be updated
11727          * once the plane becomes visible, we can skip this check
11728          */
11729         if (1) {
11730                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11731                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11732
11733                 /* Watermarks */
11734                 for (level = 0; level <= max_level; level++) {
11735                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11736                                                 &sw_plane_wm->wm[level]))
11737                                 continue;
11738
11739                         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",
11740                                   pipe_name(pipe), level,
11741                                   sw_plane_wm->wm[level].plane_en,
11742                                   sw_plane_wm->wm[level].plane_res_b,
11743                                   sw_plane_wm->wm[level].plane_res_l,
11744                                   hw_plane_wm->wm[level].plane_en,
11745                                   hw_plane_wm->wm[level].plane_res_b,
11746                                   hw_plane_wm->wm[level].plane_res_l);
11747                 }
11748
11749                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11750                                          &sw_plane_wm->trans_wm)) {
11751                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11752                                   pipe_name(pipe),
11753                                   sw_plane_wm->trans_wm.plane_en,
11754                                   sw_plane_wm->trans_wm.plane_res_b,
11755                                   sw_plane_wm->trans_wm.plane_res_l,
11756                                   hw_plane_wm->trans_wm.plane_en,
11757                                   hw_plane_wm->trans_wm.plane_res_b,
11758                                   hw_plane_wm->trans_wm.plane_res_l);
11759                 }
11760
11761                 /* DDB */
11762                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11763                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11764
11765                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11766                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11767                                   pipe_name(pipe),
11768                                   sw_ddb_entry->start, sw_ddb_entry->end,
11769                                   hw_ddb_entry->start, hw_ddb_entry->end);
11770                 }
11771         }
11772 }
11773
11774 static void
11775 verify_connector_state(struct drm_device *dev,
11776                        struct drm_atomic_state *state,
11777                        struct drm_crtc *crtc)
11778 {
11779         struct drm_connector *connector;
11780         struct drm_connector_state *new_conn_state;
11781         int i;
11782
11783         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11784                 struct drm_encoder *encoder = connector->encoder;
11785                 struct drm_crtc_state *crtc_state = NULL;
11786
11787                 if (new_conn_state->crtc != crtc)
11788                         continue;
11789
11790                 if (crtc)
11791                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11792
11793                 intel_connector_verify_state(crtc_state, new_conn_state);
11794
11795                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11796                      "connector's atomic encoder doesn't match legacy encoder\n");
11797         }
11798 }
11799
11800 static void
11801 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11802 {
11803         struct intel_encoder *encoder;
11804         struct drm_connector *connector;
11805         struct drm_connector_state *old_conn_state, *new_conn_state;
11806         int i;
11807
11808         for_each_intel_encoder(dev, encoder) {
11809                 bool enabled = false, found = false;
11810                 enum pipe pipe;
11811
11812                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11813                               encoder->base.base.id,
11814                               encoder->base.name);
11815
11816                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11817                                                    new_conn_state, i) {
11818                         if (old_conn_state->best_encoder == &encoder->base)
11819                                 found = true;
11820
11821                         if (new_conn_state->best_encoder != &encoder->base)
11822                                 continue;
11823                         found = enabled = true;
11824
11825                         I915_STATE_WARN(new_conn_state->crtc !=
11826                                         encoder->base.crtc,
11827                              "connector's crtc doesn't match encoder crtc\n");
11828                 }
11829
11830                 if (!found)
11831                         continue;
11832
11833                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11834                      "encoder's enabled state mismatch "
11835                      "(expected %i, found %i)\n",
11836                      !!encoder->base.crtc, enabled);
11837
11838                 if (!encoder->base.crtc) {
11839                         bool active;
11840
11841                         active = encoder->get_hw_state(encoder, &pipe);
11842                         I915_STATE_WARN(active,
11843                              "encoder detached but still enabled on pipe %c.\n",
11844                              pipe_name(pipe));
11845                 }
11846         }
11847 }
11848
11849 static void
11850 verify_crtc_state(struct drm_crtc *crtc,
11851                   struct drm_crtc_state *old_crtc_state,
11852                   struct drm_crtc_state *new_crtc_state)
11853 {
11854         struct drm_device *dev = crtc->dev;
11855         struct drm_i915_private *dev_priv = to_i915(dev);
11856         struct intel_encoder *encoder;
11857         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11858         struct intel_crtc_state *pipe_config, *sw_config;
11859         struct drm_atomic_state *old_state;
11860         bool active;
11861
11862         old_state = old_crtc_state->state;
11863         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11864         pipe_config = to_intel_crtc_state(old_crtc_state);
11865         memset(pipe_config, 0, sizeof(*pipe_config));
11866         pipe_config->base.crtc = crtc;
11867         pipe_config->base.state = old_state;
11868
11869         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11870
11871         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11872
11873         /* we keep both pipes enabled on 830 */
11874         if (IS_I830(dev_priv))
11875                 active = new_crtc_state->active;
11876
11877         I915_STATE_WARN(new_crtc_state->active != active,
11878              "crtc active state doesn't match with hw state "
11879              "(expected %i, found %i)\n", new_crtc_state->active, active);
11880
11881         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11882              "transitional active state does not match atomic hw state "
11883              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11884
11885         for_each_encoder_on_crtc(dev, crtc, encoder) {
11886                 enum pipe pipe;
11887
11888                 active = encoder->get_hw_state(encoder, &pipe);
11889                 I915_STATE_WARN(active != new_crtc_state->active,
11890                         "[ENCODER:%i] active %i with crtc active %i\n",
11891                         encoder->base.base.id, active, new_crtc_state->active);
11892
11893                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11894                                 "Encoder connected to wrong pipe %c\n",
11895                                 pipe_name(pipe));
11896
11897                 if (active)
11898                         encoder->get_config(encoder, pipe_config);
11899         }
11900
11901         intel_crtc_compute_pixel_rate(pipe_config);
11902
11903         if (!new_crtc_state->active)
11904                 return;
11905
11906         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11907
11908         sw_config = to_intel_crtc_state(new_crtc_state);
11909         if (!intel_pipe_config_compare(dev_priv, sw_config,
11910                                        pipe_config, false)) {
11911                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11912                 intel_dump_pipe_config(intel_crtc, pipe_config,
11913                                        "[hw state]");
11914                 intel_dump_pipe_config(intel_crtc, sw_config,
11915                                        "[sw state]");
11916         }
11917 }
11918
11919 static void
11920 intel_verify_planes(struct intel_atomic_state *state)
11921 {
11922         struct intel_plane *plane;
11923         const struct intel_plane_state *plane_state;
11924         int i;
11925
11926         for_each_new_intel_plane_in_state(state, plane,
11927                                           plane_state, i)
11928                 assert_plane(plane, plane_state->base.visible);
11929 }
11930
11931 static void
11932 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11933                          struct intel_shared_dpll *pll,
11934                          struct drm_crtc *crtc,
11935                          struct drm_crtc_state *new_state)
11936 {
11937         struct intel_dpll_hw_state dpll_hw_state;
11938         unsigned int crtc_mask;
11939         bool active;
11940
11941         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11942
11943         DRM_DEBUG_KMS("%s\n", pll->info->name);
11944
11945         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
11946
11947         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
11948                 I915_STATE_WARN(!pll->on && pll->active_mask,
11949                      "pll in active use but not on in sw tracking\n");
11950                 I915_STATE_WARN(pll->on && !pll->active_mask,
11951                      "pll is on but not used by any active crtc\n");
11952                 I915_STATE_WARN(pll->on != active,
11953                      "pll on state mismatch (expected %i, found %i)\n",
11954                      pll->on, active);
11955         }
11956
11957         if (!crtc) {
11958                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
11959                                 "more active pll users than references: %x vs %x\n",
11960                                 pll->active_mask, pll->state.crtc_mask);
11961
11962                 return;
11963         }
11964
11965         crtc_mask = drm_crtc_mask(crtc);
11966
11967         if (new_state->active)
11968                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
11969                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
11970                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11971         else
11972                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11973                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
11974                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11975
11976         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
11977                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
11978                         crtc_mask, pll->state.crtc_mask);
11979
11980         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
11981                                           &dpll_hw_state,
11982                                           sizeof(dpll_hw_state)),
11983                         "pll hw state mismatch\n");
11984 }
11985
11986 static void
11987 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
11988                          struct drm_crtc_state *old_crtc_state,
11989                          struct drm_crtc_state *new_crtc_state)
11990 {
11991         struct drm_i915_private *dev_priv = to_i915(dev);
11992         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
11993         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
11994
11995         if (new_state->shared_dpll)
11996                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
11997
11998         if (old_state->shared_dpll &&
11999             old_state->shared_dpll != new_state->shared_dpll) {
12000                 unsigned int crtc_mask = drm_crtc_mask(crtc);
12001                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12002
12003                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12004                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12005                                 pipe_name(drm_crtc_index(crtc)));
12006                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12007                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12008                                 pipe_name(drm_crtc_index(crtc)));
12009         }
12010 }
12011
12012 static void
12013 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12014                           struct drm_atomic_state *state,
12015                           struct drm_crtc_state *old_state,
12016                           struct drm_crtc_state *new_state)
12017 {
12018         if (!needs_modeset(new_state) &&
12019             !to_intel_crtc_state(new_state)->update_pipe)
12020                 return;
12021
12022         verify_wm_state(crtc, new_state);
12023         verify_connector_state(crtc->dev, state, crtc);
12024         verify_crtc_state(crtc, old_state, new_state);
12025         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12026 }
12027
12028 static void
12029 verify_disabled_dpll_state(struct drm_device *dev)
12030 {
12031         struct drm_i915_private *dev_priv = to_i915(dev);
12032         int i;
12033
12034         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12035                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12036 }
12037
12038 static void
12039 intel_modeset_verify_disabled(struct drm_device *dev,
12040                               struct drm_atomic_state *state)
12041 {
12042         verify_encoder_state(dev, state);
12043         verify_connector_state(dev, state, NULL);
12044         verify_disabled_dpll_state(dev);
12045 }
12046
12047 static void update_scanline_offset(struct intel_crtc *crtc)
12048 {
12049         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12050
12051         /*
12052          * The scanline counter increments at the leading edge of hsync.
12053          *
12054          * On most platforms it starts counting from vtotal-1 on the
12055          * first active line. That means the scanline counter value is
12056          * always one less than what we would expect. Ie. just after
12057          * start of vblank, which also occurs at start of hsync (on the
12058          * last active line), the scanline counter will read vblank_start-1.
12059          *
12060          * On gen2 the scanline counter starts counting from 1 instead
12061          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12062          * to keep the value positive), instead of adding one.
12063          *
12064          * On HSW+ the behaviour of the scanline counter depends on the output
12065          * type. For DP ports it behaves like most other platforms, but on HDMI
12066          * there's an extra 1 line difference. So we need to add two instead of
12067          * one to the value.
12068          *
12069          * On VLV/CHV DSI the scanline counter would appear to increment
12070          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12071          * that means we can't tell whether we're in vblank or not while
12072          * we're on that particular line. We must still set scanline_offset
12073          * to 1 so that the vblank timestamps come out correct when we query
12074          * the scanline counter from within the vblank interrupt handler.
12075          * However if queried just before the start of vblank we'll get an
12076          * answer that's slightly in the future.
12077          */
12078         if (IS_GEN2(dev_priv)) {
12079                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
12080                 int vtotal;
12081
12082                 vtotal = adjusted_mode->crtc_vtotal;
12083                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12084                         vtotal /= 2;
12085
12086                 crtc->scanline_offset = vtotal - 1;
12087         } else if (HAS_DDI(dev_priv) &&
12088                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
12089                 crtc->scanline_offset = 2;
12090         } else
12091                 crtc->scanline_offset = 1;
12092 }
12093
12094 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12095 {
12096         struct drm_device *dev = state->dev;
12097         struct drm_i915_private *dev_priv = to_i915(dev);
12098         struct drm_crtc *crtc;
12099         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12100         int i;
12101
12102         if (!dev_priv->display.crtc_compute_clock)
12103                 return;
12104
12105         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12106                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12107                 struct intel_shared_dpll *old_dpll =
12108                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12109
12110                 if (!needs_modeset(new_crtc_state))
12111                         continue;
12112
12113                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12114
12115                 if (!old_dpll)
12116                         continue;
12117
12118                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12119         }
12120 }
12121
12122 /*
12123  * This implements the workaround described in the "notes" section of the mode
12124  * set sequence documentation. When going from no pipes or single pipe to
12125  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12126  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12127  */
12128 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12129 {
12130         struct drm_crtc_state *crtc_state;
12131         struct intel_crtc *intel_crtc;
12132         struct drm_crtc *crtc;
12133         struct intel_crtc_state *first_crtc_state = NULL;
12134         struct intel_crtc_state *other_crtc_state = NULL;
12135         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12136         int i;
12137
12138         /* look at all crtc's that are going to be enabled in during modeset */
12139         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12140                 intel_crtc = to_intel_crtc(crtc);
12141
12142                 if (!crtc_state->active || !needs_modeset(crtc_state))
12143                         continue;
12144
12145                 if (first_crtc_state) {
12146                         other_crtc_state = to_intel_crtc_state(crtc_state);
12147                         break;
12148                 } else {
12149                         first_crtc_state = to_intel_crtc_state(crtc_state);
12150                         first_pipe = intel_crtc->pipe;
12151                 }
12152         }
12153
12154         /* No workaround needed? */
12155         if (!first_crtc_state)
12156                 return 0;
12157
12158         /* w/a possibly needed, check how many crtc's are already enabled. */
12159         for_each_intel_crtc(state->dev, intel_crtc) {
12160                 struct intel_crtc_state *pipe_config;
12161
12162                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12163                 if (IS_ERR(pipe_config))
12164                         return PTR_ERR(pipe_config);
12165
12166                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12167
12168                 if (!pipe_config->base.active ||
12169                     needs_modeset(&pipe_config->base))
12170                         continue;
12171
12172                 /* 2 or more enabled crtcs means no need for w/a */
12173                 if (enabled_pipe != INVALID_PIPE)
12174                         return 0;
12175
12176                 enabled_pipe = intel_crtc->pipe;
12177         }
12178
12179         if (enabled_pipe != INVALID_PIPE)
12180                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12181         else if (other_crtc_state)
12182                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12183
12184         return 0;
12185 }
12186
12187 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12188 {
12189         struct drm_crtc *crtc;
12190
12191         /* Add all pipes to the state */
12192         for_each_crtc(state->dev, crtc) {
12193                 struct drm_crtc_state *crtc_state;
12194
12195                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12196                 if (IS_ERR(crtc_state))
12197                         return PTR_ERR(crtc_state);
12198         }
12199
12200         return 0;
12201 }
12202
12203 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12204 {
12205         struct drm_crtc *crtc;
12206
12207         /*
12208          * Add all pipes to the state, and force
12209          * a modeset on all the active ones.
12210          */
12211         for_each_crtc(state->dev, crtc) {
12212                 struct drm_crtc_state *crtc_state;
12213                 int ret;
12214
12215                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12216                 if (IS_ERR(crtc_state))
12217                         return PTR_ERR(crtc_state);
12218
12219                 if (!crtc_state->active || needs_modeset(crtc_state))
12220                         continue;
12221
12222                 crtc_state->mode_changed = true;
12223
12224                 ret = drm_atomic_add_affected_connectors(state, crtc);
12225                 if (ret)
12226                         return ret;
12227
12228                 ret = drm_atomic_add_affected_planes(state, crtc);
12229                 if (ret)
12230                         return ret;
12231         }
12232
12233         return 0;
12234 }
12235
12236 static int intel_modeset_checks(struct drm_atomic_state *state)
12237 {
12238         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12239         struct drm_i915_private *dev_priv = to_i915(state->dev);
12240         struct drm_crtc *crtc;
12241         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12242         int ret = 0, i;
12243
12244         if (!check_digital_port_conflicts(state)) {
12245                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12246                 return -EINVAL;
12247         }
12248
12249         intel_state->modeset = true;
12250         intel_state->active_crtcs = dev_priv->active_crtcs;
12251         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12252         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12253
12254         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12255                 if (new_crtc_state->active)
12256                         intel_state->active_crtcs |= 1 << i;
12257                 else
12258                         intel_state->active_crtcs &= ~(1 << i);
12259
12260                 if (old_crtc_state->active != new_crtc_state->active)
12261                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12262         }
12263
12264         /*
12265          * See if the config requires any additional preparation, e.g.
12266          * to adjust global state with pipes off.  We need to do this
12267          * here so we can get the modeset_pipe updated config for the new
12268          * mode set on this crtc.  For other crtcs we need to use the
12269          * adjusted_mode bits in the crtc directly.
12270          */
12271         if (dev_priv->display.modeset_calc_cdclk) {
12272                 ret = dev_priv->display.modeset_calc_cdclk(state);
12273                 if (ret < 0)
12274                         return ret;
12275
12276                 /*
12277                  * Writes to dev_priv->cdclk.logical must protected by
12278                  * holding all the crtc locks, even if we don't end up
12279                  * touching the hardware
12280                  */
12281                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12282                                         &intel_state->cdclk.logical)) {
12283                         ret = intel_lock_all_pipes(state);
12284                         if (ret < 0)
12285                                 return ret;
12286                 }
12287
12288                 /* All pipes must be switched off while we change the cdclk. */
12289                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12290                                               &intel_state->cdclk.actual)) {
12291                         ret = intel_modeset_all_pipes(state);
12292                         if (ret < 0)
12293                                 return ret;
12294                 }
12295
12296                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12297                               intel_state->cdclk.logical.cdclk,
12298                               intel_state->cdclk.actual.cdclk);
12299                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12300                               intel_state->cdclk.logical.voltage_level,
12301                               intel_state->cdclk.actual.voltage_level);
12302         } else {
12303                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12304         }
12305
12306         intel_modeset_clear_plls(state);
12307
12308         if (IS_HASWELL(dev_priv))
12309                 return haswell_mode_set_planes_workaround(state);
12310
12311         return 0;
12312 }
12313
12314 /*
12315  * Handle calculation of various watermark data at the end of the atomic check
12316  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12317  * handlers to ensure that all derived state has been updated.
12318  */
12319 static int calc_watermark_data(struct drm_atomic_state *state)
12320 {
12321         struct drm_device *dev = state->dev;
12322         struct drm_i915_private *dev_priv = to_i915(dev);
12323
12324         /* Is there platform-specific watermark information to calculate? */
12325         if (dev_priv->display.compute_global_watermarks)
12326                 return dev_priv->display.compute_global_watermarks(state);
12327
12328         return 0;
12329 }
12330
12331 /**
12332  * intel_atomic_check - validate state object
12333  * @dev: drm device
12334  * @state: state to validate
12335  */
12336 static int intel_atomic_check(struct drm_device *dev,
12337                               struct drm_atomic_state *state)
12338 {
12339         struct drm_i915_private *dev_priv = to_i915(dev);
12340         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12341         struct drm_crtc *crtc;
12342         struct drm_crtc_state *old_crtc_state, *crtc_state;
12343         int ret, i;
12344         bool any_ms = false;
12345
12346         /* Catch I915_MODE_FLAG_INHERITED */
12347         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12348                                       crtc_state, i) {
12349                 if (crtc_state->mode.private_flags !=
12350                     old_crtc_state->mode.private_flags)
12351                         crtc_state->mode_changed = true;
12352         }
12353
12354         ret = drm_atomic_helper_check_modeset(dev, state);
12355         if (ret)
12356                 return ret;
12357
12358         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12359                 struct intel_crtc_state *pipe_config =
12360                         to_intel_crtc_state(crtc_state);
12361
12362                 if (!needs_modeset(crtc_state))
12363                         continue;
12364
12365                 if (!crtc_state->enable) {
12366                         any_ms = true;
12367                         continue;
12368                 }
12369
12370                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12371                 if (ret) {
12372                         intel_dump_pipe_config(to_intel_crtc(crtc),
12373                                                pipe_config, "[failed]");
12374                         return ret;
12375                 }
12376
12377                 if (i915_modparams.fastboot &&
12378                     intel_pipe_config_compare(dev_priv,
12379                                         to_intel_crtc_state(old_crtc_state),
12380                                         pipe_config, true)) {
12381                         crtc_state->mode_changed = false;
12382                         pipe_config->update_pipe = true;
12383                 }
12384
12385                 if (needs_modeset(crtc_state))
12386                         any_ms = true;
12387
12388                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12389                                        needs_modeset(crtc_state) ?
12390                                        "[modeset]" : "[fastset]");
12391         }
12392
12393         if (any_ms) {
12394                 ret = intel_modeset_checks(state);
12395
12396                 if (ret)
12397                         return ret;
12398         } else {
12399                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12400         }
12401
12402         ret = drm_atomic_helper_check_planes(dev, state);
12403         if (ret)
12404                 return ret;
12405
12406         intel_fbc_choose_crtc(dev_priv, intel_state);
12407         return calc_watermark_data(state);
12408 }
12409
12410 static int intel_atomic_prepare_commit(struct drm_device *dev,
12411                                        struct drm_atomic_state *state)
12412 {
12413         return drm_atomic_helper_prepare_planes(dev, state);
12414 }
12415
12416 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12417 {
12418         struct drm_device *dev = crtc->base.dev;
12419
12420         if (!dev->max_vblank_count)
12421                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12422
12423         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12424 }
12425
12426 static void intel_update_crtc(struct drm_crtc *crtc,
12427                               struct drm_atomic_state *state,
12428                               struct drm_crtc_state *old_crtc_state,
12429                               struct drm_crtc_state *new_crtc_state)
12430 {
12431         struct drm_device *dev = crtc->dev;
12432         struct drm_i915_private *dev_priv = to_i915(dev);
12433         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12434         struct intel_crtc_state *old_intel_cstate = to_intel_crtc_state(old_crtc_state);
12435         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12436         bool modeset = needs_modeset(new_crtc_state);
12437         struct intel_plane_state *new_plane_state =
12438                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
12439                                                  to_intel_plane(crtc->primary));
12440
12441         if (modeset) {
12442                 update_scanline_offset(intel_crtc);
12443                 dev_priv->display.crtc_enable(pipe_config, state);
12444
12445                 /* vblanks work again, re-enable pipe CRC. */
12446                 intel_crtc_enable_pipe_crc(intel_crtc);
12447         } else {
12448                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12449                                        pipe_config);
12450         }
12451
12452         if (new_plane_state)
12453                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
12454
12455         intel_begin_crtc_commit(crtc, old_crtc_state);
12456
12457         intel_update_planes_on_crtc(to_intel_atomic_state(state), intel_crtc,
12458                                     old_intel_cstate, pipe_config);
12459
12460         intel_finish_crtc_commit(crtc, old_crtc_state);
12461 }
12462
12463 static void intel_update_crtcs(struct drm_atomic_state *state)
12464 {
12465         struct drm_crtc *crtc;
12466         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12467         int i;
12468
12469         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12470                 if (!new_crtc_state->active)
12471                         continue;
12472
12473                 intel_update_crtc(crtc, state, old_crtc_state,
12474                                   new_crtc_state);
12475         }
12476 }
12477
12478 static void skl_update_crtcs(struct drm_atomic_state *state)
12479 {
12480         struct drm_i915_private *dev_priv = to_i915(state->dev);
12481         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12482         struct drm_crtc *crtc;
12483         struct intel_crtc *intel_crtc;
12484         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12485         struct intel_crtc_state *cstate;
12486         unsigned int updated = 0;
12487         bool progress;
12488         enum pipe pipe;
12489         int i;
12490         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
12491         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
12492
12493         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12494
12495         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12496                 /* ignore allocations for crtc's that have been turned off. */
12497                 if (new_crtc_state->active)
12498                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12499
12500         /* If 2nd DBuf slice required, enable it here */
12501         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
12502                 icl_dbuf_slices_update(dev_priv, required_slices);
12503
12504         /*
12505          * Whenever the number of active pipes changes, we need to make sure we
12506          * update the pipes in the right order so that their ddb allocations
12507          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12508          * cause pipe underruns and other bad stuff.
12509          */
12510         do {
12511                 progress = false;
12512
12513                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12514                         bool vbl_wait = false;
12515                         unsigned int cmask = drm_crtc_mask(crtc);
12516
12517                         intel_crtc = to_intel_crtc(crtc);
12518                         cstate = to_intel_crtc_state(new_crtc_state);
12519                         pipe = intel_crtc->pipe;
12520
12521                         if (updated & cmask || !cstate->base.active)
12522                                 continue;
12523
12524                         if (skl_ddb_allocation_overlaps(dev_priv,
12525                                                         entries,
12526                                                         &cstate->wm.skl.ddb,
12527                                                         i))
12528                                 continue;
12529
12530                         updated |= cmask;
12531                         entries[i] = &cstate->wm.skl.ddb;
12532
12533                         /*
12534                          * If this is an already active pipe, it's DDB changed,
12535                          * and this isn't the last pipe that needs updating
12536                          * then we need to wait for a vblank to pass for the
12537                          * new ddb allocation to take effect.
12538                          */
12539                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12540                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12541                             !new_crtc_state->active_changed &&
12542                             intel_state->wm_results.dirty_pipes != updated)
12543                                 vbl_wait = true;
12544
12545                         intel_update_crtc(crtc, state, old_crtc_state,
12546                                           new_crtc_state);
12547
12548                         if (vbl_wait)
12549                                 intel_wait_for_vblank(dev_priv, pipe);
12550
12551                         progress = true;
12552                 }
12553         } while (progress);
12554
12555         /* If 2nd DBuf slice is no more required disable it */
12556         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
12557                 icl_dbuf_slices_update(dev_priv, required_slices);
12558 }
12559
12560 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12561 {
12562         struct intel_atomic_state *state, *next;
12563         struct llist_node *freed;
12564
12565         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12566         llist_for_each_entry_safe(state, next, freed, freed)
12567                 drm_atomic_state_put(&state->base);
12568 }
12569
12570 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12571 {
12572         struct drm_i915_private *dev_priv =
12573                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12574
12575         intel_atomic_helper_free_state(dev_priv);
12576 }
12577
12578 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12579 {
12580         struct wait_queue_entry wait_fence, wait_reset;
12581         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12582
12583         init_wait_entry(&wait_fence, 0);
12584         init_wait_entry(&wait_reset, 0);
12585         for (;;) {
12586                 prepare_to_wait(&intel_state->commit_ready.wait,
12587                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12588                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12589                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12590
12591
12592                 if (i915_sw_fence_done(&intel_state->commit_ready)
12593                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12594                         break;
12595
12596                 schedule();
12597         }
12598         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12599         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12600 }
12601
12602 static void intel_atomic_cleanup_work(struct work_struct *work)
12603 {
12604         struct drm_atomic_state *state =
12605                 container_of(work, struct drm_atomic_state, commit_work);
12606         struct drm_i915_private *i915 = to_i915(state->dev);
12607
12608         drm_atomic_helper_cleanup_planes(&i915->drm, state);
12609         drm_atomic_helper_commit_cleanup_done(state);
12610         drm_atomic_state_put(state);
12611
12612         intel_atomic_helper_free_state(i915);
12613 }
12614
12615 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12616 {
12617         struct drm_device *dev = state->dev;
12618         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12619         struct drm_i915_private *dev_priv = to_i915(dev);
12620         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12621         struct intel_crtc_state *new_intel_crtc_state, *old_intel_crtc_state;
12622         struct drm_crtc *crtc;
12623         struct intel_crtc *intel_crtc;
12624         u64 put_domains[I915_MAX_PIPES] = {};
12625         int i;
12626
12627         intel_atomic_commit_fence_wait(intel_state);
12628
12629         drm_atomic_helper_wait_for_dependencies(state);
12630
12631         if (intel_state->modeset)
12632                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12633
12634         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12635                 old_intel_crtc_state = to_intel_crtc_state(old_crtc_state);
12636                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
12637                 intel_crtc = to_intel_crtc(crtc);
12638
12639                 if (needs_modeset(new_crtc_state) ||
12640                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12641
12642                         put_domains[intel_crtc->pipe] =
12643                                 modeset_get_crtc_power_domains(crtc,
12644                                         new_intel_crtc_state);
12645                 }
12646
12647                 if (!needs_modeset(new_crtc_state))
12648                         continue;
12649
12650                 intel_pre_plane_update(old_intel_crtc_state, new_intel_crtc_state);
12651
12652                 if (old_crtc_state->active) {
12653                         intel_crtc_disable_planes(intel_crtc, old_intel_crtc_state->active_planes);
12654
12655                         /*
12656                          * We need to disable pipe CRC before disabling the pipe,
12657                          * or we race against vblank off.
12658                          */
12659                         intel_crtc_disable_pipe_crc(intel_crtc);
12660
12661                         dev_priv->display.crtc_disable(old_intel_crtc_state, state);
12662                         intel_crtc->active = false;
12663                         intel_fbc_disable(intel_crtc);
12664                         intel_disable_shared_dpll(old_intel_crtc_state);
12665
12666                         /*
12667                          * Underruns don't always raise
12668                          * interrupts, so check manually.
12669                          */
12670                         intel_check_cpu_fifo_underruns(dev_priv);
12671                         intel_check_pch_fifo_underruns(dev_priv);
12672
12673                         if (!new_crtc_state->active) {
12674                                 /*
12675                                  * Make sure we don't call initial_watermarks
12676                                  * for ILK-style watermark updates.
12677                                  *
12678                                  * No clue what this is supposed to achieve.
12679                                  */
12680                                 if (INTEL_GEN(dev_priv) >= 9)
12681                                         dev_priv->display.initial_watermarks(intel_state,
12682                                                                              new_intel_crtc_state);
12683                         }
12684                 }
12685         }
12686
12687         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12688         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12689                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12690
12691         if (intel_state->modeset) {
12692                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12693
12694                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12695
12696                 /*
12697                  * SKL workaround: bspec recommends we disable the SAGV when we
12698                  * have more then one pipe enabled
12699                  */
12700                 if (!intel_can_enable_sagv(state))
12701                         intel_disable_sagv(dev_priv);
12702
12703                 intel_modeset_verify_disabled(dev, state);
12704         }
12705
12706         /* Complete the events for pipes that have now been disabled */
12707         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12708                 bool modeset = needs_modeset(new_crtc_state);
12709
12710                 /* Complete events for now disable pipes here. */
12711                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12712                         spin_lock_irq(&dev->event_lock);
12713                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12714                         spin_unlock_irq(&dev->event_lock);
12715
12716                         new_crtc_state->event = NULL;
12717                 }
12718         }
12719
12720         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12721         dev_priv->display.update_crtcs(state);
12722
12723         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12724          * already, but still need the state for the delayed optimization. To
12725          * fix this:
12726          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12727          * - schedule that vblank worker _before_ calling hw_done
12728          * - at the start of commit_tail, cancel it _synchrously
12729          * - switch over to the vblank wait helper in the core after that since
12730          *   we don't need out special handling any more.
12731          */
12732         drm_atomic_helper_wait_for_flip_done(dev, state);
12733
12734         /*
12735          * Now that the vblank has passed, we can go ahead and program the
12736          * optimal watermarks on platforms that need two-step watermark
12737          * programming.
12738          *
12739          * TODO: Move this (and other cleanup) to an async worker eventually.
12740          */
12741         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12742                 new_intel_crtc_state = to_intel_crtc_state(new_crtc_state);
12743
12744                 if (dev_priv->display.optimize_watermarks)
12745                         dev_priv->display.optimize_watermarks(intel_state,
12746                                                               new_intel_crtc_state);
12747         }
12748
12749         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12750                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12751
12752                 if (put_domains[i])
12753                         modeset_put_power_domains(dev_priv, put_domains[i]);
12754
12755                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12756         }
12757
12758         if (intel_state->modeset)
12759                 intel_verify_planes(intel_state);
12760
12761         if (intel_state->modeset && intel_can_enable_sagv(state))
12762                 intel_enable_sagv(dev_priv);
12763
12764         drm_atomic_helper_commit_hw_done(state);
12765
12766         if (intel_state->modeset) {
12767                 /* As one of the primary mmio accessors, KMS has a high
12768                  * likelihood of triggering bugs in unclaimed access. After we
12769                  * finish modesetting, see if an error has been flagged, and if
12770                  * so enable debugging for the next modeset - and hope we catch
12771                  * the culprit.
12772                  */
12773                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12774                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12775         }
12776
12777         /*
12778          * Defer the cleanup of the old state to a separate worker to not
12779          * impede the current task (userspace for blocking modesets) that
12780          * are executed inline. For out-of-line asynchronous modesets/flips,
12781          * deferring to a new worker seems overkill, but we would place a
12782          * schedule point (cond_resched()) here anyway to keep latencies
12783          * down.
12784          */
12785         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
12786         queue_work(system_highpri_wq, &state->commit_work);
12787 }
12788
12789 static void intel_atomic_commit_work(struct work_struct *work)
12790 {
12791         struct drm_atomic_state *state =
12792                 container_of(work, struct drm_atomic_state, commit_work);
12793
12794         intel_atomic_commit_tail(state);
12795 }
12796
12797 static int __i915_sw_fence_call
12798 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12799                           enum i915_sw_fence_notify notify)
12800 {
12801         struct intel_atomic_state *state =
12802                 container_of(fence, struct intel_atomic_state, commit_ready);
12803
12804         switch (notify) {
12805         case FENCE_COMPLETE:
12806                 /* we do blocking waits in the worker, nothing to do here */
12807                 break;
12808         case FENCE_FREE:
12809                 {
12810                         struct intel_atomic_helper *helper =
12811                                 &to_i915(state->base.dev)->atomic_helper;
12812
12813                         if (llist_add(&state->freed, &helper->free_list))
12814                                 schedule_work(&helper->free_work);
12815                         break;
12816                 }
12817         }
12818
12819         return NOTIFY_DONE;
12820 }
12821
12822 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12823 {
12824         struct drm_plane_state *old_plane_state, *new_plane_state;
12825         struct drm_plane *plane;
12826         int i;
12827
12828         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12829                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12830                                   intel_fb_obj(new_plane_state->fb),
12831                                   to_intel_plane(plane)->frontbuffer_bit);
12832 }
12833
12834 /**
12835  * intel_atomic_commit - commit validated state object
12836  * @dev: DRM device
12837  * @state: the top-level driver state object
12838  * @nonblock: nonblocking commit
12839  *
12840  * This function commits a top-level state object that has been validated
12841  * with drm_atomic_helper_check().
12842  *
12843  * RETURNS
12844  * Zero for success or -errno.
12845  */
12846 static int intel_atomic_commit(struct drm_device *dev,
12847                                struct drm_atomic_state *state,
12848                                bool nonblock)
12849 {
12850         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12851         struct drm_i915_private *dev_priv = to_i915(dev);
12852         int ret = 0;
12853
12854         drm_atomic_state_get(state);
12855         i915_sw_fence_init(&intel_state->commit_ready,
12856                            intel_atomic_commit_ready);
12857
12858         /*
12859          * The intel_legacy_cursor_update() fast path takes care
12860          * of avoiding the vblank waits for simple cursor
12861          * movement and flips. For cursor on/off and size changes,
12862          * we want to perform the vblank waits so that watermark
12863          * updates happen during the correct frames. Gen9+ have
12864          * double buffered watermarks and so shouldn't need this.
12865          *
12866          * Unset state->legacy_cursor_update before the call to
12867          * drm_atomic_helper_setup_commit() because otherwise
12868          * drm_atomic_helper_wait_for_flip_done() is a noop and
12869          * we get FIFO underruns because we didn't wait
12870          * for vblank.
12871          *
12872          * FIXME doing watermarks and fb cleanup from a vblank worker
12873          * (assuming we had any) would solve these problems.
12874          */
12875         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12876                 struct intel_crtc_state *new_crtc_state;
12877                 struct intel_crtc *crtc;
12878                 int i;
12879
12880                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12881                         if (new_crtc_state->wm.need_postvbl_update ||
12882                             new_crtc_state->update_wm_post)
12883                                 state->legacy_cursor_update = false;
12884         }
12885
12886         ret = intel_atomic_prepare_commit(dev, state);
12887         if (ret) {
12888                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12889                 i915_sw_fence_commit(&intel_state->commit_ready);
12890                 return ret;
12891         }
12892
12893         ret = drm_atomic_helper_setup_commit(state, nonblock);
12894         if (!ret)
12895                 ret = drm_atomic_helper_swap_state(state, true);
12896
12897         if (ret) {
12898                 i915_sw_fence_commit(&intel_state->commit_ready);
12899
12900                 drm_atomic_helper_cleanup_planes(dev, state);
12901                 return ret;
12902         }
12903         dev_priv->wm.distrust_bios_wm = false;
12904         intel_shared_dpll_swap_state(state);
12905         intel_atomic_track_fbs(state);
12906
12907         if (intel_state->modeset) {
12908                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12909                        sizeof(intel_state->min_cdclk));
12910                 memcpy(dev_priv->min_voltage_level,
12911                        intel_state->min_voltage_level,
12912                        sizeof(intel_state->min_voltage_level));
12913                 dev_priv->active_crtcs = intel_state->active_crtcs;
12914                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12915                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12916         }
12917
12918         drm_atomic_state_get(state);
12919         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12920
12921         i915_sw_fence_commit(&intel_state->commit_ready);
12922         if (nonblock && intel_state->modeset) {
12923                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12924         } else if (nonblock) {
12925                 queue_work(system_unbound_wq, &state->commit_work);
12926         } else {
12927                 if (intel_state->modeset)
12928                         flush_workqueue(dev_priv->modeset_wq);
12929                 intel_atomic_commit_tail(state);
12930         }
12931
12932         return 0;
12933 }
12934
12935 static const struct drm_crtc_funcs intel_crtc_funcs = {
12936         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12937         .set_config = drm_atomic_helper_set_config,
12938         .destroy = intel_crtc_destroy,
12939         .page_flip = drm_atomic_helper_page_flip,
12940         .atomic_duplicate_state = intel_crtc_duplicate_state,
12941         .atomic_destroy_state = intel_crtc_destroy_state,
12942         .set_crc_source = intel_crtc_set_crc_source,
12943         .verify_crc_source = intel_crtc_verify_crc_source,
12944         .get_crc_sources = intel_crtc_get_crc_sources,
12945 };
12946
12947 struct wait_rps_boost {
12948         struct wait_queue_entry wait;
12949
12950         struct drm_crtc *crtc;
12951         struct i915_request *request;
12952 };
12953
12954 static int do_rps_boost(struct wait_queue_entry *_wait,
12955                         unsigned mode, int sync, void *key)
12956 {
12957         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
12958         struct i915_request *rq = wait->request;
12959
12960         /*
12961          * If we missed the vblank, but the request is already running it
12962          * is reasonable to assume that it will complete before the next
12963          * vblank without our intervention, so leave RPS alone.
12964          */
12965         if (!i915_request_started(rq))
12966                 gen6_rps_boost(rq, NULL);
12967         i915_request_put(rq);
12968
12969         drm_crtc_vblank_put(wait->crtc);
12970
12971         list_del(&wait->wait.entry);
12972         kfree(wait);
12973         return 1;
12974 }
12975
12976 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
12977                                        struct dma_fence *fence)
12978 {
12979         struct wait_rps_boost *wait;
12980
12981         if (!dma_fence_is_i915(fence))
12982                 return;
12983
12984         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
12985                 return;
12986
12987         if (drm_crtc_vblank_get(crtc))
12988                 return;
12989
12990         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
12991         if (!wait) {
12992                 drm_crtc_vblank_put(crtc);
12993                 return;
12994         }
12995
12996         wait->request = to_request(dma_fence_get(fence));
12997         wait->crtc = crtc;
12998
12999         wait->wait.func = do_rps_boost;
13000         wait->wait.flags = 0;
13001
13002         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
13003 }
13004
13005 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
13006 {
13007         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
13008         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13009         struct drm_framebuffer *fb = plane_state->base.fb;
13010         struct i915_vma *vma;
13011
13012         if (plane->id == PLANE_CURSOR &&
13013             INTEL_INFO(dev_priv)->cursor_needs_physical) {
13014                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13015                 const int align = intel_cursor_alignment(dev_priv);
13016                 int err;
13017
13018                 err = i915_gem_object_attach_phys(obj, align);
13019                 if (err)
13020                         return err;
13021         }
13022
13023         vma = intel_pin_and_fence_fb_obj(fb,
13024                                          &plane_state->view,
13025                                          intel_plane_uses_fence(plane_state),
13026                                          &plane_state->flags);
13027         if (IS_ERR(vma))
13028                 return PTR_ERR(vma);
13029
13030         plane_state->vma = vma;
13031
13032         return 0;
13033 }
13034
13035 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
13036 {
13037         struct i915_vma *vma;
13038
13039         vma = fetch_and_zero(&old_plane_state->vma);
13040         if (vma)
13041                 intel_unpin_fb_vma(vma, old_plane_state->flags);
13042 }
13043
13044 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
13045 {
13046         struct i915_sched_attr attr = {
13047                 .priority = I915_PRIORITY_DISPLAY,
13048         };
13049
13050         i915_gem_object_wait_priority(obj, 0, &attr);
13051 }
13052
13053 /**
13054  * intel_prepare_plane_fb - Prepare fb for usage on plane
13055  * @plane: drm plane to prepare for
13056  * @new_state: the plane state being prepared
13057  *
13058  * Prepares a framebuffer for usage on a display plane.  Generally this
13059  * involves pinning the underlying object and updating the frontbuffer tracking
13060  * bits.  Some older platforms need special physical address handling for
13061  * cursor planes.
13062  *
13063  * Must be called with struct_mutex held.
13064  *
13065  * Returns 0 on success, negative error code on failure.
13066  */
13067 int
13068 intel_prepare_plane_fb(struct drm_plane *plane,
13069                        struct drm_plane_state *new_state)
13070 {
13071         struct intel_atomic_state *intel_state =
13072                 to_intel_atomic_state(new_state->state);
13073         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13074         struct drm_framebuffer *fb = new_state->fb;
13075         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13076         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13077         int ret;
13078
13079         if (old_obj) {
13080                 struct drm_crtc_state *crtc_state =
13081                         drm_atomic_get_new_crtc_state(new_state->state,
13082                                                       plane->state->crtc);
13083
13084                 /* Big Hammer, we also need to ensure that any pending
13085                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13086                  * current scanout is retired before unpinning the old
13087                  * framebuffer. Note that we rely on userspace rendering
13088                  * into the buffer attached to the pipe they are waiting
13089                  * on. If not, userspace generates a GPU hang with IPEHR
13090                  * point to the MI_WAIT_FOR_EVENT.
13091                  *
13092                  * This should only fail upon a hung GPU, in which case we
13093                  * can safely continue.
13094                  */
13095                 if (needs_modeset(crtc_state)) {
13096                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13097                                                               old_obj->resv, NULL,
13098                                                               false, 0,
13099                                                               GFP_KERNEL);
13100                         if (ret < 0)
13101                                 return ret;
13102                 }
13103         }
13104
13105         if (new_state->fence) { /* explicit fencing */
13106                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13107                                                     new_state->fence,
13108                                                     I915_FENCE_TIMEOUT,
13109                                                     GFP_KERNEL);
13110                 if (ret < 0)
13111                         return ret;
13112         }
13113
13114         if (!obj)
13115                 return 0;
13116
13117         ret = i915_gem_object_pin_pages(obj);
13118         if (ret)
13119                 return ret;
13120
13121         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13122         if (ret) {
13123                 i915_gem_object_unpin_pages(obj);
13124                 return ret;
13125         }
13126
13127         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
13128
13129         mutex_unlock(&dev_priv->drm.struct_mutex);
13130         i915_gem_object_unpin_pages(obj);
13131         if (ret)
13132                 return ret;
13133
13134         fb_obj_bump_render_priority(obj);
13135         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13136
13137         if (!new_state->fence) { /* implicit fencing */
13138                 struct dma_fence *fence;
13139
13140                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13141                                                       obj->resv, NULL,
13142                                                       false, I915_FENCE_TIMEOUT,
13143                                                       GFP_KERNEL);
13144                 if (ret < 0)
13145                         return ret;
13146
13147                 fence = reservation_object_get_excl_rcu(obj->resv);
13148                 if (fence) {
13149                         add_rps_boost_after_vblank(new_state->crtc, fence);
13150                         dma_fence_put(fence);
13151                 }
13152         } else {
13153                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
13154         }
13155
13156         /*
13157          * We declare pageflips to be interactive and so merit a small bias
13158          * towards upclocking to deliver the frame on time. By only changing
13159          * the RPS thresholds to sample more regularly and aim for higher
13160          * clocks we can hopefully deliver low power workloads (like kodi)
13161          * that are not quite steady state without resorting to forcing
13162          * maximum clocks following a vblank miss (see do_rps_boost()).
13163          */
13164         if (!intel_state->rps_interactive) {
13165                 intel_rps_mark_interactive(dev_priv, true);
13166                 intel_state->rps_interactive = true;
13167         }
13168
13169         return 0;
13170 }
13171
13172 /**
13173  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13174  * @plane: drm plane to clean up for
13175  * @old_state: the state from the previous modeset
13176  *
13177  * Cleans up a framebuffer that has just been removed from a plane.
13178  *
13179  * Must be called with struct_mutex held.
13180  */
13181 void
13182 intel_cleanup_plane_fb(struct drm_plane *plane,
13183                        struct drm_plane_state *old_state)
13184 {
13185         struct intel_atomic_state *intel_state =
13186                 to_intel_atomic_state(old_state->state);
13187         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13188
13189         if (intel_state->rps_interactive) {
13190                 intel_rps_mark_interactive(dev_priv, false);
13191                 intel_state->rps_interactive = false;
13192         }
13193
13194         /* Should only be called after a successful intel_prepare_plane_fb()! */
13195         mutex_lock(&dev_priv->drm.struct_mutex);
13196         intel_plane_unpin_fb(to_intel_plane_state(old_state));
13197         mutex_unlock(&dev_priv->drm.struct_mutex);
13198 }
13199
13200 int
13201 skl_max_scale(const struct intel_crtc_state *crtc_state,
13202               u32 pixel_format)
13203 {
13204         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
13205         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13206         int max_scale, mult;
13207         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
13208
13209         if (!crtc_state->base.enable)
13210                 return DRM_PLANE_HELPER_NO_SCALING;
13211
13212         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13213         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13214
13215         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
13216                 max_dotclk *= 2;
13217
13218         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13219                 return DRM_PLANE_HELPER_NO_SCALING;
13220
13221         /*
13222          * skl max scale is lower of:
13223          *    close to 3 but not 3, -1 is for that purpose
13224          *            or
13225          *    cdclk/crtc_clock
13226          */
13227         mult = pixel_format == DRM_FORMAT_NV12 ? 2 : 3;
13228         tmpclk1 = (1 << 16) * mult - 1;
13229         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
13230         max_scale = min(tmpclk1, tmpclk2);
13231
13232         return max_scale;
13233 }
13234
13235 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13236                                     struct drm_crtc_state *old_crtc_state)
13237 {
13238         struct drm_device *dev = crtc->dev;
13239         struct drm_i915_private *dev_priv = to_i915(dev);
13240         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13241         struct intel_crtc_state *old_intel_cstate =
13242                 to_intel_crtc_state(old_crtc_state);
13243         struct intel_atomic_state *old_intel_state =
13244                 to_intel_atomic_state(old_crtc_state->state);
13245         struct intel_crtc_state *intel_cstate =
13246                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13247         bool modeset = needs_modeset(&intel_cstate->base);
13248
13249         if (!modeset &&
13250             (intel_cstate->base.color_mgmt_changed ||
13251              intel_cstate->update_pipe)) {
13252                 intel_color_set_csc(&intel_cstate->base);
13253                 intel_color_load_luts(&intel_cstate->base);
13254         }
13255
13256         /* Perform vblank evasion around commit operation */
13257         intel_pipe_update_start(intel_cstate);
13258
13259         if (modeset)
13260                 goto out;
13261
13262         if (intel_cstate->update_pipe)
13263                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
13264         else if (INTEL_GEN(dev_priv) >= 9)
13265                 skl_detach_scalers(intel_cstate);
13266
13267 out:
13268         if (dev_priv->display.atomic_update_watermarks)
13269                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13270                                                            intel_cstate);
13271 }
13272
13273 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
13274                                   struct intel_crtc_state *crtc_state)
13275 {
13276         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13277
13278         if (!IS_GEN2(dev_priv))
13279                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
13280
13281         if (crtc_state->has_pch_encoder) {
13282                 enum pipe pch_transcoder =
13283                         intel_crtc_pch_transcoder(crtc);
13284
13285                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13286         }
13287 }
13288
13289 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13290                                      struct drm_crtc_state *old_crtc_state)
13291 {
13292         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13293         struct intel_atomic_state *old_intel_state =
13294                 to_intel_atomic_state(old_crtc_state->state);
13295         struct intel_crtc_state *new_crtc_state =
13296                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13297
13298         intel_pipe_update_end(new_crtc_state);
13299
13300         if (new_crtc_state->update_pipe &&
13301             !needs_modeset(&new_crtc_state->base) &&
13302             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED)
13303                 intel_crtc_arm_fifo_underrun(intel_crtc, new_crtc_state);
13304 }
13305
13306 /**
13307  * intel_plane_destroy - destroy a plane
13308  * @plane: plane to destroy
13309  *
13310  * Common destruction function for all types of planes (primary, cursor,
13311  * sprite).
13312  */
13313 void intel_plane_destroy(struct drm_plane *plane)
13314 {
13315         drm_plane_cleanup(plane);
13316         kfree(to_intel_plane(plane));
13317 }
13318
13319 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
13320                                             u32 format, u64 modifier)
13321 {
13322         switch (modifier) {
13323         case DRM_FORMAT_MOD_LINEAR:
13324         case I915_FORMAT_MOD_X_TILED:
13325                 break;
13326         default:
13327                 return false;
13328         }
13329
13330         switch (format) {
13331         case DRM_FORMAT_C8:
13332         case DRM_FORMAT_RGB565:
13333         case DRM_FORMAT_XRGB1555:
13334         case DRM_FORMAT_XRGB8888:
13335                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13336                         modifier == I915_FORMAT_MOD_X_TILED;
13337         default:
13338                 return false;
13339         }
13340 }
13341
13342 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
13343                                             u32 format, u64 modifier)
13344 {
13345         switch (modifier) {
13346         case DRM_FORMAT_MOD_LINEAR:
13347         case I915_FORMAT_MOD_X_TILED:
13348                 break;
13349         default:
13350                 return false;
13351         }
13352
13353         switch (format) {
13354         case DRM_FORMAT_C8:
13355         case DRM_FORMAT_RGB565:
13356         case DRM_FORMAT_XRGB8888:
13357         case DRM_FORMAT_XBGR8888:
13358         case DRM_FORMAT_XRGB2101010:
13359         case DRM_FORMAT_XBGR2101010:
13360                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13361                         modifier == I915_FORMAT_MOD_X_TILED;
13362         default:
13363                 return false;
13364         }
13365 }
13366
13367 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
13368                                               u32 format, u64 modifier)
13369 {
13370         return modifier == DRM_FORMAT_MOD_LINEAR &&
13371                 format == DRM_FORMAT_ARGB8888;
13372 }
13373
13374 static const struct drm_plane_funcs i965_plane_funcs = {
13375         .update_plane = drm_atomic_helper_update_plane,
13376         .disable_plane = drm_atomic_helper_disable_plane,
13377         .destroy = intel_plane_destroy,
13378         .atomic_get_property = intel_plane_atomic_get_property,
13379         .atomic_set_property = intel_plane_atomic_set_property,
13380         .atomic_duplicate_state = intel_plane_duplicate_state,
13381         .atomic_destroy_state = intel_plane_destroy_state,
13382         .format_mod_supported = i965_plane_format_mod_supported,
13383 };
13384
13385 static const struct drm_plane_funcs i8xx_plane_funcs = {
13386         .update_plane = drm_atomic_helper_update_plane,
13387         .disable_plane = drm_atomic_helper_disable_plane,
13388         .destroy = intel_plane_destroy,
13389         .atomic_get_property = intel_plane_atomic_get_property,
13390         .atomic_set_property = intel_plane_atomic_set_property,
13391         .atomic_duplicate_state = intel_plane_duplicate_state,
13392         .atomic_destroy_state = intel_plane_destroy_state,
13393         .format_mod_supported = i8xx_plane_format_mod_supported,
13394 };
13395
13396 static int
13397 intel_legacy_cursor_update(struct drm_plane *plane,
13398                            struct drm_crtc *crtc,
13399                            struct drm_framebuffer *fb,
13400                            int crtc_x, int crtc_y,
13401                            unsigned int crtc_w, unsigned int crtc_h,
13402                            uint32_t src_x, uint32_t src_y,
13403                            uint32_t src_w, uint32_t src_h,
13404                            struct drm_modeset_acquire_ctx *ctx)
13405 {
13406         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13407         int ret;
13408         struct drm_plane_state *old_plane_state, *new_plane_state;
13409         struct intel_plane *intel_plane = to_intel_plane(plane);
13410         struct drm_framebuffer *old_fb;
13411         struct intel_crtc_state *crtc_state =
13412                 to_intel_crtc_state(crtc->state);
13413         struct intel_crtc_state *new_crtc_state;
13414
13415         /*
13416          * When crtc is inactive or there is a modeset pending,
13417          * wait for it to complete in the slowpath
13418          */
13419         if (!crtc_state->base.active || needs_modeset(&crtc_state->base) ||
13420             crtc_state->update_pipe)
13421                 goto slow;
13422
13423         old_plane_state = plane->state;
13424         /*
13425          * Don't do an async update if there is an outstanding commit modifying
13426          * the plane.  This prevents our async update's changes from getting
13427          * overridden by a previous synchronous update's state.
13428          */
13429         if (old_plane_state->commit &&
13430             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13431                 goto slow;
13432
13433         /*
13434          * If any parameters change that may affect watermarks,
13435          * take the slowpath. Only changing fb or position should be
13436          * in the fastpath.
13437          */
13438         if (old_plane_state->crtc != crtc ||
13439             old_plane_state->src_w != src_w ||
13440             old_plane_state->src_h != src_h ||
13441             old_plane_state->crtc_w != crtc_w ||
13442             old_plane_state->crtc_h != crtc_h ||
13443             !old_plane_state->fb != !fb)
13444                 goto slow;
13445
13446         new_plane_state = intel_plane_duplicate_state(plane);
13447         if (!new_plane_state)
13448                 return -ENOMEM;
13449
13450         new_crtc_state = to_intel_crtc_state(intel_crtc_duplicate_state(crtc));
13451         if (!new_crtc_state) {
13452                 ret = -ENOMEM;
13453                 goto out_free;
13454         }
13455
13456         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13457
13458         new_plane_state->src_x = src_x;
13459         new_plane_state->src_y = src_y;
13460         new_plane_state->src_w = src_w;
13461         new_plane_state->src_h = src_h;
13462         new_plane_state->crtc_x = crtc_x;
13463         new_plane_state->crtc_y = crtc_y;
13464         new_plane_state->crtc_w = crtc_w;
13465         new_plane_state->crtc_h = crtc_h;
13466
13467         ret = intel_plane_atomic_check_with_state(crtc_state, new_crtc_state,
13468                                                   to_intel_plane_state(old_plane_state),
13469                                                   to_intel_plane_state(new_plane_state));
13470         if (ret)
13471                 goto out_free;
13472
13473         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13474         if (ret)
13475                 goto out_free;
13476
13477         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13478         if (ret)
13479                 goto out_unlock;
13480
13481         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13482
13483         old_fb = old_plane_state->fb;
13484         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13485                           intel_plane->frontbuffer_bit);
13486
13487         /* Swap plane state */
13488         plane->state = new_plane_state;
13489
13490         /*
13491          * We cannot swap crtc_state as it may be in use by an atomic commit or
13492          * page flip that's running simultaneously. If we swap crtc_state and
13493          * destroy the old state, we will cause a use-after-free there.
13494          *
13495          * Only update active_planes, which is needed for our internal
13496          * bookkeeping. Either value will do the right thing when updating
13497          * planes atomically. If the cursor was part of the atomic update then
13498          * we would have taken the slowpath.
13499          */
13500         crtc_state->active_planes = new_crtc_state->active_planes;
13501
13502         if (plane->state->visible) {
13503                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13504                 intel_plane->update_plane(intel_plane, crtc_state,
13505                                           to_intel_plane_state(plane->state));
13506         } else {
13507                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13508                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13509         }
13510
13511         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13512
13513 out_unlock:
13514         mutex_unlock(&dev_priv->drm.struct_mutex);
13515 out_free:
13516         if (new_crtc_state)
13517                 intel_crtc_destroy_state(crtc, &new_crtc_state->base);
13518         if (ret)
13519                 intel_plane_destroy_state(plane, new_plane_state);
13520         else
13521                 intel_plane_destroy_state(plane, old_plane_state);
13522         return ret;
13523
13524 slow:
13525         return drm_atomic_helper_update_plane(plane, crtc, fb,
13526                                               crtc_x, crtc_y, crtc_w, crtc_h,
13527                                               src_x, src_y, src_w, src_h, ctx);
13528 }
13529
13530 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13531         .update_plane = intel_legacy_cursor_update,
13532         .disable_plane = drm_atomic_helper_disable_plane,
13533         .destroy = intel_plane_destroy,
13534         .atomic_get_property = intel_plane_atomic_get_property,
13535         .atomic_set_property = intel_plane_atomic_set_property,
13536         .atomic_duplicate_state = intel_plane_duplicate_state,
13537         .atomic_destroy_state = intel_plane_destroy_state,
13538         .format_mod_supported = intel_cursor_format_mod_supported,
13539 };
13540
13541 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13542                                enum i9xx_plane_id i9xx_plane)
13543 {
13544         if (!HAS_FBC(dev_priv))
13545                 return false;
13546
13547         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13548                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13549         else if (IS_IVYBRIDGE(dev_priv))
13550                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13551                         i9xx_plane == PLANE_C;
13552         else if (INTEL_GEN(dev_priv) >= 4)
13553                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13554         else
13555                 return i9xx_plane == PLANE_A;
13556 }
13557
13558 static struct intel_plane *
13559 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13560 {
13561         struct intel_plane *plane;
13562         const struct drm_plane_funcs *plane_funcs;
13563         unsigned int supported_rotations;
13564         unsigned int possible_crtcs;
13565         const u64 *modifiers;
13566         const u32 *formats;
13567         int num_formats;
13568         int ret;
13569
13570         if (INTEL_GEN(dev_priv) >= 9)
13571                 return skl_universal_plane_create(dev_priv, pipe,
13572                                                   PLANE_PRIMARY);
13573
13574         plane = intel_plane_alloc();
13575         if (IS_ERR(plane))
13576                 return plane;
13577
13578         plane->pipe = pipe;
13579         /*
13580          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13581          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13582          */
13583         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13584                 plane->i9xx_plane = (enum i9xx_plane_id) !pipe;
13585         else
13586                 plane->i9xx_plane = (enum i9xx_plane_id) pipe;
13587         plane->id = PLANE_PRIMARY;
13588         plane->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, plane->id);
13589
13590         plane->has_fbc = i9xx_plane_has_fbc(dev_priv, plane->i9xx_plane);
13591         if (plane->has_fbc) {
13592                 struct intel_fbc *fbc = &dev_priv->fbc;
13593
13594                 fbc->possible_framebuffer_bits |= plane->frontbuffer_bit;
13595         }
13596
13597         if (INTEL_GEN(dev_priv) >= 4) {
13598                 formats = i965_primary_formats;
13599                 num_formats = ARRAY_SIZE(i965_primary_formats);
13600                 modifiers = i9xx_format_modifiers;
13601
13602                 plane->max_stride = i9xx_plane_max_stride;
13603                 plane->update_plane = i9xx_update_plane;
13604                 plane->disable_plane = i9xx_disable_plane;
13605                 plane->get_hw_state = i9xx_plane_get_hw_state;
13606                 plane->check_plane = i9xx_plane_check;
13607
13608                 plane_funcs = &i965_plane_funcs;
13609         } else {
13610                 formats = i8xx_primary_formats;
13611                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13612                 modifiers = i9xx_format_modifiers;
13613
13614                 plane->max_stride = i9xx_plane_max_stride;
13615                 plane->update_plane = i9xx_update_plane;
13616                 plane->disable_plane = i9xx_disable_plane;
13617                 plane->get_hw_state = i9xx_plane_get_hw_state;
13618                 plane->check_plane = i9xx_plane_check;
13619
13620                 plane_funcs = &i8xx_plane_funcs;
13621         }
13622
13623         possible_crtcs = BIT(pipe);
13624
13625         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13626                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
13627                                                possible_crtcs, plane_funcs,
13628                                                formats, num_formats, modifiers,
13629                                                DRM_PLANE_TYPE_PRIMARY,
13630                                                "primary %c", pipe_name(pipe));
13631         else
13632                 ret = drm_universal_plane_init(&dev_priv->drm, &plane->base,
13633                                                possible_crtcs, plane_funcs,
13634                                                formats, num_formats, modifiers,
13635                                                DRM_PLANE_TYPE_PRIMARY,
13636                                                "plane %c",
13637                                                plane_name(plane->i9xx_plane));
13638         if (ret)
13639                 goto fail;
13640
13641         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13642                 supported_rotations =
13643                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13644                         DRM_MODE_REFLECT_X;
13645         } else if (INTEL_GEN(dev_priv) >= 4) {
13646                 supported_rotations =
13647                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13648         } else {
13649                 supported_rotations = DRM_MODE_ROTATE_0;
13650         }
13651
13652         if (INTEL_GEN(dev_priv) >= 4)
13653                 drm_plane_create_rotation_property(&plane->base,
13654                                                    DRM_MODE_ROTATE_0,
13655                                                    supported_rotations);
13656
13657         drm_plane_helper_add(&plane->base, &intel_plane_helper_funcs);
13658
13659         return plane;
13660
13661 fail:
13662         intel_plane_free(plane);
13663
13664         return ERR_PTR(ret);
13665 }
13666
13667 static struct intel_plane *
13668 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13669                           enum pipe pipe)
13670 {
13671         unsigned int possible_crtcs;
13672         struct intel_plane *cursor;
13673         int ret;
13674
13675         cursor = intel_plane_alloc();
13676         if (IS_ERR(cursor))
13677                 return cursor;
13678
13679         cursor->pipe = pipe;
13680         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13681         cursor->id = PLANE_CURSOR;
13682         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13683
13684         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13685                 cursor->max_stride = i845_cursor_max_stride;
13686                 cursor->update_plane = i845_update_cursor;
13687                 cursor->disable_plane = i845_disable_cursor;
13688                 cursor->get_hw_state = i845_cursor_get_hw_state;
13689                 cursor->check_plane = i845_check_cursor;
13690         } else {
13691                 cursor->max_stride = i9xx_cursor_max_stride;
13692                 cursor->update_plane = i9xx_update_cursor;
13693                 cursor->disable_plane = i9xx_disable_cursor;
13694                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13695                 cursor->check_plane = i9xx_check_cursor;
13696         }
13697
13698         cursor->cursor.base = ~0;
13699         cursor->cursor.cntl = ~0;
13700
13701         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13702                 cursor->cursor.size = ~0;
13703
13704         possible_crtcs = BIT(pipe);
13705
13706         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13707                                        possible_crtcs, &intel_cursor_plane_funcs,
13708                                        intel_cursor_formats,
13709                                        ARRAY_SIZE(intel_cursor_formats),
13710                                        cursor_format_modifiers,
13711                                        DRM_PLANE_TYPE_CURSOR,
13712                                        "cursor %c", pipe_name(pipe));
13713         if (ret)
13714                 goto fail;
13715
13716         if (INTEL_GEN(dev_priv) >= 4)
13717                 drm_plane_create_rotation_property(&cursor->base,
13718                                                    DRM_MODE_ROTATE_0,
13719                                                    DRM_MODE_ROTATE_0 |
13720                                                    DRM_MODE_ROTATE_180);
13721
13722         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13723
13724         return cursor;
13725
13726 fail:
13727         intel_plane_free(cursor);
13728
13729         return ERR_PTR(ret);
13730 }
13731
13732 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13733                                     struct intel_crtc_state *crtc_state)
13734 {
13735         struct intel_crtc_scaler_state *scaler_state =
13736                 &crtc_state->scaler_state;
13737         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13738         int i;
13739
13740         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13741         if (!crtc->num_scalers)
13742                 return;
13743
13744         for (i = 0; i < crtc->num_scalers; i++) {
13745                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13746
13747                 scaler->in_use = 0;
13748                 scaler->mode = 0;
13749         }
13750
13751         scaler_state->scaler_id = -1;
13752 }
13753
13754 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13755 {
13756         struct intel_crtc *intel_crtc;
13757         struct intel_crtc_state *crtc_state = NULL;
13758         struct intel_plane *primary = NULL;
13759         struct intel_plane *cursor = NULL;
13760         int sprite, ret;
13761
13762         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13763         if (!intel_crtc)
13764                 return -ENOMEM;
13765
13766         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13767         if (!crtc_state) {
13768                 ret = -ENOMEM;
13769                 goto fail;
13770         }
13771         intel_crtc->config = crtc_state;
13772         intel_crtc->base.state = &crtc_state->base;
13773         crtc_state->base.crtc = &intel_crtc->base;
13774
13775         primary = intel_primary_plane_create(dev_priv, pipe);
13776         if (IS_ERR(primary)) {
13777                 ret = PTR_ERR(primary);
13778                 goto fail;
13779         }
13780         intel_crtc->plane_ids_mask |= BIT(primary->id);
13781
13782         for_each_sprite(dev_priv, pipe, sprite) {
13783                 struct intel_plane *plane;
13784
13785                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13786                 if (IS_ERR(plane)) {
13787                         ret = PTR_ERR(plane);
13788                         goto fail;
13789                 }
13790                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13791         }
13792
13793         cursor = intel_cursor_plane_create(dev_priv, pipe);
13794         if (IS_ERR(cursor)) {
13795                 ret = PTR_ERR(cursor);
13796                 goto fail;
13797         }
13798         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13799
13800         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13801                                         &primary->base, &cursor->base,
13802                                         &intel_crtc_funcs,
13803                                         "pipe %c", pipe_name(pipe));
13804         if (ret)
13805                 goto fail;
13806
13807         intel_crtc->pipe = pipe;
13808
13809         /* initialize shared scalers */
13810         intel_crtc_init_scalers(intel_crtc, crtc_state);
13811
13812         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
13813                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
13814         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
13815
13816         if (INTEL_GEN(dev_priv) < 9) {
13817                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
13818
13819                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13820                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
13821                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
13822         }
13823
13824         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13825
13826         intel_color_init(&intel_crtc->base);
13827
13828         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13829
13830         return 0;
13831
13832 fail:
13833         /*
13834          * drm_mode_config_cleanup() will free up any
13835          * crtcs/planes already initialized.
13836          */
13837         kfree(crtc_state);
13838         kfree(intel_crtc);
13839
13840         return ret;
13841 }
13842
13843 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13844 {
13845         struct drm_device *dev = connector->base.dev;
13846
13847         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13848
13849         if (!connector->base.state->crtc)
13850                 return INVALID_PIPE;
13851
13852         return to_intel_crtc(connector->base.state->crtc)->pipe;
13853 }
13854
13855 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
13856                                       struct drm_file *file)
13857 {
13858         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13859         struct drm_crtc *drmmode_crtc;
13860         struct intel_crtc *crtc;
13861
13862         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
13863         if (!drmmode_crtc)
13864                 return -ENOENT;
13865
13866         crtc = to_intel_crtc(drmmode_crtc);
13867         pipe_from_crtc_id->pipe = crtc->pipe;
13868
13869         return 0;
13870 }
13871
13872 static int intel_encoder_clones(struct intel_encoder *encoder)
13873 {
13874         struct drm_device *dev = encoder->base.dev;
13875         struct intel_encoder *source_encoder;
13876         int index_mask = 0;
13877         int entry = 0;
13878
13879         for_each_intel_encoder(dev, source_encoder) {
13880                 if (encoders_cloneable(encoder, source_encoder))
13881                         index_mask |= (1 << entry);
13882
13883                 entry++;
13884         }
13885
13886         return index_mask;
13887 }
13888
13889 static bool has_edp_a(struct drm_i915_private *dev_priv)
13890 {
13891         if (!IS_MOBILE(dev_priv))
13892                 return false;
13893
13894         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13895                 return false;
13896
13897         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13898                 return false;
13899
13900         return true;
13901 }
13902
13903 static bool intel_crt_present(struct drm_i915_private *dev_priv)
13904 {
13905         if (INTEL_GEN(dev_priv) >= 9)
13906                 return false;
13907
13908         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
13909                 return false;
13910
13911         if (IS_CHERRYVIEW(dev_priv))
13912                 return false;
13913
13914         if (HAS_PCH_LPT_H(dev_priv) &&
13915             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
13916                 return false;
13917
13918         /* DDI E can't be used if DDI A requires 4 lanes */
13919         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
13920                 return false;
13921
13922         if (!dev_priv->vbt.int_crt_support)
13923                 return false;
13924
13925         return true;
13926 }
13927
13928 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
13929 {
13930         int pps_num;
13931         int pps_idx;
13932
13933         if (HAS_DDI(dev_priv))
13934                 return;
13935         /*
13936          * This w/a is needed at least on CPT/PPT, but to be sure apply it
13937          * everywhere where registers can be write protected.
13938          */
13939         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13940                 pps_num = 2;
13941         else
13942                 pps_num = 1;
13943
13944         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
13945                 u32 val = I915_READ(PP_CONTROL(pps_idx));
13946
13947                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
13948                 I915_WRITE(PP_CONTROL(pps_idx), val);
13949         }
13950 }
13951
13952 static void intel_pps_init(struct drm_i915_private *dev_priv)
13953 {
13954         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
13955                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
13956         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13957                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
13958         else
13959                 dev_priv->pps_mmio_base = PPS_BASE;
13960
13961         intel_pps_unlock_regs_wa(dev_priv);
13962 }
13963
13964 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
13965 {
13966         struct intel_encoder *encoder;
13967         bool dpd_is_edp = false;
13968
13969         intel_pps_init(dev_priv);
13970
13971         if (INTEL_INFO(dev_priv)->num_pipes == 0)
13972                 return;
13973
13974         /*
13975          * intel_edp_init_connector() depends on this completing first, to
13976          * prevent the registeration of both eDP and LVDS and the incorrect
13977          * sharing of the PPS.
13978          */
13979         intel_lvds_init(dev_priv);
13980
13981         if (intel_crt_present(dev_priv))
13982                 intel_crt_init(dev_priv);
13983
13984         if (IS_ICELAKE(dev_priv)) {
13985                 intel_ddi_init(dev_priv, PORT_A);
13986                 intel_ddi_init(dev_priv, PORT_B);
13987                 intel_ddi_init(dev_priv, PORT_C);
13988                 intel_ddi_init(dev_priv, PORT_D);
13989                 intel_ddi_init(dev_priv, PORT_E);
13990                 intel_ddi_init(dev_priv, PORT_F);
13991         } else if (IS_GEN9_LP(dev_priv)) {
13992                 /*
13993                  * FIXME: Broxton doesn't support port detection via the
13994                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13995                  * detect the ports.
13996                  */
13997                 intel_ddi_init(dev_priv, PORT_A);
13998                 intel_ddi_init(dev_priv, PORT_B);
13999                 intel_ddi_init(dev_priv, PORT_C);
14000
14001                 vlv_dsi_init(dev_priv);
14002         } else if (HAS_DDI(dev_priv)) {
14003                 int found;
14004
14005                 /*
14006                  * Haswell uses DDI functions to detect digital outputs.
14007                  * On SKL pre-D0 the strap isn't connected, so we assume
14008                  * it's there.
14009                  */
14010                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14011                 /* WaIgnoreDDIAStrap: skl */
14012                 if (found || IS_GEN9_BC(dev_priv))
14013                         intel_ddi_init(dev_priv, PORT_A);
14014
14015                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
14016                  * register */
14017                 found = I915_READ(SFUSE_STRAP);
14018
14019                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14020                         intel_ddi_init(dev_priv, PORT_B);
14021                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14022                         intel_ddi_init(dev_priv, PORT_C);
14023                 if (found & SFUSE_STRAP_DDID_DETECTED)
14024                         intel_ddi_init(dev_priv, PORT_D);
14025                 if (found & SFUSE_STRAP_DDIF_DETECTED)
14026                         intel_ddi_init(dev_priv, PORT_F);
14027                 /*
14028                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14029                  */
14030                 if (IS_GEN9_BC(dev_priv) &&
14031                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14032                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14033                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14034                         intel_ddi_init(dev_priv, PORT_E);
14035
14036         } else if (HAS_PCH_SPLIT(dev_priv)) {
14037                 int found;
14038                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14039
14040                 if (has_edp_a(dev_priv))
14041                         intel_dp_init(dev_priv, DP_A, PORT_A);
14042
14043                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14044                         /* PCH SDVOB multiplex with HDMIB */
14045                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14046                         if (!found)
14047                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14048                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14049                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14050                 }
14051
14052                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14053                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14054
14055                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14056                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14057
14058                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14059                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14060
14061                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14062                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14063         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14064                 bool has_edp, has_port;
14065
14066                 /*
14067                  * The DP_DETECTED bit is the latched state of the DDC
14068                  * SDA pin at boot. However since eDP doesn't require DDC
14069                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14070                  * eDP ports may have been muxed to an alternate function.
14071                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14072                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14073                  * detect eDP ports.
14074                  *
14075                  * Sadly the straps seem to be missing sometimes even for HDMI
14076                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14077                  * and VBT for the presence of the port. Additionally we can't
14078                  * trust the port type the VBT declares as we've seen at least
14079                  * HDMI ports that the VBT claim are DP or eDP.
14080                  */
14081                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14082                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14083                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14084                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14085                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14086                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14087
14088                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14089                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14090                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14091                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14092                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14093                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14094
14095                 if (IS_CHERRYVIEW(dev_priv)) {
14096                         /*
14097                          * eDP not supported on port D,
14098                          * so no need to worry about it
14099                          */
14100                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14101                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14102                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14103                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14104                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14105                 }
14106
14107                 vlv_dsi_init(dev_priv);
14108         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
14109                 bool found = false;
14110
14111                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14112                         DRM_DEBUG_KMS("probing SDVOB\n");
14113                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14114                         if (!found && IS_G4X(dev_priv)) {
14115                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14116                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14117                         }
14118
14119                         if (!found && IS_G4X(dev_priv))
14120                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14121                 }
14122
14123                 /* Before G4X SDVOC doesn't have its own detect register */
14124
14125                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14126                         DRM_DEBUG_KMS("probing SDVOC\n");
14127                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14128                 }
14129
14130                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14131
14132                         if (IS_G4X(dev_priv)) {
14133                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14134                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14135                         }
14136                         if (IS_G4X(dev_priv))
14137                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14138                 }
14139
14140                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14141                         intel_dp_init(dev_priv, DP_D, PORT_D);
14142         } else if (IS_GEN2(dev_priv))
14143                 intel_dvo_init(dev_priv);
14144
14145         if (SUPPORTS_TV(dev_priv))
14146                 intel_tv_init(dev_priv);
14147
14148         intel_psr_init(dev_priv);
14149
14150         for_each_intel_encoder(&dev_priv->drm, encoder) {
14151                 encoder->base.possible_crtcs = encoder->crtc_mask;
14152                 encoder->base.possible_clones =
14153                         intel_encoder_clones(encoder);
14154         }
14155
14156         intel_init_pch_refclk(dev_priv);
14157
14158         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14159 }
14160
14161 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14162 {
14163         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14164         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14165
14166         drm_framebuffer_cleanup(fb);
14167
14168         i915_gem_object_lock(obj);
14169         WARN_ON(!obj->framebuffer_references--);
14170         i915_gem_object_unlock(obj);
14171
14172         i915_gem_object_put(obj);
14173
14174         kfree(intel_fb);
14175 }
14176
14177 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14178                                                 struct drm_file *file,
14179                                                 unsigned int *handle)
14180 {
14181         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14182
14183         if (obj->userptr.mm) {
14184                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14185                 return -EINVAL;
14186         }
14187
14188         return drm_gem_handle_create(file, &obj->base, handle);
14189 }
14190
14191 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14192                                         struct drm_file *file,
14193                                         unsigned flags, unsigned color,
14194                                         struct drm_clip_rect *clips,
14195                                         unsigned num_clips)
14196 {
14197         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14198
14199         i915_gem_object_flush_if_display(obj);
14200         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14201
14202         return 0;
14203 }
14204
14205 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14206         .destroy = intel_user_framebuffer_destroy,
14207         .create_handle = intel_user_framebuffer_create_handle,
14208         .dirty = intel_user_framebuffer_dirty,
14209 };
14210
14211 static
14212 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14213                          uint64_t fb_modifier, uint32_t pixel_format)
14214 {
14215         struct intel_crtc *crtc;
14216         struct intel_plane *plane;
14217
14218         /*
14219          * We assume the primary plane for pipe A has
14220          * the highest stride limits of them all.
14221          */
14222         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
14223         plane = to_intel_plane(crtc->base.primary);
14224
14225         return plane->max_stride(plane, pixel_format, fb_modifier,
14226                                  DRM_MODE_ROTATE_0);
14227 }
14228
14229 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14230                                   struct drm_i915_gem_object *obj,
14231                                   struct drm_mode_fb_cmd2 *mode_cmd)
14232 {
14233         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14234         struct drm_framebuffer *fb = &intel_fb->base;
14235         struct drm_format_name_buf format_name;
14236         u32 pitch_limit;
14237         unsigned int tiling, stride;
14238         int ret = -EINVAL;
14239         int i;
14240
14241         i915_gem_object_lock(obj);
14242         obj->framebuffer_references++;
14243         tiling = i915_gem_object_get_tiling(obj);
14244         stride = i915_gem_object_get_stride(obj);
14245         i915_gem_object_unlock(obj);
14246
14247         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14248                 /*
14249                  * If there's a fence, enforce that
14250                  * the fb modifier and tiling mode match.
14251                  */
14252                 if (tiling != I915_TILING_NONE &&
14253                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14254                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14255                         goto err;
14256                 }
14257         } else {
14258                 if (tiling == I915_TILING_X) {
14259                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14260                 } else if (tiling == I915_TILING_Y) {
14261                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14262                         goto err;
14263                 }
14264         }
14265
14266         /* Passed in modifier sanity checking. */
14267         switch (mode_cmd->modifier[0]) {
14268         case I915_FORMAT_MOD_Y_TILED_CCS:
14269         case I915_FORMAT_MOD_Yf_TILED_CCS:
14270                 switch (mode_cmd->pixel_format) {
14271                 case DRM_FORMAT_XBGR8888:
14272                 case DRM_FORMAT_ABGR8888:
14273                 case DRM_FORMAT_XRGB8888:
14274                 case DRM_FORMAT_ARGB8888:
14275                         break;
14276                 default:
14277                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
14278                         goto err;
14279                 }
14280                 /* fall through */
14281         case I915_FORMAT_MOD_Y_TILED:
14282         case I915_FORMAT_MOD_Yf_TILED:
14283                 if (INTEL_GEN(dev_priv) < 9) {
14284                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14285                                       mode_cmd->modifier[0]);
14286                         goto err;
14287                 }
14288         case DRM_FORMAT_MOD_LINEAR:
14289         case I915_FORMAT_MOD_X_TILED:
14290                 break;
14291         default:
14292                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14293                               mode_cmd->modifier[0]);
14294                 goto err;
14295         }
14296
14297         /*
14298          * gen2/3 display engine uses the fence if present,
14299          * so the tiling mode must match the fb modifier exactly.
14300          */
14301         if (INTEL_GEN(dev_priv) < 4 &&
14302             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14303                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14304                 goto err;
14305         }
14306
14307         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14308                                            mode_cmd->pixel_format);
14309         if (mode_cmd->pitches[0] > pitch_limit) {
14310                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14311                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14312                               "tiled" : "linear",
14313                               mode_cmd->pitches[0], pitch_limit);
14314                 goto err;
14315         }
14316
14317         /*
14318          * If there's a fence, enforce that
14319          * the fb pitch and fence stride match.
14320          */
14321         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14322                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14323                               mode_cmd->pitches[0], stride);
14324                 goto err;
14325         }
14326
14327         /* Reject formats not supported by any plane early. */
14328         switch (mode_cmd->pixel_format) {
14329         case DRM_FORMAT_C8:
14330         case DRM_FORMAT_RGB565:
14331         case DRM_FORMAT_XRGB8888:
14332         case DRM_FORMAT_ARGB8888:
14333                 break;
14334         case DRM_FORMAT_XRGB1555:
14335                 if (INTEL_GEN(dev_priv) > 3) {
14336                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14337                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14338                         goto err;
14339                 }
14340                 break;
14341         case DRM_FORMAT_ABGR8888:
14342                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14343                     INTEL_GEN(dev_priv) < 9) {
14344                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14345                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14346                         goto err;
14347                 }
14348                 break;
14349         case DRM_FORMAT_XBGR8888:
14350         case DRM_FORMAT_XRGB2101010:
14351         case DRM_FORMAT_XBGR2101010:
14352                 if (INTEL_GEN(dev_priv) < 4) {
14353                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14354                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14355                         goto err;
14356                 }
14357                 break;
14358         case DRM_FORMAT_ABGR2101010:
14359                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14360                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14361                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14362                         goto err;
14363                 }
14364                 break;
14365         case DRM_FORMAT_YUYV:
14366         case DRM_FORMAT_UYVY:
14367         case DRM_FORMAT_YVYU:
14368         case DRM_FORMAT_VYUY:
14369                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14370                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14371                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14372                         goto err;
14373                 }
14374                 break;
14375         case DRM_FORMAT_NV12:
14376                 if (INTEL_GEN(dev_priv) < 9 || IS_SKYLAKE(dev_priv) ||
14377                     IS_BROXTON(dev_priv) || INTEL_GEN(dev_priv) >= 11) {
14378                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14379                                       drm_get_format_name(mode_cmd->pixel_format,
14380                                                           &format_name));
14381                         goto err;
14382                 }
14383                 break;
14384         default:
14385                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14386                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14387                 goto err;
14388         }
14389
14390         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14391         if (mode_cmd->offsets[0] != 0)
14392                 goto err;
14393
14394         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14395
14396         if (fb->format->format == DRM_FORMAT_NV12 &&
14397             (fb->width < SKL_MIN_YUV_420_SRC_W ||
14398              fb->height < SKL_MIN_YUV_420_SRC_H ||
14399              (fb->width % 4) != 0 || (fb->height % 4) != 0)) {
14400                 DRM_DEBUG_KMS("src dimensions not correct for NV12\n");
14401                 return -EINVAL;
14402         }
14403
14404         for (i = 0; i < fb->format->num_planes; i++) {
14405                 u32 stride_alignment;
14406
14407                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14408                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14409                         goto err;
14410                 }
14411
14412                 stride_alignment = intel_fb_stride_alignment(fb, i);
14413
14414                 /*
14415                  * Display WA #0531: skl,bxt,kbl,glk
14416                  *
14417                  * Render decompression and plane width > 3840
14418                  * combined with horizontal panning requires the
14419                  * plane stride to be a multiple of 4. We'll just
14420                  * require the entire fb to accommodate that to avoid
14421                  * potential runtime errors at plane configuration time.
14422                  */
14423                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14424                     is_ccs_modifier(fb->modifier))
14425                         stride_alignment *= 4;
14426
14427                 if (fb->pitches[i] & (stride_alignment - 1)) {
14428                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14429                                       i, fb->pitches[i], stride_alignment);
14430                         goto err;
14431                 }
14432
14433                 fb->obj[i] = &obj->base;
14434         }
14435
14436         ret = intel_fill_fb_info(dev_priv, fb);
14437         if (ret)
14438                 goto err;
14439
14440         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14441         if (ret) {
14442                 DRM_ERROR("framebuffer init failed %d\n", ret);
14443                 goto err;
14444         }
14445
14446         return 0;
14447
14448 err:
14449         i915_gem_object_lock(obj);
14450         obj->framebuffer_references--;
14451         i915_gem_object_unlock(obj);
14452         return ret;
14453 }
14454
14455 static struct drm_framebuffer *
14456 intel_user_framebuffer_create(struct drm_device *dev,
14457                               struct drm_file *filp,
14458                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14459 {
14460         struct drm_framebuffer *fb;
14461         struct drm_i915_gem_object *obj;
14462         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14463
14464         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14465         if (!obj)
14466                 return ERR_PTR(-ENOENT);
14467
14468         fb = intel_framebuffer_create(obj, &mode_cmd);
14469         if (IS_ERR(fb))
14470                 i915_gem_object_put(obj);
14471
14472         return fb;
14473 }
14474
14475 static void intel_atomic_state_free(struct drm_atomic_state *state)
14476 {
14477         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14478
14479         drm_atomic_state_default_release(state);
14480
14481         i915_sw_fence_fini(&intel_state->commit_ready);
14482
14483         kfree(state);
14484 }
14485
14486 static enum drm_mode_status
14487 intel_mode_valid(struct drm_device *dev,
14488                  const struct drm_display_mode *mode)
14489 {
14490         struct drm_i915_private *dev_priv = to_i915(dev);
14491         int hdisplay_max, htotal_max;
14492         int vdisplay_max, vtotal_max;
14493
14494         /*
14495          * Can't reject DBLSCAN here because Xorg ddxen can add piles
14496          * of DBLSCAN modes to the output's mode list when they detect
14497          * the scaling mode property on the connector. And they don't
14498          * ask the kernel to validate those modes in any way until
14499          * modeset time at which point the client gets a protocol error.
14500          * So in order to not upset those clients we silently ignore the
14501          * DBLSCAN flag on such connectors. For other connectors we will
14502          * reject modes with the DBLSCAN flag in encoder->compute_config().
14503          * And we always reject DBLSCAN modes in connector->mode_valid()
14504          * as we never want such modes on the connector's mode list.
14505          */
14506
14507         if (mode->vscan > 1)
14508                 return MODE_NO_VSCAN;
14509
14510         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14511                 return MODE_H_ILLEGAL;
14512
14513         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14514                            DRM_MODE_FLAG_NCSYNC |
14515                            DRM_MODE_FLAG_PCSYNC))
14516                 return MODE_HSYNC;
14517
14518         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14519                            DRM_MODE_FLAG_PIXMUX |
14520                            DRM_MODE_FLAG_CLKDIV2))
14521                 return MODE_BAD;
14522
14523         if (INTEL_GEN(dev_priv) >= 9 ||
14524             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
14525                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
14526                 vdisplay_max = 4096;
14527                 htotal_max = 8192;
14528                 vtotal_max = 8192;
14529         } else if (INTEL_GEN(dev_priv) >= 3) {
14530                 hdisplay_max = 4096;
14531                 vdisplay_max = 4096;
14532                 htotal_max = 8192;
14533                 vtotal_max = 8192;
14534         } else {
14535                 hdisplay_max = 2048;
14536                 vdisplay_max = 2048;
14537                 htotal_max = 4096;
14538                 vtotal_max = 4096;
14539         }
14540
14541         if (mode->hdisplay > hdisplay_max ||
14542             mode->hsync_start > htotal_max ||
14543             mode->hsync_end > htotal_max ||
14544             mode->htotal > htotal_max)
14545                 return MODE_H_ILLEGAL;
14546
14547         if (mode->vdisplay > vdisplay_max ||
14548             mode->vsync_start > vtotal_max ||
14549             mode->vsync_end > vtotal_max ||
14550             mode->vtotal > vtotal_max)
14551                 return MODE_V_ILLEGAL;
14552
14553         return MODE_OK;
14554 }
14555
14556 static const struct drm_mode_config_funcs intel_mode_funcs = {
14557         .fb_create = intel_user_framebuffer_create,
14558         .get_format_info = intel_get_format_info,
14559         .output_poll_changed = intel_fbdev_output_poll_changed,
14560         .mode_valid = intel_mode_valid,
14561         .atomic_check = intel_atomic_check,
14562         .atomic_commit = intel_atomic_commit,
14563         .atomic_state_alloc = intel_atomic_state_alloc,
14564         .atomic_state_clear = intel_atomic_state_clear,
14565         .atomic_state_free = intel_atomic_state_free,
14566 };
14567
14568 /**
14569  * intel_init_display_hooks - initialize the display modesetting hooks
14570  * @dev_priv: device private
14571  */
14572 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14573 {
14574         intel_init_cdclk_hooks(dev_priv);
14575
14576         if (INTEL_GEN(dev_priv) >= 9) {
14577                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14578                 dev_priv->display.get_initial_plane_config =
14579                         skylake_get_initial_plane_config;
14580                 dev_priv->display.crtc_compute_clock =
14581                         haswell_crtc_compute_clock;
14582                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14583                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14584         } else if (HAS_DDI(dev_priv)) {
14585                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14586                 dev_priv->display.get_initial_plane_config =
14587                         i9xx_get_initial_plane_config;
14588                 dev_priv->display.crtc_compute_clock =
14589                         haswell_crtc_compute_clock;
14590                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14591                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14592         } else if (HAS_PCH_SPLIT(dev_priv)) {
14593                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14594                 dev_priv->display.get_initial_plane_config =
14595                         i9xx_get_initial_plane_config;
14596                 dev_priv->display.crtc_compute_clock =
14597                         ironlake_crtc_compute_clock;
14598                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14599                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14600         } else if (IS_CHERRYVIEW(dev_priv)) {
14601                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14602                 dev_priv->display.get_initial_plane_config =
14603                         i9xx_get_initial_plane_config;
14604                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14605                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14606                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14607         } else if (IS_VALLEYVIEW(dev_priv)) {
14608                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14609                 dev_priv->display.get_initial_plane_config =
14610                         i9xx_get_initial_plane_config;
14611                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14612                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14613                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14614         } else if (IS_G4X(dev_priv)) {
14615                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14616                 dev_priv->display.get_initial_plane_config =
14617                         i9xx_get_initial_plane_config;
14618                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14619                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14620                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14621         } else if (IS_PINEVIEW(dev_priv)) {
14622                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14623                 dev_priv->display.get_initial_plane_config =
14624                         i9xx_get_initial_plane_config;
14625                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14626                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14627                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14628         } else if (!IS_GEN2(dev_priv)) {
14629                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14630                 dev_priv->display.get_initial_plane_config =
14631                         i9xx_get_initial_plane_config;
14632                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14633                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14634                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14635         } else {
14636                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14637                 dev_priv->display.get_initial_plane_config =
14638                         i9xx_get_initial_plane_config;
14639                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14640                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14641                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14642         }
14643
14644         if (IS_GEN5(dev_priv)) {
14645                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14646         } else if (IS_GEN6(dev_priv)) {
14647                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14648         } else if (IS_IVYBRIDGE(dev_priv)) {
14649                 /* FIXME: detect B0+ stepping and use auto training */
14650                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14651         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14652                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14653         }
14654
14655         if (INTEL_GEN(dev_priv) >= 9)
14656                 dev_priv->display.update_crtcs = skl_update_crtcs;
14657         else
14658                 dev_priv->display.update_crtcs = intel_update_crtcs;
14659 }
14660
14661 /*
14662  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14663  */
14664 static void quirk_ssc_force_disable(struct drm_device *dev)
14665 {
14666         struct drm_i915_private *dev_priv = to_i915(dev);
14667         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14668         DRM_INFO("applying lvds SSC disable quirk\n");
14669 }
14670
14671 /*
14672  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14673  * brightness value
14674  */
14675 static void quirk_invert_brightness(struct drm_device *dev)
14676 {
14677         struct drm_i915_private *dev_priv = to_i915(dev);
14678         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14679         DRM_INFO("applying inverted panel brightness quirk\n");
14680 }
14681
14682 /* Some VBT's incorrectly indicate no backlight is present */
14683 static void quirk_backlight_present(struct drm_device *dev)
14684 {
14685         struct drm_i915_private *dev_priv = to_i915(dev);
14686         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14687         DRM_INFO("applying backlight present quirk\n");
14688 }
14689
14690 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14691  * which is 300 ms greater than eDP spec T12 min.
14692  */
14693 static void quirk_increase_t12_delay(struct drm_device *dev)
14694 {
14695         struct drm_i915_private *dev_priv = to_i915(dev);
14696
14697         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14698         DRM_INFO("Applying T12 delay quirk\n");
14699 }
14700
14701 /*
14702  * GeminiLake NUC HDMI outputs require additional off time
14703  * this allows the onboard retimer to correctly sync to signal
14704  */
14705 static void quirk_increase_ddi_disabled_time(struct drm_device *dev)
14706 {
14707         struct drm_i915_private *dev_priv = to_i915(dev);
14708
14709         dev_priv->quirks |= QUIRK_INCREASE_DDI_DISABLED_TIME;
14710         DRM_INFO("Applying Increase DDI Disabled quirk\n");
14711 }
14712
14713 struct intel_quirk {
14714         int device;
14715         int subsystem_vendor;
14716         int subsystem_device;
14717         void (*hook)(struct drm_device *dev);
14718 };
14719
14720 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14721 struct intel_dmi_quirk {
14722         void (*hook)(struct drm_device *dev);
14723         const struct dmi_system_id (*dmi_id_list)[];
14724 };
14725
14726 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14727 {
14728         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14729         return 1;
14730 }
14731
14732 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14733         {
14734                 .dmi_id_list = &(const struct dmi_system_id[]) {
14735                         {
14736                                 .callback = intel_dmi_reverse_brightness,
14737                                 .ident = "NCR Corporation",
14738                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14739                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14740                                 },
14741                         },
14742                         { }  /* terminating entry */
14743                 },
14744                 .hook = quirk_invert_brightness,
14745         },
14746 };
14747
14748 static struct intel_quirk intel_quirks[] = {
14749         /* Lenovo U160 cannot use SSC on LVDS */
14750         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14751
14752         /* Sony Vaio Y cannot use SSC on LVDS */
14753         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14754
14755         /* Acer Aspire 5734Z must invert backlight brightness */
14756         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14757
14758         /* Acer/eMachines G725 */
14759         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14760
14761         /* Acer/eMachines e725 */
14762         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14763
14764         /* Acer/Packard Bell NCL20 */
14765         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14766
14767         /* Acer Aspire 4736Z */
14768         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14769
14770         /* Acer Aspire 5336 */
14771         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14772
14773         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14774         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14775
14776         /* Acer C720 Chromebook (Core i3 4005U) */
14777         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14778
14779         /* Apple Macbook 2,1 (Core 2 T7400) */
14780         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14781
14782         /* Apple Macbook 4,1 */
14783         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14784
14785         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14786         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14787
14788         /* HP Chromebook 14 (Celeron 2955U) */
14789         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14790
14791         /* Dell Chromebook 11 */
14792         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14793
14794         /* Dell Chromebook 11 (2015 version) */
14795         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14796
14797         /* Toshiba Satellite P50-C-18C */
14798         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14799
14800         /* GeminiLake NUC */
14801         { 0x3185, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14802         { 0x3184, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14803         /* ASRock ITX*/
14804         { 0x3185, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14805         { 0x3184, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14806 };
14807
14808 static void intel_init_quirks(struct drm_device *dev)
14809 {
14810         struct pci_dev *d = dev->pdev;
14811         int i;
14812
14813         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14814                 struct intel_quirk *q = &intel_quirks[i];
14815
14816                 if (d->device == q->device &&
14817                     (d->subsystem_vendor == q->subsystem_vendor ||
14818                      q->subsystem_vendor == PCI_ANY_ID) &&
14819                     (d->subsystem_device == q->subsystem_device ||
14820                      q->subsystem_device == PCI_ANY_ID))
14821                         q->hook(dev);
14822         }
14823         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14824                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14825                         intel_dmi_quirks[i].hook(dev);
14826         }
14827 }
14828
14829 /* Disable the VGA plane that we never use */
14830 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14831 {
14832         struct pci_dev *pdev = dev_priv->drm.pdev;
14833         u8 sr1;
14834         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14835
14836         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14837         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14838         outb(SR01, VGA_SR_INDEX);
14839         sr1 = inb(VGA_SR_DATA);
14840         outb(sr1 | 1<<5, VGA_SR_DATA);
14841         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14842         udelay(300);
14843
14844         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14845         POSTING_READ(vga_reg);
14846 }
14847
14848 void intel_modeset_init_hw(struct drm_device *dev)
14849 {
14850         struct drm_i915_private *dev_priv = to_i915(dev);
14851
14852         intel_update_cdclk(dev_priv);
14853         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
14854         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14855 }
14856
14857 /*
14858  * Calculate what we think the watermarks should be for the state we've read
14859  * out of the hardware and then immediately program those watermarks so that
14860  * we ensure the hardware settings match our internal state.
14861  *
14862  * We can calculate what we think WM's should be by creating a duplicate of the
14863  * current state (which was constructed during hardware readout) and running it
14864  * through the atomic check code to calculate new watermark values in the
14865  * state object.
14866  */
14867 static void sanitize_watermarks(struct drm_device *dev)
14868 {
14869         struct drm_i915_private *dev_priv = to_i915(dev);
14870         struct drm_atomic_state *state;
14871         struct intel_atomic_state *intel_state;
14872         struct drm_crtc *crtc;
14873         struct drm_crtc_state *cstate;
14874         struct drm_modeset_acquire_ctx ctx;
14875         int ret;
14876         int i;
14877
14878         /* Only supported on platforms that use atomic watermark design */
14879         if (!dev_priv->display.optimize_watermarks)
14880                 return;
14881
14882         /*
14883          * We need to hold connection_mutex before calling duplicate_state so
14884          * that the connector loop is protected.
14885          */
14886         drm_modeset_acquire_init(&ctx, 0);
14887 retry:
14888         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14889         if (ret == -EDEADLK) {
14890                 drm_modeset_backoff(&ctx);
14891                 goto retry;
14892         } else if (WARN_ON(ret)) {
14893                 goto fail;
14894         }
14895
14896         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14897         if (WARN_ON(IS_ERR(state)))
14898                 goto fail;
14899
14900         intel_state = to_intel_atomic_state(state);
14901
14902         /*
14903          * Hardware readout is the only time we don't want to calculate
14904          * intermediate watermarks (since we don't trust the current
14905          * watermarks).
14906          */
14907         if (!HAS_GMCH_DISPLAY(dev_priv))
14908                 intel_state->skip_intermediate_wm = true;
14909
14910         ret = intel_atomic_check(dev, state);
14911         if (ret) {
14912                 /*
14913                  * If we fail here, it means that the hardware appears to be
14914                  * programmed in a way that shouldn't be possible, given our
14915                  * understanding of watermark requirements.  This might mean a
14916                  * mistake in the hardware readout code or a mistake in the
14917                  * watermark calculations for a given platform.  Raise a WARN
14918                  * so that this is noticeable.
14919                  *
14920                  * If this actually happens, we'll have to just leave the
14921                  * BIOS-programmed watermarks untouched and hope for the best.
14922                  */
14923                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14924                 goto put_state;
14925         }
14926
14927         /* Write calculated watermark values back */
14928         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14929                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14930
14931                 cs->wm.need_postvbl_update = true;
14932                 dev_priv->display.optimize_watermarks(intel_state, cs);
14933
14934                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
14935         }
14936
14937 put_state:
14938         drm_atomic_state_put(state);
14939 fail:
14940         drm_modeset_drop_locks(&ctx);
14941         drm_modeset_acquire_fini(&ctx);
14942 }
14943
14944 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
14945 {
14946         if (IS_GEN5(dev_priv)) {
14947                 u32 fdi_pll_clk =
14948                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
14949
14950                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
14951         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
14952                 dev_priv->fdi_pll_freq = 270000;
14953         } else {
14954                 return;
14955         }
14956
14957         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
14958 }
14959
14960 static int intel_initial_commit(struct drm_device *dev)
14961 {
14962         struct drm_atomic_state *state = NULL;
14963         struct drm_modeset_acquire_ctx ctx;
14964         struct drm_crtc *crtc;
14965         struct drm_crtc_state *crtc_state;
14966         int ret = 0;
14967
14968         state = drm_atomic_state_alloc(dev);
14969         if (!state)
14970                 return -ENOMEM;
14971
14972         drm_modeset_acquire_init(&ctx, 0);
14973
14974 retry:
14975         state->acquire_ctx = &ctx;
14976
14977         drm_for_each_crtc(crtc, dev) {
14978                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
14979                 if (IS_ERR(crtc_state)) {
14980                         ret = PTR_ERR(crtc_state);
14981                         goto out;
14982                 }
14983
14984                 if (crtc_state->active) {
14985                         ret = drm_atomic_add_affected_planes(state, crtc);
14986                         if (ret)
14987                                 goto out;
14988                 }
14989         }
14990
14991         ret = drm_atomic_commit(state);
14992
14993 out:
14994         if (ret == -EDEADLK) {
14995                 drm_atomic_state_clear(state);
14996                 drm_modeset_backoff(&ctx);
14997                 goto retry;
14998         }
14999
15000         drm_atomic_state_put(state);
15001
15002         drm_modeset_drop_locks(&ctx);
15003         drm_modeset_acquire_fini(&ctx);
15004
15005         return ret;
15006 }
15007
15008 int intel_modeset_init(struct drm_device *dev)
15009 {
15010         struct drm_i915_private *dev_priv = to_i915(dev);
15011         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15012         enum pipe pipe;
15013         struct intel_crtc *crtc;
15014         int ret;
15015
15016         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15017
15018         drm_mode_config_init(dev);
15019
15020         dev->mode_config.min_width = 0;
15021         dev->mode_config.min_height = 0;
15022
15023         dev->mode_config.preferred_depth = 24;
15024         dev->mode_config.prefer_shadow = 1;
15025
15026         dev->mode_config.allow_fb_modifiers = true;
15027
15028         dev->mode_config.funcs = &intel_mode_funcs;
15029
15030         init_llist_head(&dev_priv->atomic_helper.free_list);
15031         INIT_WORK(&dev_priv->atomic_helper.free_work,
15032                   intel_atomic_helper_free_state_worker);
15033
15034         intel_init_quirks(dev);
15035
15036         intel_init_pm(dev_priv);
15037
15038         /*
15039          * There may be no VBT; and if the BIOS enabled SSC we can
15040          * just keep using it to avoid unnecessary flicker.  Whereas if the
15041          * BIOS isn't using it, don't assume it will work even if the VBT
15042          * indicates as much.
15043          */
15044         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15045                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15046                                             DREF_SSC1_ENABLE);
15047
15048                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15049                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15050                                      bios_lvds_use_ssc ? "en" : "dis",
15051                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15052                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15053                 }
15054         }
15055
15056         /* maximum framebuffer dimensions */
15057         if (IS_GEN2(dev_priv)) {
15058                 dev->mode_config.max_width = 2048;
15059                 dev->mode_config.max_height = 2048;
15060         } else if (IS_GEN3(dev_priv)) {
15061                 dev->mode_config.max_width = 4096;
15062                 dev->mode_config.max_height = 4096;
15063         } else {
15064                 dev->mode_config.max_width = 8192;
15065                 dev->mode_config.max_height = 8192;
15066         }
15067
15068         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15069                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15070                 dev->mode_config.cursor_height = 1023;
15071         } else if (IS_GEN2(dev_priv)) {
15072                 dev->mode_config.cursor_width = 64;
15073                 dev->mode_config.cursor_height = 64;
15074         } else {
15075                 dev->mode_config.cursor_width = 256;
15076                 dev->mode_config.cursor_height = 256;
15077         }
15078
15079         dev->mode_config.fb_base = ggtt->gmadr.start;
15080
15081         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15082                       INTEL_INFO(dev_priv)->num_pipes,
15083                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15084
15085         for_each_pipe(dev_priv, pipe) {
15086                 ret = intel_crtc_init(dev_priv, pipe);
15087                 if (ret) {
15088                         drm_mode_config_cleanup(dev);
15089                         return ret;
15090                 }
15091         }
15092
15093         intel_shared_dpll_init(dev);
15094         intel_update_fdi_pll_freq(dev_priv);
15095
15096         intel_update_czclk(dev_priv);
15097         intel_modeset_init_hw(dev);
15098
15099         if (dev_priv->max_cdclk_freq == 0)
15100                 intel_update_max_cdclk(dev_priv);
15101
15102         /* Just disable it once at startup */
15103         i915_disable_vga(dev_priv);
15104         intel_setup_outputs(dev_priv);
15105
15106         drm_modeset_lock_all(dev);
15107         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15108         drm_modeset_unlock_all(dev);
15109
15110         for_each_intel_crtc(dev, crtc) {
15111                 struct intel_initial_plane_config plane_config = {};
15112
15113                 if (!crtc->active)
15114                         continue;
15115
15116                 /*
15117                  * Note that reserving the BIOS fb up front prevents us
15118                  * from stuffing other stolen allocations like the ring
15119                  * on top.  This prevents some ugliness at boot time, and
15120                  * can even allow for smooth boot transitions if the BIOS
15121                  * fb is large enough for the active pipe configuration.
15122                  */
15123                 dev_priv->display.get_initial_plane_config(crtc,
15124                                                            &plane_config);
15125
15126                 /*
15127                  * If the fb is shared between multiple heads, we'll
15128                  * just get the first one.
15129                  */
15130                 intel_find_initial_plane_obj(crtc, &plane_config);
15131         }
15132
15133         /*
15134          * Make sure hardware watermarks really match the state we read out.
15135          * Note that we need to do this after reconstructing the BIOS fb's
15136          * since the watermark calculation done here will use pstate->fb.
15137          */
15138         if (!HAS_GMCH_DISPLAY(dev_priv))
15139                 sanitize_watermarks(dev);
15140
15141         /*
15142          * Force all active planes to recompute their states. So that on
15143          * mode_setcrtc after probe, all the intel_plane_state variables
15144          * are already calculated and there is no assert_plane warnings
15145          * during bootup.
15146          */
15147         ret = intel_initial_commit(dev);
15148         if (ret)
15149                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15150
15151         return 0;
15152 }
15153
15154 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15155 {
15156         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15157         /* 640x480@60Hz, ~25175 kHz */
15158         struct dpll clock = {
15159                 .m1 = 18,
15160                 .m2 = 7,
15161                 .p1 = 13,
15162                 .p2 = 4,
15163                 .n = 2,
15164         };
15165         u32 dpll, fp;
15166         int i;
15167
15168         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15169
15170         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15171                       pipe_name(pipe), clock.vco, clock.dot);
15172
15173         fp = i9xx_dpll_compute_fp(&clock);
15174         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
15175                 DPLL_VGA_MODE_DIS |
15176                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15177                 PLL_P2_DIVIDE_BY_4 |
15178                 PLL_REF_INPUT_DREFCLK |
15179                 DPLL_VCO_ENABLE;
15180
15181         I915_WRITE(FP0(pipe), fp);
15182         I915_WRITE(FP1(pipe), fp);
15183
15184         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15185         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15186         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15187         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15188         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15189         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15190         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15191
15192         /*
15193          * Apparently we need to have VGA mode enabled prior to changing
15194          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15195          * dividers, even though the register value does change.
15196          */
15197         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15198         I915_WRITE(DPLL(pipe), dpll);
15199
15200         /* Wait for the clocks to stabilize. */
15201         POSTING_READ(DPLL(pipe));
15202         udelay(150);
15203
15204         /* The pixel multiplier can only be updated once the
15205          * DPLL is enabled and the clocks are stable.
15206          *
15207          * So write it again.
15208          */
15209         I915_WRITE(DPLL(pipe), dpll);
15210
15211         /* We do this three times for luck */
15212         for (i = 0; i < 3 ; i++) {
15213                 I915_WRITE(DPLL(pipe), dpll);
15214                 POSTING_READ(DPLL(pipe));
15215                 udelay(150); /* wait for warmup */
15216         }
15217
15218         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15219         POSTING_READ(PIPECONF(pipe));
15220
15221         intel_wait_for_pipe_scanline_moving(crtc);
15222 }
15223
15224 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15225 {
15226         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15227
15228         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15229                       pipe_name(pipe));
15230
15231         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15232         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15233         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15234         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15235         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
15236
15237         I915_WRITE(PIPECONF(pipe), 0);
15238         POSTING_READ(PIPECONF(pipe));
15239
15240         intel_wait_for_pipe_scanline_stopped(crtc);
15241
15242         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15243         POSTING_READ(DPLL(pipe));
15244 }
15245
15246 static void
15247 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15248 {
15249         struct intel_crtc *crtc;
15250
15251         if (INTEL_GEN(dev_priv) >= 4)
15252                 return;
15253
15254         for_each_intel_crtc(&dev_priv->drm, crtc) {
15255                 struct intel_plane *plane =
15256                         to_intel_plane(crtc->base.primary);
15257                 struct intel_crtc *plane_crtc;
15258                 enum pipe pipe;
15259
15260                 if (!plane->get_hw_state(plane, &pipe))
15261                         continue;
15262
15263                 if (pipe == crtc->pipe)
15264                         continue;
15265
15266                 DRM_DEBUG_KMS("[PLANE:%d:%s] attached to the wrong pipe, disabling plane\n",
15267                               plane->base.base.id, plane->base.name);
15268
15269                 plane_crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15270                 intel_plane_disable_noatomic(plane_crtc, plane);
15271         }
15272 }
15273
15274 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15275 {
15276         struct drm_device *dev = crtc->base.dev;
15277         struct intel_encoder *encoder;
15278
15279         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15280                 return true;
15281
15282         return false;
15283 }
15284
15285 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15286 {
15287         struct drm_device *dev = encoder->base.dev;
15288         struct intel_connector *connector;
15289
15290         for_each_connector_on_encoder(dev, &encoder->base, connector)
15291                 return connector;
15292
15293         return NULL;
15294 }
15295
15296 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15297                               enum pipe pch_transcoder)
15298 {
15299         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15300                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15301 }
15302
15303 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15304                                 struct drm_modeset_acquire_ctx *ctx)
15305 {
15306         struct drm_device *dev = crtc->base.dev;
15307         struct drm_i915_private *dev_priv = to_i915(dev);
15308         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15309
15310         /* Clear any frame start delays used for debugging left by the BIOS */
15311         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15312                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15313
15314                 I915_WRITE(reg,
15315                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15316         }
15317
15318         if (crtc->active) {
15319                 struct intel_plane *plane;
15320
15321                 /* Disable everything but the primary plane */
15322                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15323                         const struct intel_plane_state *plane_state =
15324                                 to_intel_plane_state(plane->base.state);
15325
15326                         if (plane_state->base.visible &&
15327                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15328                                 intel_plane_disable_noatomic(crtc, plane);
15329                 }
15330         }
15331
15332         /* Adjust the state of the output pipe according to whether we
15333          * have active connectors/encoders. */
15334         if (crtc->active && !intel_crtc_has_encoders(crtc))
15335                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15336
15337         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15338                 /*
15339                  * We start out with underrun reporting disabled to avoid races.
15340                  * For correct bookkeeping mark this on active crtcs.
15341                  *
15342                  * Also on gmch platforms we dont have any hardware bits to
15343                  * disable the underrun reporting. Which means we need to start
15344                  * out with underrun reporting disabled also on inactive pipes,
15345                  * since otherwise we'll complain about the garbage we read when
15346                  * e.g. coming up after runtime pm.
15347                  *
15348                  * No protection against concurrent access is required - at
15349                  * worst a fifo underrun happens which also sets this to false.
15350                  */
15351                 crtc->cpu_fifo_underrun_disabled = true;
15352                 /*
15353                  * We track the PCH trancoder underrun reporting state
15354                  * within the crtc. With crtc for pipe A housing the underrun
15355                  * reporting state for PCH transcoder A, crtc for pipe B housing
15356                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15357                  * and marking underrun reporting as disabled for the non-existing
15358                  * PCH transcoders B and C would prevent enabling the south
15359                  * error interrupt (see cpt_can_enable_serr_int()).
15360                  */
15361                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15362                         crtc->pch_fifo_underrun_disabled = true;
15363         }
15364 }
15365
15366 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15367 {
15368         struct intel_connector *connector;
15369
15370         /* We need to check both for a crtc link (meaning that the
15371          * encoder is active and trying to read from a pipe) and the
15372          * pipe itself being active. */
15373         bool has_active_crtc = encoder->base.crtc &&
15374                 to_intel_crtc(encoder->base.crtc)->active;
15375
15376         connector = intel_encoder_find_connector(encoder);
15377         if (connector && !has_active_crtc) {
15378                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15379                               encoder->base.base.id,
15380                               encoder->base.name);
15381
15382                 /* Connector is active, but has no active pipe. This is
15383                  * fallout from our resume register restoring. Disable
15384                  * the encoder manually again. */
15385                 if (encoder->base.crtc) {
15386                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15387
15388                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15389                                       encoder->base.base.id,
15390                                       encoder->base.name);
15391                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15392                         if (encoder->post_disable)
15393                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15394                 }
15395                 encoder->base.crtc = NULL;
15396
15397                 /* Inconsistent output/port/pipe state happens presumably due to
15398                  * a bug in one of the get_hw_state functions. Or someplace else
15399                  * in our code, like the register restore mess on resume. Clamp
15400                  * things to off as a safer default. */
15401
15402                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15403                 connector->base.encoder = NULL;
15404         }
15405
15406         /* notify opregion of the sanitized encoder state */
15407         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
15408 }
15409
15410 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15411 {
15412         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15413
15414         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15415                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15416                 i915_disable_vga(dev_priv);
15417         }
15418 }
15419
15420 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15421 {
15422         /* This function can be called both from intel_modeset_setup_hw_state or
15423          * at a very early point in our resume sequence, where the power well
15424          * structures are not yet restored. Since this function is at a very
15425          * paranoid "someone might have enabled VGA while we were not looking"
15426          * level, just check if the power well is enabled instead of trying to
15427          * follow the "don't touch the power well if we don't need it" policy
15428          * the rest of the driver uses. */
15429         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15430                 return;
15431
15432         i915_redisable_vga_power_on(dev_priv);
15433
15434         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15435 }
15436
15437 /* FIXME read out full plane state for all planes */
15438 static void readout_plane_state(struct drm_i915_private *dev_priv)
15439 {
15440         struct intel_plane *plane;
15441         struct intel_crtc *crtc;
15442
15443         for_each_intel_plane(&dev_priv->drm, plane) {
15444                 struct intel_plane_state *plane_state =
15445                         to_intel_plane_state(plane->base.state);
15446                 struct intel_crtc_state *crtc_state;
15447                 enum pipe pipe = PIPE_A;
15448                 bool visible;
15449
15450                 visible = plane->get_hw_state(plane, &pipe);
15451
15452                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15453                 crtc_state = to_intel_crtc_state(crtc->base.state);
15454
15455                 intel_set_plane_visible(crtc_state, plane_state, visible);
15456
15457                 DRM_DEBUG_KMS("[PLANE:%d:%s] hw state readout: %s, pipe %c\n",
15458                               plane->base.base.id, plane->base.name,
15459                               enableddisabled(visible), pipe_name(pipe));
15460         }
15461
15462         for_each_intel_crtc(&dev_priv->drm, crtc) {
15463                 struct intel_crtc_state *crtc_state =
15464                         to_intel_crtc_state(crtc->base.state);
15465
15466                 fixup_active_planes(crtc_state);
15467         }
15468 }
15469
15470 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15471 {
15472         struct drm_i915_private *dev_priv = to_i915(dev);
15473         enum pipe pipe;
15474         struct intel_crtc *crtc;
15475         struct intel_encoder *encoder;
15476         struct intel_connector *connector;
15477         struct drm_connector_list_iter conn_iter;
15478         int i;
15479
15480         dev_priv->active_crtcs = 0;
15481
15482         for_each_intel_crtc(dev, crtc) {
15483                 struct intel_crtc_state *crtc_state =
15484                         to_intel_crtc_state(crtc->base.state);
15485
15486                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15487                 memset(crtc_state, 0, sizeof(*crtc_state));
15488                 crtc_state->base.crtc = &crtc->base;
15489
15490                 crtc_state->base.active = crtc_state->base.enable =
15491                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15492
15493                 crtc->base.enabled = crtc_state->base.enable;
15494                 crtc->active = crtc_state->base.active;
15495
15496                 if (crtc_state->base.active)
15497                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15498
15499                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15500                               crtc->base.base.id, crtc->base.name,
15501                               enableddisabled(crtc_state->base.active));
15502         }
15503
15504         readout_plane_state(dev_priv);
15505
15506         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15507                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15508
15509                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15510                                                         &pll->state.hw_state);
15511                 pll->state.crtc_mask = 0;
15512                 for_each_intel_crtc(dev, crtc) {
15513                         struct intel_crtc_state *crtc_state =
15514                                 to_intel_crtc_state(crtc->base.state);
15515
15516                         if (crtc_state->base.active &&
15517                             crtc_state->shared_dpll == pll)
15518                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15519                 }
15520                 pll->active_mask = pll->state.crtc_mask;
15521
15522                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15523                               pll->info->name, pll->state.crtc_mask, pll->on);
15524         }
15525
15526         for_each_intel_encoder(dev, encoder) {
15527                 pipe = 0;
15528
15529                 if (encoder->get_hw_state(encoder, &pipe)) {
15530                         struct intel_crtc_state *crtc_state;
15531
15532                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15533                         crtc_state = to_intel_crtc_state(crtc->base.state);
15534
15535                         encoder->base.crtc = &crtc->base;
15536                         encoder->get_config(encoder, crtc_state);
15537                 } else {
15538                         encoder->base.crtc = NULL;
15539                 }
15540
15541                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15542                               encoder->base.base.id, encoder->base.name,
15543                               enableddisabled(encoder->base.crtc),
15544                               pipe_name(pipe));
15545         }
15546
15547         drm_connector_list_iter_begin(dev, &conn_iter);
15548         for_each_intel_connector_iter(connector, &conn_iter) {
15549                 if (connector->get_hw_state(connector)) {
15550                         connector->base.dpms = DRM_MODE_DPMS_ON;
15551
15552                         encoder = connector->encoder;
15553                         connector->base.encoder = &encoder->base;
15554
15555                         if (encoder->base.crtc &&
15556                             encoder->base.crtc->state->active) {
15557                                 /*
15558                                  * This has to be done during hardware readout
15559                                  * because anything calling .crtc_disable may
15560                                  * rely on the connector_mask being accurate.
15561                                  */
15562                                 encoder->base.crtc->state->connector_mask |=
15563                                         drm_connector_mask(&connector->base);
15564                                 encoder->base.crtc->state->encoder_mask |=
15565                                         drm_encoder_mask(&encoder->base);
15566                         }
15567
15568                 } else {
15569                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15570                         connector->base.encoder = NULL;
15571                 }
15572                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15573                               connector->base.base.id, connector->base.name,
15574                               enableddisabled(connector->base.encoder));
15575         }
15576         drm_connector_list_iter_end(&conn_iter);
15577
15578         for_each_intel_crtc(dev, crtc) {
15579                 struct intel_crtc_state *crtc_state =
15580                         to_intel_crtc_state(crtc->base.state);
15581                 int min_cdclk = 0;
15582
15583                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15584                 if (crtc_state->base.active) {
15585                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15586                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
15587                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
15588                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15589                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15590
15591                         /*
15592                          * The initial mode needs to be set in order to keep
15593                          * the atomic core happy. It wants a valid mode if the
15594                          * crtc's enabled, so we do the above call.
15595                          *
15596                          * But we don't set all the derived state fully, hence
15597                          * set a flag to indicate that a full recalculation is
15598                          * needed on the next commit.
15599                          */
15600                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15601
15602                         intel_crtc_compute_pixel_rate(crtc_state);
15603
15604                         if (dev_priv->display.modeset_calc_cdclk) {
15605                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15606                                 if (WARN_ON(min_cdclk < 0))
15607                                         min_cdclk = 0;
15608                         }
15609
15610                         drm_calc_timestamping_constants(&crtc->base,
15611                                                         &crtc_state->base.adjusted_mode);
15612                         update_scanline_offset(crtc);
15613                 }
15614
15615                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15616                 dev_priv->min_voltage_level[crtc->pipe] =
15617                         crtc_state->min_voltage_level;
15618
15619                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15620         }
15621 }
15622
15623 static void
15624 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15625 {
15626         struct intel_encoder *encoder;
15627
15628         for_each_intel_encoder(&dev_priv->drm, encoder) {
15629                 u64 get_domains;
15630                 enum intel_display_power_domain domain;
15631                 struct intel_crtc_state *crtc_state;
15632
15633                 if (!encoder->get_power_domains)
15634                         continue;
15635
15636                 /*
15637                  * MST-primary and inactive encoders don't have a crtc state
15638                  * and neither of these require any power domain references.
15639                  */
15640                 if (!encoder->base.crtc)
15641                         continue;
15642
15643                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
15644                 get_domains = encoder->get_power_domains(encoder, crtc_state);
15645                 for_each_power_domain(domain, get_domains)
15646                         intel_display_power_get(dev_priv, domain);
15647         }
15648 }
15649
15650 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15651 {
15652         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15653         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15654                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15655                            DARBF_GATING_DIS);
15656
15657         if (IS_HASWELL(dev_priv)) {
15658                 /*
15659                  * WaRsPkgCStateDisplayPMReq:hsw
15660                  * System hang if this isn't done before disabling all planes!
15661                  */
15662                 I915_WRITE(CHICKEN_PAR1_1,
15663                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15664         }
15665 }
15666
15667 /* Scan out the current hw modeset state,
15668  * and sanitizes it to the current state
15669  */
15670 static void
15671 intel_modeset_setup_hw_state(struct drm_device *dev,
15672                              struct drm_modeset_acquire_ctx *ctx)
15673 {
15674         struct drm_i915_private *dev_priv = to_i915(dev);
15675         struct intel_crtc *crtc;
15676         struct intel_encoder *encoder;
15677         int i;
15678
15679         intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
15680
15681         intel_early_display_was(dev_priv);
15682         intel_modeset_readout_hw_state(dev);
15683
15684         /* HW state is read out, now we need to sanitize this mess. */
15685         get_encoder_power_domains(dev_priv);
15686
15687         /*
15688          * intel_sanitize_plane_mapping() may need to do vblank
15689          * waits, so we need vblank interrupts restored beforehand.
15690          */
15691         for_each_intel_crtc(&dev_priv->drm, crtc) {
15692                 drm_crtc_vblank_reset(&crtc->base);
15693
15694                 if (crtc->active)
15695                         drm_crtc_vblank_on(&crtc->base);
15696         }
15697
15698         intel_sanitize_plane_mapping(dev_priv);
15699
15700         for_each_intel_encoder(dev, encoder)
15701                 intel_sanitize_encoder(encoder);
15702
15703         for_each_intel_crtc(&dev_priv->drm, crtc) {
15704                 intel_sanitize_crtc(crtc, ctx);
15705                 intel_dump_pipe_config(crtc, crtc->config,
15706                                        "[setup_hw_state]");
15707         }
15708
15709         intel_modeset_update_connector_atomic_state(dev);
15710
15711         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15712                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15713
15714                 if (!pll->on || pll->active_mask)
15715                         continue;
15716
15717                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
15718                               pll->info->name);
15719
15720                 pll->info->funcs->disable(dev_priv, pll);
15721                 pll->on = false;
15722         }
15723
15724         if (IS_G4X(dev_priv)) {
15725                 g4x_wm_get_hw_state(dev);
15726                 g4x_wm_sanitize(dev_priv);
15727         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15728                 vlv_wm_get_hw_state(dev);
15729                 vlv_wm_sanitize(dev_priv);
15730         } else if (INTEL_GEN(dev_priv) >= 9) {
15731                 skl_wm_get_hw_state(dev);
15732         } else if (HAS_PCH_SPLIT(dev_priv)) {
15733                 ilk_wm_get_hw_state(dev);
15734         }
15735
15736         for_each_intel_crtc(dev, crtc) {
15737                 u64 put_domains;
15738
15739                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15740                 if (WARN_ON(put_domains))
15741                         modeset_put_power_domains(dev_priv, put_domains);
15742         }
15743
15744         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT);
15745
15746         intel_fbc_init_pipe_state(dev_priv);
15747 }
15748
15749 void intel_display_resume(struct drm_device *dev)
15750 {
15751         struct drm_i915_private *dev_priv = to_i915(dev);
15752         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15753         struct drm_modeset_acquire_ctx ctx;
15754         int ret;
15755
15756         dev_priv->modeset_restore_state = NULL;
15757         if (state)
15758                 state->acquire_ctx = &ctx;
15759
15760         drm_modeset_acquire_init(&ctx, 0);
15761
15762         while (1) {
15763                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15764                 if (ret != -EDEADLK)
15765                         break;
15766
15767                 drm_modeset_backoff(&ctx);
15768         }
15769
15770         if (!ret)
15771                 ret = __intel_display_resume(dev, state, &ctx);
15772
15773         intel_enable_ipc(dev_priv);
15774         drm_modeset_drop_locks(&ctx);
15775         drm_modeset_acquire_fini(&ctx);
15776
15777         if (ret)
15778                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15779         if (state)
15780                 drm_atomic_state_put(state);
15781 }
15782
15783 static void intel_hpd_poll_fini(struct drm_device *dev)
15784 {
15785         struct intel_connector *connector;
15786         struct drm_connector_list_iter conn_iter;
15787
15788         /* Kill all the work that may have been queued by hpd. */
15789         drm_connector_list_iter_begin(dev, &conn_iter);
15790         for_each_intel_connector_iter(connector, &conn_iter) {
15791                 if (connector->modeset_retry_work.func)
15792                         cancel_work_sync(&connector->modeset_retry_work);
15793                 if (connector->hdcp_shim) {
15794                         cancel_delayed_work_sync(&connector->hdcp_check_work);
15795                         cancel_work_sync(&connector->hdcp_prop_work);
15796                 }
15797         }
15798         drm_connector_list_iter_end(&conn_iter);
15799 }
15800
15801 void intel_modeset_cleanup(struct drm_device *dev)
15802 {
15803         struct drm_i915_private *dev_priv = to_i915(dev);
15804
15805         flush_workqueue(dev_priv->modeset_wq);
15806
15807         flush_work(&dev_priv->atomic_helper.free_work);
15808         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15809
15810         /*
15811          * Interrupts and polling as the first thing to avoid creating havoc.
15812          * Too much stuff here (turning of connectors, ...) would
15813          * experience fancy races otherwise.
15814          */
15815         intel_irq_uninstall(dev_priv);
15816
15817         /*
15818          * Due to the hpd irq storm handling the hotplug work can re-arm the
15819          * poll handlers. Hence disable polling after hpd handling is shut down.
15820          */
15821         intel_hpd_poll_fini(dev);
15822
15823         /* poll work can call into fbdev, hence clean that up afterwards */
15824         intel_fbdev_fini(dev_priv);
15825
15826         intel_unregister_dsm_handler();
15827
15828         intel_fbc_global_disable(dev_priv);
15829
15830         /* flush any delayed tasks or pending work */
15831         flush_scheduled_work();
15832
15833         drm_mode_config_cleanup(dev);
15834
15835         intel_cleanup_overlay(dev_priv);
15836
15837         intel_teardown_gmbus(dev_priv);
15838
15839         destroy_workqueue(dev_priv->modeset_wq);
15840 }
15841
15842 /*
15843  * set vga decode state - true == enable VGA decode
15844  */
15845 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15846 {
15847         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15848         u16 gmch_ctrl;
15849
15850         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15851                 DRM_ERROR("failed to read control word\n");
15852                 return -EIO;
15853         }
15854
15855         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15856                 return 0;
15857
15858         if (state)
15859                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15860         else
15861                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15862
15863         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15864                 DRM_ERROR("failed to write control word\n");
15865                 return -EIO;
15866         }
15867
15868         return 0;
15869 }
15870
15871 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15872
15873 struct intel_display_error_state {
15874
15875         u32 power_well_driver;
15876
15877         int num_transcoders;
15878
15879         struct intel_cursor_error_state {
15880                 u32 control;
15881                 u32 position;
15882                 u32 base;
15883                 u32 size;
15884         } cursor[I915_MAX_PIPES];
15885
15886         struct intel_pipe_error_state {
15887                 bool power_domain_on;
15888                 u32 source;
15889                 u32 stat;
15890         } pipe[I915_MAX_PIPES];
15891
15892         struct intel_plane_error_state {
15893                 u32 control;
15894                 u32 stride;
15895                 u32 size;
15896                 u32 pos;
15897                 u32 addr;
15898                 u32 surface;
15899                 u32 tile_offset;
15900         } plane[I915_MAX_PIPES];
15901
15902         struct intel_transcoder_error_state {
15903                 bool power_domain_on;
15904                 enum transcoder cpu_transcoder;
15905
15906                 u32 conf;
15907
15908                 u32 htotal;
15909                 u32 hblank;
15910                 u32 hsync;
15911                 u32 vtotal;
15912                 u32 vblank;
15913                 u32 vsync;
15914         } transcoder[4];
15915 };
15916
15917 struct intel_display_error_state *
15918 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15919 {
15920         struct intel_display_error_state *error;
15921         int transcoders[] = {
15922                 TRANSCODER_A,
15923                 TRANSCODER_B,
15924                 TRANSCODER_C,
15925                 TRANSCODER_EDP,
15926         };
15927         int i;
15928
15929         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15930                 return NULL;
15931
15932         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15933         if (error == NULL)
15934                 return NULL;
15935
15936         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15937                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
15938
15939         for_each_pipe(dev_priv, i) {
15940                 error->pipe[i].power_domain_on =
15941                         __intel_display_power_is_enabled(dev_priv,
15942                                                          POWER_DOMAIN_PIPE(i));
15943                 if (!error->pipe[i].power_domain_on)
15944                         continue;
15945
15946                 error->cursor[i].control = I915_READ(CURCNTR(i));
15947                 error->cursor[i].position = I915_READ(CURPOS(i));
15948                 error->cursor[i].base = I915_READ(CURBASE(i));
15949
15950                 error->plane[i].control = I915_READ(DSPCNTR(i));
15951                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15952                 if (INTEL_GEN(dev_priv) <= 3) {
15953                         error->plane[i].size = I915_READ(DSPSIZE(i));
15954                         error->plane[i].pos = I915_READ(DSPPOS(i));
15955                 }
15956                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15957                         error->plane[i].addr = I915_READ(DSPADDR(i));
15958                 if (INTEL_GEN(dev_priv) >= 4) {
15959                         error->plane[i].surface = I915_READ(DSPSURF(i));
15960                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15961                 }
15962
15963                 error->pipe[i].source = I915_READ(PIPESRC(i));
15964
15965                 if (HAS_GMCH_DISPLAY(dev_priv))
15966                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15967         }
15968
15969         /* Note: this does not include DSI transcoders. */
15970         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15971         if (HAS_DDI(dev_priv))
15972                 error->num_transcoders++; /* Account for eDP. */
15973
15974         for (i = 0; i < error->num_transcoders; i++) {
15975                 enum transcoder cpu_transcoder = transcoders[i];
15976
15977                 error->transcoder[i].power_domain_on =
15978                         __intel_display_power_is_enabled(dev_priv,
15979                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15980                 if (!error->transcoder[i].power_domain_on)
15981                         continue;
15982
15983                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15984
15985                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15986                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15987                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15988                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15989                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15990                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15991                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15992         }
15993
15994         return error;
15995 }
15996
15997 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15998
15999 void
16000 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16001                                 struct intel_display_error_state *error)
16002 {
16003         struct drm_i915_private *dev_priv = m->i915;
16004         int i;
16005
16006         if (!error)
16007                 return;
16008
16009         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16010         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16011                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16012                            error->power_well_driver);
16013         for_each_pipe(dev_priv, i) {
16014                 err_printf(m, "Pipe [%d]:\n", i);
16015                 err_printf(m, "  Power: %s\n",
16016                            onoff(error->pipe[i].power_domain_on));
16017                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16018                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16019
16020                 err_printf(m, "Plane [%d]:\n", i);
16021                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16022                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16023                 if (INTEL_GEN(dev_priv) <= 3) {
16024                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16025                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16026                 }
16027                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16028                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16029                 if (INTEL_GEN(dev_priv) >= 4) {
16030                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16031                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16032                 }
16033
16034                 err_printf(m, "Cursor [%d]:\n", i);
16035                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16036                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16037                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16038         }
16039
16040         for (i = 0; i < error->num_transcoders; i++) {
16041                 err_printf(m, "CPU transcoder: %s\n",
16042                            transcoder_name(error->transcoder[i].cpu_transcoder));
16043                 err_printf(m, "  Power: %s\n",
16044                            onoff(error->transcoder[i].power_domain_on));
16045                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16046                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16047                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16048                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16049                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16050                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16051                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16052         }
16053 }
16054
16055 #endif