Merge tag 'drm-intel-next-2018-09-21' of git://anongit.freedesktop.org/drm/drm-intel...
[linux-block.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 static const uint32_t skl_primary_formats[] = {
78         DRM_FORMAT_C8,
79         DRM_FORMAT_RGB565,
80         DRM_FORMAT_XRGB8888,
81         DRM_FORMAT_XBGR8888,
82         DRM_FORMAT_ARGB8888,
83         DRM_FORMAT_ABGR8888,
84         DRM_FORMAT_XRGB2101010,
85         DRM_FORMAT_XBGR2101010,
86         DRM_FORMAT_YUYV,
87         DRM_FORMAT_YVYU,
88         DRM_FORMAT_UYVY,
89         DRM_FORMAT_VYUY,
90 };
91
92 static const uint32_t skl_pri_planar_formats[] = {
93         DRM_FORMAT_C8,
94         DRM_FORMAT_RGB565,
95         DRM_FORMAT_XRGB8888,
96         DRM_FORMAT_XBGR8888,
97         DRM_FORMAT_ARGB8888,
98         DRM_FORMAT_ABGR8888,
99         DRM_FORMAT_XRGB2101010,
100         DRM_FORMAT_XBGR2101010,
101         DRM_FORMAT_YUYV,
102         DRM_FORMAT_YVYU,
103         DRM_FORMAT_UYVY,
104         DRM_FORMAT_VYUY,
105         DRM_FORMAT_NV12,
106 };
107
108 static const uint64_t skl_format_modifiers_noccs[] = {
109         I915_FORMAT_MOD_Yf_TILED,
110         I915_FORMAT_MOD_Y_TILED,
111         I915_FORMAT_MOD_X_TILED,
112         DRM_FORMAT_MOD_LINEAR,
113         DRM_FORMAT_MOD_INVALID
114 };
115
116 static const uint64_t skl_format_modifiers_ccs[] = {
117         I915_FORMAT_MOD_Yf_TILED_CCS,
118         I915_FORMAT_MOD_Y_TILED_CCS,
119         I915_FORMAT_MOD_Yf_TILED,
120         I915_FORMAT_MOD_Y_TILED,
121         I915_FORMAT_MOD_X_TILED,
122         DRM_FORMAT_MOD_LINEAR,
123         DRM_FORMAT_MOD_INVALID
124 };
125
126 /* Cursor formats */
127 static const uint32_t intel_cursor_formats[] = {
128         DRM_FORMAT_ARGB8888,
129 };
130
131 static const uint64_t cursor_format_modifiers[] = {
132         DRM_FORMAT_MOD_LINEAR,
133         DRM_FORMAT_MOD_INVALID
134 };
135
136 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
137                                 struct intel_crtc_state *pipe_config);
138 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
139                                    struct intel_crtc_state *pipe_config);
140
141 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
142                                   struct drm_i915_gem_object *obj,
143                                   struct drm_mode_fb_cmd2 *mode_cmd);
144 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
145 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
146 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
147 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
148                                          struct intel_link_m_n *m_n,
149                                          struct intel_link_m_n *m2_n2);
150 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
151 static void haswell_set_pipeconf(struct drm_crtc *crtc);
152 static void haswell_set_pipemisc(struct drm_crtc *crtc);
153 static void vlv_prepare_pll(struct intel_crtc *crtc,
154                             const struct intel_crtc_state *pipe_config);
155 static void chv_prepare_pll(struct intel_crtc *crtc,
156                             const struct intel_crtc_state *pipe_config);
157 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
158 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
159 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
160                                     struct intel_crtc_state *crtc_state);
161 static void skylake_pfit_enable(struct intel_crtc *crtc);
162 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
163 static void ironlake_pfit_enable(struct intel_crtc *crtc);
164 static void intel_modeset_setup_hw_state(struct drm_device *dev,
165                                          struct drm_modeset_acquire_ctx *ctx);
166 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
167
168 struct intel_limit {
169         struct {
170                 int min, max;
171         } dot, vco, n, m, m1, m2, p, p1;
172
173         struct {
174                 int dot_limit;
175                 int p2_slow, p2_fast;
176         } p2;
177 };
178
179 /* returns HPLL frequency in kHz */
180 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
181 {
182         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
183
184         /* Obtain SKU information */
185         mutex_lock(&dev_priv->sb_lock);
186         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
187                 CCK_FUSE_HPLL_FREQ_MASK;
188         mutex_unlock(&dev_priv->sb_lock);
189
190         return vco_freq[hpll_freq] * 1000;
191 }
192
193 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
194                       const char *name, u32 reg, int ref_freq)
195 {
196         u32 val;
197         int divider;
198
199         mutex_lock(&dev_priv->sb_lock);
200         val = vlv_cck_read(dev_priv, reg);
201         mutex_unlock(&dev_priv->sb_lock);
202
203         divider = val & CCK_FREQUENCY_VALUES;
204
205         WARN((val & CCK_FREQUENCY_STATUS) !=
206              (divider << CCK_FREQUENCY_STATUS_SHIFT),
207              "%s change in progress\n", name);
208
209         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
210 }
211
212 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
213                            const char *name, u32 reg)
214 {
215         if (dev_priv->hpll_freq == 0)
216                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
217
218         return vlv_get_cck_clock(dev_priv, name, reg,
219                                  dev_priv->hpll_freq);
220 }
221
222 static void intel_update_czclk(struct drm_i915_private *dev_priv)
223 {
224         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
225                 return;
226
227         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
228                                                       CCK_CZ_CLOCK_CONTROL);
229
230         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
231 }
232
233 static inline u32 /* units of 100MHz */
234 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
235                     const struct intel_crtc_state *pipe_config)
236 {
237         if (HAS_DDI(dev_priv))
238                 return pipe_config->port_clock; /* SPLL */
239         else
240                 return dev_priv->fdi_pll_freq;
241 }
242
243 static const struct intel_limit intel_limits_i8xx_dac = {
244         .dot = { .min = 25000, .max = 350000 },
245         .vco = { .min = 908000, .max = 1512000 },
246         .n = { .min = 2, .max = 16 },
247         .m = { .min = 96, .max = 140 },
248         .m1 = { .min = 18, .max = 26 },
249         .m2 = { .min = 6, .max = 16 },
250         .p = { .min = 4, .max = 128 },
251         .p1 = { .min = 2, .max = 33 },
252         .p2 = { .dot_limit = 165000,
253                 .p2_slow = 4, .p2_fast = 2 },
254 };
255
256 static const struct intel_limit intel_limits_i8xx_dvo = {
257         .dot = { .min = 25000, .max = 350000 },
258         .vco = { .min = 908000, .max = 1512000 },
259         .n = { .min = 2, .max = 16 },
260         .m = { .min = 96, .max = 140 },
261         .m1 = { .min = 18, .max = 26 },
262         .m2 = { .min = 6, .max = 16 },
263         .p = { .min = 4, .max = 128 },
264         .p1 = { .min = 2, .max = 33 },
265         .p2 = { .dot_limit = 165000,
266                 .p2_slow = 4, .p2_fast = 4 },
267 };
268
269 static const struct intel_limit intel_limits_i8xx_lvds = {
270         .dot = { .min = 25000, .max = 350000 },
271         .vco = { .min = 908000, .max = 1512000 },
272         .n = { .min = 2, .max = 16 },
273         .m = { .min = 96, .max = 140 },
274         .m1 = { .min = 18, .max = 26 },
275         .m2 = { .min = 6, .max = 16 },
276         .p = { .min = 4, .max = 128 },
277         .p1 = { .min = 1, .max = 6 },
278         .p2 = { .dot_limit = 165000,
279                 .p2_slow = 14, .p2_fast = 7 },
280 };
281
282 static const struct intel_limit intel_limits_i9xx_sdvo = {
283         .dot = { .min = 20000, .max = 400000 },
284         .vco = { .min = 1400000, .max = 2800000 },
285         .n = { .min = 1, .max = 6 },
286         .m = { .min = 70, .max = 120 },
287         .m1 = { .min = 8, .max = 18 },
288         .m2 = { .min = 3, .max = 7 },
289         .p = { .min = 5, .max = 80 },
290         .p1 = { .min = 1, .max = 8 },
291         .p2 = { .dot_limit = 200000,
292                 .p2_slow = 10, .p2_fast = 5 },
293 };
294
295 static const struct intel_limit intel_limits_i9xx_lvds = {
296         .dot = { .min = 20000, .max = 400000 },
297         .vco = { .min = 1400000, .max = 2800000 },
298         .n = { .min = 1, .max = 6 },
299         .m = { .min = 70, .max = 120 },
300         .m1 = { .min = 8, .max = 18 },
301         .m2 = { .min = 3, .max = 7 },
302         .p = { .min = 7, .max = 98 },
303         .p1 = { .min = 1, .max = 8 },
304         .p2 = { .dot_limit = 112000,
305                 .p2_slow = 14, .p2_fast = 7 },
306 };
307
308
309 static const struct intel_limit intel_limits_g4x_sdvo = {
310         .dot = { .min = 25000, .max = 270000 },
311         .vco = { .min = 1750000, .max = 3500000},
312         .n = { .min = 1, .max = 4 },
313         .m = { .min = 104, .max = 138 },
314         .m1 = { .min = 17, .max = 23 },
315         .m2 = { .min = 5, .max = 11 },
316         .p = { .min = 10, .max = 30 },
317         .p1 = { .min = 1, .max = 3},
318         .p2 = { .dot_limit = 270000,
319                 .p2_slow = 10,
320                 .p2_fast = 10
321         },
322 };
323
324 static const struct intel_limit intel_limits_g4x_hdmi = {
325         .dot = { .min = 22000, .max = 400000 },
326         .vco = { .min = 1750000, .max = 3500000},
327         .n = { .min = 1, .max = 4 },
328         .m = { .min = 104, .max = 138 },
329         .m1 = { .min = 16, .max = 23 },
330         .m2 = { .min = 5, .max = 11 },
331         .p = { .min = 5, .max = 80 },
332         .p1 = { .min = 1, .max = 8},
333         .p2 = { .dot_limit = 165000,
334                 .p2_slow = 10, .p2_fast = 5 },
335 };
336
337 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
338         .dot = { .min = 20000, .max = 115000 },
339         .vco = { .min = 1750000, .max = 3500000 },
340         .n = { .min = 1, .max = 3 },
341         .m = { .min = 104, .max = 138 },
342         .m1 = { .min = 17, .max = 23 },
343         .m2 = { .min = 5, .max = 11 },
344         .p = { .min = 28, .max = 112 },
345         .p1 = { .min = 2, .max = 8 },
346         .p2 = { .dot_limit = 0,
347                 .p2_slow = 14, .p2_fast = 14
348         },
349 };
350
351 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
352         .dot = { .min = 80000, .max = 224000 },
353         .vco = { .min = 1750000, .max = 3500000 },
354         .n = { .min = 1, .max = 3 },
355         .m = { .min = 104, .max = 138 },
356         .m1 = { .min = 17, .max = 23 },
357         .m2 = { .min = 5, .max = 11 },
358         .p = { .min = 14, .max = 42 },
359         .p1 = { .min = 2, .max = 6 },
360         .p2 = { .dot_limit = 0,
361                 .p2_slow = 7, .p2_fast = 7
362         },
363 };
364
365 static const struct intel_limit intel_limits_pineview_sdvo = {
366         .dot = { .min = 20000, .max = 400000},
367         .vco = { .min = 1700000, .max = 3500000 },
368         /* Pineview's Ncounter is a ring counter */
369         .n = { .min = 3, .max = 6 },
370         .m = { .min = 2, .max = 256 },
371         /* Pineview only has one combined m divider, which we treat as m2. */
372         .m1 = { .min = 0, .max = 0 },
373         .m2 = { .min = 0, .max = 254 },
374         .p = { .min = 5, .max = 80 },
375         .p1 = { .min = 1, .max = 8 },
376         .p2 = { .dot_limit = 200000,
377                 .p2_slow = 10, .p2_fast = 5 },
378 };
379
380 static const struct intel_limit intel_limits_pineview_lvds = {
381         .dot = { .min = 20000, .max = 400000 },
382         .vco = { .min = 1700000, .max = 3500000 },
383         .n = { .min = 3, .max = 6 },
384         .m = { .min = 2, .max = 256 },
385         .m1 = { .min = 0, .max = 0 },
386         .m2 = { .min = 0, .max = 254 },
387         .p = { .min = 7, .max = 112 },
388         .p1 = { .min = 1, .max = 8 },
389         .p2 = { .dot_limit = 112000,
390                 .p2_slow = 14, .p2_fast = 14 },
391 };
392
393 /* Ironlake / Sandybridge
394  *
395  * We calculate clock using (register_value + 2) for N/M1/M2, so here
396  * the range value for them is (actual_value - 2).
397  */
398 static const struct intel_limit intel_limits_ironlake_dac = {
399         .dot = { .min = 25000, .max = 350000 },
400         .vco = { .min = 1760000, .max = 3510000 },
401         .n = { .min = 1, .max = 5 },
402         .m = { .min = 79, .max = 127 },
403         .m1 = { .min = 12, .max = 22 },
404         .m2 = { .min = 5, .max = 9 },
405         .p = { .min = 5, .max = 80 },
406         .p1 = { .min = 1, .max = 8 },
407         .p2 = { .dot_limit = 225000,
408                 .p2_slow = 10, .p2_fast = 5 },
409 };
410
411 static const struct intel_limit intel_limits_ironlake_single_lvds = {
412         .dot = { .min = 25000, .max = 350000 },
413         .vco = { .min = 1760000, .max = 3510000 },
414         .n = { .min = 1, .max = 3 },
415         .m = { .min = 79, .max = 118 },
416         .m1 = { .min = 12, .max = 22 },
417         .m2 = { .min = 5, .max = 9 },
418         .p = { .min = 28, .max = 112 },
419         .p1 = { .min = 2, .max = 8 },
420         .p2 = { .dot_limit = 225000,
421                 .p2_slow = 14, .p2_fast = 14 },
422 };
423
424 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
425         .dot = { .min = 25000, .max = 350000 },
426         .vco = { .min = 1760000, .max = 3510000 },
427         .n = { .min = 1, .max = 3 },
428         .m = { .min = 79, .max = 127 },
429         .m1 = { .min = 12, .max = 22 },
430         .m2 = { .min = 5, .max = 9 },
431         .p = { .min = 14, .max = 56 },
432         .p1 = { .min = 2, .max = 8 },
433         .p2 = { .dot_limit = 225000,
434                 .p2_slow = 7, .p2_fast = 7 },
435 };
436
437 /* LVDS 100mhz refclk limits. */
438 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
439         .dot = { .min = 25000, .max = 350000 },
440         .vco = { .min = 1760000, .max = 3510000 },
441         .n = { .min = 1, .max = 2 },
442         .m = { .min = 79, .max = 126 },
443         .m1 = { .min = 12, .max = 22 },
444         .m2 = { .min = 5, .max = 9 },
445         .p = { .min = 28, .max = 112 },
446         .p1 = { .min = 2, .max = 8 },
447         .p2 = { .dot_limit = 225000,
448                 .p2_slow = 14, .p2_fast = 14 },
449 };
450
451 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
452         .dot = { .min = 25000, .max = 350000 },
453         .vco = { .min = 1760000, .max = 3510000 },
454         .n = { .min = 1, .max = 3 },
455         .m = { .min = 79, .max = 126 },
456         .m1 = { .min = 12, .max = 22 },
457         .m2 = { .min = 5, .max = 9 },
458         .p = { .min = 14, .max = 42 },
459         .p1 = { .min = 2, .max = 6 },
460         .p2 = { .dot_limit = 225000,
461                 .p2_slow = 7, .p2_fast = 7 },
462 };
463
464 static const struct intel_limit intel_limits_vlv = {
465          /*
466           * These are the data rate limits (measured in fast clocks)
467           * since those are the strictest limits we have. The fast
468           * clock and actual rate limits are more relaxed, so checking
469           * them would make no difference.
470           */
471         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
472         .vco = { .min = 4000000, .max = 6000000 },
473         .n = { .min = 1, .max = 7 },
474         .m1 = { .min = 2, .max = 3 },
475         .m2 = { .min = 11, .max = 156 },
476         .p1 = { .min = 2, .max = 3 },
477         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
478 };
479
480 static const struct intel_limit intel_limits_chv = {
481         /*
482          * These are the data rate limits (measured in fast clocks)
483          * since those are the strictest limits we have.  The fast
484          * clock and actual rate limits are more relaxed, so checking
485          * them would make no difference.
486          */
487         .dot = { .min = 25000 * 5, .max = 540000 * 5},
488         .vco = { .min = 4800000, .max = 6480000 },
489         .n = { .min = 1, .max = 1 },
490         .m1 = { .min = 2, .max = 2 },
491         .m2 = { .min = 24 << 22, .max = 175 << 22 },
492         .p1 = { .min = 2, .max = 4 },
493         .p2 = { .p2_slow = 1, .p2_fast = 14 },
494 };
495
496 static const struct intel_limit intel_limits_bxt = {
497         /* FIXME: find real dot limits */
498         .dot = { .min = 0, .max = INT_MAX },
499         .vco = { .min = 4800000, .max = 6700000 },
500         .n = { .min = 1, .max = 1 },
501         .m1 = { .min = 2, .max = 2 },
502         /* FIXME: find real m2 limits */
503         .m2 = { .min = 2 << 22, .max = 255 << 22 },
504         .p1 = { .min = 2, .max = 4 },
505         .p2 = { .p2_slow = 1, .p2_fast = 20 },
506 };
507
508 static void
509 skl_wa_528(struct drm_i915_private *dev_priv, int pipe, bool enable)
510 {
511         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
512                 return;
513
514         if (enable)
515                 I915_WRITE(CHICKEN_PIPESL_1(pipe), HSW_FBCQ_DIS);
516         else
517                 I915_WRITE(CHICKEN_PIPESL_1(pipe), 0);
518 }
519
520 static void
521 skl_wa_clkgate(struct drm_i915_private *dev_priv, int pipe, bool enable)
522 {
523         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
524                 return;
525
526         if (enable)
527                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
528                            DUPS1_GATING_DIS | DUPS2_GATING_DIS);
529         else
530                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
531                            I915_READ(CLKGATE_DIS_PSL(pipe)) &
532                            ~(DUPS1_GATING_DIS | DUPS2_GATING_DIS));
533 }
534
535 static bool
536 needs_modeset(const struct drm_crtc_state *state)
537 {
538         return drm_atomic_crtc_needs_modeset(state);
539 }
540
541 /*
542  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
543  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
544  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
545  * The helpers' return value is the rate of the clock that is fed to the
546  * display engine's pipe which can be the above fast dot clock rate or a
547  * divided-down version of it.
548  */
549 /* m1 is reserved as 0 in Pineview, n is a ring counter */
550 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
551 {
552         clock->m = clock->m2 + 2;
553         clock->p = clock->p1 * clock->p2;
554         if (WARN_ON(clock->n == 0 || clock->p == 0))
555                 return 0;
556         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
557         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
558
559         return clock->dot;
560 }
561
562 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
563 {
564         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
565 }
566
567 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
568 {
569         clock->m = i9xx_dpll_compute_m(clock);
570         clock->p = clock->p1 * clock->p2;
571         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
572                 return 0;
573         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
574         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
575
576         return clock->dot;
577 }
578
579 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
580 {
581         clock->m = clock->m1 * clock->m2;
582         clock->p = clock->p1 * clock->p2;
583         if (WARN_ON(clock->n == 0 || clock->p == 0))
584                 return 0;
585         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
586         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
587
588         return clock->dot / 5;
589 }
590
591 int chv_calc_dpll_params(int refclk, struct dpll *clock)
592 {
593         clock->m = clock->m1 * clock->m2;
594         clock->p = clock->p1 * clock->p2;
595         if (WARN_ON(clock->n == 0 || clock->p == 0))
596                 return 0;
597         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
598                         clock->n << 22);
599         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
600
601         return clock->dot / 5;
602 }
603
604 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
605
606 /*
607  * Returns whether the given set of divisors are valid for a given refclk with
608  * the given connectors.
609  */
610 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
611                                const struct intel_limit *limit,
612                                const struct dpll *clock)
613 {
614         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
615                 INTELPllInvalid("n out of range\n");
616         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
617                 INTELPllInvalid("p1 out of range\n");
618         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
619                 INTELPllInvalid("m2 out of range\n");
620         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
621                 INTELPllInvalid("m1 out of range\n");
622
623         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
624             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
625                 if (clock->m1 <= clock->m2)
626                         INTELPllInvalid("m1 <= m2\n");
627
628         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
629             !IS_GEN9_LP(dev_priv)) {
630                 if (clock->p < limit->p.min || limit->p.max < clock->p)
631                         INTELPllInvalid("p out of range\n");
632                 if (clock->m < limit->m.min || limit->m.max < clock->m)
633                         INTELPllInvalid("m out of range\n");
634         }
635
636         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
637                 INTELPllInvalid("vco out of range\n");
638         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
639          * connector, etc., rather than just a single range.
640          */
641         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
642                 INTELPllInvalid("dot out of range\n");
643
644         return true;
645 }
646
647 static int
648 i9xx_select_p2_div(const struct intel_limit *limit,
649                    const struct intel_crtc_state *crtc_state,
650                    int target)
651 {
652         struct drm_device *dev = crtc_state->base.crtc->dev;
653
654         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
655                 /*
656                  * For LVDS just rely on its current settings for dual-channel.
657                  * We haven't figured out how to reliably set up different
658                  * single/dual channel state, if we even can.
659                  */
660                 if (intel_is_dual_link_lvds(dev))
661                         return limit->p2.p2_fast;
662                 else
663                         return limit->p2.p2_slow;
664         } else {
665                 if (target < limit->p2.dot_limit)
666                         return limit->p2.p2_slow;
667                 else
668                         return limit->p2.p2_fast;
669         }
670 }
671
672 /*
673  * Returns a set of divisors for the desired target clock with the given
674  * refclk, or FALSE.  The returned values represent the clock equation:
675  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
676  *
677  * Target and reference clocks are specified in kHz.
678  *
679  * If match_clock is provided, then best_clock P divider must match the P
680  * divider from @match_clock used for LVDS downclocking.
681  */
682 static bool
683 i9xx_find_best_dpll(const struct intel_limit *limit,
684                     struct intel_crtc_state *crtc_state,
685                     int target, int refclk, struct dpll *match_clock,
686                     struct dpll *best_clock)
687 {
688         struct drm_device *dev = crtc_state->base.crtc->dev;
689         struct dpll clock;
690         int err = target;
691
692         memset(best_clock, 0, sizeof(*best_clock));
693
694         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
695
696         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
697              clock.m1++) {
698                 for (clock.m2 = limit->m2.min;
699                      clock.m2 <= limit->m2.max; clock.m2++) {
700                         if (clock.m2 >= clock.m1)
701                                 break;
702                         for (clock.n = limit->n.min;
703                              clock.n <= limit->n.max; clock.n++) {
704                                 for (clock.p1 = limit->p1.min;
705                                         clock.p1 <= limit->p1.max; clock.p1++) {
706                                         int this_err;
707
708                                         i9xx_calc_dpll_params(refclk, &clock);
709                                         if (!intel_PLL_is_valid(to_i915(dev),
710                                                                 limit,
711                                                                 &clock))
712                                                 continue;
713                                         if (match_clock &&
714                                             clock.p != match_clock->p)
715                                                 continue;
716
717                                         this_err = abs(clock.dot - target);
718                                         if (this_err < err) {
719                                                 *best_clock = clock;
720                                                 err = this_err;
721                                         }
722                                 }
723                         }
724                 }
725         }
726
727         return (err != target);
728 }
729
730 /*
731  * Returns a set of divisors for the desired target clock with the given
732  * refclk, or FALSE.  The returned values represent the clock equation:
733  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
734  *
735  * Target and reference clocks are specified in kHz.
736  *
737  * If match_clock is provided, then best_clock P divider must match the P
738  * divider from @match_clock used for LVDS downclocking.
739  */
740 static bool
741 pnv_find_best_dpll(const struct intel_limit *limit,
742                    struct intel_crtc_state *crtc_state,
743                    int target, int refclk, struct dpll *match_clock,
744                    struct dpll *best_clock)
745 {
746         struct drm_device *dev = crtc_state->base.crtc->dev;
747         struct dpll clock;
748         int err = target;
749
750         memset(best_clock, 0, sizeof(*best_clock));
751
752         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
753
754         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
755              clock.m1++) {
756                 for (clock.m2 = limit->m2.min;
757                      clock.m2 <= limit->m2.max; clock.m2++) {
758                         for (clock.n = limit->n.min;
759                              clock.n <= limit->n.max; clock.n++) {
760                                 for (clock.p1 = limit->p1.min;
761                                         clock.p1 <= limit->p1.max; clock.p1++) {
762                                         int this_err;
763
764                                         pnv_calc_dpll_params(refclk, &clock);
765                                         if (!intel_PLL_is_valid(to_i915(dev),
766                                                                 limit,
767                                                                 &clock))
768                                                 continue;
769                                         if (match_clock &&
770                                             clock.p != match_clock->p)
771                                                 continue;
772
773                                         this_err = abs(clock.dot - target);
774                                         if (this_err < err) {
775                                                 *best_clock = clock;
776                                                 err = this_err;
777                                         }
778                                 }
779                         }
780                 }
781         }
782
783         return (err != target);
784 }
785
786 /*
787  * Returns a set of divisors for the desired target clock with the given
788  * refclk, or FALSE.  The returned values represent the clock equation:
789  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
790  *
791  * Target and reference clocks are specified in kHz.
792  *
793  * If match_clock is provided, then best_clock P divider must match the P
794  * divider from @match_clock used for LVDS downclocking.
795  */
796 static bool
797 g4x_find_best_dpll(const struct intel_limit *limit,
798                    struct intel_crtc_state *crtc_state,
799                    int target, int refclk, struct dpll *match_clock,
800                    struct dpll *best_clock)
801 {
802         struct drm_device *dev = crtc_state->base.crtc->dev;
803         struct dpll clock;
804         int max_n;
805         bool found = false;
806         /* approximately equals target * 0.00585 */
807         int err_most = (target >> 8) + (target >> 9);
808
809         memset(best_clock, 0, sizeof(*best_clock));
810
811         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
812
813         max_n = limit->n.max;
814         /* based on hardware requirement, prefer smaller n to precision */
815         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
816                 /* based on hardware requirement, prefere larger m1,m2 */
817                 for (clock.m1 = limit->m1.max;
818                      clock.m1 >= limit->m1.min; clock.m1--) {
819                         for (clock.m2 = limit->m2.max;
820                              clock.m2 >= limit->m2.min; clock.m2--) {
821                                 for (clock.p1 = limit->p1.max;
822                                      clock.p1 >= limit->p1.min; clock.p1--) {
823                                         int this_err;
824
825                                         i9xx_calc_dpll_params(refclk, &clock);
826                                         if (!intel_PLL_is_valid(to_i915(dev),
827                                                                 limit,
828                                                                 &clock))
829                                                 continue;
830
831                                         this_err = abs(clock.dot - target);
832                                         if (this_err < err_most) {
833                                                 *best_clock = clock;
834                                                 err_most = this_err;
835                                                 max_n = clock.n;
836                                                 found = true;
837                                         }
838                                 }
839                         }
840                 }
841         }
842         return found;
843 }
844
845 /*
846  * Check if the calculated PLL configuration is more optimal compared to the
847  * best configuration and error found so far. Return the calculated error.
848  */
849 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
850                                const struct dpll *calculated_clock,
851                                const struct dpll *best_clock,
852                                unsigned int best_error_ppm,
853                                unsigned int *error_ppm)
854 {
855         /*
856          * For CHV ignore the error and consider only the P value.
857          * Prefer a bigger P value based on HW requirements.
858          */
859         if (IS_CHERRYVIEW(to_i915(dev))) {
860                 *error_ppm = 0;
861
862                 return calculated_clock->p > best_clock->p;
863         }
864
865         if (WARN_ON_ONCE(!target_freq))
866                 return false;
867
868         *error_ppm = div_u64(1000000ULL *
869                                 abs(target_freq - calculated_clock->dot),
870                              target_freq);
871         /*
872          * Prefer a better P value over a better (smaller) error if the error
873          * is small. Ensure this preference for future configurations too by
874          * setting the error to 0.
875          */
876         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
877                 *error_ppm = 0;
878
879                 return true;
880         }
881
882         return *error_ppm + 10 < best_error_ppm;
883 }
884
885 /*
886  * Returns a set of divisors for the desired target clock with the given
887  * refclk, or FALSE.  The returned values represent the clock equation:
888  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
889  */
890 static bool
891 vlv_find_best_dpll(const struct intel_limit *limit,
892                    struct intel_crtc_state *crtc_state,
893                    int target, int refclk, struct dpll *match_clock,
894                    struct dpll *best_clock)
895 {
896         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
897         struct drm_device *dev = crtc->base.dev;
898         struct dpll clock;
899         unsigned int bestppm = 1000000;
900         /* min update 19.2 MHz */
901         int max_n = min(limit->n.max, refclk / 19200);
902         bool found = false;
903
904         target *= 5; /* fast clock */
905
906         memset(best_clock, 0, sizeof(*best_clock));
907
908         /* based on hardware requirement, prefer smaller n to precision */
909         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
910                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
911                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
912                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
913                                 clock.p = clock.p1 * clock.p2;
914                                 /* based on hardware requirement, prefer bigger m1,m2 values */
915                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
916                                         unsigned int ppm;
917
918                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
919                                                                      refclk * clock.m1);
920
921                                         vlv_calc_dpll_params(refclk, &clock);
922
923                                         if (!intel_PLL_is_valid(to_i915(dev),
924                                                                 limit,
925                                                                 &clock))
926                                                 continue;
927
928                                         if (!vlv_PLL_is_optimal(dev, target,
929                                                                 &clock,
930                                                                 best_clock,
931                                                                 bestppm, &ppm))
932                                                 continue;
933
934                                         *best_clock = clock;
935                                         bestppm = ppm;
936                                         found = true;
937                                 }
938                         }
939                 }
940         }
941
942         return found;
943 }
944
945 /*
946  * Returns a set of divisors for the desired target clock with the given
947  * refclk, or FALSE.  The returned values represent the clock equation:
948  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
949  */
950 static bool
951 chv_find_best_dpll(const struct intel_limit *limit,
952                    struct intel_crtc_state *crtc_state,
953                    int target, int refclk, struct dpll *match_clock,
954                    struct dpll *best_clock)
955 {
956         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
957         struct drm_device *dev = crtc->base.dev;
958         unsigned int best_error_ppm;
959         struct dpll clock;
960         uint64_t m2;
961         int found = false;
962
963         memset(best_clock, 0, sizeof(*best_clock));
964         best_error_ppm = 1000000;
965
966         /*
967          * Based on hardware doc, the n always set to 1, and m1 always
968          * set to 2.  If requires to support 200Mhz refclk, we need to
969          * revisit this because n may not 1 anymore.
970          */
971         clock.n = 1, clock.m1 = 2;
972         target *= 5;    /* fast clock */
973
974         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
975                 for (clock.p2 = limit->p2.p2_fast;
976                                 clock.p2 >= limit->p2.p2_slow;
977                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
978                         unsigned int error_ppm;
979
980                         clock.p = clock.p1 * clock.p2;
981
982                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
983                                         clock.n) << 22, refclk * clock.m1);
984
985                         if (m2 > INT_MAX/clock.m1)
986                                 continue;
987
988                         clock.m2 = m2;
989
990                         chv_calc_dpll_params(refclk, &clock);
991
992                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
993                                 continue;
994
995                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
996                                                 best_error_ppm, &error_ppm))
997                                 continue;
998
999                         *best_clock = clock;
1000                         best_error_ppm = error_ppm;
1001                         found = true;
1002                 }
1003         }
1004
1005         return found;
1006 }
1007
1008 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1009                         struct dpll *best_clock)
1010 {
1011         int refclk = 100000;
1012         const struct intel_limit *limit = &intel_limits_bxt;
1013
1014         return chv_find_best_dpll(limit, crtc_state,
1015                                   target_clock, refclk, NULL, best_clock);
1016 }
1017
1018 bool intel_crtc_active(struct intel_crtc *crtc)
1019 {
1020         /* Be paranoid as we can arrive here with only partial
1021          * state retrieved from the hardware during setup.
1022          *
1023          * We can ditch the adjusted_mode.crtc_clock check as soon
1024          * as Haswell has gained clock readout/fastboot support.
1025          *
1026          * We can ditch the crtc->primary->state->fb check as soon as we can
1027          * properly reconstruct framebuffers.
1028          *
1029          * FIXME: The intel_crtc->active here should be switched to
1030          * crtc->state->active once we have proper CRTC states wired up
1031          * for atomic.
1032          */
1033         return crtc->active && crtc->base.primary->state->fb &&
1034                 crtc->config->base.adjusted_mode.crtc_clock;
1035 }
1036
1037 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1038                                              enum pipe pipe)
1039 {
1040         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
1041
1042         return crtc->config->cpu_transcoder;
1043 }
1044
1045 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
1046                                     enum pipe pipe)
1047 {
1048         i915_reg_t reg = PIPEDSL(pipe);
1049         u32 line1, line2;
1050         u32 line_mask;
1051
1052         if (IS_GEN2(dev_priv))
1053                 line_mask = DSL_LINEMASK_GEN2;
1054         else
1055                 line_mask = DSL_LINEMASK_GEN3;
1056
1057         line1 = I915_READ(reg) & line_mask;
1058         msleep(5);
1059         line2 = I915_READ(reg) & line_mask;
1060
1061         return line1 != line2;
1062 }
1063
1064 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1065 {
1066         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1067         enum pipe pipe = crtc->pipe;
1068
1069         /* Wait for the display line to settle/start moving */
1070         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1071                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1072                           pipe_name(pipe), onoff(state));
1073 }
1074
1075 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1076 {
1077         wait_for_pipe_scanline_moving(crtc, false);
1078 }
1079
1080 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1081 {
1082         wait_for_pipe_scanline_moving(crtc, true);
1083 }
1084
1085 static void
1086 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1087 {
1088         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1089         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1090
1091         if (INTEL_GEN(dev_priv) >= 4) {
1092                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1093                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1094
1095                 /* Wait for the Pipe State to go off */
1096                 if (intel_wait_for_register(dev_priv,
1097                                             reg, I965_PIPECONF_ACTIVE, 0,
1098                                             100))
1099                         WARN(1, "pipe_off wait timed out\n");
1100         } else {
1101                 intel_wait_for_pipe_scanline_stopped(crtc);
1102         }
1103 }
1104
1105 /* Only for pre-ILK configs */
1106 void assert_pll(struct drm_i915_private *dev_priv,
1107                 enum pipe pipe, bool state)
1108 {
1109         u32 val;
1110         bool cur_state;
1111
1112         val = I915_READ(DPLL(pipe));
1113         cur_state = !!(val & DPLL_VCO_ENABLE);
1114         I915_STATE_WARN(cur_state != state,
1115              "PLL state assertion failure (expected %s, current %s)\n",
1116                         onoff(state), onoff(cur_state));
1117 }
1118
1119 /* XXX: the dsi pll is shared between MIPI DSI ports */
1120 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1121 {
1122         u32 val;
1123         bool cur_state;
1124
1125         mutex_lock(&dev_priv->sb_lock);
1126         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1127         mutex_unlock(&dev_priv->sb_lock);
1128
1129         cur_state = val & DSI_PLL_VCO_EN;
1130         I915_STATE_WARN(cur_state != state,
1131              "DSI PLL state assertion failure (expected %s, current %s)\n",
1132                         onoff(state), onoff(cur_state));
1133 }
1134
1135 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1136                           enum pipe pipe, bool state)
1137 {
1138         bool cur_state;
1139         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1140                                                                       pipe);
1141
1142         if (HAS_DDI(dev_priv)) {
1143                 /* DDI does not have a specific FDI_TX register */
1144                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1145                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1146         } else {
1147                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1148                 cur_state = !!(val & FDI_TX_ENABLE);
1149         }
1150         I915_STATE_WARN(cur_state != state,
1151              "FDI TX state assertion failure (expected %s, current %s)\n",
1152                         onoff(state), onoff(cur_state));
1153 }
1154 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1155 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1156
1157 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1158                           enum pipe pipe, bool state)
1159 {
1160         u32 val;
1161         bool cur_state;
1162
1163         val = I915_READ(FDI_RX_CTL(pipe));
1164         cur_state = !!(val & FDI_RX_ENABLE);
1165         I915_STATE_WARN(cur_state != state,
1166              "FDI RX state assertion failure (expected %s, current %s)\n",
1167                         onoff(state), onoff(cur_state));
1168 }
1169 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1170 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1171
1172 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1173                                       enum pipe pipe)
1174 {
1175         u32 val;
1176
1177         /* ILK FDI PLL is always enabled */
1178         if (IS_GEN5(dev_priv))
1179                 return;
1180
1181         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1182         if (HAS_DDI(dev_priv))
1183                 return;
1184
1185         val = I915_READ(FDI_TX_CTL(pipe));
1186         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1187 }
1188
1189 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1190                        enum pipe pipe, bool state)
1191 {
1192         u32 val;
1193         bool cur_state;
1194
1195         val = I915_READ(FDI_RX_CTL(pipe));
1196         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1197         I915_STATE_WARN(cur_state != state,
1198              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1199                         onoff(state), onoff(cur_state));
1200 }
1201
1202 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1203 {
1204         i915_reg_t pp_reg;
1205         u32 val;
1206         enum pipe panel_pipe = INVALID_PIPE;
1207         bool locked = true;
1208
1209         if (WARN_ON(HAS_DDI(dev_priv)))
1210                 return;
1211
1212         if (HAS_PCH_SPLIT(dev_priv)) {
1213                 u32 port_sel;
1214
1215                 pp_reg = PP_CONTROL(0);
1216                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1217
1218                 switch (port_sel) {
1219                 case PANEL_PORT_SELECT_LVDS:
1220                         intel_lvds_port_enabled(dev_priv, PCH_LVDS, &panel_pipe);
1221                         break;
1222                 case PANEL_PORT_SELECT_DPA:
1223                         intel_dp_port_enabled(dev_priv, DP_A, PORT_A, &panel_pipe);
1224                         break;
1225                 case PANEL_PORT_SELECT_DPC:
1226                         intel_dp_port_enabled(dev_priv, PCH_DP_C, PORT_C, &panel_pipe);
1227                         break;
1228                 case PANEL_PORT_SELECT_DPD:
1229                         intel_dp_port_enabled(dev_priv, PCH_DP_D, PORT_D, &panel_pipe);
1230                         break;
1231                 default:
1232                         MISSING_CASE(port_sel);
1233                         break;
1234                 }
1235         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1236                 /* presumably write lock depends on pipe, not port select */
1237                 pp_reg = PP_CONTROL(pipe);
1238                 panel_pipe = pipe;
1239         } else {
1240                 u32 port_sel;
1241
1242                 pp_reg = PP_CONTROL(0);
1243                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1244
1245                 WARN_ON(port_sel != PANEL_PORT_SELECT_LVDS);
1246                 intel_lvds_port_enabled(dev_priv, LVDS, &panel_pipe);
1247         }
1248
1249         val = I915_READ(pp_reg);
1250         if (!(val & PANEL_POWER_ON) ||
1251             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1252                 locked = false;
1253
1254         I915_STATE_WARN(panel_pipe == pipe && locked,
1255              "panel assertion failure, pipe %c regs locked\n",
1256              pipe_name(pipe));
1257 }
1258
1259 void assert_pipe(struct drm_i915_private *dev_priv,
1260                  enum pipe pipe, bool state)
1261 {
1262         bool cur_state;
1263         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1264                                                                       pipe);
1265         enum intel_display_power_domain power_domain;
1266
1267         /* we keep both pipes enabled on 830 */
1268         if (IS_I830(dev_priv))
1269                 state = true;
1270
1271         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1272         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1273                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1274                 cur_state = !!(val & PIPECONF_ENABLE);
1275
1276                 intel_display_power_put(dev_priv, power_domain);
1277         } else {
1278                 cur_state = false;
1279         }
1280
1281         I915_STATE_WARN(cur_state != state,
1282              "pipe %c assertion failure (expected %s, current %s)\n",
1283                         pipe_name(pipe), onoff(state), onoff(cur_state));
1284 }
1285
1286 static void assert_plane(struct intel_plane *plane, bool state)
1287 {
1288         enum pipe pipe;
1289         bool cur_state;
1290
1291         cur_state = plane->get_hw_state(plane, &pipe);
1292
1293         I915_STATE_WARN(cur_state != state,
1294                         "%s assertion failure (expected %s, current %s)\n",
1295                         plane->base.name, onoff(state), onoff(cur_state));
1296 }
1297
1298 #define assert_plane_enabled(p) assert_plane(p, true)
1299 #define assert_plane_disabled(p) assert_plane(p, false)
1300
1301 static void assert_planes_disabled(struct intel_crtc *crtc)
1302 {
1303         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1304         struct intel_plane *plane;
1305
1306         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1307                 assert_plane_disabled(plane);
1308 }
1309
1310 static void assert_vblank_disabled(struct drm_crtc *crtc)
1311 {
1312         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1313                 drm_crtc_vblank_put(crtc);
1314 }
1315
1316 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1317                                     enum pipe pipe)
1318 {
1319         u32 val;
1320         bool enabled;
1321
1322         val = I915_READ(PCH_TRANSCONF(pipe));
1323         enabled = !!(val & TRANS_ENABLE);
1324         I915_STATE_WARN(enabled,
1325              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1326              pipe_name(pipe));
1327 }
1328
1329 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1330                                    enum pipe pipe, enum port port,
1331                                    i915_reg_t dp_reg)
1332 {
1333         enum pipe port_pipe;
1334         bool state;
1335
1336         state = intel_dp_port_enabled(dev_priv, dp_reg, port, &port_pipe);
1337
1338         I915_STATE_WARN(state && port_pipe == pipe,
1339                         "PCH DP %c enabled on transcoder %c, should be disabled\n",
1340                         port_name(port), pipe_name(pipe));
1341
1342         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1343                         "IBX PCH DP %c still using transcoder B\n",
1344                         port_name(port));
1345 }
1346
1347 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1348                                      enum pipe pipe, enum port port,
1349                                      i915_reg_t hdmi_reg)
1350 {
1351         enum pipe port_pipe;
1352         bool state;
1353
1354         state = intel_sdvo_port_enabled(dev_priv, hdmi_reg, &port_pipe);
1355
1356         I915_STATE_WARN(state && port_pipe == pipe,
1357                         "PCH HDMI %c enabled on transcoder %c, should be disabled\n",
1358                         port_name(port), pipe_name(pipe));
1359
1360         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1361                         "IBX PCH HDMI %c still using transcoder B\n",
1362                         port_name(port));
1363 }
1364
1365 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1366                                       enum pipe pipe)
1367 {
1368         enum pipe port_pipe;
1369
1370         assert_pch_dp_disabled(dev_priv, pipe, PORT_B, PCH_DP_B);
1371         assert_pch_dp_disabled(dev_priv, pipe, PORT_C, PCH_DP_C);
1372         assert_pch_dp_disabled(dev_priv, pipe, PORT_D, PCH_DP_D);
1373
1374         I915_STATE_WARN(intel_crt_port_enabled(dev_priv, PCH_ADPA, &port_pipe) &&
1375                         port_pipe == pipe,
1376                         "PCH VGA enabled on transcoder %c, should be disabled\n",
1377                         pipe_name(pipe));
1378
1379         I915_STATE_WARN(intel_lvds_port_enabled(dev_priv, PCH_LVDS, &port_pipe) &&
1380                         port_pipe == pipe,
1381                         "PCH LVDS enabled on transcoder %c, should be disabled\n",
1382                         pipe_name(pipe));
1383
1384         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_B, PCH_HDMIB);
1385         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_C, PCH_HDMIC);
1386         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_D, PCH_HDMID);
1387 }
1388
1389 static void _vlv_enable_pll(struct intel_crtc *crtc,
1390                             const struct intel_crtc_state *pipe_config)
1391 {
1392         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1393         enum pipe pipe = crtc->pipe;
1394
1395         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1396         POSTING_READ(DPLL(pipe));
1397         udelay(150);
1398
1399         if (intel_wait_for_register(dev_priv,
1400                                     DPLL(pipe),
1401                                     DPLL_LOCK_VLV,
1402                                     DPLL_LOCK_VLV,
1403                                     1))
1404                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1405 }
1406
1407 static void vlv_enable_pll(struct intel_crtc *crtc,
1408                            const struct intel_crtc_state *pipe_config)
1409 {
1410         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1411         enum pipe pipe = crtc->pipe;
1412
1413         assert_pipe_disabled(dev_priv, pipe);
1414
1415         /* PLL is protected by panel, make sure we can write it */
1416         assert_panel_unlocked(dev_priv, pipe);
1417
1418         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1419                 _vlv_enable_pll(crtc, pipe_config);
1420
1421         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1422         POSTING_READ(DPLL_MD(pipe));
1423 }
1424
1425
1426 static void _chv_enable_pll(struct intel_crtc *crtc,
1427                             const struct intel_crtc_state *pipe_config)
1428 {
1429         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1430         enum pipe pipe = crtc->pipe;
1431         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1432         u32 tmp;
1433
1434         mutex_lock(&dev_priv->sb_lock);
1435
1436         /* Enable back the 10bit clock to display controller */
1437         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1438         tmp |= DPIO_DCLKP_EN;
1439         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1440
1441         mutex_unlock(&dev_priv->sb_lock);
1442
1443         /*
1444          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1445          */
1446         udelay(1);
1447
1448         /* Enable PLL */
1449         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1450
1451         /* Check PLL is locked */
1452         if (intel_wait_for_register(dev_priv,
1453                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1454                                     1))
1455                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1456 }
1457
1458 static void chv_enable_pll(struct intel_crtc *crtc,
1459                            const struct intel_crtc_state *pipe_config)
1460 {
1461         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1462         enum pipe pipe = crtc->pipe;
1463
1464         assert_pipe_disabled(dev_priv, pipe);
1465
1466         /* PLL is protected by panel, make sure we can write it */
1467         assert_panel_unlocked(dev_priv, pipe);
1468
1469         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1470                 _chv_enable_pll(crtc, pipe_config);
1471
1472         if (pipe != PIPE_A) {
1473                 /*
1474                  * WaPixelRepeatModeFixForC0:chv
1475                  *
1476                  * DPLLCMD is AWOL. Use chicken bits to propagate
1477                  * the value from DPLLBMD to either pipe B or C.
1478                  */
1479                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1480                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1481                 I915_WRITE(CBR4_VLV, 0);
1482                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1483
1484                 /*
1485                  * DPLLB VGA mode also seems to cause problems.
1486                  * We should always have it disabled.
1487                  */
1488                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1489         } else {
1490                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1491                 POSTING_READ(DPLL_MD(pipe));
1492         }
1493 }
1494
1495 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1496 {
1497         struct intel_crtc *crtc;
1498         int count = 0;
1499
1500         for_each_intel_crtc(&dev_priv->drm, crtc) {
1501                 count += crtc->base.state->active &&
1502                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1503         }
1504
1505         return count;
1506 }
1507
1508 static void i9xx_enable_pll(struct intel_crtc *crtc,
1509                             const struct intel_crtc_state *crtc_state)
1510 {
1511         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1512         i915_reg_t reg = DPLL(crtc->pipe);
1513         u32 dpll = crtc_state->dpll_hw_state.dpll;
1514         int i;
1515
1516         assert_pipe_disabled(dev_priv, crtc->pipe);
1517
1518         /* PLL is protected by panel, make sure we can write it */
1519         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1520                 assert_panel_unlocked(dev_priv, crtc->pipe);
1521
1522         /* Enable DVO 2x clock on both PLLs if necessary */
1523         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1524                 /*
1525                  * It appears to be important that we don't enable this
1526                  * for the current pipe before otherwise configuring the
1527                  * PLL. No idea how this should be handled if multiple
1528                  * DVO outputs are enabled simultaneosly.
1529                  */
1530                 dpll |= DPLL_DVO_2X_MODE;
1531                 I915_WRITE(DPLL(!crtc->pipe),
1532                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1533         }
1534
1535         /*
1536          * Apparently we need to have VGA mode enabled prior to changing
1537          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1538          * dividers, even though the register value does change.
1539          */
1540         I915_WRITE(reg, 0);
1541
1542         I915_WRITE(reg, dpll);
1543
1544         /* Wait for the clocks to stabilize. */
1545         POSTING_READ(reg);
1546         udelay(150);
1547
1548         if (INTEL_GEN(dev_priv) >= 4) {
1549                 I915_WRITE(DPLL_MD(crtc->pipe),
1550                            crtc_state->dpll_hw_state.dpll_md);
1551         } else {
1552                 /* The pixel multiplier can only be updated once the
1553                  * DPLL is enabled and the clocks are stable.
1554                  *
1555                  * So write it again.
1556                  */
1557                 I915_WRITE(reg, dpll);
1558         }
1559
1560         /* We do this three times for luck */
1561         for (i = 0; i < 3; i++) {
1562                 I915_WRITE(reg, dpll);
1563                 POSTING_READ(reg);
1564                 udelay(150); /* wait for warmup */
1565         }
1566 }
1567
1568 static void i9xx_disable_pll(struct intel_crtc *crtc)
1569 {
1570         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1571         enum pipe pipe = crtc->pipe;
1572
1573         /* Disable DVO 2x clock on both PLLs if necessary */
1574         if (IS_I830(dev_priv) &&
1575             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1576             !intel_num_dvo_pipes(dev_priv)) {
1577                 I915_WRITE(DPLL(PIPE_B),
1578                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1579                 I915_WRITE(DPLL(PIPE_A),
1580                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1581         }
1582
1583         /* Don't disable pipe or pipe PLLs if needed */
1584         if (IS_I830(dev_priv))
1585                 return;
1586
1587         /* Make sure the pipe isn't still relying on us */
1588         assert_pipe_disabled(dev_priv, pipe);
1589
1590         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1591         POSTING_READ(DPLL(pipe));
1592 }
1593
1594 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1595 {
1596         u32 val;
1597
1598         /* Make sure the pipe isn't still relying on us */
1599         assert_pipe_disabled(dev_priv, pipe);
1600
1601         val = DPLL_INTEGRATED_REF_CLK_VLV |
1602                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1603         if (pipe != PIPE_A)
1604                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1605
1606         I915_WRITE(DPLL(pipe), val);
1607         POSTING_READ(DPLL(pipe));
1608 }
1609
1610 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1611 {
1612         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1613         u32 val;
1614
1615         /* Make sure the pipe isn't still relying on us */
1616         assert_pipe_disabled(dev_priv, pipe);
1617
1618         val = DPLL_SSC_REF_CLK_CHV |
1619                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1620         if (pipe != PIPE_A)
1621                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1622
1623         I915_WRITE(DPLL(pipe), val);
1624         POSTING_READ(DPLL(pipe));
1625
1626         mutex_lock(&dev_priv->sb_lock);
1627
1628         /* Disable 10bit clock to display controller */
1629         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1630         val &= ~DPIO_DCLKP_EN;
1631         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1632
1633         mutex_unlock(&dev_priv->sb_lock);
1634 }
1635
1636 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1637                          struct intel_digital_port *dport,
1638                          unsigned int expected_mask)
1639 {
1640         u32 port_mask;
1641         i915_reg_t dpll_reg;
1642
1643         switch (dport->base.port) {
1644         case PORT_B:
1645                 port_mask = DPLL_PORTB_READY_MASK;
1646                 dpll_reg = DPLL(0);
1647                 break;
1648         case PORT_C:
1649                 port_mask = DPLL_PORTC_READY_MASK;
1650                 dpll_reg = DPLL(0);
1651                 expected_mask <<= 4;
1652                 break;
1653         case PORT_D:
1654                 port_mask = DPLL_PORTD_READY_MASK;
1655                 dpll_reg = DPIO_PHY_STATUS;
1656                 break;
1657         default:
1658                 BUG();
1659         }
1660
1661         if (intel_wait_for_register(dev_priv,
1662                                     dpll_reg, port_mask, expected_mask,
1663                                     1000))
1664                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1665                      port_name(dport->base.port),
1666                      I915_READ(dpll_reg) & port_mask, expected_mask);
1667 }
1668
1669 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1670                                            enum pipe pipe)
1671 {
1672         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1673                                                                 pipe);
1674         i915_reg_t reg;
1675         uint32_t val, pipeconf_val;
1676
1677         /* Make sure PCH DPLL is enabled */
1678         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1679
1680         /* FDI must be feeding us bits for PCH ports */
1681         assert_fdi_tx_enabled(dev_priv, pipe);
1682         assert_fdi_rx_enabled(dev_priv, pipe);
1683
1684         if (HAS_PCH_CPT(dev_priv)) {
1685                 /* Workaround: Set the timing override bit before enabling the
1686                  * pch transcoder. */
1687                 reg = TRANS_CHICKEN2(pipe);
1688                 val = I915_READ(reg);
1689                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1690                 I915_WRITE(reg, val);
1691         }
1692
1693         reg = PCH_TRANSCONF(pipe);
1694         val = I915_READ(reg);
1695         pipeconf_val = I915_READ(PIPECONF(pipe));
1696
1697         if (HAS_PCH_IBX(dev_priv)) {
1698                 /*
1699                  * Make the BPC in transcoder be consistent with
1700                  * that in pipeconf reg. For HDMI we must use 8bpc
1701                  * here for both 8bpc and 12bpc.
1702                  */
1703                 val &= ~PIPECONF_BPC_MASK;
1704                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1705                         val |= PIPECONF_8BPC;
1706                 else
1707                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1708         }
1709
1710         val &= ~TRANS_INTERLACE_MASK;
1711         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1712                 if (HAS_PCH_IBX(dev_priv) &&
1713                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1714                         val |= TRANS_LEGACY_INTERLACED_ILK;
1715                 else
1716                         val |= TRANS_INTERLACED;
1717         else
1718                 val |= TRANS_PROGRESSIVE;
1719
1720         I915_WRITE(reg, val | TRANS_ENABLE);
1721         if (intel_wait_for_register(dev_priv,
1722                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1723                                     100))
1724                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1725 }
1726
1727 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1728                                       enum transcoder cpu_transcoder)
1729 {
1730         u32 val, pipeconf_val;
1731
1732         /* FDI must be feeding us bits for PCH ports */
1733         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1734         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1735
1736         /* Workaround: set timing override bit. */
1737         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1738         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1739         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1740
1741         val = TRANS_ENABLE;
1742         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1743
1744         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1745             PIPECONF_INTERLACED_ILK)
1746                 val |= TRANS_INTERLACED;
1747         else
1748                 val |= TRANS_PROGRESSIVE;
1749
1750         I915_WRITE(LPT_TRANSCONF, val);
1751         if (intel_wait_for_register(dev_priv,
1752                                     LPT_TRANSCONF,
1753                                     TRANS_STATE_ENABLE,
1754                                     TRANS_STATE_ENABLE,
1755                                     100))
1756                 DRM_ERROR("Failed to enable PCH transcoder\n");
1757 }
1758
1759 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1760                                             enum pipe pipe)
1761 {
1762         i915_reg_t reg;
1763         uint32_t val;
1764
1765         /* FDI relies on the transcoder */
1766         assert_fdi_tx_disabled(dev_priv, pipe);
1767         assert_fdi_rx_disabled(dev_priv, pipe);
1768
1769         /* Ports must be off as well */
1770         assert_pch_ports_disabled(dev_priv, pipe);
1771
1772         reg = PCH_TRANSCONF(pipe);
1773         val = I915_READ(reg);
1774         val &= ~TRANS_ENABLE;
1775         I915_WRITE(reg, val);
1776         /* wait for PCH transcoder off, transcoder state */
1777         if (intel_wait_for_register(dev_priv,
1778                                     reg, TRANS_STATE_ENABLE, 0,
1779                                     50))
1780                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1781
1782         if (HAS_PCH_CPT(dev_priv)) {
1783                 /* Workaround: Clear the timing override chicken bit again. */
1784                 reg = TRANS_CHICKEN2(pipe);
1785                 val = I915_READ(reg);
1786                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1787                 I915_WRITE(reg, val);
1788         }
1789 }
1790
1791 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1792 {
1793         u32 val;
1794
1795         val = I915_READ(LPT_TRANSCONF);
1796         val &= ~TRANS_ENABLE;
1797         I915_WRITE(LPT_TRANSCONF, val);
1798         /* wait for PCH transcoder off, transcoder state */
1799         if (intel_wait_for_register(dev_priv,
1800                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1801                                     50))
1802                 DRM_ERROR("Failed to disable PCH transcoder\n");
1803
1804         /* Workaround: clear timing override bit. */
1805         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1806         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1807         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1808 }
1809
1810 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1811 {
1812         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1813
1814         if (HAS_PCH_LPT(dev_priv))
1815                 return PIPE_A;
1816         else
1817                 return crtc->pipe;
1818 }
1819
1820 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1821 {
1822         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1823         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1824         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1825         enum pipe pipe = crtc->pipe;
1826         i915_reg_t reg;
1827         u32 val;
1828
1829         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1830
1831         assert_planes_disabled(crtc);
1832
1833         /*
1834          * A pipe without a PLL won't actually be able to drive bits from
1835          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1836          * need the check.
1837          */
1838         if (HAS_GMCH_DISPLAY(dev_priv)) {
1839                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1840                         assert_dsi_pll_enabled(dev_priv);
1841                 else
1842                         assert_pll_enabled(dev_priv, pipe);
1843         } else {
1844                 if (new_crtc_state->has_pch_encoder) {
1845                         /* if driving the PCH, we need FDI enabled */
1846                         assert_fdi_rx_pll_enabled(dev_priv,
1847                                                   intel_crtc_pch_transcoder(crtc));
1848                         assert_fdi_tx_pll_enabled(dev_priv,
1849                                                   (enum pipe) cpu_transcoder);
1850                 }
1851                 /* FIXME: assert CPU port conditions for SNB+ */
1852         }
1853
1854         reg = PIPECONF(cpu_transcoder);
1855         val = I915_READ(reg);
1856         if (val & PIPECONF_ENABLE) {
1857                 /* we keep both pipes enabled on 830 */
1858                 WARN_ON(!IS_I830(dev_priv));
1859                 return;
1860         }
1861
1862         I915_WRITE(reg, val | PIPECONF_ENABLE);
1863         POSTING_READ(reg);
1864
1865         /*
1866          * Until the pipe starts PIPEDSL reads will return a stale value,
1867          * which causes an apparent vblank timestamp jump when PIPEDSL
1868          * resets to its proper value. That also messes up the frame count
1869          * when it's derived from the timestamps. So let's wait for the
1870          * pipe to start properly before we call drm_crtc_vblank_on()
1871          */
1872         if (dev_priv->drm.max_vblank_count == 0)
1873                 intel_wait_for_pipe_scanline_moving(crtc);
1874 }
1875
1876 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1877 {
1878         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1879         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1880         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1881         enum pipe pipe = crtc->pipe;
1882         i915_reg_t reg;
1883         u32 val;
1884
1885         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1886
1887         /*
1888          * Make sure planes won't keep trying to pump pixels to us,
1889          * or we might hang the display.
1890          */
1891         assert_planes_disabled(crtc);
1892
1893         reg = PIPECONF(cpu_transcoder);
1894         val = I915_READ(reg);
1895         if ((val & PIPECONF_ENABLE) == 0)
1896                 return;
1897
1898         /*
1899          * Double wide has implications for planes
1900          * so best keep it disabled when not needed.
1901          */
1902         if (old_crtc_state->double_wide)
1903                 val &= ~PIPECONF_DOUBLE_WIDE;
1904
1905         /* Don't disable pipe or pipe PLLs if needed */
1906         if (!IS_I830(dev_priv))
1907                 val &= ~PIPECONF_ENABLE;
1908
1909         I915_WRITE(reg, val);
1910         if ((val & PIPECONF_ENABLE) == 0)
1911                 intel_wait_for_pipe_off(old_crtc_state);
1912 }
1913
1914 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1915 {
1916         return IS_GEN2(dev_priv) ? 2048 : 4096;
1917 }
1918
1919 static unsigned int
1920 intel_tile_width_bytes(const struct drm_framebuffer *fb, int color_plane)
1921 {
1922         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1923         unsigned int cpp = fb->format->cpp[color_plane];
1924
1925         switch (fb->modifier) {
1926         case DRM_FORMAT_MOD_LINEAR:
1927                 return cpp;
1928         case I915_FORMAT_MOD_X_TILED:
1929                 if (IS_GEN2(dev_priv))
1930                         return 128;
1931                 else
1932                         return 512;
1933         case I915_FORMAT_MOD_Y_TILED_CCS:
1934                 if (color_plane == 1)
1935                         return 128;
1936                 /* fall through */
1937         case I915_FORMAT_MOD_Y_TILED:
1938                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
1939                         return 128;
1940                 else
1941                         return 512;
1942         case I915_FORMAT_MOD_Yf_TILED_CCS:
1943                 if (color_plane == 1)
1944                         return 128;
1945                 /* fall through */
1946         case I915_FORMAT_MOD_Yf_TILED:
1947                 switch (cpp) {
1948                 case 1:
1949                         return 64;
1950                 case 2:
1951                 case 4:
1952                         return 128;
1953                 case 8:
1954                 case 16:
1955                         return 256;
1956                 default:
1957                         MISSING_CASE(cpp);
1958                         return cpp;
1959                 }
1960                 break;
1961         default:
1962                 MISSING_CASE(fb->modifier);
1963                 return cpp;
1964         }
1965 }
1966
1967 static unsigned int
1968 intel_tile_height(const struct drm_framebuffer *fb, int color_plane)
1969 {
1970         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
1971                 return 1;
1972         else
1973                 return intel_tile_size(to_i915(fb->dev)) /
1974                         intel_tile_width_bytes(fb, color_plane);
1975 }
1976
1977 /* Return the tile dimensions in pixel units */
1978 static void intel_tile_dims(const struct drm_framebuffer *fb, int color_plane,
1979                             unsigned int *tile_width,
1980                             unsigned int *tile_height)
1981 {
1982         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, color_plane);
1983         unsigned int cpp = fb->format->cpp[color_plane];
1984
1985         *tile_width = tile_width_bytes / cpp;
1986         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1987 }
1988
1989 unsigned int
1990 intel_fb_align_height(const struct drm_framebuffer *fb,
1991                       int color_plane, unsigned int height)
1992 {
1993         unsigned int tile_height = intel_tile_height(fb, color_plane);
1994
1995         return ALIGN(height, tile_height);
1996 }
1997
1998 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
1999 {
2000         unsigned int size = 0;
2001         int i;
2002
2003         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2004                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2005
2006         return size;
2007 }
2008
2009 static void
2010 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2011                         const struct drm_framebuffer *fb,
2012                         unsigned int rotation)
2013 {
2014         view->type = I915_GGTT_VIEW_NORMAL;
2015         if (drm_rotation_90_or_270(rotation)) {
2016                 view->type = I915_GGTT_VIEW_ROTATED;
2017                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2018         }
2019 }
2020
2021 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2022 {
2023         if (IS_I830(dev_priv))
2024                 return 16 * 1024;
2025         else if (IS_I85X(dev_priv))
2026                 return 256;
2027         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2028                 return 32;
2029         else
2030                 return 4 * 1024;
2031 }
2032
2033 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2034 {
2035         if (INTEL_GEN(dev_priv) >= 9)
2036                 return 256 * 1024;
2037         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2038                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2039                 return 128 * 1024;
2040         else if (INTEL_GEN(dev_priv) >= 4)
2041                 return 4 * 1024;
2042         else
2043                 return 0;
2044 }
2045
2046 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2047                                          int color_plane)
2048 {
2049         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2050
2051         /* AUX_DIST needs only 4K alignment */
2052         if (color_plane == 1)
2053                 return 4096;
2054
2055         switch (fb->modifier) {
2056         case DRM_FORMAT_MOD_LINEAR:
2057                 return intel_linear_alignment(dev_priv);
2058         case I915_FORMAT_MOD_X_TILED:
2059                 if (INTEL_GEN(dev_priv) >= 9)
2060                         return 256 * 1024;
2061                 return 0;
2062         case I915_FORMAT_MOD_Y_TILED_CCS:
2063         case I915_FORMAT_MOD_Yf_TILED_CCS:
2064         case I915_FORMAT_MOD_Y_TILED:
2065         case I915_FORMAT_MOD_Yf_TILED:
2066                 return 1 * 1024 * 1024;
2067         default:
2068                 MISSING_CASE(fb->modifier);
2069                 return 0;
2070         }
2071 }
2072
2073 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2074 {
2075         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2076         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2077
2078         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2079 }
2080
2081 struct i915_vma *
2082 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2083                            const struct i915_ggtt_view *view,
2084                            bool uses_fence,
2085                            unsigned long *out_flags)
2086 {
2087         struct drm_device *dev = fb->dev;
2088         struct drm_i915_private *dev_priv = to_i915(dev);
2089         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2090         struct i915_vma *vma;
2091         unsigned int pinctl;
2092         u32 alignment;
2093
2094         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2095
2096         alignment = intel_surf_alignment(fb, 0);
2097
2098         /* Note that the w/a also requires 64 PTE of padding following the
2099          * bo. We currently fill all unused PTE with the shadow page and so
2100          * we should always have valid PTE following the scanout preventing
2101          * the VT-d warning.
2102          */
2103         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2104                 alignment = 256 * 1024;
2105
2106         /*
2107          * Global gtt pte registers are special registers which actually forward
2108          * writes to a chunk of system memory. Which means that there is no risk
2109          * that the register values disappear as soon as we call
2110          * intel_runtime_pm_put(), so it is correct to wrap only the
2111          * pin/unpin/fence and not more.
2112          */
2113         intel_runtime_pm_get(dev_priv);
2114
2115         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2116
2117         pinctl = 0;
2118
2119         /* Valleyview is definitely limited to scanning out the first
2120          * 512MiB. Lets presume this behaviour was inherited from the
2121          * g4x display engine and that all earlier gen are similarly
2122          * limited. Testing suggests that it is a little more
2123          * complicated than this. For example, Cherryview appears quite
2124          * happy to scanout from anywhere within its global aperture.
2125          */
2126         if (HAS_GMCH_DISPLAY(dev_priv))
2127                 pinctl |= PIN_MAPPABLE;
2128
2129         vma = i915_gem_object_pin_to_display_plane(obj,
2130                                                    alignment, view, pinctl);
2131         if (IS_ERR(vma))
2132                 goto err;
2133
2134         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2135                 int ret;
2136
2137                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2138                  * fence, whereas 965+ only requires a fence if using
2139                  * framebuffer compression.  For simplicity, we always, when
2140                  * possible, install a fence as the cost is not that onerous.
2141                  *
2142                  * If we fail to fence the tiled scanout, then either the
2143                  * modeset will reject the change (which is highly unlikely as
2144                  * the affected systems, all but one, do not have unmappable
2145                  * space) or we will not be able to enable full powersaving
2146                  * techniques (also likely not to apply due to various limits
2147                  * FBC and the like impose on the size of the buffer, which
2148                  * presumably we violated anyway with this unmappable buffer).
2149                  * Anyway, it is presumably better to stumble onwards with
2150                  * something and try to run the system in a "less than optimal"
2151                  * mode that matches the user configuration.
2152                  */
2153                 ret = i915_vma_pin_fence(vma);
2154                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2155                         i915_gem_object_unpin_from_display_plane(vma);
2156                         vma = ERR_PTR(ret);
2157                         goto err;
2158                 }
2159
2160                 if (ret == 0 && vma->fence)
2161                         *out_flags |= PLANE_HAS_FENCE;
2162         }
2163
2164         i915_vma_get(vma);
2165 err:
2166         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2167
2168         intel_runtime_pm_put(dev_priv);
2169         return vma;
2170 }
2171
2172 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2173 {
2174         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2175
2176         if (flags & PLANE_HAS_FENCE)
2177                 i915_vma_unpin_fence(vma);
2178         i915_gem_object_unpin_from_display_plane(vma);
2179         i915_vma_put(vma);
2180 }
2181
2182 static int intel_fb_pitch(const struct drm_framebuffer *fb, int color_plane,
2183                           unsigned int rotation)
2184 {
2185         if (drm_rotation_90_or_270(rotation))
2186                 return to_intel_framebuffer(fb)->rotated[color_plane].pitch;
2187         else
2188                 return fb->pitches[color_plane];
2189 }
2190
2191 /*
2192  * Convert the x/y offsets into a linear offset.
2193  * Only valid with 0/180 degree rotation, which is fine since linear
2194  * offset is only used with linear buffers on pre-hsw and tiled buffers
2195  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2196  */
2197 u32 intel_fb_xy_to_linear(int x, int y,
2198                           const struct intel_plane_state *state,
2199                           int color_plane)
2200 {
2201         const struct drm_framebuffer *fb = state->base.fb;
2202         unsigned int cpp = fb->format->cpp[color_plane];
2203         unsigned int pitch = state->color_plane[color_plane].stride;
2204
2205         return y * pitch + x * cpp;
2206 }
2207
2208 /*
2209  * Add the x/y offsets derived from fb->offsets[] to the user
2210  * specified plane src x/y offsets. The resulting x/y offsets
2211  * specify the start of scanout from the beginning of the gtt mapping.
2212  */
2213 void intel_add_fb_offsets(int *x, int *y,
2214                           const struct intel_plane_state *state,
2215                           int color_plane)
2216
2217 {
2218         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2219         unsigned int rotation = state->base.rotation;
2220
2221         if (drm_rotation_90_or_270(rotation)) {
2222                 *x += intel_fb->rotated[color_plane].x;
2223                 *y += intel_fb->rotated[color_plane].y;
2224         } else {
2225                 *x += intel_fb->normal[color_plane].x;
2226                 *y += intel_fb->normal[color_plane].y;
2227         }
2228 }
2229
2230 static u32 intel_adjust_tile_offset(int *x, int *y,
2231                                     unsigned int tile_width,
2232                                     unsigned int tile_height,
2233                                     unsigned int tile_size,
2234                                     unsigned int pitch_tiles,
2235                                     u32 old_offset,
2236                                     u32 new_offset)
2237 {
2238         unsigned int pitch_pixels = pitch_tiles * tile_width;
2239         unsigned int tiles;
2240
2241         WARN_ON(old_offset & (tile_size - 1));
2242         WARN_ON(new_offset & (tile_size - 1));
2243         WARN_ON(new_offset > old_offset);
2244
2245         tiles = (old_offset - new_offset) / tile_size;
2246
2247         *y += tiles / pitch_tiles * tile_height;
2248         *x += tiles % pitch_tiles * tile_width;
2249
2250         /* minimize x in case it got needlessly big */
2251         *y += *x / pitch_pixels * tile_height;
2252         *x %= pitch_pixels;
2253
2254         return new_offset;
2255 }
2256
2257 static u32 intel_adjust_aligned_offset(int *x, int *y,
2258                                        const struct drm_framebuffer *fb,
2259                                        int color_plane,
2260                                        unsigned int rotation,
2261                                        unsigned int pitch,
2262                                        u32 old_offset, u32 new_offset)
2263 {
2264         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2265         unsigned int cpp = fb->format->cpp[color_plane];
2266
2267         WARN_ON(new_offset > old_offset);
2268
2269         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2270                 unsigned int tile_size, tile_width, tile_height;
2271                 unsigned int pitch_tiles;
2272
2273                 tile_size = intel_tile_size(dev_priv);
2274                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2275
2276                 if (drm_rotation_90_or_270(rotation)) {
2277                         pitch_tiles = pitch / tile_height;
2278                         swap(tile_width, tile_height);
2279                 } else {
2280                         pitch_tiles = pitch / (tile_width * cpp);
2281                 }
2282
2283                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2284                                          tile_size, pitch_tiles,
2285                                          old_offset, new_offset);
2286         } else {
2287                 old_offset += *y * pitch + *x * cpp;
2288
2289                 *y = (old_offset - new_offset) / pitch;
2290                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2291         }
2292
2293         return new_offset;
2294 }
2295
2296 /*
2297  * Adjust the tile offset by moving the difference into
2298  * the x/y offsets.
2299  */
2300 static u32 intel_plane_adjust_aligned_offset(int *x, int *y,
2301                                              const struct intel_plane_state *state,
2302                                              int color_plane,
2303                                              u32 old_offset, u32 new_offset)
2304 {
2305         return intel_adjust_aligned_offset(x, y, state->base.fb, color_plane,
2306                                            state->base.rotation,
2307                                            state->color_plane[color_plane].stride,
2308                                            old_offset, new_offset);
2309 }
2310
2311 /*
2312  * Computes the aligned offset to the base tile and adjusts
2313  * x, y. bytes per pixel is assumed to be a power-of-two.
2314  *
2315  * In the 90/270 rotated case, x and y are assumed
2316  * to be already rotated to match the rotated GTT view, and
2317  * pitch is the tile_height aligned framebuffer height.
2318  *
2319  * This function is used when computing the derived information
2320  * under intel_framebuffer, so using any of that information
2321  * here is not allowed. Anything under drm_framebuffer can be
2322  * used. This is why the user has to pass in the pitch since it
2323  * is specified in the rotated orientation.
2324  */
2325 static u32 intel_compute_aligned_offset(struct drm_i915_private *dev_priv,
2326                                         int *x, int *y,
2327                                         const struct drm_framebuffer *fb,
2328                                         int color_plane,
2329                                         unsigned int pitch,
2330                                         unsigned int rotation,
2331                                         u32 alignment)
2332 {
2333         uint64_t fb_modifier = fb->modifier;
2334         unsigned int cpp = fb->format->cpp[color_plane];
2335         u32 offset, offset_aligned;
2336
2337         if (alignment)
2338                 alignment--;
2339
2340         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2341                 unsigned int tile_size, tile_width, tile_height;
2342                 unsigned int tile_rows, tiles, pitch_tiles;
2343
2344                 tile_size = intel_tile_size(dev_priv);
2345                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2346
2347                 if (drm_rotation_90_or_270(rotation)) {
2348                         pitch_tiles = pitch / tile_height;
2349                         swap(tile_width, tile_height);
2350                 } else {
2351                         pitch_tiles = pitch / (tile_width * cpp);
2352                 }
2353
2354                 tile_rows = *y / tile_height;
2355                 *y %= tile_height;
2356
2357                 tiles = *x / tile_width;
2358                 *x %= tile_width;
2359
2360                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2361                 offset_aligned = offset & ~alignment;
2362
2363                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2364                                          tile_size, pitch_tiles,
2365                                          offset, offset_aligned);
2366         } else {
2367                 offset = *y * pitch + *x * cpp;
2368                 offset_aligned = offset & ~alignment;
2369
2370                 *y = (offset & alignment) / pitch;
2371                 *x = ((offset & alignment) - *y * pitch) / cpp;
2372         }
2373
2374         return offset_aligned;
2375 }
2376
2377 static u32 intel_plane_compute_aligned_offset(int *x, int *y,
2378                                               const struct intel_plane_state *state,
2379                                               int color_plane)
2380 {
2381         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2382         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2383         const struct drm_framebuffer *fb = state->base.fb;
2384         unsigned int rotation = state->base.rotation;
2385         int pitch = state->color_plane[color_plane].stride;
2386         u32 alignment;
2387
2388         if (intel_plane->id == PLANE_CURSOR)
2389                 alignment = intel_cursor_alignment(dev_priv);
2390         else
2391                 alignment = intel_surf_alignment(fb, color_plane);
2392
2393         return intel_compute_aligned_offset(dev_priv, x, y, fb, color_plane,
2394                                             pitch, rotation, alignment);
2395 }
2396
2397 /* Convert the fb->offset[] into x/y offsets */
2398 static int intel_fb_offset_to_xy(int *x, int *y,
2399                                  const struct drm_framebuffer *fb,
2400                                  int color_plane)
2401 {
2402         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2403
2404         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2405             fb->offsets[color_plane] % intel_tile_size(dev_priv))
2406                 return -EINVAL;
2407
2408         *x = 0;
2409         *y = 0;
2410
2411         intel_adjust_aligned_offset(x, y,
2412                                     fb, color_plane, DRM_MODE_ROTATE_0,
2413                                     fb->pitches[color_plane],
2414                                     fb->offsets[color_plane], 0);
2415
2416         return 0;
2417 }
2418
2419 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2420 {
2421         switch (fb_modifier) {
2422         case I915_FORMAT_MOD_X_TILED:
2423                 return I915_TILING_X;
2424         case I915_FORMAT_MOD_Y_TILED:
2425         case I915_FORMAT_MOD_Y_TILED_CCS:
2426                 return I915_TILING_Y;
2427         default:
2428                 return I915_TILING_NONE;
2429         }
2430 }
2431
2432 /*
2433  * From the Sky Lake PRM:
2434  * "The Color Control Surface (CCS) contains the compression status of
2435  *  the cache-line pairs. The compression state of the cache-line pair
2436  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2437  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2438  *  cache-line-pairs. CCS is always Y tiled."
2439  *
2440  * Since cache line pairs refers to horizontally adjacent cache lines,
2441  * each cache line in the CCS corresponds to an area of 32x16 cache
2442  * lines on the main surface. Since each pixel is 4 bytes, this gives
2443  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2444  * main surface.
2445  */
2446 static const struct drm_format_info ccs_formats[] = {
2447         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2448         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2449         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2450         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2451 };
2452
2453 static const struct drm_format_info *
2454 lookup_format_info(const struct drm_format_info formats[],
2455                    int num_formats, u32 format)
2456 {
2457         int i;
2458
2459         for (i = 0; i < num_formats; i++) {
2460                 if (formats[i].format == format)
2461                         return &formats[i];
2462         }
2463
2464         return NULL;
2465 }
2466
2467 static const struct drm_format_info *
2468 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2469 {
2470         switch (cmd->modifier[0]) {
2471         case I915_FORMAT_MOD_Y_TILED_CCS:
2472         case I915_FORMAT_MOD_Yf_TILED_CCS:
2473                 return lookup_format_info(ccs_formats,
2474                                           ARRAY_SIZE(ccs_formats),
2475                                           cmd->pixel_format);
2476         default:
2477                 return NULL;
2478         }
2479 }
2480
2481 bool is_ccs_modifier(u64 modifier)
2482 {
2483         return modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2484                modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
2485 }
2486
2487 static int
2488 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2489                    struct drm_framebuffer *fb)
2490 {
2491         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2492         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2493         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2494         u32 gtt_offset_rotated = 0;
2495         unsigned int max_size = 0;
2496         int i, num_planes = fb->format->num_planes;
2497         unsigned int tile_size = intel_tile_size(dev_priv);
2498
2499         for (i = 0; i < num_planes; i++) {
2500                 unsigned int width, height;
2501                 unsigned int cpp, size;
2502                 u32 offset;
2503                 int x, y;
2504                 int ret;
2505
2506                 cpp = fb->format->cpp[i];
2507                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2508                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2509
2510                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2511                 if (ret) {
2512                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2513                                       i, fb->offsets[i]);
2514                         return ret;
2515                 }
2516
2517                 if (is_ccs_modifier(fb->modifier) && i == 1) {
2518                         int hsub = fb->format->hsub;
2519                         int vsub = fb->format->vsub;
2520                         int tile_width, tile_height;
2521                         int main_x, main_y;
2522                         int ccs_x, ccs_y;
2523
2524                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2525                         tile_width *= hsub;
2526                         tile_height *= vsub;
2527
2528                         ccs_x = (x * hsub) % tile_width;
2529                         ccs_y = (y * vsub) % tile_height;
2530                         main_x = intel_fb->normal[0].x % tile_width;
2531                         main_y = intel_fb->normal[0].y % tile_height;
2532
2533                         /*
2534                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2535                          * x/y offsets must match between CCS and the main surface.
2536                          */
2537                         if (main_x != ccs_x || main_y != ccs_y) {
2538                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2539                                               main_x, main_y,
2540                                               ccs_x, ccs_y,
2541                                               intel_fb->normal[0].x,
2542                                               intel_fb->normal[0].y,
2543                                               x, y);
2544                                 return -EINVAL;
2545                         }
2546                 }
2547
2548                 /*
2549                  * The fence (if used) is aligned to the start of the object
2550                  * so having the framebuffer wrap around across the edge of the
2551                  * fenced region doesn't really work. We have no API to configure
2552                  * the fence start offset within the object (nor could we probably
2553                  * on gen2/3). So it's just easier if we just require that the
2554                  * fb layout agrees with the fence layout. We already check that the
2555                  * fb stride matches the fence stride elsewhere.
2556                  */
2557                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2558                     (x + width) * cpp > fb->pitches[i]) {
2559                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2560                                       i, fb->offsets[i]);
2561                         return -EINVAL;
2562                 }
2563
2564                 /*
2565                  * First pixel of the framebuffer from
2566                  * the start of the normal gtt mapping.
2567                  */
2568                 intel_fb->normal[i].x = x;
2569                 intel_fb->normal[i].y = y;
2570
2571                 offset = intel_compute_aligned_offset(dev_priv, &x, &y, fb, i,
2572                                                       fb->pitches[i],
2573                                                       DRM_MODE_ROTATE_0,
2574                                                       tile_size);
2575                 offset /= tile_size;
2576
2577                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2578                         unsigned int tile_width, tile_height;
2579                         unsigned int pitch_tiles;
2580                         struct drm_rect r;
2581
2582                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2583
2584                         rot_info->plane[i].offset = offset;
2585                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2586                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2587                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2588
2589                         intel_fb->rotated[i].pitch =
2590                                 rot_info->plane[i].height * tile_height;
2591
2592                         /* how many tiles does this plane need */
2593                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2594                         /*
2595                          * If the plane isn't horizontally tile aligned,
2596                          * we need one more tile.
2597                          */
2598                         if (x != 0)
2599                                 size++;
2600
2601                         /* rotate the x/y offsets to match the GTT view */
2602                         r.x1 = x;
2603                         r.y1 = y;
2604                         r.x2 = x + width;
2605                         r.y2 = y + height;
2606                         drm_rect_rotate(&r,
2607                                         rot_info->plane[i].width * tile_width,
2608                                         rot_info->plane[i].height * tile_height,
2609                                         DRM_MODE_ROTATE_270);
2610                         x = r.x1;
2611                         y = r.y1;
2612
2613                         /* rotate the tile dimensions to match the GTT view */
2614                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2615                         swap(tile_width, tile_height);
2616
2617                         /*
2618                          * We only keep the x/y offsets, so push all of the
2619                          * gtt offset into the x/y offsets.
2620                          */
2621                         intel_adjust_tile_offset(&x, &y,
2622                                                  tile_width, tile_height,
2623                                                  tile_size, pitch_tiles,
2624                                                  gtt_offset_rotated * tile_size, 0);
2625
2626                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2627
2628                         /*
2629                          * First pixel of the framebuffer from
2630                          * the start of the rotated gtt mapping.
2631                          */
2632                         intel_fb->rotated[i].x = x;
2633                         intel_fb->rotated[i].y = y;
2634                 } else {
2635                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2636                                             x * cpp, tile_size);
2637                 }
2638
2639                 /* how many tiles in total needed in the bo */
2640                 max_size = max(max_size, offset + size);
2641         }
2642
2643         if (mul_u32_u32(max_size, tile_size) > obj->base.size) {
2644                 DRM_DEBUG_KMS("fb too big for bo (need %llu bytes, have %zu bytes)\n",
2645                               mul_u32_u32(max_size, tile_size), obj->base.size);
2646                 return -EINVAL;
2647         }
2648
2649         return 0;
2650 }
2651
2652 static int i9xx_format_to_fourcc(int format)
2653 {
2654         switch (format) {
2655         case DISPPLANE_8BPP:
2656                 return DRM_FORMAT_C8;
2657         case DISPPLANE_BGRX555:
2658                 return DRM_FORMAT_XRGB1555;
2659         case DISPPLANE_BGRX565:
2660                 return DRM_FORMAT_RGB565;
2661         default:
2662         case DISPPLANE_BGRX888:
2663                 return DRM_FORMAT_XRGB8888;
2664         case DISPPLANE_RGBX888:
2665                 return DRM_FORMAT_XBGR8888;
2666         case DISPPLANE_BGRX101010:
2667                 return DRM_FORMAT_XRGB2101010;
2668         case DISPPLANE_RGBX101010:
2669                 return DRM_FORMAT_XBGR2101010;
2670         }
2671 }
2672
2673 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2674 {
2675         switch (format) {
2676         case PLANE_CTL_FORMAT_RGB_565:
2677                 return DRM_FORMAT_RGB565;
2678         case PLANE_CTL_FORMAT_NV12:
2679                 return DRM_FORMAT_NV12;
2680         default:
2681         case PLANE_CTL_FORMAT_XRGB_8888:
2682                 if (rgb_order) {
2683                         if (alpha)
2684                                 return DRM_FORMAT_ABGR8888;
2685                         else
2686                                 return DRM_FORMAT_XBGR8888;
2687                 } else {
2688                         if (alpha)
2689                                 return DRM_FORMAT_ARGB8888;
2690                         else
2691                                 return DRM_FORMAT_XRGB8888;
2692                 }
2693         case PLANE_CTL_FORMAT_XRGB_2101010:
2694                 if (rgb_order)
2695                         return DRM_FORMAT_XBGR2101010;
2696                 else
2697                         return DRM_FORMAT_XRGB2101010;
2698         }
2699 }
2700
2701 static bool
2702 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2703                               struct intel_initial_plane_config *plane_config)
2704 {
2705         struct drm_device *dev = crtc->base.dev;
2706         struct drm_i915_private *dev_priv = to_i915(dev);
2707         struct drm_i915_gem_object *obj = NULL;
2708         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2709         struct drm_framebuffer *fb = &plane_config->fb->base;
2710         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2711         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2712                                     PAGE_SIZE);
2713
2714         size_aligned -= base_aligned;
2715
2716         if (plane_config->size == 0)
2717                 return false;
2718
2719         /* If the FB is too big, just don't use it since fbdev is not very
2720          * important and we should probably use that space with FBC or other
2721          * features. */
2722         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2723                 return false;
2724
2725         mutex_lock(&dev->struct_mutex);
2726         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2727                                                              base_aligned,
2728                                                              base_aligned,
2729                                                              size_aligned);
2730         mutex_unlock(&dev->struct_mutex);
2731         if (!obj)
2732                 return false;
2733
2734         if (plane_config->tiling == I915_TILING_X)
2735                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2736
2737         mode_cmd.pixel_format = fb->format->format;
2738         mode_cmd.width = fb->width;
2739         mode_cmd.height = fb->height;
2740         mode_cmd.pitches[0] = fb->pitches[0];
2741         mode_cmd.modifier[0] = fb->modifier;
2742         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2743
2744         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2745                 DRM_DEBUG_KMS("intel fb init failed\n");
2746                 goto out_unref_obj;
2747         }
2748
2749
2750         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2751         return true;
2752
2753 out_unref_obj:
2754         i915_gem_object_put(obj);
2755         return false;
2756 }
2757
2758 static void
2759 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2760                         struct intel_plane_state *plane_state,
2761                         bool visible)
2762 {
2763         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2764
2765         plane_state->base.visible = visible;
2766
2767         /* FIXME pre-g4x don't work like this */
2768         if (visible) {
2769                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
2770                 crtc_state->active_planes |= BIT(plane->id);
2771         } else {
2772                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
2773                 crtc_state->active_planes &= ~BIT(plane->id);
2774         }
2775
2776         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2777                       crtc_state->base.crtc->name,
2778                       crtc_state->active_planes);
2779 }
2780
2781 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2782                                          struct intel_plane *plane)
2783 {
2784         struct intel_crtc_state *crtc_state =
2785                 to_intel_crtc_state(crtc->base.state);
2786         struct intel_plane_state *plane_state =
2787                 to_intel_plane_state(plane->base.state);
2788
2789         intel_set_plane_visible(crtc_state, plane_state, false);
2790
2791         if (plane->id == PLANE_PRIMARY)
2792                 intel_pre_disable_primary_noatomic(&crtc->base);
2793
2794         trace_intel_disable_plane(&plane->base, crtc);
2795         plane->disable_plane(plane, crtc);
2796 }
2797
2798 static void
2799 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2800                              struct intel_initial_plane_config *plane_config)
2801 {
2802         struct drm_device *dev = intel_crtc->base.dev;
2803         struct drm_i915_private *dev_priv = to_i915(dev);
2804         struct drm_crtc *c;
2805         struct drm_i915_gem_object *obj;
2806         struct drm_plane *primary = intel_crtc->base.primary;
2807         struct drm_plane_state *plane_state = primary->state;
2808         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2809         struct intel_plane *intel_plane = to_intel_plane(primary);
2810         struct intel_plane_state *intel_state =
2811                 to_intel_plane_state(plane_state);
2812         struct drm_framebuffer *fb;
2813
2814         if (!plane_config->fb)
2815                 return;
2816
2817         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2818                 fb = &plane_config->fb->base;
2819                 goto valid_fb;
2820         }
2821
2822         kfree(plane_config->fb);
2823
2824         /*
2825          * Failed to alloc the obj, check to see if we should share
2826          * an fb with another CRTC instead
2827          */
2828         for_each_crtc(dev, c) {
2829                 struct intel_plane_state *state;
2830
2831                 if (c == &intel_crtc->base)
2832                         continue;
2833
2834                 if (!to_intel_crtc(c)->active)
2835                         continue;
2836
2837                 state = to_intel_plane_state(c->primary->state);
2838                 if (!state->vma)
2839                         continue;
2840
2841                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2842                         fb = state->base.fb;
2843                         drm_framebuffer_get(fb);
2844                         goto valid_fb;
2845                 }
2846         }
2847
2848         /*
2849          * We've failed to reconstruct the BIOS FB.  Current display state
2850          * indicates that the primary plane is visible, but has a NULL FB,
2851          * which will lead to problems later if we don't fix it up.  The
2852          * simplest solution is to just disable the primary plane now and
2853          * pretend the BIOS never had it enabled.
2854          */
2855         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2856
2857         return;
2858
2859 valid_fb:
2860         intel_fill_fb_ggtt_view(&intel_state->view, fb,
2861                                 intel_state->base.rotation);
2862         intel_state->color_plane[0].stride =
2863                 intel_fb_pitch(fb, 0, intel_state->base.rotation);
2864
2865         mutex_lock(&dev->struct_mutex);
2866         intel_state->vma =
2867                 intel_pin_and_fence_fb_obj(fb,
2868                                            &intel_state->view,
2869                                            intel_plane_uses_fence(intel_state),
2870                                            &intel_state->flags);
2871         mutex_unlock(&dev->struct_mutex);
2872         if (IS_ERR(intel_state->vma)) {
2873                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2874                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2875
2876                 intel_state->vma = NULL;
2877                 drm_framebuffer_put(fb);
2878                 return;
2879         }
2880
2881         obj = intel_fb_obj(fb);
2882         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
2883
2884         plane_state->src_x = 0;
2885         plane_state->src_y = 0;
2886         plane_state->src_w = fb->width << 16;
2887         plane_state->src_h = fb->height << 16;
2888
2889         plane_state->crtc_x = 0;
2890         plane_state->crtc_y = 0;
2891         plane_state->crtc_w = fb->width;
2892         plane_state->crtc_h = fb->height;
2893
2894         intel_state->base.src = drm_plane_state_src(plane_state);
2895         intel_state->base.dst = drm_plane_state_dest(plane_state);
2896
2897         if (i915_gem_object_is_tiled(obj))
2898                 dev_priv->preserve_bios_swizzle = true;
2899
2900         plane_state->fb = fb;
2901         plane_state->crtc = &intel_crtc->base;
2902
2903         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2904                                 to_intel_plane_state(plane_state),
2905                                 true);
2906
2907         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2908                   &obj->frontbuffer_bits);
2909 }
2910
2911 static int skl_max_plane_width(const struct drm_framebuffer *fb,
2912                                int color_plane,
2913                                unsigned int rotation)
2914 {
2915         int cpp = fb->format->cpp[color_plane];
2916
2917         switch (fb->modifier) {
2918         case DRM_FORMAT_MOD_LINEAR:
2919         case I915_FORMAT_MOD_X_TILED:
2920                 switch (cpp) {
2921                 case 8:
2922                         return 4096;
2923                 case 4:
2924                 case 2:
2925                 case 1:
2926                         return 8192;
2927                 default:
2928                         MISSING_CASE(cpp);
2929                         break;
2930                 }
2931                 break;
2932         case I915_FORMAT_MOD_Y_TILED_CCS:
2933         case I915_FORMAT_MOD_Yf_TILED_CCS:
2934                 /* FIXME AUX plane? */
2935         case I915_FORMAT_MOD_Y_TILED:
2936         case I915_FORMAT_MOD_Yf_TILED:
2937                 switch (cpp) {
2938                 case 8:
2939                         return 2048;
2940                 case 4:
2941                         return 4096;
2942                 case 2:
2943                 case 1:
2944                         return 8192;
2945                 default:
2946                         MISSING_CASE(cpp);
2947                         break;
2948                 }
2949                 break;
2950         default:
2951                 MISSING_CASE(fb->modifier);
2952         }
2953
2954         return 2048;
2955 }
2956
2957 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2958                                            int main_x, int main_y, u32 main_offset)
2959 {
2960         const struct drm_framebuffer *fb = plane_state->base.fb;
2961         int hsub = fb->format->hsub;
2962         int vsub = fb->format->vsub;
2963         int aux_x = plane_state->color_plane[1].x;
2964         int aux_y = plane_state->color_plane[1].y;
2965         u32 aux_offset = plane_state->color_plane[1].offset;
2966         u32 alignment = intel_surf_alignment(fb, 1);
2967
2968         while (aux_offset >= main_offset && aux_y <= main_y) {
2969                 int x, y;
2970
2971                 if (aux_x == main_x && aux_y == main_y)
2972                         break;
2973
2974                 if (aux_offset == 0)
2975                         break;
2976
2977                 x = aux_x / hsub;
2978                 y = aux_y / vsub;
2979                 aux_offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 1,
2980                                                                aux_offset, aux_offset - alignment);
2981                 aux_x = x * hsub + aux_x % hsub;
2982                 aux_y = y * vsub + aux_y % vsub;
2983         }
2984
2985         if (aux_x != main_x || aux_y != main_y)
2986                 return false;
2987
2988         plane_state->color_plane[1].offset = aux_offset;
2989         plane_state->color_plane[1].x = aux_x;
2990         plane_state->color_plane[1].y = aux_y;
2991
2992         return true;
2993 }
2994
2995 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2996 {
2997         const struct drm_framebuffer *fb = plane_state->base.fb;
2998         unsigned int rotation = plane_state->base.rotation;
2999         int x = plane_state->base.src.x1 >> 16;
3000         int y = plane_state->base.src.y1 >> 16;
3001         int w = drm_rect_width(&plane_state->base.src) >> 16;
3002         int h = drm_rect_height(&plane_state->base.src) >> 16;
3003         int max_width = skl_max_plane_width(fb, 0, rotation);
3004         int max_height = 4096;
3005         u32 alignment, offset, aux_offset = plane_state->color_plane[1].offset;
3006
3007         if (w > max_width || h > max_height) {
3008                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
3009                               w, h, max_width, max_height);
3010                 return -EINVAL;
3011         }
3012
3013         intel_add_fb_offsets(&x, &y, plane_state, 0);
3014         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 0);
3015         alignment = intel_surf_alignment(fb, 0);
3016
3017         /*
3018          * AUX surface offset is specified as the distance from the
3019          * main surface offset, and it must be non-negative. Make
3020          * sure that is what we will get.
3021          */
3022         if (offset > aux_offset)
3023                 offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3024                                                            offset, aux_offset & ~(alignment - 1));
3025
3026         /*
3027          * When using an X-tiled surface, the plane blows up
3028          * if the x offset + width exceed the stride.
3029          *
3030          * TODO: linear and Y-tiled seem fine, Yf untested,
3031          */
3032         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3033                 int cpp = fb->format->cpp[0];
3034
3035                 while ((x + w) * cpp > plane_state->color_plane[0].stride) {
3036                         if (offset == 0) {
3037                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3038                                 return -EINVAL;
3039                         }
3040
3041                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3042                                                                    offset, offset - alignment);
3043                 }
3044         }
3045
3046         /*
3047          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3048          * they match with the main surface x/y offsets.
3049          */
3050         if (is_ccs_modifier(fb->modifier)) {
3051                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3052                         if (offset == 0)
3053                                 break;
3054
3055                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3056                                                                    offset, offset - alignment);
3057                 }
3058
3059                 if (x != plane_state->color_plane[1].x || y != plane_state->color_plane[1].y) {
3060                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3061                         return -EINVAL;
3062                 }
3063         }
3064
3065         plane_state->color_plane[0].offset = offset;
3066         plane_state->color_plane[0].x = x;
3067         plane_state->color_plane[0].y = y;
3068
3069         return 0;
3070 }
3071
3072 static int
3073 skl_check_nv12_surface(struct intel_plane_state *plane_state)
3074 {
3075         /* Display WA #1106 */
3076         if (plane_state->base.rotation !=
3077             (DRM_MODE_REFLECT_X | DRM_MODE_ROTATE_90) &&
3078             plane_state->base.rotation != DRM_MODE_ROTATE_270)
3079                 return 0;
3080
3081         /*
3082          * src coordinates are rotated here.
3083          * We check height but report it as width
3084          */
3085         if (((drm_rect_height(&plane_state->base.src) >> 16) % 4) != 0) {
3086                 DRM_DEBUG_KMS("src width must be multiple "
3087                               "of 4 for rotated NV12\n");
3088                 return -EINVAL;
3089         }
3090
3091         return 0;
3092 }
3093
3094 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3095 {
3096         const struct drm_framebuffer *fb = plane_state->base.fb;
3097         unsigned int rotation = plane_state->base.rotation;
3098         int max_width = skl_max_plane_width(fb, 1, rotation);
3099         int max_height = 4096;
3100         int x = plane_state->base.src.x1 >> 17;
3101         int y = plane_state->base.src.y1 >> 17;
3102         int w = drm_rect_width(&plane_state->base.src) >> 17;
3103         int h = drm_rect_height(&plane_state->base.src) >> 17;
3104         u32 offset;
3105
3106         intel_add_fb_offsets(&x, &y, plane_state, 1);
3107         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3108
3109         /* FIXME not quite sure how/if these apply to the chroma plane */
3110         if (w > max_width || h > max_height) {
3111                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3112                               w, h, max_width, max_height);
3113                 return -EINVAL;
3114         }
3115
3116         plane_state->color_plane[1].offset = offset;
3117         plane_state->color_plane[1].x = x;
3118         plane_state->color_plane[1].y = y;
3119
3120         return 0;
3121 }
3122
3123 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3124 {
3125         const struct drm_framebuffer *fb = plane_state->base.fb;
3126         int src_x = plane_state->base.src.x1 >> 16;
3127         int src_y = plane_state->base.src.y1 >> 16;
3128         int hsub = fb->format->hsub;
3129         int vsub = fb->format->vsub;
3130         int x = src_x / hsub;
3131         int y = src_y / vsub;
3132         u32 offset;
3133
3134         intel_add_fb_offsets(&x, &y, plane_state, 1);
3135         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3136
3137         plane_state->color_plane[1].offset = offset;
3138         plane_state->color_plane[1].x = x * hsub + src_x % hsub;
3139         plane_state->color_plane[1].y = y * vsub + src_y % vsub;
3140
3141         return 0;
3142 }
3143
3144 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3145 {
3146         const struct drm_framebuffer *fb = plane_state->base.fb;
3147         unsigned int rotation = plane_state->base.rotation;
3148         int ret;
3149
3150         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3151         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3152         plane_state->color_plane[1].stride = intel_fb_pitch(fb, 1, rotation);
3153
3154         if (!plane_state->base.visible)
3155                 return 0;
3156
3157         /* Rotate src coordinates to match rotated GTT view */
3158         if (drm_rotation_90_or_270(rotation))
3159                 drm_rect_rotate(&plane_state->base.src,
3160                                 fb->width << 16, fb->height << 16,
3161                                 DRM_MODE_ROTATE_270);
3162
3163         /*
3164          * Handle the AUX surface first since
3165          * the main surface setup depends on it.
3166          */
3167         if (fb->format->format == DRM_FORMAT_NV12) {
3168                 ret = skl_check_nv12_surface(plane_state);
3169                 if (ret)
3170                         return ret;
3171                 ret = skl_check_nv12_aux_surface(plane_state);
3172                 if (ret)
3173                         return ret;
3174         } else if (is_ccs_modifier(fb->modifier)) {
3175                 ret = skl_check_ccs_aux_surface(plane_state);
3176                 if (ret)
3177                         return ret;
3178         } else {
3179                 plane_state->color_plane[1].offset = ~0xfff;
3180                 plane_state->color_plane[1].x = 0;
3181                 plane_state->color_plane[1].y = 0;
3182         }
3183
3184         ret = skl_check_main_surface(plane_state);
3185         if (ret)
3186                 return ret;
3187
3188         return 0;
3189 }
3190
3191 unsigned int
3192 i9xx_plane_max_stride(struct intel_plane *plane,
3193                       u32 pixel_format, u64 modifier,
3194                       unsigned int rotation)
3195 {
3196         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3197
3198         if (!HAS_GMCH_DISPLAY(dev_priv)) {
3199                 return 32*1024;
3200         } else if (INTEL_GEN(dev_priv) >= 4) {
3201                 if (modifier == I915_FORMAT_MOD_X_TILED)
3202                         return 16*1024;
3203                 else
3204                         return 32*1024;
3205         } else if (INTEL_GEN(dev_priv) >= 3) {
3206                 if (modifier == I915_FORMAT_MOD_X_TILED)
3207                         return 8*1024;
3208                 else
3209                         return 16*1024;
3210         } else {
3211                 if (plane->i9xx_plane == PLANE_C)
3212                         return 4*1024;
3213                 else
3214                         return 8*1024;
3215         }
3216 }
3217
3218 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3219                           const struct intel_plane_state *plane_state)
3220 {
3221         struct drm_i915_private *dev_priv =
3222                 to_i915(plane_state->base.plane->dev);
3223         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3224         const struct drm_framebuffer *fb = plane_state->base.fb;
3225         unsigned int rotation = plane_state->base.rotation;
3226         u32 dspcntr;
3227
3228         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3229
3230         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3231             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3232                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3233
3234         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3235                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3236
3237         if (INTEL_GEN(dev_priv) < 5)
3238                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3239
3240         switch (fb->format->format) {
3241         case DRM_FORMAT_C8:
3242                 dspcntr |= DISPPLANE_8BPP;
3243                 break;
3244         case DRM_FORMAT_XRGB1555:
3245                 dspcntr |= DISPPLANE_BGRX555;
3246                 break;
3247         case DRM_FORMAT_RGB565:
3248                 dspcntr |= DISPPLANE_BGRX565;
3249                 break;
3250         case DRM_FORMAT_XRGB8888:
3251                 dspcntr |= DISPPLANE_BGRX888;
3252                 break;
3253         case DRM_FORMAT_XBGR8888:
3254                 dspcntr |= DISPPLANE_RGBX888;
3255                 break;
3256         case DRM_FORMAT_XRGB2101010:
3257                 dspcntr |= DISPPLANE_BGRX101010;
3258                 break;
3259         case DRM_FORMAT_XBGR2101010:
3260                 dspcntr |= DISPPLANE_RGBX101010;
3261                 break;
3262         default:
3263                 MISSING_CASE(fb->format->format);
3264                 return 0;
3265         }
3266
3267         if (INTEL_GEN(dev_priv) >= 4 &&
3268             fb->modifier == I915_FORMAT_MOD_X_TILED)
3269                 dspcntr |= DISPPLANE_TILED;
3270
3271         if (rotation & DRM_MODE_ROTATE_180)
3272                 dspcntr |= DISPPLANE_ROTATE_180;
3273
3274         if (rotation & DRM_MODE_REFLECT_X)
3275                 dspcntr |= DISPPLANE_MIRROR;
3276
3277         return dspcntr;
3278 }
3279
3280 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3281 {
3282         struct drm_i915_private *dev_priv =
3283                 to_i915(plane_state->base.plane->dev);
3284         const struct drm_framebuffer *fb = plane_state->base.fb;
3285         unsigned int rotation = plane_state->base.rotation;
3286         int src_x = plane_state->base.src.x1 >> 16;
3287         int src_y = plane_state->base.src.y1 >> 16;
3288         u32 offset;
3289
3290         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3291         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3292
3293         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3294
3295         if (INTEL_GEN(dev_priv) >= 4)
3296                 offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
3297                                                             plane_state, 0);
3298         else
3299                 offset = 0;
3300
3301         /* HSW/BDW do this automagically in hardware */
3302         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3303                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3304                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3305
3306                 if (rotation & DRM_MODE_ROTATE_180) {
3307                         src_x += src_w - 1;
3308                         src_y += src_h - 1;
3309                 } else if (rotation & DRM_MODE_REFLECT_X) {
3310                         src_x += src_w - 1;
3311                 }
3312         }
3313
3314         plane_state->color_plane[0].offset = offset;
3315         plane_state->color_plane[0].x = src_x;
3316         plane_state->color_plane[0].y = src_y;
3317
3318         return 0;
3319 }
3320
3321 static int
3322 i9xx_plane_check(struct intel_crtc_state *crtc_state,
3323                  struct intel_plane_state *plane_state)
3324 {
3325         int ret;
3326
3327         ret = chv_plane_check_rotation(plane_state);
3328         if (ret)
3329                 return ret;
3330
3331         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
3332                                                   &crtc_state->base,
3333                                                   DRM_PLANE_HELPER_NO_SCALING,
3334                                                   DRM_PLANE_HELPER_NO_SCALING,
3335                                                   false, true);
3336         if (ret)
3337                 return ret;
3338
3339         if (!plane_state->base.visible)
3340                 return 0;
3341
3342         ret = intel_plane_check_src_coordinates(plane_state);
3343         if (ret)
3344                 return ret;
3345
3346         ret = i9xx_check_plane_surface(plane_state);
3347         if (ret)
3348                 return ret;
3349
3350         plane_state->ctl = i9xx_plane_ctl(crtc_state, plane_state);
3351
3352         return 0;
3353 }
3354
3355 static void i9xx_update_plane(struct intel_plane *plane,
3356                               const struct intel_crtc_state *crtc_state,
3357                               const struct intel_plane_state *plane_state)
3358 {
3359         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3360         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3361         u32 linear_offset;
3362         u32 dspcntr = plane_state->ctl;
3363         i915_reg_t reg = DSPCNTR(i9xx_plane);
3364         int x = plane_state->color_plane[0].x;
3365         int y = plane_state->color_plane[0].y;
3366         unsigned long irqflags;
3367         u32 dspaddr_offset;
3368
3369         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3370
3371         if (INTEL_GEN(dev_priv) >= 4)
3372                 dspaddr_offset = plane_state->color_plane[0].offset;
3373         else
3374                 dspaddr_offset = linear_offset;
3375
3376         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3377
3378         if (INTEL_GEN(dev_priv) < 4) {
3379                 /* pipesrc and dspsize control the size that is scaled from,
3380                  * which should always be the user's requested size.
3381                  */
3382                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3383                               ((crtc_state->pipe_src_h - 1) << 16) |
3384                               (crtc_state->pipe_src_w - 1));
3385                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3386         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3387                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3388                               ((crtc_state->pipe_src_h - 1) << 16) |
3389                               (crtc_state->pipe_src_w - 1));
3390                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3391                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3392         }
3393
3394         I915_WRITE_FW(reg, dspcntr);
3395
3396         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), plane_state->color_plane[0].stride);
3397         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3398                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3399                               intel_plane_ggtt_offset(plane_state) +
3400                               dspaddr_offset);
3401                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3402         } else if (INTEL_GEN(dev_priv) >= 4) {
3403                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3404                               intel_plane_ggtt_offset(plane_state) +
3405                               dspaddr_offset);
3406                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3407                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3408         } else {
3409                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3410                               intel_plane_ggtt_offset(plane_state) +
3411                               dspaddr_offset);
3412         }
3413         POSTING_READ_FW(reg);
3414
3415         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3416 }
3417
3418 static void i9xx_disable_plane(struct intel_plane *plane,
3419                                struct intel_crtc *crtc)
3420 {
3421         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3422         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3423         unsigned long irqflags;
3424
3425         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3426
3427         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3428         if (INTEL_GEN(dev_priv) >= 4)
3429                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3430         else
3431                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3432         POSTING_READ_FW(DSPCNTR(i9xx_plane));
3433
3434         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3435 }
3436
3437 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3438                                     enum pipe *pipe)
3439 {
3440         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3441         enum intel_display_power_domain power_domain;
3442         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3443         bool ret;
3444         u32 val;
3445
3446         /*
3447          * Not 100% correct for planes that can move between pipes,
3448          * but that's only the case for gen2-4 which don't have any
3449          * display power wells.
3450          */
3451         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3452         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3453                 return false;
3454
3455         val = I915_READ(DSPCNTR(i9xx_plane));
3456
3457         ret = val & DISPLAY_PLANE_ENABLE;
3458
3459         if (INTEL_GEN(dev_priv) >= 5)
3460                 *pipe = plane->pipe;
3461         else
3462                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3463                         DISPPLANE_SEL_PIPE_SHIFT;
3464
3465         intel_display_power_put(dev_priv, power_domain);
3466
3467         return ret;
3468 }
3469
3470 static u32
3471 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int color_plane)
3472 {
3473         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3474                 return 64;
3475         else
3476                 return intel_tile_width_bytes(fb, color_plane);
3477 }
3478
3479 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3480 {
3481         struct drm_device *dev = intel_crtc->base.dev;
3482         struct drm_i915_private *dev_priv = to_i915(dev);
3483
3484         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3485         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3486         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3487 }
3488
3489 /*
3490  * This function detaches (aka. unbinds) unused scalers in hardware
3491  */
3492 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3493 {
3494         struct intel_crtc_scaler_state *scaler_state;
3495         int i;
3496
3497         scaler_state = &intel_crtc->config->scaler_state;
3498
3499         /* loop through and disable scalers that aren't in use */
3500         for (i = 0; i < intel_crtc->num_scalers; i++) {
3501                 if (!scaler_state->scalers[i].in_use)
3502                         skl_detach_scaler(intel_crtc, i);
3503         }
3504 }
3505
3506 u32 skl_plane_stride(const struct intel_plane_state *plane_state,
3507                      int color_plane)
3508 {
3509         const struct drm_framebuffer *fb = plane_state->base.fb;
3510         unsigned int rotation = plane_state->base.rotation;
3511         u32 stride = plane_state->color_plane[color_plane].stride;
3512
3513         if (color_plane >= fb->format->num_planes)
3514                 return 0;
3515
3516         /*
3517          * The stride is either expressed as a multiple of 64 bytes chunks for
3518          * linear buffers or in number of tiles for tiled buffers.
3519          */
3520         if (drm_rotation_90_or_270(rotation))
3521                 stride /= intel_tile_height(fb, color_plane);
3522         else
3523                 stride /= intel_fb_stride_alignment(fb, color_plane);
3524
3525         return stride;
3526 }
3527
3528 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3529 {
3530         switch (pixel_format) {
3531         case DRM_FORMAT_C8:
3532                 return PLANE_CTL_FORMAT_INDEXED;
3533         case DRM_FORMAT_RGB565:
3534                 return PLANE_CTL_FORMAT_RGB_565;
3535         case DRM_FORMAT_XBGR8888:
3536         case DRM_FORMAT_ABGR8888:
3537                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3538         case DRM_FORMAT_XRGB8888:
3539         case DRM_FORMAT_ARGB8888:
3540                 return PLANE_CTL_FORMAT_XRGB_8888;
3541         case DRM_FORMAT_XRGB2101010:
3542                 return PLANE_CTL_FORMAT_XRGB_2101010;
3543         case DRM_FORMAT_XBGR2101010:
3544                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3545         case DRM_FORMAT_YUYV:
3546                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3547         case DRM_FORMAT_YVYU:
3548                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3549         case DRM_FORMAT_UYVY:
3550                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3551         case DRM_FORMAT_VYUY:
3552                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3553         case DRM_FORMAT_NV12:
3554                 return PLANE_CTL_FORMAT_NV12;
3555         default:
3556                 MISSING_CASE(pixel_format);
3557         }
3558
3559         return 0;
3560 }
3561
3562 /*
3563  * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3564  * to be already pre-multiplied. We need to add a knob (or a different
3565  * DRM_FORMAT) for user-space to configure that.
3566  */
3567 static u32 skl_plane_ctl_alpha(uint32_t pixel_format)
3568 {
3569         switch (pixel_format) {
3570         case DRM_FORMAT_ABGR8888:
3571         case DRM_FORMAT_ARGB8888:
3572                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3573         default:
3574                 return PLANE_CTL_ALPHA_DISABLE;
3575         }
3576 }
3577
3578 static u32 glk_plane_color_ctl_alpha(uint32_t pixel_format)
3579 {
3580         switch (pixel_format) {
3581         case DRM_FORMAT_ABGR8888:
3582         case DRM_FORMAT_ARGB8888:
3583                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3584         default:
3585                 return PLANE_COLOR_ALPHA_DISABLE;
3586         }
3587 }
3588
3589 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3590 {
3591         switch (fb_modifier) {
3592         case DRM_FORMAT_MOD_LINEAR:
3593                 break;
3594         case I915_FORMAT_MOD_X_TILED:
3595                 return PLANE_CTL_TILED_X;
3596         case I915_FORMAT_MOD_Y_TILED:
3597                 return PLANE_CTL_TILED_Y;
3598         case I915_FORMAT_MOD_Y_TILED_CCS:
3599                 return PLANE_CTL_TILED_Y | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3600         case I915_FORMAT_MOD_Yf_TILED:
3601                 return PLANE_CTL_TILED_YF;
3602         case I915_FORMAT_MOD_Yf_TILED_CCS:
3603                 return PLANE_CTL_TILED_YF | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3604         default:
3605                 MISSING_CASE(fb_modifier);
3606         }
3607
3608         return 0;
3609 }
3610
3611 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3612 {
3613         switch (rotate) {
3614         case DRM_MODE_ROTATE_0:
3615                 break;
3616         /*
3617          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3618          * while i915 HW rotation is clockwise, thats why this swapping.
3619          */
3620         case DRM_MODE_ROTATE_90:
3621                 return PLANE_CTL_ROTATE_270;
3622         case DRM_MODE_ROTATE_180:
3623                 return PLANE_CTL_ROTATE_180;
3624         case DRM_MODE_ROTATE_270:
3625                 return PLANE_CTL_ROTATE_90;
3626         default:
3627                 MISSING_CASE(rotate);
3628         }
3629
3630         return 0;
3631 }
3632
3633 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3634 {
3635         switch (reflect) {
3636         case 0:
3637                 break;
3638         case DRM_MODE_REFLECT_X:
3639                 return PLANE_CTL_FLIP_HORIZONTAL;
3640         case DRM_MODE_REFLECT_Y:
3641         default:
3642                 MISSING_CASE(reflect);
3643         }
3644
3645         return 0;
3646 }
3647
3648 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3649                   const struct intel_plane_state *plane_state)
3650 {
3651         struct drm_i915_private *dev_priv =
3652                 to_i915(plane_state->base.plane->dev);
3653         const struct drm_framebuffer *fb = plane_state->base.fb;
3654         unsigned int rotation = plane_state->base.rotation;
3655         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3656         u32 plane_ctl;
3657
3658         plane_ctl = PLANE_CTL_ENABLE;
3659
3660         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3661                 plane_ctl |= skl_plane_ctl_alpha(fb->format->format);
3662                 plane_ctl |=
3663                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3664                         PLANE_CTL_PIPE_CSC_ENABLE |
3665                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3666
3667                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3668                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3669
3670                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3671                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3672         }
3673
3674         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3675         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3676         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3677
3678         if (INTEL_GEN(dev_priv) >= 10)
3679                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3680                                                 DRM_MODE_REFLECT_MASK);
3681
3682         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3683                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3684         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3685                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3686
3687         return plane_ctl;
3688 }
3689
3690 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3691                         const struct intel_plane_state *plane_state)
3692 {
3693         struct drm_i915_private *dev_priv =
3694                 to_i915(plane_state->base.plane->dev);
3695         const struct drm_framebuffer *fb = plane_state->base.fb;
3696         u32 plane_color_ctl = 0;
3697
3698         if (INTEL_GEN(dev_priv) < 11) {
3699                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3700                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3701         }
3702         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3703         plane_color_ctl |= glk_plane_color_ctl_alpha(fb->format->format);
3704
3705         if (fb->format->is_yuv) {
3706                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3707                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3708                 else
3709                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3710
3711                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3712                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3713         }
3714
3715         return plane_color_ctl;
3716 }
3717
3718 static int
3719 __intel_display_resume(struct drm_device *dev,
3720                        struct drm_atomic_state *state,
3721                        struct drm_modeset_acquire_ctx *ctx)
3722 {
3723         struct drm_crtc_state *crtc_state;
3724         struct drm_crtc *crtc;
3725         int i, ret;
3726
3727         intel_modeset_setup_hw_state(dev, ctx);
3728         i915_redisable_vga(to_i915(dev));
3729
3730         if (!state)
3731                 return 0;
3732
3733         /*
3734          * We've duplicated the state, pointers to the old state are invalid.
3735          *
3736          * Don't attempt to use the old state until we commit the duplicated state.
3737          */
3738         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3739                 /*
3740                  * Force recalculation even if we restore
3741                  * current state. With fast modeset this may not result
3742                  * in a modeset when the state is compatible.
3743                  */
3744                 crtc_state->mode_changed = true;
3745         }
3746
3747         /* ignore any reset values/BIOS leftovers in the WM registers */
3748         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3749                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3750
3751         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3752
3753         WARN_ON(ret == -EDEADLK);
3754         return ret;
3755 }
3756
3757 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3758 {
3759         return intel_has_gpu_reset(dev_priv) &&
3760                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3761 }
3762
3763 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3764 {
3765         struct drm_device *dev = &dev_priv->drm;
3766         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3767         struct drm_atomic_state *state;
3768         int ret;
3769
3770         /* reset doesn't touch the display */
3771         if (!i915_modparams.force_reset_modeset_test &&
3772             !gpu_reset_clobbers_display(dev_priv))
3773                 return;
3774
3775         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3776         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3777         wake_up_all(&dev_priv->gpu_error.wait_queue);
3778
3779         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3780                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3781                 i915_gem_set_wedged(dev_priv);
3782         }
3783
3784         /*
3785          * Need mode_config.mutex so that we don't
3786          * trample ongoing ->detect() and whatnot.
3787          */
3788         mutex_lock(&dev->mode_config.mutex);
3789         drm_modeset_acquire_init(ctx, 0);
3790         while (1) {
3791                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3792                 if (ret != -EDEADLK)
3793                         break;
3794
3795                 drm_modeset_backoff(ctx);
3796         }
3797         /*
3798          * Disabling the crtcs gracefully seems nicer. Also the
3799          * g33 docs say we should at least disable all the planes.
3800          */
3801         state = drm_atomic_helper_duplicate_state(dev, ctx);
3802         if (IS_ERR(state)) {
3803                 ret = PTR_ERR(state);
3804                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3805                 return;
3806         }
3807
3808         ret = drm_atomic_helper_disable_all(dev, ctx);
3809         if (ret) {
3810                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3811                 drm_atomic_state_put(state);
3812                 return;
3813         }
3814
3815         dev_priv->modeset_restore_state = state;
3816         state->acquire_ctx = ctx;
3817 }
3818
3819 void intel_finish_reset(struct drm_i915_private *dev_priv)
3820 {
3821         struct drm_device *dev = &dev_priv->drm;
3822         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3823         struct drm_atomic_state *state;
3824         int ret;
3825
3826         /* reset doesn't touch the display */
3827         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
3828                 return;
3829
3830         state = fetch_and_zero(&dev_priv->modeset_restore_state);
3831         if (!state)
3832                 goto unlock;
3833
3834         /* reset doesn't touch the display */
3835         if (!gpu_reset_clobbers_display(dev_priv)) {
3836                 /* for testing only restore the display */
3837                 ret = __intel_display_resume(dev, state, ctx);
3838                 if (ret)
3839                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3840         } else {
3841                 /*
3842                  * The display has been reset as well,
3843                  * so need a full re-initialization.
3844                  */
3845                 intel_runtime_pm_disable_interrupts(dev_priv);
3846                 intel_runtime_pm_enable_interrupts(dev_priv);
3847
3848                 intel_pps_unlock_regs_wa(dev_priv);
3849                 intel_modeset_init_hw(dev);
3850                 intel_init_clock_gating(dev_priv);
3851
3852                 spin_lock_irq(&dev_priv->irq_lock);
3853                 if (dev_priv->display.hpd_irq_setup)
3854                         dev_priv->display.hpd_irq_setup(dev_priv);
3855                 spin_unlock_irq(&dev_priv->irq_lock);
3856
3857                 ret = __intel_display_resume(dev, state, ctx);
3858                 if (ret)
3859                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3860
3861                 intel_hpd_init(dev_priv);
3862         }
3863
3864         drm_atomic_state_put(state);
3865 unlock:
3866         drm_modeset_drop_locks(ctx);
3867         drm_modeset_acquire_fini(ctx);
3868         mutex_unlock(&dev->mode_config.mutex);
3869
3870         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3871 }
3872
3873 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3874                                      const struct intel_crtc_state *new_crtc_state)
3875 {
3876         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3877         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3878
3879         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3880         crtc->base.mode = new_crtc_state->base.mode;
3881
3882         /*
3883          * Update pipe size and adjust fitter if needed: the reason for this is
3884          * that in compute_mode_changes we check the native mode (not the pfit
3885          * mode) to see if we can flip rather than do a full mode set. In the
3886          * fastboot case, we'll flip, but if we don't update the pipesrc and
3887          * pfit state, we'll end up with a big fb scanned out into the wrong
3888          * sized surface.
3889          */
3890
3891         I915_WRITE(PIPESRC(crtc->pipe),
3892                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3893                    (new_crtc_state->pipe_src_h - 1));
3894
3895         /* on skylake this is done by detaching scalers */
3896         if (INTEL_GEN(dev_priv) >= 9) {
3897                 skl_detach_scalers(crtc);
3898
3899                 if (new_crtc_state->pch_pfit.enabled)
3900                         skylake_pfit_enable(crtc);
3901         } else if (HAS_PCH_SPLIT(dev_priv)) {
3902                 if (new_crtc_state->pch_pfit.enabled)
3903                         ironlake_pfit_enable(crtc);
3904                 else if (old_crtc_state->pch_pfit.enabled)
3905                         ironlake_pfit_disable(crtc, true);
3906         }
3907 }
3908
3909 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3910 {
3911         struct drm_device *dev = crtc->base.dev;
3912         struct drm_i915_private *dev_priv = to_i915(dev);
3913         int pipe = crtc->pipe;
3914         i915_reg_t reg;
3915         u32 temp;
3916
3917         /* enable normal train */
3918         reg = FDI_TX_CTL(pipe);
3919         temp = I915_READ(reg);
3920         if (IS_IVYBRIDGE(dev_priv)) {
3921                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3922                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3923         } else {
3924                 temp &= ~FDI_LINK_TRAIN_NONE;
3925                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3926         }
3927         I915_WRITE(reg, temp);
3928
3929         reg = FDI_RX_CTL(pipe);
3930         temp = I915_READ(reg);
3931         if (HAS_PCH_CPT(dev_priv)) {
3932                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3933                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3934         } else {
3935                 temp &= ~FDI_LINK_TRAIN_NONE;
3936                 temp |= FDI_LINK_TRAIN_NONE;
3937         }
3938         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3939
3940         /* wait one idle pattern time */
3941         POSTING_READ(reg);
3942         udelay(1000);
3943
3944         /* IVB wants error correction enabled */
3945         if (IS_IVYBRIDGE(dev_priv))
3946                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3947                            FDI_FE_ERRC_ENABLE);
3948 }
3949
3950 /* The FDI link training functions for ILK/Ibexpeak. */
3951 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3952                                     const struct intel_crtc_state *crtc_state)
3953 {
3954         struct drm_device *dev = crtc->base.dev;
3955         struct drm_i915_private *dev_priv = to_i915(dev);
3956         int pipe = crtc->pipe;
3957         i915_reg_t reg;
3958         u32 temp, tries;
3959
3960         /* FDI needs bits from pipe first */
3961         assert_pipe_enabled(dev_priv, pipe);
3962
3963         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3964            for train result */
3965         reg = FDI_RX_IMR(pipe);
3966         temp = I915_READ(reg);
3967         temp &= ~FDI_RX_SYMBOL_LOCK;
3968         temp &= ~FDI_RX_BIT_LOCK;
3969         I915_WRITE(reg, temp);
3970         I915_READ(reg);
3971         udelay(150);
3972
3973         /* enable CPU FDI TX and PCH FDI RX */
3974         reg = FDI_TX_CTL(pipe);
3975         temp = I915_READ(reg);
3976         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3977         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3978         temp &= ~FDI_LINK_TRAIN_NONE;
3979         temp |= FDI_LINK_TRAIN_PATTERN_1;
3980         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3981
3982         reg = FDI_RX_CTL(pipe);
3983         temp = I915_READ(reg);
3984         temp &= ~FDI_LINK_TRAIN_NONE;
3985         temp |= FDI_LINK_TRAIN_PATTERN_1;
3986         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3987
3988         POSTING_READ(reg);
3989         udelay(150);
3990
3991         /* Ironlake workaround, enable clock pointer after FDI enable*/
3992         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3993         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3994                    FDI_RX_PHASE_SYNC_POINTER_EN);
3995
3996         reg = FDI_RX_IIR(pipe);
3997         for (tries = 0; tries < 5; tries++) {
3998                 temp = I915_READ(reg);
3999                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4000
4001                 if ((temp & FDI_RX_BIT_LOCK)) {
4002                         DRM_DEBUG_KMS("FDI train 1 done.\n");
4003                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4004                         break;
4005                 }
4006         }
4007         if (tries == 5)
4008                 DRM_ERROR("FDI train 1 fail!\n");
4009
4010         /* Train 2 */
4011         reg = FDI_TX_CTL(pipe);
4012         temp = I915_READ(reg);
4013         temp &= ~FDI_LINK_TRAIN_NONE;
4014         temp |= FDI_LINK_TRAIN_PATTERN_2;
4015         I915_WRITE(reg, temp);
4016
4017         reg = FDI_RX_CTL(pipe);
4018         temp = I915_READ(reg);
4019         temp &= ~FDI_LINK_TRAIN_NONE;
4020         temp |= FDI_LINK_TRAIN_PATTERN_2;
4021         I915_WRITE(reg, temp);
4022
4023         POSTING_READ(reg);
4024         udelay(150);
4025
4026         reg = FDI_RX_IIR(pipe);
4027         for (tries = 0; tries < 5; tries++) {
4028                 temp = I915_READ(reg);
4029                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4030
4031                 if (temp & FDI_RX_SYMBOL_LOCK) {
4032                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4033                         DRM_DEBUG_KMS("FDI train 2 done.\n");
4034                         break;
4035                 }
4036         }
4037         if (tries == 5)
4038                 DRM_ERROR("FDI train 2 fail!\n");
4039
4040         DRM_DEBUG_KMS("FDI train done\n");
4041
4042 }
4043
4044 static const int snb_b_fdi_train_param[] = {
4045         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4046         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4047         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4048         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4049 };
4050
4051 /* The FDI link training functions for SNB/Cougarpoint. */
4052 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4053                                 const struct intel_crtc_state *crtc_state)
4054 {
4055         struct drm_device *dev = crtc->base.dev;
4056         struct drm_i915_private *dev_priv = to_i915(dev);
4057         int pipe = crtc->pipe;
4058         i915_reg_t reg;
4059         u32 temp, i, retry;
4060
4061         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4062            for train result */
4063         reg = FDI_RX_IMR(pipe);
4064         temp = I915_READ(reg);
4065         temp &= ~FDI_RX_SYMBOL_LOCK;
4066         temp &= ~FDI_RX_BIT_LOCK;
4067         I915_WRITE(reg, temp);
4068
4069         POSTING_READ(reg);
4070         udelay(150);
4071
4072         /* enable CPU FDI TX and PCH FDI RX */
4073         reg = FDI_TX_CTL(pipe);
4074         temp = I915_READ(reg);
4075         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4076         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4077         temp &= ~FDI_LINK_TRAIN_NONE;
4078         temp |= FDI_LINK_TRAIN_PATTERN_1;
4079         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4080         /* SNB-B */
4081         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4082         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4083
4084         I915_WRITE(FDI_RX_MISC(pipe),
4085                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4086
4087         reg = FDI_RX_CTL(pipe);
4088         temp = I915_READ(reg);
4089         if (HAS_PCH_CPT(dev_priv)) {
4090                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4091                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4092         } else {
4093                 temp &= ~FDI_LINK_TRAIN_NONE;
4094                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4095         }
4096         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4097
4098         POSTING_READ(reg);
4099         udelay(150);
4100
4101         for (i = 0; i < 4; i++) {
4102                 reg = FDI_TX_CTL(pipe);
4103                 temp = I915_READ(reg);
4104                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4105                 temp |= snb_b_fdi_train_param[i];
4106                 I915_WRITE(reg, temp);
4107
4108                 POSTING_READ(reg);
4109                 udelay(500);
4110
4111                 for (retry = 0; retry < 5; retry++) {
4112                         reg = FDI_RX_IIR(pipe);
4113                         temp = I915_READ(reg);
4114                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4115                         if (temp & FDI_RX_BIT_LOCK) {
4116                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4117                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4118                                 break;
4119                         }
4120                         udelay(50);
4121                 }
4122                 if (retry < 5)
4123                         break;
4124         }
4125         if (i == 4)
4126                 DRM_ERROR("FDI train 1 fail!\n");
4127
4128         /* Train 2 */
4129         reg = FDI_TX_CTL(pipe);
4130         temp = I915_READ(reg);
4131         temp &= ~FDI_LINK_TRAIN_NONE;
4132         temp |= FDI_LINK_TRAIN_PATTERN_2;
4133         if (IS_GEN6(dev_priv)) {
4134                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4135                 /* SNB-B */
4136                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4137         }
4138         I915_WRITE(reg, temp);
4139
4140         reg = FDI_RX_CTL(pipe);
4141         temp = I915_READ(reg);
4142         if (HAS_PCH_CPT(dev_priv)) {
4143                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4144                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4145         } else {
4146                 temp &= ~FDI_LINK_TRAIN_NONE;
4147                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4148         }
4149         I915_WRITE(reg, temp);
4150
4151         POSTING_READ(reg);
4152         udelay(150);
4153
4154         for (i = 0; i < 4; i++) {
4155                 reg = FDI_TX_CTL(pipe);
4156                 temp = I915_READ(reg);
4157                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4158                 temp |= snb_b_fdi_train_param[i];
4159                 I915_WRITE(reg, temp);
4160
4161                 POSTING_READ(reg);
4162                 udelay(500);
4163
4164                 for (retry = 0; retry < 5; retry++) {
4165                         reg = FDI_RX_IIR(pipe);
4166                         temp = I915_READ(reg);
4167                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4168                         if (temp & FDI_RX_SYMBOL_LOCK) {
4169                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4170                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4171                                 break;
4172                         }
4173                         udelay(50);
4174                 }
4175                 if (retry < 5)
4176                         break;
4177         }
4178         if (i == 4)
4179                 DRM_ERROR("FDI train 2 fail!\n");
4180
4181         DRM_DEBUG_KMS("FDI train done.\n");
4182 }
4183
4184 /* Manual link training for Ivy Bridge A0 parts */
4185 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4186                                       const struct intel_crtc_state *crtc_state)
4187 {
4188         struct drm_device *dev = crtc->base.dev;
4189         struct drm_i915_private *dev_priv = to_i915(dev);
4190         int pipe = crtc->pipe;
4191         i915_reg_t reg;
4192         u32 temp, i, j;
4193
4194         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4195            for train result */
4196         reg = FDI_RX_IMR(pipe);
4197         temp = I915_READ(reg);
4198         temp &= ~FDI_RX_SYMBOL_LOCK;
4199         temp &= ~FDI_RX_BIT_LOCK;
4200         I915_WRITE(reg, temp);
4201
4202         POSTING_READ(reg);
4203         udelay(150);
4204
4205         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4206                       I915_READ(FDI_RX_IIR(pipe)));
4207
4208         /* Try each vswing and preemphasis setting twice before moving on */
4209         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4210                 /* disable first in case we need to retry */
4211                 reg = FDI_TX_CTL(pipe);
4212                 temp = I915_READ(reg);
4213                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4214                 temp &= ~FDI_TX_ENABLE;
4215                 I915_WRITE(reg, temp);
4216
4217                 reg = FDI_RX_CTL(pipe);
4218                 temp = I915_READ(reg);
4219                 temp &= ~FDI_LINK_TRAIN_AUTO;
4220                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4221                 temp &= ~FDI_RX_ENABLE;
4222                 I915_WRITE(reg, temp);
4223
4224                 /* enable CPU FDI TX and PCH FDI RX */
4225                 reg = FDI_TX_CTL(pipe);
4226                 temp = I915_READ(reg);
4227                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4228                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4229                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4230                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4231                 temp |= snb_b_fdi_train_param[j/2];
4232                 temp |= FDI_COMPOSITE_SYNC;
4233                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4234
4235                 I915_WRITE(FDI_RX_MISC(pipe),
4236                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4237
4238                 reg = FDI_RX_CTL(pipe);
4239                 temp = I915_READ(reg);
4240                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4241                 temp |= FDI_COMPOSITE_SYNC;
4242                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4243
4244                 POSTING_READ(reg);
4245                 udelay(1); /* should be 0.5us */
4246
4247                 for (i = 0; i < 4; i++) {
4248                         reg = FDI_RX_IIR(pipe);
4249                         temp = I915_READ(reg);
4250                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4251
4252                         if (temp & FDI_RX_BIT_LOCK ||
4253                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4254                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4255                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4256                                               i);
4257                                 break;
4258                         }
4259                         udelay(1); /* should be 0.5us */
4260                 }
4261                 if (i == 4) {
4262                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4263                         continue;
4264                 }
4265
4266                 /* Train 2 */
4267                 reg = FDI_TX_CTL(pipe);
4268                 temp = I915_READ(reg);
4269                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4270                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4271                 I915_WRITE(reg, temp);
4272
4273                 reg = FDI_RX_CTL(pipe);
4274                 temp = I915_READ(reg);
4275                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4276                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4277                 I915_WRITE(reg, temp);
4278
4279                 POSTING_READ(reg);
4280                 udelay(2); /* should be 1.5us */
4281
4282                 for (i = 0; i < 4; i++) {
4283                         reg = FDI_RX_IIR(pipe);
4284                         temp = I915_READ(reg);
4285                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4286
4287                         if (temp & FDI_RX_SYMBOL_LOCK ||
4288                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4289                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4290                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4291                                               i);
4292                                 goto train_done;
4293                         }
4294                         udelay(2); /* should be 1.5us */
4295                 }
4296                 if (i == 4)
4297                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4298         }
4299
4300 train_done:
4301         DRM_DEBUG_KMS("FDI train done.\n");
4302 }
4303
4304 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4305 {
4306         struct drm_device *dev = intel_crtc->base.dev;
4307         struct drm_i915_private *dev_priv = to_i915(dev);
4308         int pipe = intel_crtc->pipe;
4309         i915_reg_t reg;
4310         u32 temp;
4311
4312         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4313         reg = FDI_RX_CTL(pipe);
4314         temp = I915_READ(reg);
4315         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4316         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4317         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4318         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4319
4320         POSTING_READ(reg);
4321         udelay(200);
4322
4323         /* Switch from Rawclk to PCDclk */
4324         temp = I915_READ(reg);
4325         I915_WRITE(reg, temp | FDI_PCDCLK);
4326
4327         POSTING_READ(reg);
4328         udelay(200);
4329
4330         /* Enable CPU FDI TX PLL, always on for Ironlake */
4331         reg = FDI_TX_CTL(pipe);
4332         temp = I915_READ(reg);
4333         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4334                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4335
4336                 POSTING_READ(reg);
4337                 udelay(100);
4338         }
4339 }
4340
4341 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4342 {
4343         struct drm_device *dev = intel_crtc->base.dev;
4344         struct drm_i915_private *dev_priv = to_i915(dev);
4345         int pipe = intel_crtc->pipe;
4346         i915_reg_t reg;
4347         u32 temp;
4348
4349         /* Switch from PCDclk to Rawclk */
4350         reg = FDI_RX_CTL(pipe);
4351         temp = I915_READ(reg);
4352         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4353
4354         /* Disable CPU FDI TX PLL */
4355         reg = FDI_TX_CTL(pipe);
4356         temp = I915_READ(reg);
4357         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4358
4359         POSTING_READ(reg);
4360         udelay(100);
4361
4362         reg = FDI_RX_CTL(pipe);
4363         temp = I915_READ(reg);
4364         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4365
4366         /* Wait for the clocks to turn off. */
4367         POSTING_READ(reg);
4368         udelay(100);
4369 }
4370
4371 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4372 {
4373         struct drm_device *dev = crtc->dev;
4374         struct drm_i915_private *dev_priv = to_i915(dev);
4375         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4376         int pipe = intel_crtc->pipe;
4377         i915_reg_t reg;
4378         u32 temp;
4379
4380         /* disable CPU FDI tx and PCH FDI rx */
4381         reg = FDI_TX_CTL(pipe);
4382         temp = I915_READ(reg);
4383         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4384         POSTING_READ(reg);
4385
4386         reg = FDI_RX_CTL(pipe);
4387         temp = I915_READ(reg);
4388         temp &= ~(0x7 << 16);
4389         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4390         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4391
4392         POSTING_READ(reg);
4393         udelay(100);
4394
4395         /* Ironlake workaround, disable clock pointer after downing FDI */
4396         if (HAS_PCH_IBX(dev_priv))
4397                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4398
4399         /* still set train pattern 1 */
4400         reg = FDI_TX_CTL(pipe);
4401         temp = I915_READ(reg);
4402         temp &= ~FDI_LINK_TRAIN_NONE;
4403         temp |= FDI_LINK_TRAIN_PATTERN_1;
4404         I915_WRITE(reg, temp);
4405
4406         reg = FDI_RX_CTL(pipe);
4407         temp = I915_READ(reg);
4408         if (HAS_PCH_CPT(dev_priv)) {
4409                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4410                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4411         } else {
4412                 temp &= ~FDI_LINK_TRAIN_NONE;
4413                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4414         }
4415         /* BPC in FDI rx is consistent with that in PIPECONF */
4416         temp &= ~(0x07 << 16);
4417         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4418         I915_WRITE(reg, temp);
4419
4420         POSTING_READ(reg);
4421         udelay(100);
4422 }
4423
4424 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4425 {
4426         struct drm_crtc *crtc;
4427         bool cleanup_done;
4428
4429         drm_for_each_crtc(crtc, &dev_priv->drm) {
4430                 struct drm_crtc_commit *commit;
4431                 spin_lock(&crtc->commit_lock);
4432                 commit = list_first_entry_or_null(&crtc->commit_list,
4433                                                   struct drm_crtc_commit, commit_entry);
4434                 cleanup_done = commit ?
4435                         try_wait_for_completion(&commit->cleanup_done) : true;
4436                 spin_unlock(&crtc->commit_lock);
4437
4438                 if (cleanup_done)
4439                         continue;
4440
4441                 drm_crtc_wait_one_vblank(crtc);
4442
4443                 return true;
4444         }
4445
4446         return false;
4447 }
4448
4449 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4450 {
4451         u32 temp;
4452
4453         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4454
4455         mutex_lock(&dev_priv->sb_lock);
4456
4457         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4458         temp |= SBI_SSCCTL_DISABLE;
4459         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4460
4461         mutex_unlock(&dev_priv->sb_lock);
4462 }
4463
4464 /* Program iCLKIP clock to the desired frequency */
4465 static void lpt_program_iclkip(struct intel_crtc *crtc)
4466 {
4467         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4468         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4469         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4470         u32 temp;
4471
4472         lpt_disable_iclkip(dev_priv);
4473
4474         /* The iCLK virtual clock root frequency is in MHz,
4475          * but the adjusted_mode->crtc_clock in in KHz. To get the
4476          * divisors, it is necessary to divide one by another, so we
4477          * convert the virtual clock precision to KHz here for higher
4478          * precision.
4479          */
4480         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4481                 u32 iclk_virtual_root_freq = 172800 * 1000;
4482                 u32 iclk_pi_range = 64;
4483                 u32 desired_divisor;
4484
4485                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4486                                                     clock << auxdiv);
4487                 divsel = (desired_divisor / iclk_pi_range) - 2;
4488                 phaseinc = desired_divisor % iclk_pi_range;
4489
4490                 /*
4491                  * Near 20MHz is a corner case which is
4492                  * out of range for the 7-bit divisor
4493                  */
4494                 if (divsel <= 0x7f)
4495                         break;
4496         }
4497
4498         /* This should not happen with any sane values */
4499         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4500                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4501         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4502                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4503
4504         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4505                         clock,
4506                         auxdiv,
4507                         divsel,
4508                         phasedir,
4509                         phaseinc);
4510
4511         mutex_lock(&dev_priv->sb_lock);
4512
4513         /* Program SSCDIVINTPHASE6 */
4514         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4515         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4516         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4517         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4518         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4519         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4520         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4521         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4522
4523         /* Program SSCAUXDIV */
4524         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4525         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4526         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4527         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4528
4529         /* Enable modulator and associated divider */
4530         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4531         temp &= ~SBI_SSCCTL_DISABLE;
4532         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4533
4534         mutex_unlock(&dev_priv->sb_lock);
4535
4536         /* Wait for initialization time */
4537         udelay(24);
4538
4539         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4540 }
4541
4542 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4543 {
4544         u32 divsel, phaseinc, auxdiv;
4545         u32 iclk_virtual_root_freq = 172800 * 1000;
4546         u32 iclk_pi_range = 64;
4547         u32 desired_divisor;
4548         u32 temp;
4549
4550         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4551                 return 0;
4552
4553         mutex_lock(&dev_priv->sb_lock);
4554
4555         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4556         if (temp & SBI_SSCCTL_DISABLE) {
4557                 mutex_unlock(&dev_priv->sb_lock);
4558                 return 0;
4559         }
4560
4561         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4562         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4563                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4564         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4565                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4566
4567         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4568         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4569                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4570
4571         mutex_unlock(&dev_priv->sb_lock);
4572
4573         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4574
4575         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4576                                  desired_divisor << auxdiv);
4577 }
4578
4579 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4580                                                 enum pipe pch_transcoder)
4581 {
4582         struct drm_device *dev = crtc->base.dev;
4583         struct drm_i915_private *dev_priv = to_i915(dev);
4584         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4585
4586         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4587                    I915_READ(HTOTAL(cpu_transcoder)));
4588         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4589                    I915_READ(HBLANK(cpu_transcoder)));
4590         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4591                    I915_READ(HSYNC(cpu_transcoder)));
4592
4593         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4594                    I915_READ(VTOTAL(cpu_transcoder)));
4595         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4596                    I915_READ(VBLANK(cpu_transcoder)));
4597         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4598                    I915_READ(VSYNC(cpu_transcoder)));
4599         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4600                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4601 }
4602
4603 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4604 {
4605         struct drm_i915_private *dev_priv = to_i915(dev);
4606         uint32_t temp;
4607
4608         temp = I915_READ(SOUTH_CHICKEN1);
4609         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4610                 return;
4611
4612         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4613         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4614
4615         temp &= ~FDI_BC_BIFURCATION_SELECT;
4616         if (enable)
4617                 temp |= FDI_BC_BIFURCATION_SELECT;
4618
4619         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4620         I915_WRITE(SOUTH_CHICKEN1, temp);
4621         POSTING_READ(SOUTH_CHICKEN1);
4622 }
4623
4624 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4625 {
4626         struct drm_device *dev = intel_crtc->base.dev;
4627
4628         switch (intel_crtc->pipe) {
4629         case PIPE_A:
4630                 break;
4631         case PIPE_B:
4632                 if (intel_crtc->config->fdi_lanes > 2)
4633                         cpt_set_fdi_bc_bifurcation(dev, false);
4634                 else
4635                         cpt_set_fdi_bc_bifurcation(dev, true);
4636
4637                 break;
4638         case PIPE_C:
4639                 cpt_set_fdi_bc_bifurcation(dev, true);
4640
4641                 break;
4642         default:
4643                 BUG();
4644         }
4645 }
4646
4647 /*
4648  * Finds the encoder associated with the given CRTC. This can only be
4649  * used when we know that the CRTC isn't feeding multiple encoders!
4650  */
4651 static struct intel_encoder *
4652 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
4653                            const struct intel_crtc_state *crtc_state)
4654 {
4655         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4656         const struct drm_connector_state *connector_state;
4657         const struct drm_connector *connector;
4658         struct intel_encoder *encoder = NULL;
4659         int num_encoders = 0;
4660         int i;
4661
4662         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
4663                 if (connector_state->crtc != &crtc->base)
4664                         continue;
4665
4666                 encoder = to_intel_encoder(connector_state->best_encoder);
4667                 num_encoders++;
4668         }
4669
4670         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
4671              num_encoders, pipe_name(crtc->pipe));
4672
4673         return encoder;
4674 }
4675
4676 /*
4677  * Enable PCH resources required for PCH ports:
4678  *   - PCH PLLs
4679  *   - FDI training & RX/TX
4680  *   - update transcoder timings
4681  *   - DP transcoding bits
4682  *   - transcoder
4683  */
4684 static void ironlake_pch_enable(const struct intel_atomic_state *state,
4685                                 const struct intel_crtc_state *crtc_state)
4686 {
4687         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4688         struct drm_device *dev = crtc->base.dev;
4689         struct drm_i915_private *dev_priv = to_i915(dev);
4690         int pipe = crtc->pipe;
4691         u32 temp;
4692
4693         assert_pch_transcoder_disabled(dev_priv, pipe);
4694
4695         if (IS_IVYBRIDGE(dev_priv))
4696                 ivybridge_update_fdi_bc_bifurcation(crtc);
4697
4698         /* Write the TU size bits before fdi link training, so that error
4699          * detection works. */
4700         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4701                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4702
4703         /* For PCH output, training FDI link */
4704         dev_priv->display.fdi_link_train(crtc, crtc_state);
4705
4706         /* We need to program the right clock selection before writing the pixel
4707          * mutliplier into the DPLL. */
4708         if (HAS_PCH_CPT(dev_priv)) {
4709                 u32 sel;
4710
4711                 temp = I915_READ(PCH_DPLL_SEL);
4712                 temp |= TRANS_DPLL_ENABLE(pipe);
4713                 sel = TRANS_DPLLB_SEL(pipe);
4714                 if (crtc_state->shared_dpll ==
4715                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4716                         temp |= sel;
4717                 else
4718                         temp &= ~sel;
4719                 I915_WRITE(PCH_DPLL_SEL, temp);
4720         }
4721
4722         /* XXX: pch pll's can be enabled any time before we enable the PCH
4723          * transcoder, and we actually should do this to not upset any PCH
4724          * transcoder that already use the clock when we share it.
4725          *
4726          * Note that enable_shared_dpll tries to do the right thing, but
4727          * get_shared_dpll unconditionally resets the pll - we need that to have
4728          * the right LVDS enable sequence. */
4729         intel_enable_shared_dpll(crtc);
4730
4731         /* set transcoder timing, panel must allow it */
4732         assert_panel_unlocked(dev_priv, pipe);
4733         ironlake_pch_transcoder_set_timings(crtc, pipe);
4734
4735         intel_fdi_normal_train(crtc);
4736
4737         /* For PCH DP, enable TRANS_DP_CTL */
4738         if (HAS_PCH_CPT(dev_priv) &&
4739             intel_crtc_has_dp_encoder(crtc_state)) {
4740                 const struct drm_display_mode *adjusted_mode =
4741                         &crtc_state->base.adjusted_mode;
4742                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4743                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4744                 enum port port;
4745
4746                 temp = I915_READ(reg);
4747                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4748                           TRANS_DP_SYNC_MASK |
4749                           TRANS_DP_BPC_MASK);
4750                 temp |= TRANS_DP_OUTPUT_ENABLE;
4751                 temp |= bpc << 9; /* same format but at 11:9 */
4752
4753                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4754                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4755                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4756                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4757
4758                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
4759                 WARN_ON(port < PORT_B || port > PORT_D);
4760                 temp |= TRANS_DP_PORT_SEL(port);
4761
4762                 I915_WRITE(reg, temp);
4763         }
4764
4765         ironlake_enable_pch_transcoder(dev_priv, pipe);
4766 }
4767
4768 static void lpt_pch_enable(const struct intel_atomic_state *state,
4769                            const struct intel_crtc_state *crtc_state)
4770 {
4771         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4772         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4773         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4774
4775         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4776
4777         lpt_program_iclkip(crtc);
4778
4779         /* Set transcoder timing. */
4780         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4781
4782         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4783 }
4784
4785 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4786 {
4787         struct drm_i915_private *dev_priv = to_i915(dev);
4788         i915_reg_t dslreg = PIPEDSL(pipe);
4789         u32 temp;
4790
4791         temp = I915_READ(dslreg);
4792         udelay(500);
4793         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4794                 if (wait_for(I915_READ(dslreg) != temp, 5))
4795                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4796         }
4797 }
4798
4799 /*
4800  * The hardware phase 0.0 refers to the center of the pixel.
4801  * We want to start from the top/left edge which is phase
4802  * -0.5. That matches how the hardware calculates the scaling
4803  * factors (from top-left of the first pixel to bottom-right
4804  * of the last pixel, as opposed to the pixel centers).
4805  *
4806  * For 4:2:0 subsampled chroma planes we obviously have to
4807  * adjust that so that the chroma sample position lands in
4808  * the right spot.
4809  *
4810  * Note that for packed YCbCr 4:2:2 formats there is no way to
4811  * control chroma siting. The hardware simply replicates the
4812  * chroma samples for both of the luma samples, and thus we don't
4813  * actually get the expected MPEG2 chroma siting convention :(
4814  * The same behaviour is observed on pre-SKL platforms as well.
4815  */
4816 u16 skl_scaler_calc_phase(int sub, bool chroma_cosited)
4817 {
4818         int phase = -0x8000;
4819         u16 trip = 0;
4820
4821         if (chroma_cosited)
4822                 phase += (sub - 1) * 0x8000 / sub;
4823
4824         if (phase < 0)
4825                 phase = 0x10000 + phase;
4826         else
4827                 trip = PS_PHASE_TRIP;
4828
4829         return ((phase >> 2) & PS_PHASE_MASK) | trip;
4830 }
4831
4832 static int
4833 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4834                   unsigned int scaler_user, int *scaler_id,
4835                   int src_w, int src_h, int dst_w, int dst_h,
4836                   bool plane_scaler_check,
4837                   uint32_t pixel_format)
4838 {
4839         struct intel_crtc_scaler_state *scaler_state =
4840                 &crtc_state->scaler_state;
4841         struct intel_crtc *intel_crtc =
4842                 to_intel_crtc(crtc_state->base.crtc);
4843         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4844         const struct drm_display_mode *adjusted_mode =
4845                 &crtc_state->base.adjusted_mode;
4846         int need_scaling;
4847
4848         /*
4849          * Src coordinates are already rotated by 270 degrees for
4850          * the 90/270 degree plane rotation cases (to match the
4851          * GTT mapping), hence no need to account for rotation here.
4852          */
4853         need_scaling = src_w != dst_w || src_h != dst_h;
4854
4855         if (plane_scaler_check)
4856                 if (pixel_format == DRM_FORMAT_NV12)
4857                         need_scaling = true;
4858
4859         if (crtc_state->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4860                 need_scaling = true;
4861
4862         /*
4863          * Scaling/fitting not supported in IF-ID mode in GEN9+
4864          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4865          * Once NV12 is enabled, handle it here while allocating scaler
4866          * for NV12.
4867          */
4868         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4869             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4870                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4871                 return -EINVAL;
4872         }
4873
4874         /*
4875          * if plane is being disabled or scaler is no more required or force detach
4876          *  - free scaler binded to this plane/crtc
4877          *  - in order to do this, update crtc->scaler_usage
4878          *
4879          * Here scaler state in crtc_state is set free so that
4880          * scaler can be assigned to other user. Actual register
4881          * update to free the scaler is done in plane/panel-fit programming.
4882          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4883          */
4884         if (force_detach || !need_scaling) {
4885                 if (*scaler_id >= 0) {
4886                         scaler_state->scaler_users &= ~(1 << scaler_user);
4887                         scaler_state->scalers[*scaler_id].in_use = 0;
4888
4889                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4890                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4891                                 intel_crtc->pipe, scaler_user, *scaler_id,
4892                                 scaler_state->scaler_users);
4893                         *scaler_id = -1;
4894                 }
4895                 return 0;
4896         }
4897
4898         if (plane_scaler_check && pixel_format == DRM_FORMAT_NV12 &&
4899             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
4900                 DRM_DEBUG_KMS("NV12: src dimensions not met\n");
4901                 return -EINVAL;
4902         }
4903
4904         /* range checks */
4905         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4906             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4907             (IS_GEN11(dev_priv) &&
4908              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
4909               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
4910             (!IS_GEN11(dev_priv) &&
4911              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4912               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
4913                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4914                         "size is out of scaler range\n",
4915                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4916                 return -EINVAL;
4917         }
4918
4919         /* mark this plane as a scaler user in crtc_state */
4920         scaler_state->scaler_users |= (1 << scaler_user);
4921         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4922                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4923                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4924                 scaler_state->scaler_users);
4925
4926         return 0;
4927 }
4928
4929 /**
4930  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4931  *
4932  * @state: crtc's scaler state
4933  *
4934  * Return
4935  *     0 - scaler_usage updated successfully
4936  *    error - requested scaling cannot be supported or other error condition
4937  */
4938 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4939 {
4940         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4941
4942         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4943                                  &state->scaler_state.scaler_id,
4944                                  state->pipe_src_w, state->pipe_src_h,
4945                                  adjusted_mode->crtc_hdisplay,
4946                                  adjusted_mode->crtc_vdisplay, false, 0);
4947 }
4948
4949 /**
4950  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4951  * @crtc_state: crtc's scaler state
4952  * @plane_state: atomic plane state to update
4953  *
4954  * Return
4955  *     0 - scaler_usage updated successfully
4956  *    error - requested scaling cannot be supported or other error condition
4957  */
4958 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4959                                    struct intel_plane_state *plane_state)
4960 {
4961
4962         struct intel_plane *intel_plane =
4963                 to_intel_plane(plane_state->base.plane);
4964         struct drm_framebuffer *fb = plane_state->base.fb;
4965         int ret;
4966
4967         bool force_detach = !fb || !plane_state->base.visible;
4968
4969         ret = skl_update_scaler(crtc_state, force_detach,
4970                                 drm_plane_index(&intel_plane->base),
4971                                 &plane_state->scaler_id,
4972                                 drm_rect_width(&plane_state->base.src) >> 16,
4973                                 drm_rect_height(&plane_state->base.src) >> 16,
4974                                 drm_rect_width(&plane_state->base.dst),
4975                                 drm_rect_height(&plane_state->base.dst),
4976                                 fb ? true : false, fb ? fb->format->format : 0);
4977
4978         if (ret || plane_state->scaler_id < 0)
4979                 return ret;
4980
4981         /* check colorkey */
4982         if (plane_state->ckey.flags) {
4983                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4984                               intel_plane->base.base.id,
4985                               intel_plane->base.name);
4986                 return -EINVAL;
4987         }
4988
4989         /* Check src format */
4990         switch (fb->format->format) {
4991         case DRM_FORMAT_RGB565:
4992         case DRM_FORMAT_XBGR8888:
4993         case DRM_FORMAT_XRGB8888:
4994         case DRM_FORMAT_ABGR8888:
4995         case DRM_FORMAT_ARGB8888:
4996         case DRM_FORMAT_XRGB2101010:
4997         case DRM_FORMAT_XBGR2101010:
4998         case DRM_FORMAT_YUYV:
4999         case DRM_FORMAT_YVYU:
5000         case DRM_FORMAT_UYVY:
5001         case DRM_FORMAT_VYUY:
5002         case DRM_FORMAT_NV12:
5003                 break;
5004         default:
5005                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
5006                               intel_plane->base.base.id, intel_plane->base.name,
5007                               fb->base.id, fb->format->format);
5008                 return -EINVAL;
5009         }
5010
5011         return 0;
5012 }
5013
5014 static void skylake_scaler_disable(struct intel_crtc *crtc)
5015 {
5016         int i;
5017
5018         for (i = 0; i < crtc->num_scalers; i++)
5019                 skl_detach_scaler(crtc, i);
5020 }
5021
5022 static void skylake_pfit_enable(struct intel_crtc *crtc)
5023 {
5024         struct drm_device *dev = crtc->base.dev;
5025         struct drm_i915_private *dev_priv = to_i915(dev);
5026         int pipe = crtc->pipe;
5027         struct intel_crtc_scaler_state *scaler_state =
5028                 &crtc->config->scaler_state;
5029
5030         if (crtc->config->pch_pfit.enabled) {
5031                 u16 uv_rgb_hphase, uv_rgb_vphase;
5032                 int id;
5033
5034                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
5035                         return;
5036
5037                 uv_rgb_hphase = skl_scaler_calc_phase(1, false);
5038                 uv_rgb_vphase = skl_scaler_calc_phase(1, false);
5039
5040                 id = scaler_state->scaler_id;
5041                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5042                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5043                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5044                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5045                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5046                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5047                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
5048                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
5049         }
5050 }
5051
5052 static void ironlake_pfit_enable(struct intel_crtc *crtc)
5053 {
5054         struct drm_device *dev = crtc->base.dev;
5055         struct drm_i915_private *dev_priv = to_i915(dev);
5056         int pipe = crtc->pipe;
5057
5058         if (crtc->config->pch_pfit.enabled) {
5059                 /* Force use of hard-coded filter coefficients
5060                  * as some pre-programmed values are broken,
5061                  * e.g. x201.
5062                  */
5063                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5064                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5065                                                  PF_PIPE_SEL_IVB(pipe));
5066                 else
5067                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5068                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
5069                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
5070         }
5071 }
5072
5073 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5074 {
5075         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5076         struct drm_device *dev = crtc->base.dev;
5077         struct drm_i915_private *dev_priv = to_i915(dev);
5078
5079         if (!crtc_state->ips_enabled)
5080                 return;
5081
5082         /*
5083          * We can only enable IPS after we enable a plane and wait for a vblank
5084          * This function is called from post_plane_update, which is run after
5085          * a vblank wait.
5086          */
5087         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5088
5089         if (IS_BROADWELL(dev_priv)) {
5090                 mutex_lock(&dev_priv->pcu_lock);
5091                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5092                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5093                 mutex_unlock(&dev_priv->pcu_lock);
5094                 /* Quoting Art Runyan: "its not safe to expect any particular
5095                  * value in IPS_CTL bit 31 after enabling IPS through the
5096                  * mailbox." Moreover, the mailbox may return a bogus state,
5097                  * so we need to just enable it and continue on.
5098                  */
5099         } else {
5100                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5101                 /* The bit only becomes 1 in the next vblank, so this wait here
5102                  * is essentially intel_wait_for_vblank. If we don't have this
5103                  * and don't wait for vblanks until the end of crtc_enable, then
5104                  * the HW state readout code will complain that the expected
5105                  * IPS_CTL value is not the one we read. */
5106                 if (intel_wait_for_register(dev_priv,
5107                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5108                                             50))
5109                         DRM_ERROR("Timed out waiting for IPS enable\n");
5110         }
5111 }
5112
5113 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5114 {
5115         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5116         struct drm_device *dev = crtc->base.dev;
5117         struct drm_i915_private *dev_priv = to_i915(dev);
5118
5119         if (!crtc_state->ips_enabled)
5120                 return;
5121
5122         if (IS_BROADWELL(dev_priv)) {
5123                 mutex_lock(&dev_priv->pcu_lock);
5124                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5125                 mutex_unlock(&dev_priv->pcu_lock);
5126                 /*
5127                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5128                  * 42ms timeout value leads to occasional timeouts so use 100ms
5129                  * instead.
5130                  */
5131                 if (intel_wait_for_register(dev_priv,
5132                                             IPS_CTL, IPS_ENABLE, 0,
5133                                             100))
5134                         DRM_ERROR("Timed out waiting for IPS disable\n");
5135         } else {
5136                 I915_WRITE(IPS_CTL, 0);
5137                 POSTING_READ(IPS_CTL);
5138         }
5139
5140         /* We need to wait for a vblank before we can disable the plane. */
5141         intel_wait_for_vblank(dev_priv, crtc->pipe);
5142 }
5143
5144 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5145 {
5146         if (intel_crtc->overlay) {
5147                 struct drm_device *dev = intel_crtc->base.dev;
5148
5149                 mutex_lock(&dev->struct_mutex);
5150                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5151                 mutex_unlock(&dev->struct_mutex);
5152         }
5153
5154         /* Let userspace switch the overlay on again. In most cases userspace
5155          * has to recompute where to put it anyway.
5156          */
5157 }
5158
5159 /**
5160  * intel_post_enable_primary - Perform operations after enabling primary plane
5161  * @crtc: the CRTC whose primary plane was just enabled
5162  * @new_crtc_state: the enabling state
5163  *
5164  * Performs potentially sleeping operations that must be done after the primary
5165  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5166  * called due to an explicit primary plane update, or due to an implicit
5167  * re-enable that is caused when a sprite plane is updated to no longer
5168  * completely hide the primary plane.
5169  */
5170 static void
5171 intel_post_enable_primary(struct drm_crtc *crtc,
5172                           const struct intel_crtc_state *new_crtc_state)
5173 {
5174         struct drm_device *dev = crtc->dev;
5175         struct drm_i915_private *dev_priv = to_i915(dev);
5176         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5177         int pipe = intel_crtc->pipe;
5178
5179         /*
5180          * Gen2 reports pipe underruns whenever all planes are disabled.
5181          * So don't enable underrun reporting before at least some planes
5182          * are enabled.
5183          * FIXME: Need to fix the logic to work when we turn off all planes
5184          * but leave the pipe running.
5185          */
5186         if (IS_GEN2(dev_priv))
5187                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5188
5189         /* Underruns don't always raise interrupts, so check manually. */
5190         intel_check_cpu_fifo_underruns(dev_priv);
5191         intel_check_pch_fifo_underruns(dev_priv);
5192 }
5193
5194 /* FIXME get rid of this and use pre_plane_update */
5195 static void
5196 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5197 {
5198         struct drm_device *dev = crtc->dev;
5199         struct drm_i915_private *dev_priv = to_i915(dev);
5200         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5201         int pipe = intel_crtc->pipe;
5202
5203         /*
5204          * Gen2 reports pipe underruns whenever all planes are disabled.
5205          * So disable underrun reporting before all the planes get disabled.
5206          */
5207         if (IS_GEN2(dev_priv))
5208                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5209
5210         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5211
5212         /*
5213          * Vblank time updates from the shadow to live plane control register
5214          * are blocked if the memory self-refresh mode is active at that
5215          * moment. So to make sure the plane gets truly disabled, disable
5216          * first the self-refresh mode. The self-refresh enable bit in turn
5217          * will be checked/applied by the HW only at the next frame start
5218          * event which is after the vblank start event, so we need to have a
5219          * wait-for-vblank between disabling the plane and the pipe.
5220          */
5221         if (HAS_GMCH_DISPLAY(dev_priv) &&
5222             intel_set_memory_cxsr(dev_priv, false))
5223                 intel_wait_for_vblank(dev_priv, pipe);
5224 }
5225
5226 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5227                                        const struct intel_crtc_state *new_crtc_state)
5228 {
5229         if (!old_crtc_state->ips_enabled)
5230                 return false;
5231
5232         if (needs_modeset(&new_crtc_state->base))
5233                 return true;
5234
5235         return !new_crtc_state->ips_enabled;
5236 }
5237
5238 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5239                                        const struct intel_crtc_state *new_crtc_state)
5240 {
5241         if (!new_crtc_state->ips_enabled)
5242                 return false;
5243
5244         if (needs_modeset(&new_crtc_state->base))
5245                 return true;
5246
5247         /*
5248          * We can't read out IPS on broadwell, assume the worst and
5249          * forcibly enable IPS on the first fastset.
5250          */
5251         if (new_crtc_state->update_pipe &&
5252             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5253                 return true;
5254
5255         return !old_crtc_state->ips_enabled;
5256 }
5257
5258 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5259                           const struct intel_crtc_state *crtc_state)
5260 {
5261         if (!crtc_state->nv12_planes)
5262                 return false;
5263
5264         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
5265                 return false;
5266
5267         if ((INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv)) ||
5268             IS_CANNONLAKE(dev_priv))
5269                 return true;
5270
5271         return false;
5272 }
5273
5274 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5275 {
5276         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5277         struct drm_device *dev = crtc->base.dev;
5278         struct drm_i915_private *dev_priv = to_i915(dev);
5279         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5280         struct intel_crtc_state *pipe_config =
5281                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5282                                                 crtc);
5283         struct drm_plane *primary = crtc->base.primary;
5284         struct drm_plane_state *old_primary_state =
5285                 drm_atomic_get_old_plane_state(old_state, primary);
5286
5287         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5288
5289         if (pipe_config->update_wm_post && pipe_config->base.active)
5290                 intel_update_watermarks(crtc);
5291
5292         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5293                 hsw_enable_ips(pipe_config);
5294
5295         if (old_primary_state) {
5296                 struct drm_plane_state *new_primary_state =
5297                         drm_atomic_get_new_plane_state(old_state, primary);
5298
5299                 intel_fbc_post_update(crtc);
5300
5301                 if (new_primary_state->visible &&
5302                     (needs_modeset(&pipe_config->base) ||
5303                      !old_primary_state->visible))
5304                         intel_post_enable_primary(&crtc->base, pipe_config);
5305         }
5306
5307         /* Display WA 827 */
5308         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5309             !needs_nv12_wa(dev_priv, pipe_config)) {
5310                 skl_wa_clkgate(dev_priv, crtc->pipe, false);
5311                 skl_wa_528(dev_priv, crtc->pipe, false);
5312         }
5313 }
5314
5315 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5316                                    struct intel_crtc_state *pipe_config)
5317 {
5318         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5319         struct drm_device *dev = crtc->base.dev;
5320         struct drm_i915_private *dev_priv = to_i915(dev);
5321         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5322         struct drm_plane *primary = crtc->base.primary;
5323         struct drm_plane_state *old_primary_state =
5324                 drm_atomic_get_old_plane_state(old_state, primary);
5325         bool modeset = needs_modeset(&pipe_config->base);
5326         struct intel_atomic_state *old_intel_state =
5327                 to_intel_atomic_state(old_state);
5328
5329         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5330                 hsw_disable_ips(old_crtc_state);
5331
5332         if (old_primary_state) {
5333                 struct intel_plane_state *new_primary_state =
5334                         intel_atomic_get_new_plane_state(old_intel_state,
5335                                                          to_intel_plane(primary));
5336
5337                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5338                 /*
5339                  * Gen2 reports pipe underruns whenever all planes are disabled.
5340                  * So disable underrun reporting before all the planes get disabled.
5341                  */
5342                 if (IS_GEN2(dev_priv) && old_primary_state->visible &&
5343                     (modeset || !new_primary_state->base.visible))
5344                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5345         }
5346
5347         /* Display WA 827 */
5348         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5349             needs_nv12_wa(dev_priv, pipe_config)) {
5350                 skl_wa_clkgate(dev_priv, crtc->pipe, true);
5351                 skl_wa_528(dev_priv, crtc->pipe, true);
5352         }
5353
5354         /*
5355          * Vblank time updates from the shadow to live plane control register
5356          * are blocked if the memory self-refresh mode is active at that
5357          * moment. So to make sure the plane gets truly disabled, disable
5358          * first the self-refresh mode. The self-refresh enable bit in turn
5359          * will be checked/applied by the HW only at the next frame start
5360          * event which is after the vblank start event, so we need to have a
5361          * wait-for-vblank between disabling the plane and the pipe.
5362          */
5363         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5364             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5365                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5366
5367         /*
5368          * IVB workaround: must disable low power watermarks for at least
5369          * one frame before enabling scaling.  LP watermarks can be re-enabled
5370          * when scaling is disabled.
5371          *
5372          * WaCxSRDisabledForSpriteScaling:ivb
5373          */
5374         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5375                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5376
5377         /*
5378          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5379          * watermark programming here.
5380          */
5381         if (needs_modeset(&pipe_config->base))
5382                 return;
5383
5384         /*
5385          * For platforms that support atomic watermarks, program the
5386          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5387          * will be the intermediate values that are safe for both pre- and
5388          * post- vblank; when vblank happens, the 'active' values will be set
5389          * to the final 'target' values and we'll do this again to get the
5390          * optimal watermarks.  For gen9+ platforms, the values we program here
5391          * will be the final target values which will get automatically latched
5392          * at vblank time; no further programming will be necessary.
5393          *
5394          * If a platform hasn't been transitioned to atomic watermarks yet,
5395          * we'll continue to update watermarks the old way, if flags tell
5396          * us to.
5397          */
5398         if (dev_priv->display.initial_watermarks != NULL)
5399                 dev_priv->display.initial_watermarks(old_intel_state,
5400                                                      pipe_config);
5401         else if (pipe_config->update_wm_pre)
5402                 intel_update_watermarks(crtc);
5403 }
5404
5405 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5406 {
5407         struct drm_device *dev = crtc->dev;
5408         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5409         struct drm_plane *p;
5410         int pipe = intel_crtc->pipe;
5411
5412         intel_crtc_dpms_overlay_disable(intel_crtc);
5413
5414         drm_for_each_plane_mask(p, dev, plane_mask)
5415                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5416
5417         /*
5418          * FIXME: Once we grow proper nuclear flip support out of this we need
5419          * to compute the mask of flip planes precisely. For the time being
5420          * consider this a flip to a NULL plane.
5421          */
5422         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5423 }
5424
5425 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5426                                           struct intel_crtc_state *crtc_state,
5427                                           struct drm_atomic_state *old_state)
5428 {
5429         struct drm_connector_state *conn_state;
5430         struct drm_connector *conn;
5431         int i;
5432
5433         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5434                 struct intel_encoder *encoder =
5435                         to_intel_encoder(conn_state->best_encoder);
5436
5437                 if (conn_state->crtc != crtc)
5438                         continue;
5439
5440                 if (encoder->pre_pll_enable)
5441                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5442         }
5443 }
5444
5445 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5446                                       struct intel_crtc_state *crtc_state,
5447                                       struct drm_atomic_state *old_state)
5448 {
5449         struct drm_connector_state *conn_state;
5450         struct drm_connector *conn;
5451         int i;
5452
5453         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5454                 struct intel_encoder *encoder =
5455                         to_intel_encoder(conn_state->best_encoder);
5456
5457                 if (conn_state->crtc != crtc)
5458                         continue;
5459
5460                 if (encoder->pre_enable)
5461                         encoder->pre_enable(encoder, crtc_state, conn_state);
5462         }
5463 }
5464
5465 static void intel_encoders_enable(struct drm_crtc *crtc,
5466                                   struct intel_crtc_state *crtc_state,
5467                                   struct drm_atomic_state *old_state)
5468 {
5469         struct drm_connector_state *conn_state;
5470         struct drm_connector *conn;
5471         int i;
5472
5473         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5474                 struct intel_encoder *encoder =
5475                         to_intel_encoder(conn_state->best_encoder);
5476
5477                 if (conn_state->crtc != crtc)
5478                         continue;
5479
5480                 encoder->enable(encoder, crtc_state, conn_state);
5481                 intel_opregion_notify_encoder(encoder, true);
5482         }
5483 }
5484
5485 static void intel_encoders_disable(struct drm_crtc *crtc,
5486                                    struct intel_crtc_state *old_crtc_state,
5487                                    struct drm_atomic_state *old_state)
5488 {
5489         struct drm_connector_state *old_conn_state;
5490         struct drm_connector *conn;
5491         int i;
5492
5493         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5494                 struct intel_encoder *encoder =
5495                         to_intel_encoder(old_conn_state->best_encoder);
5496
5497                 if (old_conn_state->crtc != crtc)
5498                         continue;
5499
5500                 intel_opregion_notify_encoder(encoder, false);
5501                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5502         }
5503 }
5504
5505 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5506                                         struct intel_crtc_state *old_crtc_state,
5507                                         struct drm_atomic_state *old_state)
5508 {
5509         struct drm_connector_state *old_conn_state;
5510         struct drm_connector *conn;
5511         int i;
5512
5513         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5514                 struct intel_encoder *encoder =
5515                         to_intel_encoder(old_conn_state->best_encoder);
5516
5517                 if (old_conn_state->crtc != crtc)
5518                         continue;
5519
5520                 if (encoder->post_disable)
5521                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5522         }
5523 }
5524
5525 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5526                                             struct intel_crtc_state *old_crtc_state,
5527                                             struct drm_atomic_state *old_state)
5528 {
5529         struct drm_connector_state *old_conn_state;
5530         struct drm_connector *conn;
5531         int i;
5532
5533         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5534                 struct intel_encoder *encoder =
5535                         to_intel_encoder(old_conn_state->best_encoder);
5536
5537                 if (old_conn_state->crtc != crtc)
5538                         continue;
5539
5540                 if (encoder->post_pll_disable)
5541                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5542         }
5543 }
5544
5545 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5546                                  struct drm_atomic_state *old_state)
5547 {
5548         struct drm_crtc *crtc = pipe_config->base.crtc;
5549         struct drm_device *dev = crtc->dev;
5550         struct drm_i915_private *dev_priv = to_i915(dev);
5551         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5552         int pipe = intel_crtc->pipe;
5553         struct intel_atomic_state *old_intel_state =
5554                 to_intel_atomic_state(old_state);
5555
5556         if (WARN_ON(intel_crtc->active))
5557                 return;
5558
5559         /*
5560          * Sometimes spurious CPU pipe underruns happen during FDI
5561          * training, at least with VGA+HDMI cloning. Suppress them.
5562          *
5563          * On ILK we get an occasional spurious CPU pipe underruns
5564          * between eDP port A enable and vdd enable. Also PCH port
5565          * enable seems to result in the occasional CPU pipe underrun.
5566          *
5567          * Spurious PCH underruns also occur during PCH enabling.
5568          */
5569         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5570         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5571
5572         if (intel_crtc->config->has_pch_encoder)
5573                 intel_prepare_shared_dpll(intel_crtc);
5574
5575         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5576                 intel_dp_set_m_n(intel_crtc, M1_N1);
5577
5578         intel_set_pipe_timings(intel_crtc);
5579         intel_set_pipe_src_size(intel_crtc);
5580
5581         if (intel_crtc->config->has_pch_encoder) {
5582                 intel_cpu_transcoder_set_m_n(intel_crtc,
5583                                      &intel_crtc->config->fdi_m_n, NULL);
5584         }
5585
5586         ironlake_set_pipeconf(crtc);
5587
5588         intel_crtc->active = true;
5589
5590         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5591
5592         if (intel_crtc->config->has_pch_encoder) {
5593                 /* Note: FDI PLL enabling _must_ be done before we enable the
5594                  * cpu pipes, hence this is separate from all the other fdi/pch
5595                  * enabling. */
5596                 ironlake_fdi_pll_enable(intel_crtc);
5597         } else {
5598                 assert_fdi_tx_disabled(dev_priv, pipe);
5599                 assert_fdi_rx_disabled(dev_priv, pipe);
5600         }
5601
5602         ironlake_pfit_enable(intel_crtc);
5603
5604         /*
5605          * On ILK+ LUT must be loaded before the pipe is running but with
5606          * clocks enabled
5607          */
5608         intel_color_load_luts(&pipe_config->base);
5609
5610         if (dev_priv->display.initial_watermarks != NULL)
5611                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5612         intel_enable_pipe(pipe_config);
5613
5614         if (intel_crtc->config->has_pch_encoder)
5615                 ironlake_pch_enable(old_intel_state, pipe_config);
5616
5617         assert_vblank_disabled(crtc);
5618         drm_crtc_vblank_on(crtc);
5619
5620         intel_encoders_enable(crtc, pipe_config, old_state);
5621
5622         if (HAS_PCH_CPT(dev_priv))
5623                 cpt_verify_modeset(dev, intel_crtc->pipe);
5624
5625         /*
5626          * Must wait for vblank to avoid spurious PCH FIFO underruns.
5627          * And a second vblank wait is needed at least on ILK with
5628          * some interlaced HDMI modes. Let's do the double wait always
5629          * in case there are more corner cases we don't know about.
5630          */
5631         if (intel_crtc->config->has_pch_encoder) {
5632                 intel_wait_for_vblank(dev_priv, pipe);
5633                 intel_wait_for_vblank(dev_priv, pipe);
5634         }
5635         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5636         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5637 }
5638
5639 /* IPS only exists on ULT machines and is tied to pipe A. */
5640 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5641 {
5642         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5643 }
5644
5645 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5646                                             enum pipe pipe, bool apply)
5647 {
5648         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5649         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5650
5651         if (apply)
5652                 val |= mask;
5653         else
5654                 val &= ~mask;
5655
5656         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5657 }
5658
5659 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5660 {
5661         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5662         enum pipe pipe = crtc->pipe;
5663         uint32_t val;
5664
5665         val = MBUS_DBOX_BW_CREDIT(1) | MBUS_DBOX_A_CREDIT(2);
5666
5667         /* Program B credit equally to all pipes */
5668         val |= MBUS_DBOX_B_CREDIT(24 / INTEL_INFO(dev_priv)->num_pipes);
5669
5670         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5671 }
5672
5673 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5674                                 struct drm_atomic_state *old_state)
5675 {
5676         struct drm_crtc *crtc = pipe_config->base.crtc;
5677         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5678         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5679         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5680         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5681         struct intel_atomic_state *old_intel_state =
5682                 to_intel_atomic_state(old_state);
5683         bool psl_clkgate_wa;
5684         u32 pipe_chicken;
5685
5686         if (WARN_ON(intel_crtc->active))
5687                 return;
5688
5689         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5690
5691         if (intel_crtc->config->shared_dpll)
5692                 intel_enable_shared_dpll(intel_crtc);
5693
5694         if (INTEL_GEN(dev_priv) >= 11)
5695                 icl_map_plls_to_ports(crtc, pipe_config, old_state);
5696
5697         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5698
5699         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5700                 intel_dp_set_m_n(intel_crtc, M1_N1);
5701
5702         if (!transcoder_is_dsi(cpu_transcoder))
5703                 intel_set_pipe_timings(intel_crtc);
5704
5705         intel_set_pipe_src_size(intel_crtc);
5706
5707         if (cpu_transcoder != TRANSCODER_EDP &&
5708             !transcoder_is_dsi(cpu_transcoder)) {
5709                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5710                            intel_crtc->config->pixel_multiplier - 1);
5711         }
5712
5713         if (intel_crtc->config->has_pch_encoder) {
5714                 intel_cpu_transcoder_set_m_n(intel_crtc,
5715                                      &intel_crtc->config->fdi_m_n, NULL);
5716         }
5717
5718         if (!transcoder_is_dsi(cpu_transcoder))
5719                 haswell_set_pipeconf(crtc);
5720
5721         haswell_set_pipemisc(crtc);
5722
5723         intel_color_set_csc(&pipe_config->base);
5724
5725         intel_crtc->active = true;
5726
5727         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5728         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5729                          intel_crtc->config->pch_pfit.enabled;
5730         if (psl_clkgate_wa)
5731                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5732
5733         if (INTEL_GEN(dev_priv) >= 9)
5734                 skylake_pfit_enable(intel_crtc);
5735         else
5736                 ironlake_pfit_enable(intel_crtc);
5737
5738         /*
5739          * On ILK+ LUT must be loaded before the pipe is running but with
5740          * clocks enabled
5741          */
5742         intel_color_load_luts(&pipe_config->base);
5743
5744         /*
5745          * Display WA #1153: enable hardware to bypass the alpha math
5746          * and rounding for per-pixel values 00 and 0xff
5747          */
5748         if (INTEL_GEN(dev_priv) >= 11) {
5749                 pipe_chicken = I915_READ(PIPE_CHICKEN(pipe));
5750                 if (!(pipe_chicken & PER_PIXEL_ALPHA_BYPASS_EN))
5751                         I915_WRITE_FW(PIPE_CHICKEN(pipe),
5752                                       pipe_chicken | PER_PIXEL_ALPHA_BYPASS_EN);
5753         }
5754
5755         intel_ddi_set_pipe_settings(pipe_config);
5756         if (!transcoder_is_dsi(cpu_transcoder))
5757                 intel_ddi_enable_transcoder_func(pipe_config);
5758
5759         if (dev_priv->display.initial_watermarks != NULL)
5760                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5761
5762         if (INTEL_GEN(dev_priv) >= 11)
5763                 icl_pipe_mbus_enable(intel_crtc);
5764
5765         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5766         if (!transcoder_is_dsi(cpu_transcoder))
5767                 intel_enable_pipe(pipe_config);
5768
5769         if (intel_crtc->config->has_pch_encoder)
5770                 lpt_pch_enable(old_intel_state, pipe_config);
5771
5772         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5773                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5774
5775         assert_vblank_disabled(crtc);
5776         drm_crtc_vblank_on(crtc);
5777
5778         intel_encoders_enable(crtc, pipe_config, old_state);
5779
5780         if (psl_clkgate_wa) {
5781                 intel_wait_for_vblank(dev_priv, pipe);
5782                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5783         }
5784
5785         /* If we change the relative order between pipe/planes enabling, we need
5786          * to change the workaround. */
5787         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5788         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5789                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5790                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5791         }
5792 }
5793
5794 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5795 {
5796         struct drm_device *dev = crtc->base.dev;
5797         struct drm_i915_private *dev_priv = to_i915(dev);
5798         int pipe = crtc->pipe;
5799
5800         /* To avoid upsetting the power well on haswell only disable the pfit if
5801          * it's in use. The hw state code will make sure we get this right. */
5802         if (force || crtc->config->pch_pfit.enabled) {
5803                 I915_WRITE(PF_CTL(pipe), 0);
5804                 I915_WRITE(PF_WIN_POS(pipe), 0);
5805                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5806         }
5807 }
5808
5809 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5810                                   struct drm_atomic_state *old_state)
5811 {
5812         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5813         struct drm_device *dev = crtc->dev;
5814         struct drm_i915_private *dev_priv = to_i915(dev);
5815         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5816         int pipe = intel_crtc->pipe;
5817
5818         /*
5819          * Sometimes spurious CPU pipe underruns happen when the
5820          * pipe is already disabled, but FDI RX/TX is still enabled.
5821          * Happens at least with VGA+HDMI cloning. Suppress them.
5822          */
5823         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5824         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5825
5826         intel_encoders_disable(crtc, old_crtc_state, old_state);
5827
5828         drm_crtc_vblank_off(crtc);
5829         assert_vblank_disabled(crtc);
5830
5831         intel_disable_pipe(old_crtc_state);
5832
5833         ironlake_pfit_disable(intel_crtc, false);
5834
5835         if (intel_crtc->config->has_pch_encoder)
5836                 ironlake_fdi_disable(crtc);
5837
5838         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5839
5840         if (intel_crtc->config->has_pch_encoder) {
5841                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5842
5843                 if (HAS_PCH_CPT(dev_priv)) {
5844                         i915_reg_t reg;
5845                         u32 temp;
5846
5847                         /* disable TRANS_DP_CTL */
5848                         reg = TRANS_DP_CTL(pipe);
5849                         temp = I915_READ(reg);
5850                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5851                                   TRANS_DP_PORT_SEL_MASK);
5852                         temp |= TRANS_DP_PORT_SEL_NONE;
5853                         I915_WRITE(reg, temp);
5854
5855                         /* disable DPLL_SEL */
5856                         temp = I915_READ(PCH_DPLL_SEL);
5857                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5858                         I915_WRITE(PCH_DPLL_SEL, temp);
5859                 }
5860
5861                 ironlake_fdi_pll_disable(intel_crtc);
5862         }
5863
5864         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5865         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5866 }
5867
5868 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5869                                  struct drm_atomic_state *old_state)
5870 {
5871         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5872         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5873         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5874         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
5875
5876         intel_encoders_disable(crtc, old_crtc_state, old_state);
5877
5878         drm_crtc_vblank_off(crtc);
5879         assert_vblank_disabled(crtc);
5880
5881         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5882         if (!transcoder_is_dsi(cpu_transcoder))
5883                 intel_disable_pipe(old_crtc_state);
5884
5885         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
5886                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
5887
5888         if (!transcoder_is_dsi(cpu_transcoder))
5889                 intel_ddi_disable_transcoder_func(old_crtc_state);
5890
5891         if (INTEL_GEN(dev_priv) >= 9)
5892                 skylake_scaler_disable(intel_crtc);
5893         else
5894                 ironlake_pfit_disable(intel_crtc, false);
5895
5896         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5897
5898         if (INTEL_GEN(dev_priv) >= 11)
5899                 icl_unmap_plls_to_ports(crtc, old_crtc_state, old_state);
5900 }
5901
5902 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5903 {
5904         struct drm_device *dev = crtc->base.dev;
5905         struct drm_i915_private *dev_priv = to_i915(dev);
5906         struct intel_crtc_state *pipe_config = crtc->config;
5907
5908         if (!pipe_config->gmch_pfit.control)
5909                 return;
5910
5911         /*
5912          * The panel fitter should only be adjusted whilst the pipe is disabled,
5913          * according to register description and PRM.
5914          */
5915         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5916         assert_pipe_disabled(dev_priv, crtc->pipe);
5917
5918         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5919         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5920
5921         /* Border color in case we don't scale up to the full screen. Black by
5922          * default, change to something else for debugging. */
5923         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5924 }
5925
5926 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
5927 {
5928         if (IS_ICELAKE(dev_priv))
5929                 return port >= PORT_C && port <= PORT_F;
5930
5931         return false;
5932 }
5933
5934 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
5935 {
5936         if (!intel_port_is_tc(dev_priv, port))
5937                 return PORT_TC_NONE;
5938
5939         return port - PORT_C;
5940 }
5941
5942 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5943 {
5944         switch (port) {
5945         case PORT_A:
5946                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5947         case PORT_B:
5948                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5949         case PORT_C:
5950                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5951         case PORT_D:
5952                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5953         case PORT_E:
5954                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5955         case PORT_F:
5956                 return POWER_DOMAIN_PORT_DDI_F_LANES;
5957         default:
5958                 MISSING_CASE(port);
5959                 return POWER_DOMAIN_PORT_OTHER;
5960         }
5961 }
5962
5963 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5964                                   struct intel_crtc_state *crtc_state)
5965 {
5966         struct drm_device *dev = crtc->dev;
5967         struct drm_i915_private *dev_priv = to_i915(dev);
5968         struct drm_encoder *encoder;
5969         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5970         enum pipe pipe = intel_crtc->pipe;
5971         u64 mask;
5972         enum transcoder transcoder = crtc_state->cpu_transcoder;
5973
5974         if (!crtc_state->base.active)
5975                 return 0;
5976
5977         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
5978         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
5979         if (crtc_state->pch_pfit.enabled ||
5980             crtc_state->pch_pfit.force_thru)
5981                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5982
5983         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5984                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5985
5986                 mask |= BIT_ULL(intel_encoder->power_domain);
5987         }
5988
5989         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5990                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
5991
5992         if (crtc_state->shared_dpll)
5993                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5994
5995         return mask;
5996 }
5997
5998 static u64
5999 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
6000                                struct intel_crtc_state *crtc_state)
6001 {
6002         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6003         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6004         enum intel_display_power_domain domain;
6005         u64 domains, new_domains, old_domains;
6006
6007         old_domains = intel_crtc->enabled_power_domains;
6008         intel_crtc->enabled_power_domains = new_domains =
6009                 get_crtc_power_domains(crtc, crtc_state);
6010
6011         domains = new_domains & ~old_domains;
6012
6013         for_each_power_domain(domain, domains)
6014                 intel_display_power_get(dev_priv, domain);
6015
6016         return old_domains & ~new_domains;
6017 }
6018
6019 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
6020                                       u64 domains)
6021 {
6022         enum intel_display_power_domain domain;
6023
6024         for_each_power_domain(domain, domains)
6025                 intel_display_power_put(dev_priv, domain);
6026 }
6027
6028 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6029                                    struct drm_atomic_state *old_state)
6030 {
6031         struct intel_atomic_state *old_intel_state =
6032                 to_intel_atomic_state(old_state);
6033         struct drm_crtc *crtc = pipe_config->base.crtc;
6034         struct drm_device *dev = crtc->dev;
6035         struct drm_i915_private *dev_priv = to_i915(dev);
6036         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6037         int pipe = intel_crtc->pipe;
6038
6039         if (WARN_ON(intel_crtc->active))
6040                 return;
6041
6042         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6043                 intel_dp_set_m_n(intel_crtc, M1_N1);
6044
6045         intel_set_pipe_timings(intel_crtc);
6046         intel_set_pipe_src_size(intel_crtc);
6047
6048         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6049                 struct drm_i915_private *dev_priv = to_i915(dev);
6050
6051                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6052                 I915_WRITE(CHV_CANVAS(pipe), 0);
6053         }
6054
6055         i9xx_set_pipeconf(intel_crtc);
6056
6057         intel_color_set_csc(&pipe_config->base);
6058
6059         intel_crtc->active = true;
6060
6061         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6062
6063         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6064
6065         if (IS_CHERRYVIEW(dev_priv)) {
6066                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6067                 chv_enable_pll(intel_crtc, intel_crtc->config);
6068         } else {
6069                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6070                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6071         }
6072
6073         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6074
6075         i9xx_pfit_enable(intel_crtc);
6076
6077         intel_color_load_luts(&pipe_config->base);
6078
6079         dev_priv->display.initial_watermarks(old_intel_state,
6080                                              pipe_config);
6081         intel_enable_pipe(pipe_config);
6082
6083         assert_vblank_disabled(crtc);
6084         drm_crtc_vblank_on(crtc);
6085
6086         intel_encoders_enable(crtc, pipe_config, old_state);
6087 }
6088
6089 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6090 {
6091         struct drm_device *dev = crtc->base.dev;
6092         struct drm_i915_private *dev_priv = to_i915(dev);
6093
6094         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6095         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6096 }
6097
6098 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6099                              struct drm_atomic_state *old_state)
6100 {
6101         struct intel_atomic_state *old_intel_state =
6102                 to_intel_atomic_state(old_state);
6103         struct drm_crtc *crtc = pipe_config->base.crtc;
6104         struct drm_device *dev = crtc->dev;
6105         struct drm_i915_private *dev_priv = to_i915(dev);
6106         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6107         enum pipe pipe = intel_crtc->pipe;
6108
6109         if (WARN_ON(intel_crtc->active))
6110                 return;
6111
6112         i9xx_set_pll_dividers(intel_crtc);
6113
6114         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6115                 intel_dp_set_m_n(intel_crtc, M1_N1);
6116
6117         intel_set_pipe_timings(intel_crtc);
6118         intel_set_pipe_src_size(intel_crtc);
6119
6120         i9xx_set_pipeconf(intel_crtc);
6121
6122         intel_crtc->active = true;
6123
6124         if (!IS_GEN2(dev_priv))
6125                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6126
6127         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6128
6129         i9xx_enable_pll(intel_crtc, pipe_config);
6130
6131         i9xx_pfit_enable(intel_crtc);
6132
6133         intel_color_load_luts(&pipe_config->base);
6134
6135         if (dev_priv->display.initial_watermarks != NULL)
6136                 dev_priv->display.initial_watermarks(old_intel_state,
6137                                                      intel_crtc->config);
6138         else
6139                 intel_update_watermarks(intel_crtc);
6140         intel_enable_pipe(pipe_config);
6141
6142         assert_vblank_disabled(crtc);
6143         drm_crtc_vblank_on(crtc);
6144
6145         intel_encoders_enable(crtc, pipe_config, old_state);
6146 }
6147
6148 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6149 {
6150         struct drm_device *dev = crtc->base.dev;
6151         struct drm_i915_private *dev_priv = to_i915(dev);
6152
6153         if (!crtc->config->gmch_pfit.control)
6154                 return;
6155
6156         assert_pipe_disabled(dev_priv, crtc->pipe);
6157
6158         DRM_DEBUG_KMS("disabling pfit, current: 0x%08x\n",
6159                       I915_READ(PFIT_CONTROL));
6160         I915_WRITE(PFIT_CONTROL, 0);
6161 }
6162
6163 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6164                               struct drm_atomic_state *old_state)
6165 {
6166         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6167         struct drm_device *dev = crtc->dev;
6168         struct drm_i915_private *dev_priv = to_i915(dev);
6169         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6170         int pipe = intel_crtc->pipe;
6171
6172         /*
6173          * On gen2 planes are double buffered but the pipe isn't, so we must
6174          * wait for planes to fully turn off before disabling the pipe.
6175          */
6176         if (IS_GEN2(dev_priv))
6177                 intel_wait_for_vblank(dev_priv, pipe);
6178
6179         intel_encoders_disable(crtc, old_crtc_state, old_state);
6180
6181         drm_crtc_vblank_off(crtc);
6182         assert_vblank_disabled(crtc);
6183
6184         intel_disable_pipe(old_crtc_state);
6185
6186         i9xx_pfit_disable(intel_crtc);
6187
6188         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6189
6190         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6191                 if (IS_CHERRYVIEW(dev_priv))
6192                         chv_disable_pll(dev_priv, pipe);
6193                 else if (IS_VALLEYVIEW(dev_priv))
6194                         vlv_disable_pll(dev_priv, pipe);
6195                 else
6196                         i9xx_disable_pll(intel_crtc);
6197         }
6198
6199         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6200
6201         if (!IS_GEN2(dev_priv))
6202                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6203
6204         if (!dev_priv->display.initial_watermarks)
6205                 intel_update_watermarks(intel_crtc);
6206
6207         /* clock the pipe down to 640x480@60 to potentially save power */
6208         if (IS_I830(dev_priv))
6209                 i830_enable_pipe(dev_priv, pipe);
6210 }
6211
6212 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6213                                         struct drm_modeset_acquire_ctx *ctx)
6214 {
6215         struct intel_encoder *encoder;
6216         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6217         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6218         enum intel_display_power_domain domain;
6219         struct intel_plane *plane;
6220         u64 domains;
6221         struct drm_atomic_state *state;
6222         struct intel_crtc_state *crtc_state;
6223         int ret;
6224
6225         if (!intel_crtc->active)
6226                 return;
6227
6228         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6229                 const struct intel_plane_state *plane_state =
6230                         to_intel_plane_state(plane->base.state);
6231
6232                 if (plane_state->base.visible)
6233                         intel_plane_disable_noatomic(intel_crtc, plane);
6234         }
6235
6236         state = drm_atomic_state_alloc(crtc->dev);
6237         if (!state) {
6238                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6239                               crtc->base.id, crtc->name);
6240                 return;
6241         }
6242
6243         state->acquire_ctx = ctx;
6244
6245         /* Everything's already locked, -EDEADLK can't happen. */
6246         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6247         ret = drm_atomic_add_affected_connectors(state, crtc);
6248
6249         WARN_ON(IS_ERR(crtc_state) || ret);
6250
6251         dev_priv->display.crtc_disable(crtc_state, state);
6252
6253         drm_atomic_state_put(state);
6254
6255         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6256                       crtc->base.id, crtc->name);
6257
6258         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6259         crtc->state->active = false;
6260         intel_crtc->active = false;
6261         crtc->enabled = false;
6262         crtc->state->connector_mask = 0;
6263         crtc->state->encoder_mask = 0;
6264
6265         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6266                 encoder->base.crtc = NULL;
6267
6268         intel_fbc_disable(intel_crtc);
6269         intel_update_watermarks(intel_crtc);
6270         intel_disable_shared_dpll(intel_crtc);
6271
6272         domains = intel_crtc->enabled_power_domains;
6273         for_each_power_domain(domain, domains)
6274                 intel_display_power_put(dev_priv, domain);
6275         intel_crtc->enabled_power_domains = 0;
6276
6277         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6278         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6279         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6280 }
6281
6282 /*
6283  * turn all crtc's off, but do not adjust state
6284  * This has to be paired with a call to intel_modeset_setup_hw_state.
6285  */
6286 int intel_display_suspend(struct drm_device *dev)
6287 {
6288         struct drm_i915_private *dev_priv = to_i915(dev);
6289         struct drm_atomic_state *state;
6290         int ret;
6291
6292         state = drm_atomic_helper_suspend(dev);
6293         ret = PTR_ERR_OR_ZERO(state);
6294         if (ret)
6295                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6296         else
6297                 dev_priv->modeset_restore_state = state;
6298         return ret;
6299 }
6300
6301 void intel_encoder_destroy(struct drm_encoder *encoder)
6302 {
6303         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6304
6305         drm_encoder_cleanup(encoder);
6306         kfree(intel_encoder);
6307 }
6308
6309 /* Cross check the actual hw state with our own modeset state tracking (and it's
6310  * internal consistency). */
6311 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6312                                          struct drm_connector_state *conn_state)
6313 {
6314         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6315
6316         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6317                       connector->base.base.id,
6318                       connector->base.name);
6319
6320         if (connector->get_hw_state(connector)) {
6321                 struct intel_encoder *encoder = connector->encoder;
6322
6323                 I915_STATE_WARN(!crtc_state,
6324                          "connector enabled without attached crtc\n");
6325
6326                 if (!crtc_state)
6327                         return;
6328
6329                 I915_STATE_WARN(!crtc_state->active,
6330                       "connector is active, but attached crtc isn't\n");
6331
6332                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6333                         return;
6334
6335                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6336                         "atomic encoder doesn't match attached encoder\n");
6337
6338                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6339                         "attached encoder crtc differs from connector crtc\n");
6340         } else {
6341                 I915_STATE_WARN(crtc_state && crtc_state->active,
6342                         "attached crtc is active, but connector isn't\n");
6343                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6344                         "best encoder set without crtc!\n");
6345         }
6346 }
6347
6348 int intel_connector_init(struct intel_connector *connector)
6349 {
6350         struct intel_digital_connector_state *conn_state;
6351
6352         /*
6353          * Allocate enough memory to hold intel_digital_connector_state,
6354          * This might be a few bytes too many, but for connectors that don't
6355          * need it we'll free the state and allocate a smaller one on the first
6356          * succesful commit anyway.
6357          */
6358         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
6359         if (!conn_state)
6360                 return -ENOMEM;
6361
6362         __drm_atomic_helper_connector_reset(&connector->base,
6363                                             &conn_state->base);
6364
6365         return 0;
6366 }
6367
6368 struct intel_connector *intel_connector_alloc(void)
6369 {
6370         struct intel_connector *connector;
6371
6372         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6373         if (!connector)
6374                 return NULL;
6375
6376         if (intel_connector_init(connector) < 0) {
6377                 kfree(connector);
6378                 return NULL;
6379         }
6380
6381         return connector;
6382 }
6383
6384 /*
6385  * Free the bits allocated by intel_connector_alloc.
6386  * This should only be used after intel_connector_alloc has returned
6387  * successfully, and before drm_connector_init returns successfully.
6388  * Otherwise the destroy callbacks for the connector and the state should
6389  * take care of proper cleanup/free
6390  */
6391 void intel_connector_free(struct intel_connector *connector)
6392 {
6393         kfree(to_intel_digital_connector_state(connector->base.state));
6394         kfree(connector);
6395 }
6396
6397 /* Simple connector->get_hw_state implementation for encoders that support only
6398  * one connector and no cloning and hence the encoder state determines the state
6399  * of the connector. */
6400 bool intel_connector_get_hw_state(struct intel_connector *connector)
6401 {
6402         enum pipe pipe = 0;
6403         struct intel_encoder *encoder = connector->encoder;
6404
6405         return encoder->get_hw_state(encoder, &pipe);
6406 }
6407
6408 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6409 {
6410         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6411                 return crtc_state->fdi_lanes;
6412
6413         return 0;
6414 }
6415
6416 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6417                                      struct intel_crtc_state *pipe_config)
6418 {
6419         struct drm_i915_private *dev_priv = to_i915(dev);
6420         struct drm_atomic_state *state = pipe_config->base.state;
6421         struct intel_crtc *other_crtc;
6422         struct intel_crtc_state *other_crtc_state;
6423
6424         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6425                       pipe_name(pipe), pipe_config->fdi_lanes);
6426         if (pipe_config->fdi_lanes > 4) {
6427                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6428                               pipe_name(pipe), pipe_config->fdi_lanes);
6429                 return -EINVAL;
6430         }
6431
6432         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6433                 if (pipe_config->fdi_lanes > 2) {
6434                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6435                                       pipe_config->fdi_lanes);
6436                         return -EINVAL;
6437                 } else {
6438                         return 0;
6439                 }
6440         }
6441
6442         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6443                 return 0;
6444
6445         /* Ivybridge 3 pipe is really complicated */
6446         switch (pipe) {
6447         case PIPE_A:
6448                 return 0;
6449         case PIPE_B:
6450                 if (pipe_config->fdi_lanes <= 2)
6451                         return 0;
6452
6453                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6454                 other_crtc_state =
6455                         intel_atomic_get_crtc_state(state, other_crtc);
6456                 if (IS_ERR(other_crtc_state))
6457                         return PTR_ERR(other_crtc_state);
6458
6459                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6460                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6461                                       pipe_name(pipe), pipe_config->fdi_lanes);
6462                         return -EINVAL;
6463                 }
6464                 return 0;
6465         case PIPE_C:
6466                 if (pipe_config->fdi_lanes > 2) {
6467                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6468                                       pipe_name(pipe), pipe_config->fdi_lanes);
6469                         return -EINVAL;
6470                 }
6471
6472                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6473                 other_crtc_state =
6474                         intel_atomic_get_crtc_state(state, other_crtc);
6475                 if (IS_ERR(other_crtc_state))
6476                         return PTR_ERR(other_crtc_state);
6477
6478                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6479                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6480                         return -EINVAL;
6481                 }
6482                 return 0;
6483         default:
6484                 BUG();
6485         }
6486 }
6487
6488 #define RETRY 1
6489 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6490                                        struct intel_crtc_state *pipe_config)
6491 {
6492         struct drm_device *dev = intel_crtc->base.dev;
6493         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6494         int lane, link_bw, fdi_dotclock, ret;
6495         bool needs_recompute = false;
6496
6497 retry:
6498         /* FDI is a binary signal running at ~2.7GHz, encoding
6499          * each output octet as 10 bits. The actual frequency
6500          * is stored as a divider into a 100MHz clock, and the
6501          * mode pixel clock is stored in units of 1KHz.
6502          * Hence the bw of each lane in terms of the mode signal
6503          * is:
6504          */
6505         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6506
6507         fdi_dotclock = adjusted_mode->crtc_clock;
6508
6509         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6510                                            pipe_config->pipe_bpp);
6511
6512         pipe_config->fdi_lanes = lane;
6513
6514         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6515                                link_bw, &pipe_config->fdi_m_n, false);
6516
6517         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6518         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6519                 pipe_config->pipe_bpp -= 2*3;
6520                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6521                               pipe_config->pipe_bpp);
6522                 needs_recompute = true;
6523                 pipe_config->bw_constrained = true;
6524
6525                 goto retry;
6526         }
6527
6528         if (needs_recompute)
6529                 return RETRY;
6530
6531         return ret;
6532 }
6533
6534 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6535 {
6536         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6537         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6538
6539         /* IPS only exists on ULT machines and is tied to pipe A. */
6540         if (!hsw_crtc_supports_ips(crtc))
6541                 return false;
6542
6543         if (!i915_modparams.enable_ips)
6544                 return false;
6545
6546         if (crtc_state->pipe_bpp > 24)
6547                 return false;
6548
6549         /*
6550          * We compare against max which means we must take
6551          * the increased cdclk requirement into account when
6552          * calculating the new cdclk.
6553          *
6554          * Should measure whether using a lower cdclk w/o IPS
6555          */
6556         if (IS_BROADWELL(dev_priv) &&
6557             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6558                 return false;
6559
6560         return true;
6561 }
6562
6563 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6564 {
6565         struct drm_i915_private *dev_priv =
6566                 to_i915(crtc_state->base.crtc->dev);
6567         struct intel_atomic_state *intel_state =
6568                 to_intel_atomic_state(crtc_state->base.state);
6569
6570         if (!hsw_crtc_state_ips_capable(crtc_state))
6571                 return false;
6572
6573         if (crtc_state->ips_force_disable)
6574                 return false;
6575
6576         /* IPS should be fine as long as at least one plane is enabled. */
6577         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6578                 return false;
6579
6580         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6581         if (IS_BROADWELL(dev_priv) &&
6582             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6583                 return false;
6584
6585         return true;
6586 }
6587
6588 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6589 {
6590         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6591
6592         /* GDG double wide on either pipe, otherwise pipe A only */
6593         return INTEL_GEN(dev_priv) < 4 &&
6594                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6595 }
6596
6597 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6598 {
6599         uint32_t pixel_rate;
6600
6601         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6602
6603         /*
6604          * We only use IF-ID interlacing. If we ever use
6605          * PF-ID we'll need to adjust the pixel_rate here.
6606          */
6607
6608         if (pipe_config->pch_pfit.enabled) {
6609                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6610                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6611
6612                 pipe_w = pipe_config->pipe_src_w;
6613                 pipe_h = pipe_config->pipe_src_h;
6614
6615                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6616                 pfit_h = pfit_size & 0xFFFF;
6617                 if (pipe_w < pfit_w)
6618                         pipe_w = pfit_w;
6619                 if (pipe_h < pfit_h)
6620                         pipe_h = pfit_h;
6621
6622                 if (WARN_ON(!pfit_w || !pfit_h))
6623                         return pixel_rate;
6624
6625                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6626                                      pfit_w * pfit_h);
6627         }
6628
6629         return pixel_rate;
6630 }
6631
6632 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6633 {
6634         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6635
6636         if (HAS_GMCH_DISPLAY(dev_priv))
6637                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6638                 crtc_state->pixel_rate =
6639                         crtc_state->base.adjusted_mode.crtc_clock;
6640         else
6641                 crtc_state->pixel_rate =
6642                         ilk_pipe_pixel_rate(crtc_state);
6643 }
6644
6645 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6646                                      struct intel_crtc_state *pipe_config)
6647 {
6648         struct drm_device *dev = crtc->base.dev;
6649         struct drm_i915_private *dev_priv = to_i915(dev);
6650         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6651         int clock_limit = dev_priv->max_dotclk_freq;
6652
6653         if (INTEL_GEN(dev_priv) < 4) {
6654                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6655
6656                 /*
6657                  * Enable double wide mode when the dot clock
6658                  * is > 90% of the (display) core speed.
6659                  */
6660                 if (intel_crtc_supports_double_wide(crtc) &&
6661                     adjusted_mode->crtc_clock > clock_limit) {
6662                         clock_limit = dev_priv->max_dotclk_freq;
6663                         pipe_config->double_wide = true;
6664                 }
6665         }
6666
6667         if (adjusted_mode->crtc_clock > clock_limit) {
6668                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6669                               adjusted_mode->crtc_clock, clock_limit,
6670                               yesno(pipe_config->double_wide));
6671                 return -EINVAL;
6672         }
6673
6674         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6675                 /*
6676                  * There is only one pipe CSC unit per pipe, and we need that
6677                  * for output conversion from RGB->YCBCR. So if CTM is already
6678                  * applied we can't support YCBCR420 output.
6679                  */
6680                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6681                 return -EINVAL;
6682         }
6683
6684         /*
6685          * Pipe horizontal size must be even in:
6686          * - DVO ganged mode
6687          * - LVDS dual channel mode
6688          * - Double wide pipe
6689          */
6690         if (pipe_config->pipe_src_w & 1) {
6691                 if (pipe_config->double_wide) {
6692                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6693                         return -EINVAL;
6694                 }
6695
6696                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6697                     intel_is_dual_link_lvds(dev)) {
6698                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6699                         return -EINVAL;
6700                 }
6701         }
6702
6703         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6704          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6705          */
6706         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6707                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6708                 return -EINVAL;
6709
6710         intel_crtc_compute_pixel_rate(pipe_config);
6711
6712         if (pipe_config->has_pch_encoder)
6713                 return ironlake_fdi_compute_config(crtc, pipe_config);
6714
6715         return 0;
6716 }
6717
6718 static void
6719 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6720 {
6721         while (*num > DATA_LINK_M_N_MASK ||
6722                *den > DATA_LINK_M_N_MASK) {
6723                 *num >>= 1;
6724                 *den >>= 1;
6725         }
6726 }
6727
6728 static void compute_m_n(unsigned int m, unsigned int n,
6729                         uint32_t *ret_m, uint32_t *ret_n,
6730                         bool constant_n)
6731 {
6732         /*
6733          * Several DP dongles in particular seem to be fussy about
6734          * too large link M/N values. Give N value as 0x8000 that
6735          * should be acceptable by specific devices. 0x8000 is the
6736          * specified fixed N value for asynchronous clock mode,
6737          * which the devices expect also in synchronous clock mode.
6738          */
6739         if (constant_n)
6740                 *ret_n = 0x8000;
6741         else
6742                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6743
6744         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6745         intel_reduce_m_n_ratio(ret_m, ret_n);
6746 }
6747
6748 void
6749 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6750                        int pixel_clock, int link_clock,
6751                        struct intel_link_m_n *m_n,
6752                        bool constant_n)
6753 {
6754         m_n->tu = 64;
6755
6756         compute_m_n(bits_per_pixel * pixel_clock,
6757                     link_clock * nlanes * 8,
6758                     &m_n->gmch_m, &m_n->gmch_n,
6759                     constant_n);
6760
6761         compute_m_n(pixel_clock, link_clock,
6762                     &m_n->link_m, &m_n->link_n,
6763                     constant_n);
6764 }
6765
6766 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6767 {
6768         if (i915_modparams.panel_use_ssc >= 0)
6769                 return i915_modparams.panel_use_ssc != 0;
6770         return dev_priv->vbt.lvds_use_ssc
6771                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6772 }
6773
6774 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6775 {
6776         return (1 << dpll->n) << 16 | dpll->m2;
6777 }
6778
6779 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6780 {
6781         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6782 }
6783
6784 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6785                                      struct intel_crtc_state *crtc_state,
6786                                      struct dpll *reduced_clock)
6787 {
6788         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6789         u32 fp, fp2 = 0;
6790
6791         if (IS_PINEVIEW(dev_priv)) {
6792                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6793                 if (reduced_clock)
6794                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6795         } else {
6796                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6797                 if (reduced_clock)
6798                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6799         }
6800
6801         crtc_state->dpll_hw_state.fp0 = fp;
6802
6803         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6804             reduced_clock) {
6805                 crtc_state->dpll_hw_state.fp1 = fp2;
6806         } else {
6807                 crtc_state->dpll_hw_state.fp1 = fp;
6808         }
6809 }
6810
6811 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6812                 pipe)
6813 {
6814         u32 reg_val;
6815
6816         /*
6817          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6818          * and set it to a reasonable value instead.
6819          */
6820         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6821         reg_val &= 0xffffff00;
6822         reg_val |= 0x00000030;
6823         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6824
6825         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6826         reg_val &= 0x00ffffff;
6827         reg_val |= 0x8c000000;
6828         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6829
6830         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6831         reg_val &= 0xffffff00;
6832         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6833
6834         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6835         reg_val &= 0x00ffffff;
6836         reg_val |= 0xb0000000;
6837         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6838 }
6839
6840 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6841                                          struct intel_link_m_n *m_n)
6842 {
6843         struct drm_device *dev = crtc->base.dev;
6844         struct drm_i915_private *dev_priv = to_i915(dev);
6845         int pipe = crtc->pipe;
6846
6847         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6848         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6849         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6850         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6851 }
6852
6853 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6854                                          struct intel_link_m_n *m_n,
6855                                          struct intel_link_m_n *m2_n2)
6856 {
6857         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6858         int pipe = crtc->pipe;
6859         enum transcoder transcoder = crtc->config->cpu_transcoder;
6860
6861         if (INTEL_GEN(dev_priv) >= 5) {
6862                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6863                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6864                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6865                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6866                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6867                  * for gen < 8) and if DRRS is supported (to make sure the
6868                  * registers are not unnecessarily accessed).
6869                  */
6870                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6871                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6872                         I915_WRITE(PIPE_DATA_M2(transcoder),
6873                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6874                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6875                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6876                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6877                 }
6878         } else {
6879                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6880                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6881                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6882                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6883         }
6884 }
6885
6886 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6887 {
6888         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6889
6890         if (m_n == M1_N1) {
6891                 dp_m_n = &crtc->config->dp_m_n;
6892                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6893         } else if (m_n == M2_N2) {
6894
6895                 /*
6896                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6897                  * needs to be programmed into M1_N1.
6898                  */
6899                 dp_m_n = &crtc->config->dp_m2_n2;
6900         } else {
6901                 DRM_ERROR("Unsupported divider value\n");
6902                 return;
6903         }
6904
6905         if (crtc->config->has_pch_encoder)
6906                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6907         else
6908                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6909 }
6910
6911 static void vlv_compute_dpll(struct intel_crtc *crtc,
6912                              struct intel_crtc_state *pipe_config)
6913 {
6914         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6915                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6916         if (crtc->pipe != PIPE_A)
6917                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6918
6919         /* DPLL not used with DSI, but still need the rest set up */
6920         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6921                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6922                         DPLL_EXT_BUFFER_ENABLE_VLV;
6923
6924         pipe_config->dpll_hw_state.dpll_md =
6925                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6926 }
6927
6928 static void chv_compute_dpll(struct intel_crtc *crtc,
6929                              struct intel_crtc_state *pipe_config)
6930 {
6931         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6932                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6933         if (crtc->pipe != PIPE_A)
6934                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6935
6936         /* DPLL not used with DSI, but still need the rest set up */
6937         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6938                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6939
6940         pipe_config->dpll_hw_state.dpll_md =
6941                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6942 }
6943
6944 static void vlv_prepare_pll(struct intel_crtc *crtc,
6945                             const struct intel_crtc_state *pipe_config)
6946 {
6947         struct drm_device *dev = crtc->base.dev;
6948         struct drm_i915_private *dev_priv = to_i915(dev);
6949         enum pipe pipe = crtc->pipe;
6950         u32 mdiv;
6951         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6952         u32 coreclk, reg_val;
6953
6954         /* Enable Refclk */
6955         I915_WRITE(DPLL(pipe),
6956                    pipe_config->dpll_hw_state.dpll &
6957                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6958
6959         /* No need to actually set up the DPLL with DSI */
6960         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6961                 return;
6962
6963         mutex_lock(&dev_priv->sb_lock);
6964
6965         bestn = pipe_config->dpll.n;
6966         bestm1 = pipe_config->dpll.m1;
6967         bestm2 = pipe_config->dpll.m2;
6968         bestp1 = pipe_config->dpll.p1;
6969         bestp2 = pipe_config->dpll.p2;
6970
6971         /* See eDP HDMI DPIO driver vbios notes doc */
6972
6973         /* PLL B needs special handling */
6974         if (pipe == PIPE_B)
6975                 vlv_pllb_recal_opamp(dev_priv, pipe);
6976
6977         /* Set up Tx target for periodic Rcomp update */
6978         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6979
6980         /* Disable target IRef on PLL */
6981         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6982         reg_val &= 0x00ffffff;
6983         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6984
6985         /* Disable fast lock */
6986         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6987
6988         /* Set idtafcrecal before PLL is enabled */
6989         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6990         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6991         mdiv |= ((bestn << DPIO_N_SHIFT));
6992         mdiv |= (1 << DPIO_K_SHIFT);
6993
6994         /*
6995          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6996          * but we don't support that).
6997          * Note: don't use the DAC post divider as it seems unstable.
6998          */
6999         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7000         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7001
7002         mdiv |= DPIO_ENABLE_CALIBRATION;
7003         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7004
7005         /* Set HBR and RBR LPF coefficients */
7006         if (pipe_config->port_clock == 162000 ||
7007             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
7008             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
7009                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7010                                  0x009f0003);
7011         else
7012                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7013                                  0x00d0000f);
7014
7015         if (intel_crtc_has_dp_encoder(pipe_config)) {
7016                 /* Use SSC source */
7017                 if (pipe == PIPE_A)
7018                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7019                                          0x0df40000);
7020                 else
7021                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7022                                          0x0df70000);
7023         } else { /* HDMI or VGA */
7024                 /* Use bend source */
7025                 if (pipe == PIPE_A)
7026                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7027                                          0x0df70000);
7028                 else
7029                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7030                                          0x0df40000);
7031         }
7032
7033         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7034         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7035         if (intel_crtc_has_dp_encoder(crtc->config))
7036                 coreclk |= 0x01000000;
7037         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7038
7039         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7040         mutex_unlock(&dev_priv->sb_lock);
7041 }
7042
7043 static void chv_prepare_pll(struct intel_crtc *crtc,
7044                             const struct intel_crtc_state *pipe_config)
7045 {
7046         struct drm_device *dev = crtc->base.dev;
7047         struct drm_i915_private *dev_priv = to_i915(dev);
7048         enum pipe pipe = crtc->pipe;
7049         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7050         u32 loopfilter, tribuf_calcntr;
7051         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7052         u32 dpio_val;
7053         int vco;
7054
7055         /* Enable Refclk and SSC */
7056         I915_WRITE(DPLL(pipe),
7057                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7058
7059         /* No need to actually set up the DPLL with DSI */
7060         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7061                 return;
7062
7063         bestn = pipe_config->dpll.n;
7064         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7065         bestm1 = pipe_config->dpll.m1;
7066         bestm2 = pipe_config->dpll.m2 >> 22;
7067         bestp1 = pipe_config->dpll.p1;
7068         bestp2 = pipe_config->dpll.p2;
7069         vco = pipe_config->dpll.vco;
7070         dpio_val = 0;
7071         loopfilter = 0;
7072
7073         mutex_lock(&dev_priv->sb_lock);
7074
7075         /* p1 and p2 divider */
7076         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7077                         5 << DPIO_CHV_S1_DIV_SHIFT |
7078                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7079                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7080                         1 << DPIO_CHV_K_DIV_SHIFT);
7081
7082         /* Feedback post-divider - m2 */
7083         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7084
7085         /* Feedback refclk divider - n and m1 */
7086         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7087                         DPIO_CHV_M1_DIV_BY_2 |
7088                         1 << DPIO_CHV_N_DIV_SHIFT);
7089
7090         /* M2 fraction division */
7091         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7092
7093         /* M2 fraction division enable */
7094         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7095         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7096         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7097         if (bestm2_frac)
7098                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7099         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7100
7101         /* Program digital lock detect threshold */
7102         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7103         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7104                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7105         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7106         if (!bestm2_frac)
7107                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7108         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7109
7110         /* Loop filter */
7111         if (vco == 5400000) {
7112                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7113                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7114                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7115                 tribuf_calcntr = 0x9;
7116         } else if (vco <= 6200000) {
7117                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7118                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7119                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7120                 tribuf_calcntr = 0x9;
7121         } else if (vco <= 6480000) {
7122                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7123                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7124                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7125                 tribuf_calcntr = 0x8;
7126         } else {
7127                 /* Not supported. Apply the same limits as in the max case */
7128                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7129                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7130                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7131                 tribuf_calcntr = 0;
7132         }
7133         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7134
7135         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7136         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7137         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7138         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7139
7140         /* AFC Recal */
7141         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7142                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7143                         DPIO_AFC_RECAL);
7144
7145         mutex_unlock(&dev_priv->sb_lock);
7146 }
7147
7148 /**
7149  * vlv_force_pll_on - forcibly enable just the PLL
7150  * @dev_priv: i915 private structure
7151  * @pipe: pipe PLL to enable
7152  * @dpll: PLL configuration
7153  *
7154  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7155  * in cases where we need the PLL enabled even when @pipe is not going to
7156  * be enabled.
7157  */
7158 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7159                      const struct dpll *dpll)
7160 {
7161         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7162         struct intel_crtc_state *pipe_config;
7163
7164         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7165         if (!pipe_config)
7166                 return -ENOMEM;
7167
7168         pipe_config->base.crtc = &crtc->base;
7169         pipe_config->pixel_multiplier = 1;
7170         pipe_config->dpll = *dpll;
7171
7172         if (IS_CHERRYVIEW(dev_priv)) {
7173                 chv_compute_dpll(crtc, pipe_config);
7174                 chv_prepare_pll(crtc, pipe_config);
7175                 chv_enable_pll(crtc, pipe_config);
7176         } else {
7177                 vlv_compute_dpll(crtc, pipe_config);
7178                 vlv_prepare_pll(crtc, pipe_config);
7179                 vlv_enable_pll(crtc, pipe_config);
7180         }
7181
7182         kfree(pipe_config);
7183
7184         return 0;
7185 }
7186
7187 /**
7188  * vlv_force_pll_off - forcibly disable just the PLL
7189  * @dev_priv: i915 private structure
7190  * @pipe: pipe PLL to disable
7191  *
7192  * Disable the PLL for @pipe. To be used in cases where we need
7193  * the PLL enabled even when @pipe is not going to be enabled.
7194  */
7195 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7196 {
7197         if (IS_CHERRYVIEW(dev_priv))
7198                 chv_disable_pll(dev_priv, pipe);
7199         else
7200                 vlv_disable_pll(dev_priv, pipe);
7201 }
7202
7203 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7204                               struct intel_crtc_state *crtc_state,
7205                               struct dpll *reduced_clock)
7206 {
7207         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7208         u32 dpll;
7209         struct dpll *clock = &crtc_state->dpll;
7210
7211         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7212
7213         dpll = DPLL_VGA_MODE_DIS;
7214
7215         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7216                 dpll |= DPLLB_MODE_LVDS;
7217         else
7218                 dpll |= DPLLB_MODE_DAC_SERIAL;
7219
7220         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7221             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7222                 dpll |= (crtc_state->pixel_multiplier - 1)
7223                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7224         }
7225
7226         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7227             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7228                 dpll |= DPLL_SDVO_HIGH_SPEED;
7229
7230         if (intel_crtc_has_dp_encoder(crtc_state))
7231                 dpll |= DPLL_SDVO_HIGH_SPEED;
7232
7233         /* compute bitmask from p1 value */
7234         if (IS_PINEVIEW(dev_priv))
7235                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7236         else {
7237                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7238                 if (IS_G4X(dev_priv) && reduced_clock)
7239                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7240         }
7241         switch (clock->p2) {
7242         case 5:
7243                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7244                 break;
7245         case 7:
7246                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7247                 break;
7248         case 10:
7249                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7250                 break;
7251         case 14:
7252                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7253                 break;
7254         }
7255         if (INTEL_GEN(dev_priv) >= 4)
7256                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7257
7258         if (crtc_state->sdvo_tv_clock)
7259                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7260         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7261                  intel_panel_use_ssc(dev_priv))
7262                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7263         else
7264                 dpll |= PLL_REF_INPUT_DREFCLK;
7265
7266         dpll |= DPLL_VCO_ENABLE;
7267         crtc_state->dpll_hw_state.dpll = dpll;
7268
7269         if (INTEL_GEN(dev_priv) >= 4) {
7270                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7271                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7272                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7273         }
7274 }
7275
7276 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7277                               struct intel_crtc_state *crtc_state,
7278                               struct dpll *reduced_clock)
7279 {
7280         struct drm_device *dev = crtc->base.dev;
7281         struct drm_i915_private *dev_priv = to_i915(dev);
7282         u32 dpll;
7283         struct dpll *clock = &crtc_state->dpll;
7284
7285         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7286
7287         dpll = DPLL_VGA_MODE_DIS;
7288
7289         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7290                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7291         } else {
7292                 if (clock->p1 == 2)
7293                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7294                 else
7295                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7296                 if (clock->p2 == 4)
7297                         dpll |= PLL_P2_DIVIDE_BY_4;
7298         }
7299
7300         if (!IS_I830(dev_priv) &&
7301             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7302                 dpll |= DPLL_DVO_2X_MODE;
7303
7304         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7305             intel_panel_use_ssc(dev_priv))
7306                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7307         else
7308                 dpll |= PLL_REF_INPUT_DREFCLK;
7309
7310         dpll |= DPLL_VCO_ENABLE;
7311         crtc_state->dpll_hw_state.dpll = dpll;
7312 }
7313
7314 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7315 {
7316         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7317         enum pipe pipe = intel_crtc->pipe;
7318         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7319         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7320         uint32_t crtc_vtotal, crtc_vblank_end;
7321         int vsyncshift = 0;
7322
7323         /* We need to be careful not to changed the adjusted mode, for otherwise
7324          * the hw state checker will get angry at the mismatch. */
7325         crtc_vtotal = adjusted_mode->crtc_vtotal;
7326         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7327
7328         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7329                 /* the chip adds 2 halflines automatically */
7330                 crtc_vtotal -= 1;
7331                 crtc_vblank_end -= 1;
7332
7333                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7334                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7335                 else
7336                         vsyncshift = adjusted_mode->crtc_hsync_start -
7337                                 adjusted_mode->crtc_htotal / 2;
7338                 if (vsyncshift < 0)
7339                         vsyncshift += adjusted_mode->crtc_htotal;
7340         }
7341
7342         if (INTEL_GEN(dev_priv) > 3)
7343                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7344
7345         I915_WRITE(HTOTAL(cpu_transcoder),
7346                    (adjusted_mode->crtc_hdisplay - 1) |
7347                    ((adjusted_mode->crtc_htotal - 1) << 16));
7348         I915_WRITE(HBLANK(cpu_transcoder),
7349                    (adjusted_mode->crtc_hblank_start - 1) |
7350                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7351         I915_WRITE(HSYNC(cpu_transcoder),
7352                    (adjusted_mode->crtc_hsync_start - 1) |
7353                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7354
7355         I915_WRITE(VTOTAL(cpu_transcoder),
7356                    (adjusted_mode->crtc_vdisplay - 1) |
7357                    ((crtc_vtotal - 1) << 16));
7358         I915_WRITE(VBLANK(cpu_transcoder),
7359                    (adjusted_mode->crtc_vblank_start - 1) |
7360                    ((crtc_vblank_end - 1) << 16));
7361         I915_WRITE(VSYNC(cpu_transcoder),
7362                    (adjusted_mode->crtc_vsync_start - 1) |
7363                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7364
7365         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7366          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7367          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7368          * bits. */
7369         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7370             (pipe == PIPE_B || pipe == PIPE_C))
7371                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7372
7373 }
7374
7375 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7376 {
7377         struct drm_device *dev = intel_crtc->base.dev;
7378         struct drm_i915_private *dev_priv = to_i915(dev);
7379         enum pipe pipe = intel_crtc->pipe;
7380
7381         /* pipesrc controls the size that is scaled from, which should
7382          * always be the user's requested size.
7383          */
7384         I915_WRITE(PIPESRC(pipe),
7385                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7386                    (intel_crtc->config->pipe_src_h - 1));
7387 }
7388
7389 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7390                                    struct intel_crtc_state *pipe_config)
7391 {
7392         struct drm_device *dev = crtc->base.dev;
7393         struct drm_i915_private *dev_priv = to_i915(dev);
7394         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7395         uint32_t tmp;
7396
7397         tmp = I915_READ(HTOTAL(cpu_transcoder));
7398         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7399         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7400         tmp = I915_READ(HBLANK(cpu_transcoder));
7401         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7402         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7403         tmp = I915_READ(HSYNC(cpu_transcoder));
7404         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7405         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7406
7407         tmp = I915_READ(VTOTAL(cpu_transcoder));
7408         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7409         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7410         tmp = I915_READ(VBLANK(cpu_transcoder));
7411         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7412         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7413         tmp = I915_READ(VSYNC(cpu_transcoder));
7414         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7415         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7416
7417         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7418                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7419                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7420                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7421         }
7422 }
7423
7424 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7425                                     struct intel_crtc_state *pipe_config)
7426 {
7427         struct drm_device *dev = crtc->base.dev;
7428         struct drm_i915_private *dev_priv = to_i915(dev);
7429         u32 tmp;
7430
7431         tmp = I915_READ(PIPESRC(crtc->pipe));
7432         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7433         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7434
7435         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7436         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7437 }
7438
7439 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7440                                  struct intel_crtc_state *pipe_config)
7441 {
7442         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7443         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7444         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7445         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7446
7447         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7448         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7449         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7450         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7451
7452         mode->flags = pipe_config->base.adjusted_mode.flags;
7453         mode->type = DRM_MODE_TYPE_DRIVER;
7454
7455         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7456
7457         mode->hsync = drm_mode_hsync(mode);
7458         mode->vrefresh = drm_mode_vrefresh(mode);
7459         drm_mode_set_name(mode);
7460 }
7461
7462 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7463 {
7464         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7465         uint32_t pipeconf;
7466
7467         pipeconf = 0;
7468
7469         /* we keep both pipes enabled on 830 */
7470         if (IS_I830(dev_priv))
7471                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7472
7473         if (intel_crtc->config->double_wide)
7474                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7475
7476         /* only g4x and later have fancy bpc/dither controls */
7477         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7478             IS_CHERRYVIEW(dev_priv)) {
7479                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7480                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7481                         pipeconf |= PIPECONF_DITHER_EN |
7482                                     PIPECONF_DITHER_TYPE_SP;
7483
7484                 switch (intel_crtc->config->pipe_bpp) {
7485                 case 18:
7486                         pipeconf |= PIPECONF_6BPC;
7487                         break;
7488                 case 24:
7489                         pipeconf |= PIPECONF_8BPC;
7490                         break;
7491                 case 30:
7492                         pipeconf |= PIPECONF_10BPC;
7493                         break;
7494                 default:
7495                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7496                         BUG();
7497                 }
7498         }
7499
7500         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7501                 if (INTEL_GEN(dev_priv) < 4 ||
7502                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7503                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7504                 else
7505                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7506         } else
7507                 pipeconf |= PIPECONF_PROGRESSIVE;
7508
7509         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7510              intel_crtc->config->limited_color_range)
7511                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7512
7513         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7514         POSTING_READ(PIPECONF(intel_crtc->pipe));
7515 }
7516
7517 static int i8xx_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 = 48000;
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_i8xx_lvds;
7535         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7536                 limit = &intel_limits_i8xx_dvo;
7537         } else {
7538                 limit = &intel_limits_i8xx_dac;
7539         }
7540
7541         if (!crtc_state->clock_set &&
7542             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7543                                  refclk, NULL, &crtc_state->dpll)) {
7544                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7545                 return -EINVAL;
7546         }
7547
7548         i8xx_compute_dpll(crtc, crtc_state, NULL);
7549
7550         return 0;
7551 }
7552
7553 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7554                                   struct intel_crtc_state *crtc_state)
7555 {
7556         struct drm_device *dev = crtc->base.dev;
7557         struct drm_i915_private *dev_priv = to_i915(dev);
7558         const struct intel_limit *limit;
7559         int refclk = 96000;
7560
7561         memset(&crtc_state->dpll_hw_state, 0,
7562                sizeof(crtc_state->dpll_hw_state));
7563
7564         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7565                 if (intel_panel_use_ssc(dev_priv)) {
7566                         refclk = dev_priv->vbt.lvds_ssc_freq;
7567                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7568                 }
7569
7570                 if (intel_is_dual_link_lvds(dev))
7571                         limit = &intel_limits_g4x_dual_channel_lvds;
7572                 else
7573                         limit = &intel_limits_g4x_single_channel_lvds;
7574         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7575                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7576                 limit = &intel_limits_g4x_hdmi;
7577         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7578                 limit = &intel_limits_g4x_sdvo;
7579         } else {
7580                 /* The option is for other outputs */
7581                 limit = &intel_limits_i9xx_sdvo;
7582         }
7583
7584         if (!crtc_state->clock_set &&
7585             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7586                                 refclk, NULL, &crtc_state->dpll)) {
7587                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7588                 return -EINVAL;
7589         }
7590
7591         i9xx_compute_dpll(crtc, crtc_state, NULL);
7592
7593         return 0;
7594 }
7595
7596 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7597                                   struct intel_crtc_state *crtc_state)
7598 {
7599         struct drm_device *dev = crtc->base.dev;
7600         struct drm_i915_private *dev_priv = to_i915(dev);
7601         const struct intel_limit *limit;
7602         int refclk = 96000;
7603
7604         memset(&crtc_state->dpll_hw_state, 0,
7605                sizeof(crtc_state->dpll_hw_state));
7606
7607         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7608                 if (intel_panel_use_ssc(dev_priv)) {
7609                         refclk = dev_priv->vbt.lvds_ssc_freq;
7610                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7611                 }
7612
7613                 limit = &intel_limits_pineview_lvds;
7614         } else {
7615                 limit = &intel_limits_pineview_sdvo;
7616         }
7617
7618         if (!crtc_state->clock_set &&
7619             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7620                                 refclk, NULL, &crtc_state->dpll)) {
7621                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7622                 return -EINVAL;
7623         }
7624
7625         i9xx_compute_dpll(crtc, crtc_state, NULL);
7626
7627         return 0;
7628 }
7629
7630 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7631                                    struct intel_crtc_state *crtc_state)
7632 {
7633         struct drm_device *dev = crtc->base.dev;
7634         struct drm_i915_private *dev_priv = to_i915(dev);
7635         const struct intel_limit *limit;
7636         int refclk = 96000;
7637
7638         memset(&crtc_state->dpll_hw_state, 0,
7639                sizeof(crtc_state->dpll_hw_state));
7640
7641         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7642                 if (intel_panel_use_ssc(dev_priv)) {
7643                         refclk = dev_priv->vbt.lvds_ssc_freq;
7644                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7645                 }
7646
7647                 limit = &intel_limits_i9xx_lvds;
7648         } else {
7649                 limit = &intel_limits_i9xx_sdvo;
7650         }
7651
7652         if (!crtc_state->clock_set &&
7653             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7654                                  refclk, NULL, &crtc_state->dpll)) {
7655                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7656                 return -EINVAL;
7657         }
7658
7659         i9xx_compute_dpll(crtc, crtc_state, NULL);
7660
7661         return 0;
7662 }
7663
7664 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7665                                   struct intel_crtc_state *crtc_state)
7666 {
7667         int refclk = 100000;
7668         const struct intel_limit *limit = &intel_limits_chv;
7669
7670         memset(&crtc_state->dpll_hw_state, 0,
7671                sizeof(crtc_state->dpll_hw_state));
7672
7673         if (!crtc_state->clock_set &&
7674             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7675                                 refclk, NULL, &crtc_state->dpll)) {
7676                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7677                 return -EINVAL;
7678         }
7679
7680         chv_compute_dpll(crtc, crtc_state);
7681
7682         return 0;
7683 }
7684
7685 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7686                                   struct intel_crtc_state *crtc_state)
7687 {
7688         int refclk = 100000;
7689         const struct intel_limit *limit = &intel_limits_vlv;
7690
7691         memset(&crtc_state->dpll_hw_state, 0,
7692                sizeof(crtc_state->dpll_hw_state));
7693
7694         if (!crtc_state->clock_set &&
7695             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7696                                 refclk, NULL, &crtc_state->dpll)) {
7697                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7698                 return -EINVAL;
7699         }
7700
7701         vlv_compute_dpll(crtc, crtc_state);
7702
7703         return 0;
7704 }
7705
7706 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7707                                  struct intel_crtc_state *pipe_config)
7708 {
7709         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7710         uint32_t tmp;
7711
7712         if (INTEL_GEN(dev_priv) <= 3 &&
7713             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7714                 return;
7715
7716         tmp = I915_READ(PFIT_CONTROL);
7717         if (!(tmp & PFIT_ENABLE))
7718                 return;
7719
7720         /* Check whether the pfit is attached to our pipe. */
7721         if (INTEL_GEN(dev_priv) < 4) {
7722                 if (crtc->pipe != PIPE_B)
7723                         return;
7724         } else {
7725                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7726                         return;
7727         }
7728
7729         pipe_config->gmch_pfit.control = tmp;
7730         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7731 }
7732
7733 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7734                                struct intel_crtc_state *pipe_config)
7735 {
7736         struct drm_device *dev = crtc->base.dev;
7737         struct drm_i915_private *dev_priv = to_i915(dev);
7738         int pipe = pipe_config->cpu_transcoder;
7739         struct dpll clock;
7740         u32 mdiv;
7741         int refclk = 100000;
7742
7743         /* In case of DSI, DPLL will not be used */
7744         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7745                 return;
7746
7747         mutex_lock(&dev_priv->sb_lock);
7748         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7749         mutex_unlock(&dev_priv->sb_lock);
7750
7751         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7752         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7753         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7754         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7755         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7756
7757         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7758 }
7759
7760 static void
7761 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7762                               struct intel_initial_plane_config *plane_config)
7763 {
7764         struct drm_device *dev = crtc->base.dev;
7765         struct drm_i915_private *dev_priv = to_i915(dev);
7766         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7767         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7768         enum pipe pipe;
7769         u32 val, base, offset;
7770         int fourcc, pixel_format;
7771         unsigned int aligned_height;
7772         struct drm_framebuffer *fb;
7773         struct intel_framebuffer *intel_fb;
7774
7775         if (!plane->get_hw_state(plane, &pipe))
7776                 return;
7777
7778         WARN_ON(pipe != crtc->pipe);
7779
7780         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7781         if (!intel_fb) {
7782                 DRM_DEBUG_KMS("failed to alloc fb\n");
7783                 return;
7784         }
7785
7786         fb = &intel_fb->base;
7787
7788         fb->dev = dev;
7789
7790         val = I915_READ(DSPCNTR(i9xx_plane));
7791
7792         if (INTEL_GEN(dev_priv) >= 4) {
7793                 if (val & DISPPLANE_TILED) {
7794                         plane_config->tiling = I915_TILING_X;
7795                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7796                 }
7797         }
7798
7799         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7800         fourcc = i9xx_format_to_fourcc(pixel_format);
7801         fb->format = drm_format_info(fourcc);
7802
7803         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7804                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7805                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7806         } else if (INTEL_GEN(dev_priv) >= 4) {
7807                 if (plane_config->tiling)
7808                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7809                 else
7810                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7811                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7812         } else {
7813                 base = I915_READ(DSPADDR(i9xx_plane));
7814         }
7815         plane_config->base = base;
7816
7817         val = I915_READ(PIPESRC(pipe));
7818         fb->width = ((val >> 16) & 0xfff) + 1;
7819         fb->height = ((val >> 0) & 0xfff) + 1;
7820
7821         val = I915_READ(DSPSTRIDE(i9xx_plane));
7822         fb->pitches[0] = val & 0xffffffc0;
7823
7824         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7825
7826         plane_config->size = fb->pitches[0] * aligned_height;
7827
7828         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7829                       crtc->base.name, plane->base.name, fb->width, fb->height,
7830                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7831                       plane_config->size);
7832
7833         plane_config->fb = intel_fb;
7834 }
7835
7836 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7837                                struct intel_crtc_state *pipe_config)
7838 {
7839         struct drm_device *dev = crtc->base.dev;
7840         struct drm_i915_private *dev_priv = to_i915(dev);
7841         int pipe = pipe_config->cpu_transcoder;
7842         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7843         struct dpll clock;
7844         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7845         int refclk = 100000;
7846
7847         /* In case of DSI, DPLL will not be used */
7848         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7849                 return;
7850
7851         mutex_lock(&dev_priv->sb_lock);
7852         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7853         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7854         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7855         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7856         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7857         mutex_unlock(&dev_priv->sb_lock);
7858
7859         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7860         clock.m2 = (pll_dw0 & 0xff) << 22;
7861         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7862                 clock.m2 |= pll_dw2 & 0x3fffff;
7863         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7864         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7865         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7866
7867         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7868 }
7869
7870 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7871                                  struct intel_crtc_state *pipe_config)
7872 {
7873         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7874         enum intel_display_power_domain power_domain;
7875         uint32_t tmp;
7876         bool ret;
7877
7878         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7879         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7880                 return false;
7881
7882         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7883         pipe_config->shared_dpll = NULL;
7884
7885         ret = false;
7886
7887         tmp = I915_READ(PIPECONF(crtc->pipe));
7888         if (!(tmp & PIPECONF_ENABLE))
7889                 goto out;
7890
7891         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7892             IS_CHERRYVIEW(dev_priv)) {
7893                 switch (tmp & PIPECONF_BPC_MASK) {
7894                 case PIPECONF_6BPC:
7895                         pipe_config->pipe_bpp = 18;
7896                         break;
7897                 case PIPECONF_8BPC:
7898                         pipe_config->pipe_bpp = 24;
7899                         break;
7900                 case PIPECONF_10BPC:
7901                         pipe_config->pipe_bpp = 30;
7902                         break;
7903                 default:
7904                         break;
7905                 }
7906         }
7907
7908         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7909             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7910                 pipe_config->limited_color_range = true;
7911
7912         if (INTEL_GEN(dev_priv) < 4)
7913                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7914
7915         intel_get_pipe_timings(crtc, pipe_config);
7916         intel_get_pipe_src_size(crtc, pipe_config);
7917
7918         i9xx_get_pfit_config(crtc, pipe_config);
7919
7920         if (INTEL_GEN(dev_priv) >= 4) {
7921                 /* No way to read it out on pipes B and C */
7922                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7923                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7924                 else
7925                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7926                 pipe_config->pixel_multiplier =
7927                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7928                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7929                 pipe_config->dpll_hw_state.dpll_md = tmp;
7930         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7931                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7932                 tmp = I915_READ(DPLL(crtc->pipe));
7933                 pipe_config->pixel_multiplier =
7934                         ((tmp & SDVO_MULTIPLIER_MASK)
7935                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7936         } else {
7937                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7938                  * port and will be fixed up in the encoder->get_config
7939                  * function. */
7940                 pipe_config->pixel_multiplier = 1;
7941         }
7942         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7943         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7944                 /*
7945                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7946                  * on 830. Filter it out here so that we don't
7947                  * report errors due to that.
7948                  */
7949                 if (IS_I830(dev_priv))
7950                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7951
7952                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7953                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7954         } else {
7955                 /* Mask out read-only status bits. */
7956                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7957                                                      DPLL_PORTC_READY_MASK |
7958                                                      DPLL_PORTB_READY_MASK);
7959         }
7960
7961         if (IS_CHERRYVIEW(dev_priv))
7962                 chv_crtc_clock_get(crtc, pipe_config);
7963         else if (IS_VALLEYVIEW(dev_priv))
7964                 vlv_crtc_clock_get(crtc, pipe_config);
7965         else
7966                 i9xx_crtc_clock_get(crtc, pipe_config);
7967
7968         /*
7969          * Normally the dotclock is filled in by the encoder .get_config()
7970          * but in case the pipe is enabled w/o any ports we need a sane
7971          * default.
7972          */
7973         pipe_config->base.adjusted_mode.crtc_clock =
7974                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7975
7976         ret = true;
7977
7978 out:
7979         intel_display_power_put(dev_priv, power_domain);
7980
7981         return ret;
7982 }
7983
7984 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7985 {
7986         struct intel_encoder *encoder;
7987         int i;
7988         u32 val, final;
7989         bool has_lvds = false;
7990         bool has_cpu_edp = false;
7991         bool has_panel = false;
7992         bool has_ck505 = false;
7993         bool can_ssc = false;
7994         bool using_ssc_source = false;
7995
7996         /* We need to take the global config into account */
7997         for_each_intel_encoder(&dev_priv->drm, encoder) {
7998                 switch (encoder->type) {
7999                 case INTEL_OUTPUT_LVDS:
8000                         has_panel = true;
8001                         has_lvds = true;
8002                         break;
8003                 case INTEL_OUTPUT_EDP:
8004                         has_panel = true;
8005                         if (encoder->port == PORT_A)
8006                                 has_cpu_edp = true;
8007                         break;
8008                 default:
8009                         break;
8010                 }
8011         }
8012
8013         if (HAS_PCH_IBX(dev_priv)) {
8014                 has_ck505 = dev_priv->vbt.display_clock_mode;
8015                 can_ssc = has_ck505;
8016         } else {
8017                 has_ck505 = false;
8018                 can_ssc = true;
8019         }
8020
8021         /* Check if any DPLLs are using the SSC source */
8022         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8023                 u32 temp = I915_READ(PCH_DPLL(i));
8024
8025                 if (!(temp & DPLL_VCO_ENABLE))
8026                         continue;
8027
8028                 if ((temp & PLL_REF_INPUT_MASK) ==
8029                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8030                         using_ssc_source = true;
8031                         break;
8032                 }
8033         }
8034
8035         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8036                       has_panel, has_lvds, has_ck505, using_ssc_source);
8037
8038         /* Ironlake: try to setup display ref clock before DPLL
8039          * enabling. This is only under driver's control after
8040          * PCH B stepping, previous chipset stepping should be
8041          * ignoring this setting.
8042          */
8043         val = I915_READ(PCH_DREF_CONTROL);
8044
8045         /* As we must carefully and slowly disable/enable each source in turn,
8046          * compute the final state we want first and check if we need to
8047          * make any changes at all.
8048          */
8049         final = val;
8050         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8051         if (has_ck505)
8052                 final |= DREF_NONSPREAD_CK505_ENABLE;
8053         else
8054                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8055
8056         final &= ~DREF_SSC_SOURCE_MASK;
8057         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8058         final &= ~DREF_SSC1_ENABLE;
8059
8060         if (has_panel) {
8061                 final |= DREF_SSC_SOURCE_ENABLE;
8062
8063                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8064                         final |= DREF_SSC1_ENABLE;
8065
8066                 if (has_cpu_edp) {
8067                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8068                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8069                         else
8070                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8071                 } else
8072                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8073         } else if (using_ssc_source) {
8074                 final |= DREF_SSC_SOURCE_ENABLE;
8075                 final |= DREF_SSC1_ENABLE;
8076         }
8077
8078         if (final == val)
8079                 return;
8080
8081         /* Always enable nonspread source */
8082         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8083
8084         if (has_ck505)
8085                 val |= DREF_NONSPREAD_CK505_ENABLE;
8086         else
8087                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8088
8089         if (has_panel) {
8090                 val &= ~DREF_SSC_SOURCE_MASK;
8091                 val |= DREF_SSC_SOURCE_ENABLE;
8092
8093                 /* SSC must be turned on before enabling the CPU output  */
8094                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8095                         DRM_DEBUG_KMS("Using SSC on panel\n");
8096                         val |= DREF_SSC1_ENABLE;
8097                 } else
8098                         val &= ~DREF_SSC1_ENABLE;
8099
8100                 /* Get SSC going before enabling the outputs */
8101                 I915_WRITE(PCH_DREF_CONTROL, val);
8102                 POSTING_READ(PCH_DREF_CONTROL);
8103                 udelay(200);
8104
8105                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8106
8107                 /* Enable CPU source on CPU attached eDP */
8108                 if (has_cpu_edp) {
8109                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8110                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8111                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8112                         } else
8113                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8114                 } else
8115                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8116
8117                 I915_WRITE(PCH_DREF_CONTROL, val);
8118                 POSTING_READ(PCH_DREF_CONTROL);
8119                 udelay(200);
8120         } else {
8121                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8122
8123                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8124
8125                 /* Turn off CPU output */
8126                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8127
8128                 I915_WRITE(PCH_DREF_CONTROL, val);
8129                 POSTING_READ(PCH_DREF_CONTROL);
8130                 udelay(200);
8131
8132                 if (!using_ssc_source) {
8133                         DRM_DEBUG_KMS("Disabling SSC source\n");
8134
8135                         /* Turn off the SSC source */
8136                         val &= ~DREF_SSC_SOURCE_MASK;
8137                         val |= DREF_SSC_SOURCE_DISABLE;
8138
8139                         /* Turn off SSC1 */
8140                         val &= ~DREF_SSC1_ENABLE;
8141
8142                         I915_WRITE(PCH_DREF_CONTROL, val);
8143                         POSTING_READ(PCH_DREF_CONTROL);
8144                         udelay(200);
8145                 }
8146         }
8147
8148         BUG_ON(val != final);
8149 }
8150
8151 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8152 {
8153         uint32_t tmp;
8154
8155         tmp = I915_READ(SOUTH_CHICKEN2);
8156         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8157         I915_WRITE(SOUTH_CHICKEN2, tmp);
8158
8159         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8160                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8161                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8162
8163         tmp = I915_READ(SOUTH_CHICKEN2);
8164         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8165         I915_WRITE(SOUTH_CHICKEN2, tmp);
8166
8167         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8168                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8169                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8170 }
8171
8172 /* WaMPhyProgramming:hsw */
8173 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8174 {
8175         uint32_t tmp;
8176
8177         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8178         tmp &= ~(0xFF << 24);
8179         tmp |= (0x12 << 24);
8180         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8181
8182         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8183         tmp |= (1 << 11);
8184         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8185
8186         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8187         tmp |= (1 << 11);
8188         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8189
8190         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8191         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8192         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8193
8194         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8195         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8196         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8197
8198         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8199         tmp &= ~(7 << 13);
8200         tmp |= (5 << 13);
8201         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8202
8203         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8204         tmp &= ~(7 << 13);
8205         tmp |= (5 << 13);
8206         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8207
8208         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8209         tmp &= ~0xFF;
8210         tmp |= 0x1C;
8211         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8212
8213         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8214         tmp &= ~0xFF;
8215         tmp |= 0x1C;
8216         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8217
8218         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8219         tmp &= ~(0xFF << 16);
8220         tmp |= (0x1C << 16);
8221         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8222
8223         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8224         tmp &= ~(0xFF << 16);
8225         tmp |= (0x1C << 16);
8226         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8227
8228         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8229         tmp |= (1 << 27);
8230         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8231
8232         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8233         tmp |= (1 << 27);
8234         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8235
8236         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8237         tmp &= ~(0xF << 28);
8238         tmp |= (4 << 28);
8239         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8240
8241         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8242         tmp &= ~(0xF << 28);
8243         tmp |= (4 << 28);
8244         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8245 }
8246
8247 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8248  * Programming" based on the parameters passed:
8249  * - Sequence to enable CLKOUT_DP
8250  * - Sequence to enable CLKOUT_DP without spread
8251  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8252  */
8253 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8254                                  bool with_spread, bool with_fdi)
8255 {
8256         uint32_t reg, tmp;
8257
8258         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8259                 with_spread = true;
8260         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8261             with_fdi, "LP PCH doesn't have FDI\n"))
8262                 with_fdi = false;
8263
8264         mutex_lock(&dev_priv->sb_lock);
8265
8266         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8267         tmp &= ~SBI_SSCCTL_DISABLE;
8268         tmp |= SBI_SSCCTL_PATHALT;
8269         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8270
8271         udelay(24);
8272
8273         if (with_spread) {
8274                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8275                 tmp &= ~SBI_SSCCTL_PATHALT;
8276                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8277
8278                 if (with_fdi) {
8279                         lpt_reset_fdi_mphy(dev_priv);
8280                         lpt_program_fdi_mphy(dev_priv);
8281                 }
8282         }
8283
8284         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8285         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8286         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8287         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8288
8289         mutex_unlock(&dev_priv->sb_lock);
8290 }
8291
8292 /* Sequence to disable CLKOUT_DP */
8293 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8294 {
8295         uint32_t reg, tmp;
8296
8297         mutex_lock(&dev_priv->sb_lock);
8298
8299         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8300         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8301         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8302         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8303
8304         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8305         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8306                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8307                         tmp |= SBI_SSCCTL_PATHALT;
8308                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8309                         udelay(32);
8310                 }
8311                 tmp |= SBI_SSCCTL_DISABLE;
8312                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8313         }
8314
8315         mutex_unlock(&dev_priv->sb_lock);
8316 }
8317
8318 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8319
8320 static const uint16_t sscdivintphase[] = {
8321         [BEND_IDX( 50)] = 0x3B23,
8322         [BEND_IDX( 45)] = 0x3B23,
8323         [BEND_IDX( 40)] = 0x3C23,
8324         [BEND_IDX( 35)] = 0x3C23,
8325         [BEND_IDX( 30)] = 0x3D23,
8326         [BEND_IDX( 25)] = 0x3D23,
8327         [BEND_IDX( 20)] = 0x3E23,
8328         [BEND_IDX( 15)] = 0x3E23,
8329         [BEND_IDX( 10)] = 0x3F23,
8330         [BEND_IDX(  5)] = 0x3F23,
8331         [BEND_IDX(  0)] = 0x0025,
8332         [BEND_IDX( -5)] = 0x0025,
8333         [BEND_IDX(-10)] = 0x0125,
8334         [BEND_IDX(-15)] = 0x0125,
8335         [BEND_IDX(-20)] = 0x0225,
8336         [BEND_IDX(-25)] = 0x0225,
8337         [BEND_IDX(-30)] = 0x0325,
8338         [BEND_IDX(-35)] = 0x0325,
8339         [BEND_IDX(-40)] = 0x0425,
8340         [BEND_IDX(-45)] = 0x0425,
8341         [BEND_IDX(-50)] = 0x0525,
8342 };
8343
8344 /*
8345  * Bend CLKOUT_DP
8346  * steps -50 to 50 inclusive, in steps of 5
8347  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8348  * change in clock period = -(steps / 10) * 5.787 ps
8349  */
8350 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8351 {
8352         uint32_t tmp;
8353         int idx = BEND_IDX(steps);
8354
8355         if (WARN_ON(steps % 5 != 0))
8356                 return;
8357
8358         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8359                 return;
8360
8361         mutex_lock(&dev_priv->sb_lock);
8362
8363         if (steps % 10 != 0)
8364                 tmp = 0xAAAAAAAB;
8365         else
8366                 tmp = 0x00000000;
8367         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8368
8369         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8370         tmp &= 0xffff0000;
8371         tmp |= sscdivintphase[idx];
8372         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8373
8374         mutex_unlock(&dev_priv->sb_lock);
8375 }
8376
8377 #undef BEND_IDX
8378
8379 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8380 {
8381         struct intel_encoder *encoder;
8382         bool has_vga = false;
8383
8384         for_each_intel_encoder(&dev_priv->drm, encoder) {
8385                 switch (encoder->type) {
8386                 case INTEL_OUTPUT_ANALOG:
8387                         has_vga = true;
8388                         break;
8389                 default:
8390                         break;
8391                 }
8392         }
8393
8394         if (has_vga) {
8395                 lpt_bend_clkout_dp(dev_priv, 0);
8396                 lpt_enable_clkout_dp(dev_priv, true, true);
8397         } else {
8398                 lpt_disable_clkout_dp(dev_priv);
8399         }
8400 }
8401
8402 /*
8403  * Initialize reference clocks when the driver loads
8404  */
8405 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8406 {
8407         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8408                 ironlake_init_pch_refclk(dev_priv);
8409         else if (HAS_PCH_LPT(dev_priv))
8410                 lpt_init_pch_refclk(dev_priv);
8411 }
8412
8413 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8414 {
8415         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8416         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8417         int pipe = intel_crtc->pipe;
8418         uint32_t val;
8419
8420         val = 0;
8421
8422         switch (intel_crtc->config->pipe_bpp) {
8423         case 18:
8424                 val |= PIPECONF_6BPC;
8425                 break;
8426         case 24:
8427                 val |= PIPECONF_8BPC;
8428                 break;
8429         case 30:
8430                 val |= PIPECONF_10BPC;
8431                 break;
8432         case 36:
8433                 val |= PIPECONF_12BPC;
8434                 break;
8435         default:
8436                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8437                 BUG();
8438         }
8439
8440         if (intel_crtc->config->dither)
8441                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8442
8443         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8444                 val |= PIPECONF_INTERLACED_ILK;
8445         else
8446                 val |= PIPECONF_PROGRESSIVE;
8447
8448         if (intel_crtc->config->limited_color_range)
8449                 val |= PIPECONF_COLOR_RANGE_SELECT;
8450
8451         I915_WRITE(PIPECONF(pipe), val);
8452         POSTING_READ(PIPECONF(pipe));
8453 }
8454
8455 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8456 {
8457         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8458         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8459         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8460         u32 val = 0;
8461
8462         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8463                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8464
8465         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8466                 val |= PIPECONF_INTERLACED_ILK;
8467         else
8468                 val |= PIPECONF_PROGRESSIVE;
8469
8470         I915_WRITE(PIPECONF(cpu_transcoder), val);
8471         POSTING_READ(PIPECONF(cpu_transcoder));
8472 }
8473
8474 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8475 {
8476         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8477         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8478         struct intel_crtc_state *config = intel_crtc->config;
8479
8480         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8481                 u32 val = 0;
8482
8483                 switch (intel_crtc->config->pipe_bpp) {
8484                 case 18:
8485                         val |= PIPEMISC_DITHER_6_BPC;
8486                         break;
8487                 case 24:
8488                         val |= PIPEMISC_DITHER_8_BPC;
8489                         break;
8490                 case 30:
8491                         val |= PIPEMISC_DITHER_10_BPC;
8492                         break;
8493                 case 36:
8494                         val |= PIPEMISC_DITHER_12_BPC;
8495                         break;
8496                 default:
8497                         /* Case prevented by pipe_config_set_bpp. */
8498                         BUG();
8499                 }
8500
8501                 if (intel_crtc->config->dither)
8502                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8503
8504                 if (config->ycbcr420) {
8505                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8506                                 PIPEMISC_YUV420_ENABLE |
8507                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8508                 }
8509
8510                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8511         }
8512 }
8513
8514 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8515 {
8516         /*
8517          * Account for spread spectrum to avoid
8518          * oversubscribing the link. Max center spread
8519          * is 2.5%; use 5% for safety's sake.
8520          */
8521         u32 bps = target_clock * bpp * 21 / 20;
8522         return DIV_ROUND_UP(bps, link_bw * 8);
8523 }
8524
8525 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8526 {
8527         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8528 }
8529
8530 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8531                                   struct intel_crtc_state *crtc_state,
8532                                   struct dpll *reduced_clock)
8533 {
8534         struct drm_crtc *crtc = &intel_crtc->base;
8535         struct drm_device *dev = crtc->dev;
8536         struct drm_i915_private *dev_priv = to_i915(dev);
8537         u32 dpll, fp, fp2;
8538         int factor;
8539
8540         /* Enable autotuning of the PLL clock (if permissible) */
8541         factor = 21;
8542         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8543                 if ((intel_panel_use_ssc(dev_priv) &&
8544                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8545                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8546                         factor = 25;
8547         } else if (crtc_state->sdvo_tv_clock)
8548                 factor = 20;
8549
8550         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8551
8552         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8553                 fp |= FP_CB_TUNE;
8554
8555         if (reduced_clock) {
8556                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8557
8558                 if (reduced_clock->m < factor * reduced_clock->n)
8559                         fp2 |= FP_CB_TUNE;
8560         } else {
8561                 fp2 = fp;
8562         }
8563
8564         dpll = 0;
8565
8566         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8567                 dpll |= DPLLB_MODE_LVDS;
8568         else
8569                 dpll |= DPLLB_MODE_DAC_SERIAL;
8570
8571         dpll |= (crtc_state->pixel_multiplier - 1)
8572                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8573
8574         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8575             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8576                 dpll |= DPLL_SDVO_HIGH_SPEED;
8577
8578         if (intel_crtc_has_dp_encoder(crtc_state))
8579                 dpll |= DPLL_SDVO_HIGH_SPEED;
8580
8581         /*
8582          * The high speed IO clock is only really required for
8583          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8584          * possible to share the DPLL between CRT and HDMI. Enabling
8585          * the clock needlessly does no real harm, except use up a
8586          * bit of power potentially.
8587          *
8588          * We'll limit this to IVB with 3 pipes, since it has only two
8589          * DPLLs and so DPLL sharing is the only way to get three pipes
8590          * driving PCH ports at the same time. On SNB we could do this,
8591          * and potentially avoid enabling the second DPLL, but it's not
8592          * clear if it''s a win or loss power wise. No point in doing
8593          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8594          */
8595         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8596             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8597                 dpll |= DPLL_SDVO_HIGH_SPEED;
8598
8599         /* compute bitmask from p1 value */
8600         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8601         /* also FPA1 */
8602         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8603
8604         switch (crtc_state->dpll.p2) {
8605         case 5:
8606                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8607                 break;
8608         case 7:
8609                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8610                 break;
8611         case 10:
8612                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8613                 break;
8614         case 14:
8615                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8616                 break;
8617         }
8618
8619         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8620             intel_panel_use_ssc(dev_priv))
8621                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8622         else
8623                 dpll |= PLL_REF_INPUT_DREFCLK;
8624
8625         dpll |= DPLL_VCO_ENABLE;
8626
8627         crtc_state->dpll_hw_state.dpll = dpll;
8628         crtc_state->dpll_hw_state.fp0 = fp;
8629         crtc_state->dpll_hw_state.fp1 = fp2;
8630 }
8631
8632 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8633                                        struct intel_crtc_state *crtc_state)
8634 {
8635         struct drm_device *dev = crtc->base.dev;
8636         struct drm_i915_private *dev_priv = to_i915(dev);
8637         const struct intel_limit *limit;
8638         int refclk = 120000;
8639
8640         memset(&crtc_state->dpll_hw_state, 0,
8641                sizeof(crtc_state->dpll_hw_state));
8642
8643         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8644         if (!crtc_state->has_pch_encoder)
8645                 return 0;
8646
8647         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8648                 if (intel_panel_use_ssc(dev_priv)) {
8649                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8650                                       dev_priv->vbt.lvds_ssc_freq);
8651                         refclk = dev_priv->vbt.lvds_ssc_freq;
8652                 }
8653
8654                 if (intel_is_dual_link_lvds(dev)) {
8655                         if (refclk == 100000)
8656                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8657                         else
8658                                 limit = &intel_limits_ironlake_dual_lvds;
8659                 } else {
8660                         if (refclk == 100000)
8661                                 limit = &intel_limits_ironlake_single_lvds_100m;
8662                         else
8663                                 limit = &intel_limits_ironlake_single_lvds;
8664                 }
8665         } else {
8666                 limit = &intel_limits_ironlake_dac;
8667         }
8668
8669         if (!crtc_state->clock_set &&
8670             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8671                                 refclk, NULL, &crtc_state->dpll)) {
8672                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8673                 return -EINVAL;
8674         }
8675
8676         ironlake_compute_dpll(crtc, crtc_state, NULL);
8677
8678         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8679                 DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
8680                               pipe_name(crtc->pipe));
8681                 return -EINVAL;
8682         }
8683
8684         return 0;
8685 }
8686
8687 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8688                                          struct intel_link_m_n *m_n)
8689 {
8690         struct drm_device *dev = crtc->base.dev;
8691         struct drm_i915_private *dev_priv = to_i915(dev);
8692         enum pipe pipe = crtc->pipe;
8693
8694         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8695         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8696         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8697                 & ~TU_SIZE_MASK;
8698         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8699         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8700                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8701 }
8702
8703 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8704                                          enum transcoder transcoder,
8705                                          struct intel_link_m_n *m_n,
8706                                          struct intel_link_m_n *m2_n2)
8707 {
8708         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8709         enum pipe pipe = crtc->pipe;
8710
8711         if (INTEL_GEN(dev_priv) >= 5) {
8712                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8713                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8714                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8715                         & ~TU_SIZE_MASK;
8716                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8717                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8718                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8719                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8720                  * gen < 8) and if DRRS is supported (to make sure the
8721                  * registers are not unnecessarily read).
8722                  */
8723                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8724                         crtc->config->has_drrs) {
8725                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8726                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8727                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8728                                         & ~TU_SIZE_MASK;
8729                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8730                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8731                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8732                 }
8733         } else {
8734                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8735                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8736                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8737                         & ~TU_SIZE_MASK;
8738                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8739                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8740                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8741         }
8742 }
8743
8744 void intel_dp_get_m_n(struct intel_crtc *crtc,
8745                       struct intel_crtc_state *pipe_config)
8746 {
8747         if (pipe_config->has_pch_encoder)
8748                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8749         else
8750                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8751                                              &pipe_config->dp_m_n,
8752                                              &pipe_config->dp_m2_n2);
8753 }
8754
8755 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8756                                         struct intel_crtc_state *pipe_config)
8757 {
8758         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8759                                      &pipe_config->fdi_m_n, NULL);
8760 }
8761
8762 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8763                                     struct intel_crtc_state *pipe_config)
8764 {
8765         struct drm_device *dev = crtc->base.dev;
8766         struct drm_i915_private *dev_priv = to_i915(dev);
8767         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8768         uint32_t ps_ctrl = 0;
8769         int id = -1;
8770         int i;
8771
8772         /* find scaler attached to this pipe */
8773         for (i = 0; i < crtc->num_scalers; i++) {
8774                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8775                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8776                         id = i;
8777                         pipe_config->pch_pfit.enabled = true;
8778                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8779                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8780                         break;
8781                 }
8782         }
8783
8784         scaler_state->scaler_id = id;
8785         if (id >= 0) {
8786                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8787         } else {
8788                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8789         }
8790 }
8791
8792 static void
8793 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8794                                  struct intel_initial_plane_config *plane_config)
8795 {
8796         struct drm_device *dev = crtc->base.dev;
8797         struct drm_i915_private *dev_priv = to_i915(dev);
8798         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8799         enum plane_id plane_id = plane->id;
8800         enum pipe pipe;
8801         u32 val, base, offset, stride_mult, tiling, alpha;
8802         int fourcc, pixel_format;
8803         unsigned int aligned_height;
8804         struct drm_framebuffer *fb;
8805         struct intel_framebuffer *intel_fb;
8806
8807         if (!plane->get_hw_state(plane, &pipe))
8808                 return;
8809
8810         WARN_ON(pipe != crtc->pipe);
8811
8812         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8813         if (!intel_fb) {
8814                 DRM_DEBUG_KMS("failed to alloc fb\n");
8815                 return;
8816         }
8817
8818         fb = &intel_fb->base;
8819
8820         fb->dev = dev;
8821
8822         val = I915_READ(PLANE_CTL(pipe, plane_id));
8823
8824         if (INTEL_GEN(dev_priv) >= 11)
8825                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8826         else
8827                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8828
8829         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8830                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8831                 alpha &= PLANE_COLOR_ALPHA_MASK;
8832         } else {
8833                 alpha = val & PLANE_CTL_ALPHA_MASK;
8834         }
8835
8836         fourcc = skl_format_to_fourcc(pixel_format,
8837                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8838         fb->format = drm_format_info(fourcc);
8839
8840         tiling = val & PLANE_CTL_TILED_MASK;
8841         switch (tiling) {
8842         case PLANE_CTL_TILED_LINEAR:
8843                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8844                 break;
8845         case PLANE_CTL_TILED_X:
8846                 plane_config->tiling = I915_TILING_X;
8847                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8848                 break;
8849         case PLANE_CTL_TILED_Y:
8850                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8851                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8852                 else
8853                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8854                 break;
8855         case PLANE_CTL_TILED_YF:
8856                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8857                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8858                 else
8859                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8860                 break;
8861         default:
8862                 MISSING_CASE(tiling);
8863                 goto error;
8864         }
8865
8866         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8867         plane_config->base = base;
8868
8869         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8870
8871         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8872         fb->height = ((val >> 16) & 0xfff) + 1;
8873         fb->width = ((val >> 0) & 0x1fff) + 1;
8874
8875         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8876         stride_mult = intel_fb_stride_alignment(fb, 0);
8877         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8878
8879         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8880
8881         plane_config->size = fb->pitches[0] * aligned_height;
8882
8883         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8884                       crtc->base.name, plane->base.name, fb->width, fb->height,
8885                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8886                       plane_config->size);
8887
8888         plane_config->fb = intel_fb;
8889         return;
8890
8891 error:
8892         kfree(intel_fb);
8893 }
8894
8895 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8896                                      struct intel_crtc_state *pipe_config)
8897 {
8898         struct drm_device *dev = crtc->base.dev;
8899         struct drm_i915_private *dev_priv = to_i915(dev);
8900         uint32_t tmp;
8901
8902         tmp = I915_READ(PF_CTL(crtc->pipe));
8903
8904         if (tmp & PF_ENABLE) {
8905                 pipe_config->pch_pfit.enabled = true;
8906                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8907                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8908
8909                 /* We currently do not free assignements of panel fitters on
8910                  * ivb/hsw (since we don't use the higher upscaling modes which
8911                  * differentiates them) so just WARN about this case for now. */
8912                 if (IS_GEN7(dev_priv)) {
8913                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8914                                 PF_PIPE_SEL_IVB(crtc->pipe));
8915                 }
8916         }
8917 }
8918
8919 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8920                                      struct intel_crtc_state *pipe_config)
8921 {
8922         struct drm_device *dev = crtc->base.dev;
8923         struct drm_i915_private *dev_priv = to_i915(dev);
8924         enum intel_display_power_domain power_domain;
8925         uint32_t tmp;
8926         bool ret;
8927
8928         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8929         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8930                 return false;
8931
8932         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8933         pipe_config->shared_dpll = NULL;
8934
8935         ret = false;
8936         tmp = I915_READ(PIPECONF(crtc->pipe));
8937         if (!(tmp & PIPECONF_ENABLE))
8938                 goto out;
8939
8940         switch (tmp & PIPECONF_BPC_MASK) {
8941         case PIPECONF_6BPC:
8942                 pipe_config->pipe_bpp = 18;
8943                 break;
8944         case PIPECONF_8BPC:
8945                 pipe_config->pipe_bpp = 24;
8946                 break;
8947         case PIPECONF_10BPC:
8948                 pipe_config->pipe_bpp = 30;
8949                 break;
8950         case PIPECONF_12BPC:
8951                 pipe_config->pipe_bpp = 36;
8952                 break;
8953         default:
8954                 break;
8955         }
8956
8957         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8958                 pipe_config->limited_color_range = true;
8959
8960         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8961                 struct intel_shared_dpll *pll;
8962                 enum intel_dpll_id pll_id;
8963
8964                 pipe_config->has_pch_encoder = true;
8965
8966                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8967                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8968                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8969
8970                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8971
8972                 if (HAS_PCH_IBX(dev_priv)) {
8973                         /*
8974                          * The pipe->pch transcoder and pch transcoder->pll
8975                          * mapping is fixed.
8976                          */
8977                         pll_id = (enum intel_dpll_id) crtc->pipe;
8978                 } else {
8979                         tmp = I915_READ(PCH_DPLL_SEL);
8980                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8981                                 pll_id = DPLL_ID_PCH_PLL_B;
8982                         else
8983                                 pll_id= DPLL_ID_PCH_PLL_A;
8984                 }
8985
8986                 pipe_config->shared_dpll =
8987                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8988                 pll = pipe_config->shared_dpll;
8989
8990                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
8991                                                 &pipe_config->dpll_hw_state));
8992
8993                 tmp = pipe_config->dpll_hw_state.dpll;
8994                 pipe_config->pixel_multiplier =
8995                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8996                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8997
8998                 ironlake_pch_clock_get(crtc, pipe_config);
8999         } else {
9000                 pipe_config->pixel_multiplier = 1;
9001         }
9002
9003         intel_get_pipe_timings(crtc, pipe_config);
9004         intel_get_pipe_src_size(crtc, pipe_config);
9005
9006         ironlake_get_pfit_config(crtc, pipe_config);
9007
9008         ret = true;
9009
9010 out:
9011         intel_display_power_put(dev_priv, power_domain);
9012
9013         return ret;
9014 }
9015
9016 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9017 {
9018         struct drm_device *dev = &dev_priv->drm;
9019         struct intel_crtc *crtc;
9020
9021         for_each_intel_crtc(dev, crtc)
9022                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9023                      pipe_name(crtc->pipe));
9024
9025         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL2),
9026                         "Display power well on\n");
9027         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9028         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9029         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9030         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
9031         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9032              "CPU PWM1 enabled\n");
9033         if (IS_HASWELL(dev_priv))
9034                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9035                      "CPU PWM2 enabled\n");
9036         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9037              "PCH PWM1 enabled\n");
9038         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9039              "Utility pin enabled\n");
9040         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9041
9042         /*
9043          * In theory we can still leave IRQs enabled, as long as only the HPD
9044          * interrupts remain enabled. We used to check for that, but since it's
9045          * gen-specific and since we only disable LCPLL after we fully disable
9046          * the interrupts, the check below should be enough.
9047          */
9048         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9049 }
9050
9051 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9052 {
9053         if (IS_HASWELL(dev_priv))
9054                 return I915_READ(D_COMP_HSW);
9055         else
9056                 return I915_READ(D_COMP_BDW);
9057 }
9058
9059 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9060 {
9061         if (IS_HASWELL(dev_priv)) {
9062                 mutex_lock(&dev_priv->pcu_lock);
9063                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9064                                             val))
9065                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
9066                 mutex_unlock(&dev_priv->pcu_lock);
9067         } else {
9068                 I915_WRITE(D_COMP_BDW, val);
9069                 POSTING_READ(D_COMP_BDW);
9070         }
9071 }
9072
9073 /*
9074  * This function implements pieces of two sequences from BSpec:
9075  * - Sequence for display software to disable LCPLL
9076  * - Sequence for display software to allow package C8+
9077  * The steps implemented here are just the steps that actually touch the LCPLL
9078  * register. Callers should take care of disabling all the display engine
9079  * functions, doing the mode unset, fixing interrupts, etc.
9080  */
9081 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9082                               bool switch_to_fclk, bool allow_power_down)
9083 {
9084         uint32_t val;
9085
9086         assert_can_disable_lcpll(dev_priv);
9087
9088         val = I915_READ(LCPLL_CTL);
9089
9090         if (switch_to_fclk) {
9091                 val |= LCPLL_CD_SOURCE_FCLK;
9092                 I915_WRITE(LCPLL_CTL, val);
9093
9094                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9095                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9096                         DRM_ERROR("Switching to FCLK failed\n");
9097
9098                 val = I915_READ(LCPLL_CTL);
9099         }
9100
9101         val |= LCPLL_PLL_DISABLE;
9102         I915_WRITE(LCPLL_CTL, val);
9103         POSTING_READ(LCPLL_CTL);
9104
9105         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9106                 DRM_ERROR("LCPLL still locked\n");
9107
9108         val = hsw_read_dcomp(dev_priv);
9109         val |= D_COMP_COMP_DISABLE;
9110         hsw_write_dcomp(dev_priv, val);
9111         ndelay(100);
9112
9113         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9114                      1))
9115                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9116
9117         if (allow_power_down) {
9118                 val = I915_READ(LCPLL_CTL);
9119                 val |= LCPLL_POWER_DOWN_ALLOW;
9120                 I915_WRITE(LCPLL_CTL, val);
9121                 POSTING_READ(LCPLL_CTL);
9122         }
9123 }
9124
9125 /*
9126  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9127  * source.
9128  */
9129 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9130 {
9131         uint32_t val;
9132
9133         val = I915_READ(LCPLL_CTL);
9134
9135         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9136                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9137                 return;
9138
9139         /*
9140          * Make sure we're not on PC8 state before disabling PC8, otherwise
9141          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9142          */
9143         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9144
9145         if (val & LCPLL_POWER_DOWN_ALLOW) {
9146                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9147                 I915_WRITE(LCPLL_CTL, val);
9148                 POSTING_READ(LCPLL_CTL);
9149         }
9150
9151         val = hsw_read_dcomp(dev_priv);
9152         val |= D_COMP_COMP_FORCE;
9153         val &= ~D_COMP_COMP_DISABLE;
9154         hsw_write_dcomp(dev_priv, val);
9155
9156         val = I915_READ(LCPLL_CTL);
9157         val &= ~LCPLL_PLL_DISABLE;
9158         I915_WRITE(LCPLL_CTL, val);
9159
9160         if (intel_wait_for_register(dev_priv,
9161                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9162                                     5))
9163                 DRM_ERROR("LCPLL not locked yet\n");
9164
9165         if (val & LCPLL_CD_SOURCE_FCLK) {
9166                 val = I915_READ(LCPLL_CTL);
9167                 val &= ~LCPLL_CD_SOURCE_FCLK;
9168                 I915_WRITE(LCPLL_CTL, val);
9169
9170                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9171                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9172                         DRM_ERROR("Switching back to LCPLL failed\n");
9173         }
9174
9175         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9176
9177         intel_update_cdclk(dev_priv);
9178         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
9179 }
9180
9181 /*
9182  * Package states C8 and deeper are really deep PC states that can only be
9183  * reached when all the devices on the system allow it, so even if the graphics
9184  * device allows PC8+, it doesn't mean the system will actually get to these
9185  * states. Our driver only allows PC8+ when going into runtime PM.
9186  *
9187  * The requirements for PC8+ are that all the outputs are disabled, the power
9188  * well is disabled and most interrupts are disabled, and these are also
9189  * requirements for runtime PM. When these conditions are met, we manually do
9190  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9191  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9192  * hang the machine.
9193  *
9194  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9195  * the state of some registers, so when we come back from PC8+ we need to
9196  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9197  * need to take care of the registers kept by RC6. Notice that this happens even
9198  * if we don't put the device in PCI D3 state (which is what currently happens
9199  * because of the runtime PM support).
9200  *
9201  * For more, read "Display Sequences for Package C8" on the hardware
9202  * documentation.
9203  */
9204 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9205 {
9206         uint32_t val;
9207
9208         DRM_DEBUG_KMS("Enabling package C8+\n");
9209
9210         if (HAS_PCH_LPT_LP(dev_priv)) {
9211                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9212                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9213                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9214         }
9215
9216         lpt_disable_clkout_dp(dev_priv);
9217         hsw_disable_lcpll(dev_priv, true, true);
9218 }
9219
9220 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9221 {
9222         uint32_t val;
9223
9224         DRM_DEBUG_KMS("Disabling package C8+\n");
9225
9226         hsw_restore_lcpll(dev_priv);
9227         lpt_init_pch_refclk(dev_priv);
9228
9229         if (HAS_PCH_LPT_LP(dev_priv)) {
9230                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9231                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9232                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9233         }
9234 }
9235
9236 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9237                                       struct intel_crtc_state *crtc_state)
9238 {
9239         struct intel_atomic_state *state =
9240                 to_intel_atomic_state(crtc_state->base.state);
9241
9242         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9243                 struct intel_encoder *encoder =
9244                         intel_get_crtc_new_encoder(state, crtc_state);
9245
9246                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9247                         DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9248                                       pipe_name(crtc->pipe));
9249                         return -EINVAL;
9250                 }
9251         }
9252
9253         return 0;
9254 }
9255
9256 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9257                                    enum port port,
9258                                    struct intel_crtc_state *pipe_config)
9259 {
9260         enum intel_dpll_id id;
9261         u32 temp;
9262
9263         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9264         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9265
9266         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9267                 return;
9268
9269         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9270 }
9271
9272 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9273                                 enum port port,
9274                                 struct intel_crtc_state *pipe_config)
9275 {
9276         enum intel_dpll_id id;
9277         u32 temp;
9278
9279         /* TODO: TBT pll not implemented. */
9280         switch (port) {
9281         case PORT_A:
9282         case PORT_B:
9283                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9284                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9285                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9286
9287                 if (WARN_ON(id != DPLL_ID_ICL_DPLL0 && id != DPLL_ID_ICL_DPLL1))
9288                         return;
9289                 break;
9290         case PORT_C:
9291                 id = DPLL_ID_ICL_MGPLL1;
9292                 break;
9293         case PORT_D:
9294                 id = DPLL_ID_ICL_MGPLL2;
9295                 break;
9296         case PORT_E:
9297                 id = DPLL_ID_ICL_MGPLL3;
9298                 break;
9299         case PORT_F:
9300                 id = DPLL_ID_ICL_MGPLL4;
9301                 break;
9302         default:
9303                 MISSING_CASE(port);
9304                 return;
9305         }
9306
9307         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9308 }
9309
9310 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9311                                 enum port port,
9312                                 struct intel_crtc_state *pipe_config)
9313 {
9314         enum intel_dpll_id id;
9315
9316         switch (port) {
9317         case PORT_A:
9318                 id = DPLL_ID_SKL_DPLL0;
9319                 break;
9320         case PORT_B:
9321                 id = DPLL_ID_SKL_DPLL1;
9322                 break;
9323         case PORT_C:
9324                 id = DPLL_ID_SKL_DPLL2;
9325                 break;
9326         default:
9327                 DRM_ERROR("Incorrect port type\n");
9328                 return;
9329         }
9330
9331         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9332 }
9333
9334 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9335                                 enum port port,
9336                                 struct intel_crtc_state *pipe_config)
9337 {
9338         enum intel_dpll_id id;
9339         u32 temp;
9340
9341         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9342         id = temp >> (port * 3 + 1);
9343
9344         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9345                 return;
9346
9347         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9348 }
9349
9350 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9351                                 enum port port,
9352                                 struct intel_crtc_state *pipe_config)
9353 {
9354         enum intel_dpll_id id;
9355         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9356
9357         switch (ddi_pll_sel) {
9358         case PORT_CLK_SEL_WRPLL1:
9359                 id = DPLL_ID_WRPLL1;
9360                 break;
9361         case PORT_CLK_SEL_WRPLL2:
9362                 id = DPLL_ID_WRPLL2;
9363                 break;
9364         case PORT_CLK_SEL_SPLL:
9365                 id = DPLL_ID_SPLL;
9366                 break;
9367         case PORT_CLK_SEL_LCPLL_810:
9368                 id = DPLL_ID_LCPLL_810;
9369                 break;
9370         case PORT_CLK_SEL_LCPLL_1350:
9371                 id = DPLL_ID_LCPLL_1350;
9372                 break;
9373         case PORT_CLK_SEL_LCPLL_2700:
9374                 id = DPLL_ID_LCPLL_2700;
9375                 break;
9376         default:
9377                 MISSING_CASE(ddi_pll_sel);
9378                 /* fall through */
9379         case PORT_CLK_SEL_NONE:
9380                 return;
9381         }
9382
9383         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9384 }
9385
9386 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9387                                      struct intel_crtc_state *pipe_config,
9388                                      u64 *power_domain_mask)
9389 {
9390         struct drm_device *dev = crtc->base.dev;
9391         struct drm_i915_private *dev_priv = to_i915(dev);
9392         enum intel_display_power_domain power_domain;
9393         u32 tmp;
9394
9395         /*
9396          * The pipe->transcoder mapping is fixed with the exception of the eDP
9397          * transcoder handled below.
9398          */
9399         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9400
9401         /*
9402          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9403          * consistency and less surprising code; it's in always on power).
9404          */
9405         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9406         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9407                 enum pipe trans_edp_pipe;
9408                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9409                 default:
9410                         WARN(1, "unknown pipe linked to edp transcoder\n");
9411                         /* fall through */
9412                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9413                 case TRANS_DDI_EDP_INPUT_A_ON:
9414                         trans_edp_pipe = PIPE_A;
9415                         break;
9416                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9417                         trans_edp_pipe = PIPE_B;
9418                         break;
9419                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9420                         trans_edp_pipe = PIPE_C;
9421                         break;
9422                 }
9423
9424                 if (trans_edp_pipe == crtc->pipe)
9425                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9426         }
9427
9428         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9429         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9430                 return false;
9431         *power_domain_mask |= BIT_ULL(power_domain);
9432
9433         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9434
9435         return tmp & PIPECONF_ENABLE;
9436 }
9437
9438 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9439                                          struct intel_crtc_state *pipe_config,
9440                                          u64 *power_domain_mask)
9441 {
9442         struct drm_device *dev = crtc->base.dev;
9443         struct drm_i915_private *dev_priv = to_i915(dev);
9444         enum intel_display_power_domain power_domain;
9445         enum port port;
9446         enum transcoder cpu_transcoder;
9447         u32 tmp;
9448
9449         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9450                 if (port == PORT_A)
9451                         cpu_transcoder = TRANSCODER_DSI_A;
9452                 else
9453                         cpu_transcoder = TRANSCODER_DSI_C;
9454
9455                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9456                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9457                         continue;
9458                 *power_domain_mask |= BIT_ULL(power_domain);
9459
9460                 /*
9461                  * The PLL needs to be enabled with a valid divider
9462                  * configuration, otherwise accessing DSI registers will hang
9463                  * the machine. See BSpec North Display Engine
9464                  * registers/MIPI[BXT]. We can break out here early, since we
9465                  * need the same DSI PLL to be enabled for both DSI ports.
9466                  */
9467                 if (!bxt_dsi_pll_is_enabled(dev_priv))
9468                         break;
9469
9470                 /* XXX: this works for video mode only */
9471                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9472                 if (!(tmp & DPI_ENABLE))
9473                         continue;
9474
9475                 tmp = I915_READ(MIPI_CTRL(port));
9476                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9477                         continue;
9478
9479                 pipe_config->cpu_transcoder = cpu_transcoder;
9480                 break;
9481         }
9482
9483         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9484 }
9485
9486 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9487                                        struct intel_crtc_state *pipe_config)
9488 {
9489         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9490         struct intel_shared_dpll *pll;
9491         enum port port;
9492         uint32_t tmp;
9493
9494         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9495
9496         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9497
9498         if (IS_ICELAKE(dev_priv))
9499                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
9500         else if (IS_CANNONLAKE(dev_priv))
9501                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9502         else if (IS_GEN9_BC(dev_priv))
9503                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9504         else if (IS_GEN9_LP(dev_priv))
9505                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9506         else
9507                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9508
9509         pll = pipe_config->shared_dpll;
9510         if (pll) {
9511                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9512                                                 &pipe_config->dpll_hw_state));
9513         }
9514
9515         /*
9516          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9517          * DDI E. So just check whether this pipe is wired to DDI E and whether
9518          * the PCH transcoder is on.
9519          */
9520         if (INTEL_GEN(dev_priv) < 9 &&
9521             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9522                 pipe_config->has_pch_encoder = true;
9523
9524                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9525                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9526                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9527
9528                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9529         }
9530 }
9531
9532 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9533                                     struct intel_crtc_state *pipe_config)
9534 {
9535         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9536         enum intel_display_power_domain power_domain;
9537         u64 power_domain_mask;
9538         bool active;
9539
9540         intel_crtc_init_scalers(crtc, pipe_config);
9541
9542         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9543         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9544                 return false;
9545         power_domain_mask = BIT_ULL(power_domain);
9546
9547         pipe_config->shared_dpll = NULL;
9548
9549         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9550
9551         if (IS_GEN9_LP(dev_priv) &&
9552             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9553                 WARN_ON(active);
9554                 active = true;
9555         }
9556
9557         if (!active)
9558                 goto out;
9559
9560         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9561                 haswell_get_ddi_port_state(crtc, pipe_config);
9562                 intel_get_pipe_timings(crtc, pipe_config);
9563         }
9564
9565         intel_get_pipe_src_size(crtc, pipe_config);
9566
9567         pipe_config->gamma_mode =
9568                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9569
9570         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
9571                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9572                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9573
9574                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10) {
9575                         bool blend_mode_420 = tmp &
9576                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9577
9578                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9579                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9580                             pipe_config->ycbcr420 != blend_mode_420)
9581                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9582                 } else if (clrspace_yuv) {
9583                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9584                 }
9585         }
9586
9587         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9588         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9589                 power_domain_mask |= BIT_ULL(power_domain);
9590                 if (INTEL_GEN(dev_priv) >= 9)
9591                         skylake_get_pfit_config(crtc, pipe_config);
9592                 else
9593                         ironlake_get_pfit_config(crtc, pipe_config);
9594         }
9595
9596         if (hsw_crtc_supports_ips(crtc)) {
9597                 if (IS_HASWELL(dev_priv))
9598                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9599                 else {
9600                         /*
9601                          * We cannot readout IPS state on broadwell, set to
9602                          * true so we can set it to a defined state on first
9603                          * commit.
9604                          */
9605                         pipe_config->ips_enabled = true;
9606                 }
9607         }
9608
9609         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9610             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9611                 pipe_config->pixel_multiplier =
9612                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9613         } else {
9614                 pipe_config->pixel_multiplier = 1;
9615         }
9616
9617 out:
9618         for_each_power_domain(power_domain, power_domain_mask)
9619                 intel_display_power_put(dev_priv, power_domain);
9620
9621         return active;
9622 }
9623
9624 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9625 {
9626         struct drm_i915_private *dev_priv =
9627                 to_i915(plane_state->base.plane->dev);
9628         const struct drm_framebuffer *fb = plane_state->base.fb;
9629         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9630         u32 base;
9631
9632         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9633                 base = obj->phys_handle->busaddr;
9634         else
9635                 base = intel_plane_ggtt_offset(plane_state);
9636
9637         base += plane_state->color_plane[0].offset;
9638
9639         /* ILK+ do this automagically */
9640         if (HAS_GMCH_DISPLAY(dev_priv) &&
9641             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9642                 base += (plane_state->base.crtc_h *
9643                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9644
9645         return base;
9646 }
9647
9648 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9649 {
9650         int x = plane_state->base.crtc_x;
9651         int y = plane_state->base.crtc_y;
9652         u32 pos = 0;
9653
9654         if (x < 0) {
9655                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9656                 x = -x;
9657         }
9658         pos |= x << CURSOR_X_SHIFT;
9659
9660         if (y < 0) {
9661                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9662                 y = -y;
9663         }
9664         pos |= y << CURSOR_Y_SHIFT;
9665
9666         return pos;
9667 }
9668
9669 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9670 {
9671         const struct drm_mode_config *config =
9672                 &plane_state->base.plane->dev->mode_config;
9673         int width = plane_state->base.crtc_w;
9674         int height = plane_state->base.crtc_h;
9675
9676         return width > 0 && width <= config->cursor_width &&
9677                 height > 0 && height <= config->cursor_height;
9678 }
9679
9680 static int intel_cursor_check_surface(struct intel_plane_state *plane_state)
9681 {
9682         const struct drm_framebuffer *fb = plane_state->base.fb;
9683         unsigned int rotation = plane_state->base.rotation;
9684         int src_x, src_y;
9685         u32 offset;
9686
9687         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
9688         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
9689
9690         src_x = plane_state->base.src_x >> 16;
9691         src_y = plane_state->base.src_y >> 16;
9692
9693         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9694         offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
9695                                                     plane_state, 0);
9696
9697         if (src_x != 0 || src_y != 0) {
9698                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9699                 return -EINVAL;
9700         }
9701
9702         plane_state->color_plane[0].offset = offset;
9703
9704         return 0;
9705 }
9706
9707 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9708                               struct intel_plane_state *plane_state)
9709 {
9710         const struct drm_framebuffer *fb = plane_state->base.fb;
9711         int ret;
9712
9713         if (fb && fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9714                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9715                 return -EINVAL;
9716         }
9717
9718         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9719                                                   &crtc_state->base,
9720                                                   DRM_PLANE_HELPER_NO_SCALING,
9721                                                   DRM_PLANE_HELPER_NO_SCALING,
9722                                                   true, true);
9723         if (ret)
9724                 return ret;
9725
9726         if (!plane_state->base.visible)
9727                 return 0;
9728
9729         ret = intel_plane_check_src_coordinates(plane_state);
9730         if (ret)
9731                 return ret;
9732
9733         ret = intel_cursor_check_surface(plane_state);
9734         if (ret)
9735                 return ret;
9736
9737         return 0;
9738 }
9739
9740 static unsigned int
9741 i845_cursor_max_stride(struct intel_plane *plane,
9742                        u32 pixel_format, u64 modifier,
9743                        unsigned int rotation)
9744 {
9745         return 2048;
9746 }
9747
9748 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9749                            const struct intel_plane_state *plane_state)
9750 {
9751         return CURSOR_ENABLE |
9752                 CURSOR_GAMMA_ENABLE |
9753                 CURSOR_FORMAT_ARGB |
9754                 CURSOR_STRIDE(plane_state->color_plane[0].stride);
9755 }
9756
9757 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9758 {
9759         int width = plane_state->base.crtc_w;
9760
9761         /*
9762          * 845g/865g are only limited by the width of their cursors,
9763          * the height is arbitrary up to the precision of the register.
9764          */
9765         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9766 }
9767
9768 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
9769                              struct intel_plane_state *plane_state)
9770 {
9771         const struct drm_framebuffer *fb = plane_state->base.fb;
9772         int ret;
9773
9774         ret = intel_check_cursor(crtc_state, plane_state);
9775         if (ret)
9776                 return ret;
9777
9778         /* if we want to turn off the cursor ignore width and height */
9779         if (!fb)
9780                 return 0;
9781
9782         /* Check for which cursor types we support */
9783         if (!i845_cursor_size_ok(plane_state)) {
9784                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9785                           plane_state->base.crtc_w,
9786                           plane_state->base.crtc_h);
9787                 return -EINVAL;
9788         }
9789
9790         WARN_ON(plane_state->base.visible &&
9791                 plane_state->color_plane[0].stride != fb->pitches[0]);
9792
9793         switch (fb->pitches[0]) {
9794         case 256:
9795         case 512:
9796         case 1024:
9797         case 2048:
9798                 break;
9799         default:
9800                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9801                               fb->pitches[0]);
9802                 return -EINVAL;
9803         }
9804
9805         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9806
9807         return 0;
9808 }
9809
9810 static void i845_update_cursor(struct intel_plane *plane,
9811                                const struct intel_crtc_state *crtc_state,
9812                                const struct intel_plane_state *plane_state)
9813 {
9814         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9815         u32 cntl = 0, base = 0, pos = 0, size = 0;
9816         unsigned long irqflags;
9817
9818         if (plane_state && plane_state->base.visible) {
9819                 unsigned int width = plane_state->base.crtc_w;
9820                 unsigned int height = plane_state->base.crtc_h;
9821
9822                 cntl = plane_state->ctl;
9823                 size = (height << 12) | width;
9824
9825                 base = intel_cursor_base(plane_state);
9826                 pos = intel_cursor_position(plane_state);
9827         }
9828
9829         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9830
9831         /* On these chipsets we can only modify the base/size/stride
9832          * whilst the cursor is disabled.
9833          */
9834         if (plane->cursor.base != base ||
9835             plane->cursor.size != size ||
9836             plane->cursor.cntl != cntl) {
9837                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9838                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9839                 I915_WRITE_FW(CURSIZE, size);
9840                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9841                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9842
9843                 plane->cursor.base = base;
9844                 plane->cursor.size = size;
9845                 plane->cursor.cntl = cntl;
9846         } else {
9847                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9848         }
9849
9850         POSTING_READ_FW(CURCNTR(PIPE_A));
9851
9852         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9853 }
9854
9855 static void i845_disable_cursor(struct intel_plane *plane,
9856                                 struct intel_crtc *crtc)
9857 {
9858         i845_update_cursor(plane, NULL, NULL);
9859 }
9860
9861 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
9862                                      enum pipe *pipe)
9863 {
9864         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9865         enum intel_display_power_domain power_domain;
9866         bool ret;
9867
9868         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9869         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9870                 return false;
9871
9872         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9873
9874         *pipe = PIPE_A;
9875
9876         intel_display_power_put(dev_priv, power_domain);
9877
9878         return ret;
9879 }
9880
9881 static unsigned int
9882 i9xx_cursor_max_stride(struct intel_plane *plane,
9883                        u32 pixel_format, u64 modifier,
9884                        unsigned int rotation)
9885 {
9886         return plane->base.dev->mode_config.cursor_width * 4;
9887 }
9888
9889 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9890                            const struct intel_plane_state *plane_state)
9891 {
9892         struct drm_i915_private *dev_priv =
9893                 to_i915(plane_state->base.plane->dev);
9894         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9895         u32 cntl = 0;
9896
9897         if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
9898                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
9899
9900         if (INTEL_GEN(dev_priv) <= 10) {
9901                 cntl |= MCURSOR_GAMMA_ENABLE;
9902
9903                 if (HAS_DDI(dev_priv))
9904                         cntl |= MCURSOR_PIPE_CSC_ENABLE;
9905         }
9906
9907         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
9908                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9909
9910         switch (plane_state->base.crtc_w) {
9911         case 64:
9912                 cntl |= MCURSOR_MODE_64_ARGB_AX;
9913                 break;
9914         case 128:
9915                 cntl |= MCURSOR_MODE_128_ARGB_AX;
9916                 break;
9917         case 256:
9918                 cntl |= MCURSOR_MODE_256_ARGB_AX;
9919                 break;
9920         default:
9921                 MISSING_CASE(plane_state->base.crtc_w);
9922                 return 0;
9923         }
9924
9925         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9926                 cntl |= MCURSOR_ROTATE_180;
9927
9928         return cntl;
9929 }
9930
9931 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9932 {
9933         struct drm_i915_private *dev_priv =
9934                 to_i915(plane_state->base.plane->dev);
9935         int width = plane_state->base.crtc_w;
9936         int height = plane_state->base.crtc_h;
9937
9938         if (!intel_cursor_size_ok(plane_state))
9939                 return false;
9940
9941         /* Cursor width is limited to a few power-of-two sizes */
9942         switch (width) {
9943         case 256:
9944         case 128:
9945         case 64:
9946                 break;
9947         default:
9948                 return false;
9949         }
9950
9951         /*
9952          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9953          * height from 8 lines up to the cursor width, when the
9954          * cursor is not rotated. Everything else requires square
9955          * cursors.
9956          */
9957         if (HAS_CUR_FBC(dev_priv) &&
9958             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9959                 if (height < 8 || height > width)
9960                         return false;
9961         } else {
9962                 if (height != width)
9963                         return false;
9964         }
9965
9966         return true;
9967 }
9968
9969 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
9970                              struct intel_plane_state *plane_state)
9971 {
9972         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
9973         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9974         const struct drm_framebuffer *fb = plane_state->base.fb;
9975         enum pipe pipe = plane->pipe;
9976         int ret;
9977
9978         ret = intel_check_cursor(crtc_state, plane_state);
9979         if (ret)
9980                 return ret;
9981
9982         /* if we want to turn off the cursor ignore width and height */
9983         if (!fb)
9984                 return 0;
9985
9986         /* Check for which cursor types we support */
9987         if (!i9xx_cursor_size_ok(plane_state)) {
9988                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9989                           plane_state->base.crtc_w,
9990                           plane_state->base.crtc_h);
9991                 return -EINVAL;
9992         }
9993
9994         WARN_ON(plane_state->base.visible &&
9995                 plane_state->color_plane[0].stride != fb->pitches[0]);
9996
9997         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9998                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9999                               fb->pitches[0], plane_state->base.crtc_w);
10000                 return -EINVAL;
10001         }
10002
10003         /*
10004          * There's something wrong with the cursor on CHV pipe C.
10005          * If it straddles the left edge of the screen then
10006          * moving it away from the edge or disabling it often
10007          * results in a pipe underrun, and often that can lead to
10008          * dead pipe (constant underrun reported, and it scans
10009          * out just a solid color). To recover from that, the
10010          * display power well must be turned off and on again.
10011          * Refuse the put the cursor into that compromised position.
10012          */
10013         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
10014             plane_state->base.visible && plane_state->base.crtc_x < 0) {
10015                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
10016                 return -EINVAL;
10017         }
10018
10019         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
10020
10021         return 0;
10022 }
10023
10024 static void i9xx_update_cursor(struct intel_plane *plane,
10025                                const struct intel_crtc_state *crtc_state,
10026                                const struct intel_plane_state *plane_state)
10027 {
10028         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10029         enum pipe pipe = plane->pipe;
10030         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
10031         unsigned long irqflags;
10032
10033         if (plane_state && plane_state->base.visible) {
10034                 cntl = plane_state->ctl;
10035
10036                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
10037                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
10038
10039                 base = intel_cursor_base(plane_state);
10040                 pos = intel_cursor_position(plane_state);
10041         }
10042
10043         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10044
10045         /*
10046          * On some platforms writing CURCNTR first will also
10047          * cause CURPOS to be armed by the CURBASE write.
10048          * Without the CURCNTR write the CURPOS write would
10049          * arm itself. Thus we always start the full update
10050          * with a CURCNTR write.
10051          *
10052          * On other platforms CURPOS always requires the
10053          * CURBASE write to arm the update. Additonally
10054          * a write to any of the cursor register will cancel
10055          * an already armed cursor update. Thus leaving out
10056          * the CURBASE write after CURPOS could lead to a
10057          * cursor that doesn't appear to move, or even change
10058          * shape. Thus we always write CURBASE.
10059          *
10060          * CURCNTR and CUR_FBC_CTL are always
10061          * armed by the CURBASE write only.
10062          */
10063         if (plane->cursor.base != base ||
10064             plane->cursor.size != fbc_ctl ||
10065             plane->cursor.cntl != cntl) {
10066                 I915_WRITE_FW(CURCNTR(pipe), cntl);
10067                 if (HAS_CUR_FBC(dev_priv))
10068                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
10069                 I915_WRITE_FW(CURPOS(pipe), pos);
10070                 I915_WRITE_FW(CURBASE(pipe), base);
10071
10072                 plane->cursor.base = base;
10073                 plane->cursor.size = fbc_ctl;
10074                 plane->cursor.cntl = cntl;
10075         } else {
10076                 I915_WRITE_FW(CURPOS(pipe), pos);
10077                 I915_WRITE_FW(CURBASE(pipe), base);
10078         }
10079
10080         POSTING_READ_FW(CURBASE(pipe));
10081
10082         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10083 }
10084
10085 static void i9xx_disable_cursor(struct intel_plane *plane,
10086                                 struct intel_crtc *crtc)
10087 {
10088         i9xx_update_cursor(plane, NULL, NULL);
10089 }
10090
10091 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10092                                      enum pipe *pipe)
10093 {
10094         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10095         enum intel_display_power_domain power_domain;
10096         bool ret;
10097         u32 val;
10098
10099         /*
10100          * Not 100% correct for planes that can move between pipes,
10101          * but that's only the case for gen2-3 which don't have any
10102          * display power wells.
10103          */
10104         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10105         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10106                 return false;
10107
10108         val = I915_READ(CURCNTR(plane->pipe));
10109
10110         ret = val & MCURSOR_MODE;
10111
10112         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10113                 *pipe = plane->pipe;
10114         else
10115                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10116                         MCURSOR_PIPE_SELECT_SHIFT;
10117
10118         intel_display_power_put(dev_priv, power_domain);
10119
10120         return ret;
10121 }
10122
10123 /* VESA 640x480x72Hz mode to set on the pipe */
10124 static const struct drm_display_mode load_detect_mode = {
10125         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10126                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10127 };
10128
10129 struct drm_framebuffer *
10130 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10131                          struct drm_mode_fb_cmd2 *mode_cmd)
10132 {
10133         struct intel_framebuffer *intel_fb;
10134         int ret;
10135
10136         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10137         if (!intel_fb)
10138                 return ERR_PTR(-ENOMEM);
10139
10140         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10141         if (ret)
10142                 goto err;
10143
10144         return &intel_fb->base;
10145
10146 err:
10147         kfree(intel_fb);
10148         return ERR_PTR(ret);
10149 }
10150
10151 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10152                                         struct drm_crtc *crtc)
10153 {
10154         struct drm_plane *plane;
10155         struct drm_plane_state *plane_state;
10156         int ret, i;
10157
10158         ret = drm_atomic_add_affected_planes(state, crtc);
10159         if (ret)
10160                 return ret;
10161
10162         for_each_new_plane_in_state(state, plane, plane_state, i) {
10163                 if (plane_state->crtc != crtc)
10164                         continue;
10165
10166                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10167                 if (ret)
10168                         return ret;
10169
10170                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10171         }
10172
10173         return 0;
10174 }
10175
10176 int intel_get_load_detect_pipe(struct drm_connector *connector,
10177                                const struct drm_display_mode *mode,
10178                                struct intel_load_detect_pipe *old,
10179                                struct drm_modeset_acquire_ctx *ctx)
10180 {
10181         struct intel_crtc *intel_crtc;
10182         struct intel_encoder *intel_encoder =
10183                 intel_attached_encoder(connector);
10184         struct drm_crtc *possible_crtc;
10185         struct drm_encoder *encoder = &intel_encoder->base;
10186         struct drm_crtc *crtc = NULL;
10187         struct drm_device *dev = encoder->dev;
10188         struct drm_i915_private *dev_priv = to_i915(dev);
10189         struct drm_mode_config *config = &dev->mode_config;
10190         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10191         struct drm_connector_state *connector_state;
10192         struct intel_crtc_state *crtc_state;
10193         int ret, i = -1;
10194
10195         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10196                       connector->base.id, connector->name,
10197                       encoder->base.id, encoder->name);
10198
10199         old->restore_state = NULL;
10200
10201         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10202
10203         /*
10204          * Algorithm gets a little messy:
10205          *
10206          *   - if the connector already has an assigned crtc, use it (but make
10207          *     sure it's on first)
10208          *
10209          *   - try to find the first unused crtc that can drive this connector,
10210          *     and use that if we find one
10211          */
10212
10213         /* See if we already have a CRTC for this connector */
10214         if (connector->state->crtc) {
10215                 crtc = connector->state->crtc;
10216
10217                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10218                 if (ret)
10219                         goto fail;
10220
10221                 /* Make sure the crtc and connector are running */
10222                 goto found;
10223         }
10224
10225         /* Find an unused one (if possible) */
10226         for_each_crtc(dev, possible_crtc) {
10227                 i++;
10228                 if (!(encoder->possible_crtcs & (1 << i)))
10229                         continue;
10230
10231                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10232                 if (ret)
10233                         goto fail;
10234
10235                 if (possible_crtc->state->enable) {
10236                         drm_modeset_unlock(&possible_crtc->mutex);
10237                         continue;
10238                 }
10239
10240                 crtc = possible_crtc;
10241                 break;
10242         }
10243
10244         /*
10245          * If we didn't find an unused CRTC, don't use any.
10246          */
10247         if (!crtc) {
10248                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10249                 ret = -ENODEV;
10250                 goto fail;
10251         }
10252
10253 found:
10254         intel_crtc = to_intel_crtc(crtc);
10255
10256         state = drm_atomic_state_alloc(dev);
10257         restore_state = drm_atomic_state_alloc(dev);
10258         if (!state || !restore_state) {
10259                 ret = -ENOMEM;
10260                 goto fail;
10261         }
10262
10263         state->acquire_ctx = ctx;
10264         restore_state->acquire_ctx = ctx;
10265
10266         connector_state = drm_atomic_get_connector_state(state, connector);
10267         if (IS_ERR(connector_state)) {
10268                 ret = PTR_ERR(connector_state);
10269                 goto fail;
10270         }
10271
10272         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10273         if (ret)
10274                 goto fail;
10275
10276         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10277         if (IS_ERR(crtc_state)) {
10278                 ret = PTR_ERR(crtc_state);
10279                 goto fail;
10280         }
10281
10282         crtc_state->base.active = crtc_state->base.enable = true;
10283
10284         if (!mode)
10285                 mode = &load_detect_mode;
10286
10287         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10288         if (ret)
10289                 goto fail;
10290
10291         ret = intel_modeset_disable_planes(state, crtc);
10292         if (ret)
10293                 goto fail;
10294
10295         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10296         if (!ret)
10297                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10298         if (!ret)
10299                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10300         if (ret) {
10301                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10302                 goto fail;
10303         }
10304
10305         ret = drm_atomic_commit(state);
10306         if (ret) {
10307                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10308                 goto fail;
10309         }
10310
10311         old->restore_state = restore_state;
10312         drm_atomic_state_put(state);
10313
10314         /* let the connector get through one full cycle before testing */
10315         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10316         return true;
10317
10318 fail:
10319         if (state) {
10320                 drm_atomic_state_put(state);
10321                 state = NULL;
10322         }
10323         if (restore_state) {
10324                 drm_atomic_state_put(restore_state);
10325                 restore_state = NULL;
10326         }
10327
10328         if (ret == -EDEADLK)
10329                 return ret;
10330
10331         return false;
10332 }
10333
10334 void intel_release_load_detect_pipe(struct drm_connector *connector,
10335                                     struct intel_load_detect_pipe *old,
10336                                     struct drm_modeset_acquire_ctx *ctx)
10337 {
10338         struct intel_encoder *intel_encoder =
10339                 intel_attached_encoder(connector);
10340         struct drm_encoder *encoder = &intel_encoder->base;
10341         struct drm_atomic_state *state = old->restore_state;
10342         int ret;
10343
10344         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10345                       connector->base.id, connector->name,
10346                       encoder->base.id, encoder->name);
10347
10348         if (!state)
10349                 return;
10350
10351         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10352         if (ret)
10353                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10354         drm_atomic_state_put(state);
10355 }
10356
10357 static int i9xx_pll_refclk(struct drm_device *dev,
10358                            const struct intel_crtc_state *pipe_config)
10359 {
10360         struct drm_i915_private *dev_priv = to_i915(dev);
10361         u32 dpll = pipe_config->dpll_hw_state.dpll;
10362
10363         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10364                 return dev_priv->vbt.lvds_ssc_freq;
10365         else if (HAS_PCH_SPLIT(dev_priv))
10366                 return 120000;
10367         else if (!IS_GEN2(dev_priv))
10368                 return 96000;
10369         else
10370                 return 48000;
10371 }
10372
10373 /* Returns the clock of the currently programmed mode of the given pipe. */
10374 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10375                                 struct intel_crtc_state *pipe_config)
10376 {
10377         struct drm_device *dev = crtc->base.dev;
10378         struct drm_i915_private *dev_priv = to_i915(dev);
10379         int pipe = pipe_config->cpu_transcoder;
10380         u32 dpll = pipe_config->dpll_hw_state.dpll;
10381         u32 fp;
10382         struct dpll clock;
10383         int port_clock;
10384         int refclk = i9xx_pll_refclk(dev, pipe_config);
10385
10386         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10387                 fp = pipe_config->dpll_hw_state.fp0;
10388         else
10389                 fp = pipe_config->dpll_hw_state.fp1;
10390
10391         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10392         if (IS_PINEVIEW(dev_priv)) {
10393                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10394                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10395         } else {
10396                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10397                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10398         }
10399
10400         if (!IS_GEN2(dev_priv)) {
10401                 if (IS_PINEVIEW(dev_priv))
10402                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10403                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10404                 else
10405                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10406                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10407
10408                 switch (dpll & DPLL_MODE_MASK) {
10409                 case DPLLB_MODE_DAC_SERIAL:
10410                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10411                                 5 : 10;
10412                         break;
10413                 case DPLLB_MODE_LVDS:
10414                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10415                                 7 : 14;
10416                         break;
10417                 default:
10418                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10419                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10420                         return;
10421                 }
10422
10423                 if (IS_PINEVIEW(dev_priv))
10424                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10425                 else
10426                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10427         } else {
10428                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10429                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10430
10431                 if (is_lvds) {
10432                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10433                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10434
10435                         if (lvds & LVDS_CLKB_POWER_UP)
10436                                 clock.p2 = 7;
10437                         else
10438                                 clock.p2 = 14;
10439                 } else {
10440                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10441                                 clock.p1 = 2;
10442                         else {
10443                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10444                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10445                         }
10446                         if (dpll & PLL_P2_DIVIDE_BY_4)
10447                                 clock.p2 = 4;
10448                         else
10449                                 clock.p2 = 2;
10450                 }
10451
10452                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10453         }
10454
10455         /*
10456          * This value includes pixel_multiplier. We will use
10457          * port_clock to compute adjusted_mode.crtc_clock in the
10458          * encoder's get_config() function.
10459          */
10460         pipe_config->port_clock = port_clock;
10461 }
10462
10463 int intel_dotclock_calculate(int link_freq,
10464                              const struct intel_link_m_n *m_n)
10465 {
10466         /*
10467          * The calculation for the data clock is:
10468          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10469          * But we want to avoid losing precison if possible, so:
10470          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10471          *
10472          * and the link clock is simpler:
10473          * link_clock = (m * link_clock) / n
10474          */
10475
10476         if (!m_n->link_n)
10477                 return 0;
10478
10479         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10480 }
10481
10482 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10483                                    struct intel_crtc_state *pipe_config)
10484 {
10485         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10486
10487         /* read out port_clock from the DPLL */
10488         i9xx_crtc_clock_get(crtc, pipe_config);
10489
10490         /*
10491          * In case there is an active pipe without active ports,
10492          * we may need some idea for the dotclock anyway.
10493          * Calculate one based on the FDI configuration.
10494          */
10495         pipe_config->base.adjusted_mode.crtc_clock =
10496                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10497                                          &pipe_config->fdi_m_n);
10498 }
10499
10500 /* Returns the currently programmed mode of the given encoder. */
10501 struct drm_display_mode *
10502 intel_encoder_current_mode(struct intel_encoder *encoder)
10503 {
10504         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10505         struct intel_crtc_state *crtc_state;
10506         struct drm_display_mode *mode;
10507         struct intel_crtc *crtc;
10508         enum pipe pipe;
10509
10510         if (!encoder->get_hw_state(encoder, &pipe))
10511                 return NULL;
10512
10513         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10514
10515         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10516         if (!mode)
10517                 return NULL;
10518
10519         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10520         if (!crtc_state) {
10521                 kfree(mode);
10522                 return NULL;
10523         }
10524
10525         crtc_state->base.crtc = &crtc->base;
10526
10527         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10528                 kfree(crtc_state);
10529                 kfree(mode);
10530                 return NULL;
10531         }
10532
10533         encoder->get_config(encoder, crtc_state);
10534
10535         intel_mode_from_pipe_config(mode, crtc_state);
10536
10537         kfree(crtc_state);
10538
10539         return mode;
10540 }
10541
10542 static void intel_crtc_destroy(struct drm_crtc *crtc)
10543 {
10544         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10545
10546         drm_crtc_cleanup(crtc);
10547         kfree(intel_crtc);
10548 }
10549
10550 /**
10551  * intel_wm_need_update - Check whether watermarks need updating
10552  * @plane: drm plane
10553  * @state: new plane state
10554  *
10555  * Check current plane state versus the new one to determine whether
10556  * watermarks need to be recalculated.
10557  *
10558  * Returns true or false.
10559  */
10560 static bool intel_wm_need_update(struct drm_plane *plane,
10561                                  struct drm_plane_state *state)
10562 {
10563         struct intel_plane_state *new = to_intel_plane_state(state);
10564         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10565
10566         /* Update watermarks on tiling or size changes. */
10567         if (new->base.visible != cur->base.visible)
10568                 return true;
10569
10570         if (!cur->base.fb || !new->base.fb)
10571                 return false;
10572
10573         if (cur->base.fb->modifier != new->base.fb->modifier ||
10574             cur->base.rotation != new->base.rotation ||
10575             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10576             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10577             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10578             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10579                 return true;
10580
10581         return false;
10582 }
10583
10584 static bool needs_scaling(const struct intel_plane_state *state)
10585 {
10586         int src_w = drm_rect_width(&state->base.src) >> 16;
10587         int src_h = drm_rect_height(&state->base.src) >> 16;
10588         int dst_w = drm_rect_width(&state->base.dst);
10589         int dst_h = drm_rect_height(&state->base.dst);
10590
10591         return (src_w != dst_w || src_h != dst_h);
10592 }
10593
10594 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10595                                     struct drm_crtc_state *crtc_state,
10596                                     const struct intel_plane_state *old_plane_state,
10597                                     struct drm_plane_state *plane_state)
10598 {
10599         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10600         struct drm_crtc *crtc = crtc_state->crtc;
10601         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10602         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10603         struct drm_device *dev = crtc->dev;
10604         struct drm_i915_private *dev_priv = to_i915(dev);
10605         bool mode_changed = needs_modeset(crtc_state);
10606         bool was_crtc_enabled = old_crtc_state->base.active;
10607         bool is_crtc_enabled = crtc_state->active;
10608         bool turn_off, turn_on, visible, was_visible;
10609         struct drm_framebuffer *fb = plane_state->fb;
10610         int ret;
10611
10612         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10613                 ret = skl_update_scaler_plane(
10614                         to_intel_crtc_state(crtc_state),
10615                         to_intel_plane_state(plane_state));
10616                 if (ret)
10617                         return ret;
10618         }
10619
10620         was_visible = old_plane_state->base.visible;
10621         visible = plane_state->visible;
10622
10623         if (!was_crtc_enabled && WARN_ON(was_visible))
10624                 was_visible = false;
10625
10626         /*
10627          * Visibility is calculated as if the crtc was on, but
10628          * after scaler setup everything depends on it being off
10629          * when the crtc isn't active.
10630          *
10631          * FIXME this is wrong for watermarks. Watermarks should also
10632          * be computed as if the pipe would be active. Perhaps move
10633          * per-plane wm computation to the .check_plane() hook, and
10634          * only combine the results from all planes in the current place?
10635          */
10636         if (!is_crtc_enabled) {
10637                 plane_state->visible = visible = false;
10638                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10639         }
10640
10641         if (!was_visible && !visible)
10642                 return 0;
10643
10644         if (fb != old_plane_state->base.fb)
10645                 pipe_config->fb_changed = true;
10646
10647         turn_off = was_visible && (!visible || mode_changed);
10648         turn_on = visible && (!was_visible || mode_changed);
10649
10650         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10651                          intel_crtc->base.base.id, intel_crtc->base.name,
10652                          plane->base.base.id, plane->base.name,
10653                          fb ? fb->base.id : -1);
10654
10655         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10656                          plane->base.base.id, plane->base.name,
10657                          was_visible, visible,
10658                          turn_off, turn_on, mode_changed);
10659
10660         if (turn_on) {
10661                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10662                         pipe_config->update_wm_pre = true;
10663
10664                 /* must disable cxsr around plane enable/disable */
10665                 if (plane->id != PLANE_CURSOR)
10666                         pipe_config->disable_cxsr = true;
10667         } else if (turn_off) {
10668                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10669                         pipe_config->update_wm_post = true;
10670
10671                 /* must disable cxsr around plane enable/disable */
10672                 if (plane->id != PLANE_CURSOR)
10673                         pipe_config->disable_cxsr = true;
10674         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10675                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10676                         /* FIXME bollocks */
10677                         pipe_config->update_wm_pre = true;
10678                         pipe_config->update_wm_post = true;
10679                 }
10680         }
10681
10682         if (visible || was_visible)
10683                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10684
10685         /*
10686          * WaCxSRDisabledForSpriteScaling:ivb
10687          *
10688          * cstate->update_wm was already set above, so this flag will
10689          * take effect when we commit and program watermarks.
10690          */
10691         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
10692             needs_scaling(to_intel_plane_state(plane_state)) &&
10693             !needs_scaling(old_plane_state))
10694                 pipe_config->disable_lp_wm = true;
10695
10696         return 0;
10697 }
10698
10699 static bool encoders_cloneable(const struct intel_encoder *a,
10700                                const struct intel_encoder *b)
10701 {
10702         /* masks could be asymmetric, so check both ways */
10703         return a == b || (a->cloneable & (1 << b->type) &&
10704                           b->cloneable & (1 << a->type));
10705 }
10706
10707 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10708                                          struct intel_crtc *crtc,
10709                                          struct intel_encoder *encoder)
10710 {
10711         struct intel_encoder *source_encoder;
10712         struct drm_connector *connector;
10713         struct drm_connector_state *connector_state;
10714         int i;
10715
10716         for_each_new_connector_in_state(state, connector, connector_state, i) {
10717                 if (connector_state->crtc != &crtc->base)
10718                         continue;
10719
10720                 source_encoder =
10721                         to_intel_encoder(connector_state->best_encoder);
10722                 if (!encoders_cloneable(encoder, source_encoder))
10723                         return false;
10724         }
10725
10726         return true;
10727 }
10728
10729 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10730                                    struct drm_crtc_state *crtc_state)
10731 {
10732         struct drm_device *dev = crtc->dev;
10733         struct drm_i915_private *dev_priv = to_i915(dev);
10734         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10735         struct intel_crtc_state *pipe_config =
10736                 to_intel_crtc_state(crtc_state);
10737         struct drm_atomic_state *state = crtc_state->state;
10738         int ret;
10739         bool mode_changed = needs_modeset(crtc_state);
10740
10741         if (mode_changed && !crtc_state->active)
10742                 pipe_config->update_wm_post = true;
10743
10744         if (mode_changed && crtc_state->enable &&
10745             dev_priv->display.crtc_compute_clock &&
10746             !WARN_ON(pipe_config->shared_dpll)) {
10747                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10748                                                            pipe_config);
10749                 if (ret)
10750                         return ret;
10751         }
10752
10753         if (crtc_state->color_mgmt_changed) {
10754                 ret = intel_color_check(crtc, crtc_state);
10755                 if (ret)
10756                         return ret;
10757
10758                 /*
10759                  * Changing color management on Intel hardware is
10760                  * handled as part of planes update.
10761                  */
10762                 crtc_state->planes_changed = true;
10763         }
10764
10765         ret = 0;
10766         if (dev_priv->display.compute_pipe_wm) {
10767                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10768                 if (ret) {
10769                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10770                         return ret;
10771                 }
10772         }
10773
10774         if (dev_priv->display.compute_intermediate_wm &&
10775             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10776                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10777                         return 0;
10778
10779                 /*
10780                  * Calculate 'intermediate' watermarks that satisfy both the
10781                  * old state and the new state.  We can program these
10782                  * immediately.
10783                  */
10784                 ret = dev_priv->display.compute_intermediate_wm(dev,
10785                                                                 intel_crtc,
10786                                                                 pipe_config);
10787                 if (ret) {
10788                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10789                         return ret;
10790                 }
10791         } else if (dev_priv->display.compute_intermediate_wm) {
10792                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10793                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10794         }
10795
10796         if (INTEL_GEN(dev_priv) >= 9) {
10797                 if (mode_changed)
10798                         ret = skl_update_scaler_crtc(pipe_config);
10799
10800                 if (!ret)
10801                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10802                                                             pipe_config);
10803                 if (!ret)
10804                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10805                                                          pipe_config);
10806         }
10807
10808         if (HAS_IPS(dev_priv))
10809                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10810
10811         return ret;
10812 }
10813
10814 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10815         .atomic_begin = intel_begin_crtc_commit,
10816         .atomic_flush = intel_finish_crtc_commit,
10817         .atomic_check = intel_crtc_atomic_check,
10818 };
10819
10820 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10821 {
10822         struct intel_connector *connector;
10823         struct drm_connector_list_iter conn_iter;
10824
10825         drm_connector_list_iter_begin(dev, &conn_iter);
10826         for_each_intel_connector_iter(connector, &conn_iter) {
10827                 if (connector->base.state->crtc)
10828                         drm_connector_put(&connector->base);
10829
10830                 if (connector->base.encoder) {
10831                         connector->base.state->best_encoder =
10832                                 connector->base.encoder;
10833                         connector->base.state->crtc =
10834                                 connector->base.encoder->crtc;
10835
10836                         drm_connector_get(&connector->base);
10837                 } else {
10838                         connector->base.state->best_encoder = NULL;
10839                         connector->base.state->crtc = NULL;
10840                 }
10841         }
10842         drm_connector_list_iter_end(&conn_iter);
10843 }
10844
10845 static void
10846 connected_sink_compute_bpp(struct intel_connector *connector,
10847                            struct intel_crtc_state *pipe_config)
10848 {
10849         const struct drm_display_info *info = &connector->base.display_info;
10850         int bpp = pipe_config->pipe_bpp;
10851
10852         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10853                       connector->base.base.id,
10854                       connector->base.name);
10855
10856         /* Don't use an invalid EDID bpc value */
10857         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10858                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10859                               bpp, info->bpc * 3);
10860                 pipe_config->pipe_bpp = info->bpc * 3;
10861         }
10862
10863         /* Clamp bpp to 8 on screens without EDID 1.4 */
10864         if (info->bpc == 0 && bpp > 24) {
10865                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10866                               bpp);
10867                 pipe_config->pipe_bpp = 24;
10868         }
10869 }
10870
10871 static int
10872 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10873                           struct intel_crtc_state *pipe_config)
10874 {
10875         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10876         struct drm_atomic_state *state;
10877         struct drm_connector *connector;
10878         struct drm_connector_state *connector_state;
10879         int bpp, i;
10880
10881         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10882             IS_CHERRYVIEW(dev_priv)))
10883                 bpp = 10*3;
10884         else if (INTEL_GEN(dev_priv) >= 5)
10885                 bpp = 12*3;
10886         else
10887                 bpp = 8*3;
10888
10889
10890         pipe_config->pipe_bpp = bpp;
10891
10892         state = pipe_config->base.state;
10893
10894         /* Clamp display bpp to EDID value */
10895         for_each_new_connector_in_state(state, connector, connector_state, i) {
10896                 if (connector_state->crtc != &crtc->base)
10897                         continue;
10898
10899                 connected_sink_compute_bpp(to_intel_connector(connector),
10900                                            pipe_config);
10901         }
10902
10903         return bpp;
10904 }
10905
10906 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10907 {
10908         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10909                         "type: 0x%x flags: 0x%x\n",
10910                 mode->crtc_clock,
10911                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10912                 mode->crtc_hsync_end, mode->crtc_htotal,
10913                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10914                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10915 }
10916
10917 static inline void
10918 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10919                       unsigned int lane_count, struct intel_link_m_n *m_n)
10920 {
10921         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10922                       id, lane_count,
10923                       m_n->gmch_m, m_n->gmch_n,
10924                       m_n->link_m, m_n->link_n, m_n->tu);
10925 }
10926
10927 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10928
10929 static const char * const output_type_str[] = {
10930         OUTPUT_TYPE(UNUSED),
10931         OUTPUT_TYPE(ANALOG),
10932         OUTPUT_TYPE(DVO),
10933         OUTPUT_TYPE(SDVO),
10934         OUTPUT_TYPE(LVDS),
10935         OUTPUT_TYPE(TVOUT),
10936         OUTPUT_TYPE(HDMI),
10937         OUTPUT_TYPE(DP),
10938         OUTPUT_TYPE(EDP),
10939         OUTPUT_TYPE(DSI),
10940         OUTPUT_TYPE(DDI),
10941         OUTPUT_TYPE(DP_MST),
10942 };
10943
10944 #undef OUTPUT_TYPE
10945
10946 static void snprintf_output_types(char *buf, size_t len,
10947                                   unsigned int output_types)
10948 {
10949         char *str = buf;
10950         int i;
10951
10952         str[0] = '\0';
10953
10954         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
10955                 int r;
10956
10957                 if ((output_types & BIT(i)) == 0)
10958                         continue;
10959
10960                 r = snprintf(str, len, "%s%s",
10961                              str != buf ? "," : "", output_type_str[i]);
10962                 if (r >= len)
10963                         break;
10964                 str += r;
10965                 len -= r;
10966
10967                 output_types &= ~BIT(i);
10968         }
10969
10970         WARN_ON_ONCE(output_types != 0);
10971 }
10972
10973 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10974                                    struct intel_crtc_state *pipe_config,
10975                                    const char *context)
10976 {
10977         struct drm_device *dev = crtc->base.dev;
10978         struct drm_i915_private *dev_priv = to_i915(dev);
10979         struct drm_plane *plane;
10980         struct intel_plane *intel_plane;
10981         struct intel_plane_state *state;
10982         struct drm_framebuffer *fb;
10983         char buf[64];
10984
10985         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10986                       crtc->base.base.id, crtc->base.name, context);
10987
10988         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
10989         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
10990                       buf, pipe_config->output_types);
10991
10992         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
10993                       transcoder_name(pipe_config->cpu_transcoder),
10994                       pipe_config->pipe_bpp, pipe_config->dither);
10995
10996         if (pipe_config->has_pch_encoder)
10997                 intel_dump_m_n_config(pipe_config, "fdi",
10998                                       pipe_config->fdi_lanes,
10999                                       &pipe_config->fdi_m_n);
11000
11001         if (pipe_config->ycbcr420)
11002                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
11003
11004         if (intel_crtc_has_dp_encoder(pipe_config)) {
11005                 intel_dump_m_n_config(pipe_config, "dp m_n",
11006                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11007                 if (pipe_config->has_drrs)
11008                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11009                                               pipe_config->lane_count,
11010                                               &pipe_config->dp_m2_n2);
11011         }
11012
11013         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11014                       pipe_config->has_audio, pipe_config->has_infoframe);
11015
11016         DRM_DEBUG_KMS("requested mode:\n");
11017         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11018         DRM_DEBUG_KMS("adjusted mode:\n");
11019         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11020         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11021         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11022                       pipe_config->port_clock,
11023                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11024                       pipe_config->pixel_rate);
11025
11026         if (INTEL_GEN(dev_priv) >= 9)
11027                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11028                               crtc->num_scalers,
11029                               pipe_config->scaler_state.scaler_users,
11030                               pipe_config->scaler_state.scaler_id);
11031
11032         if (HAS_GMCH_DISPLAY(dev_priv))
11033                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11034                               pipe_config->gmch_pfit.control,
11035                               pipe_config->gmch_pfit.pgm_ratios,
11036                               pipe_config->gmch_pfit.lvds_border_bits);
11037         else
11038                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11039                               pipe_config->pch_pfit.pos,
11040                               pipe_config->pch_pfit.size,
11041                               enableddisabled(pipe_config->pch_pfit.enabled));
11042
11043         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11044                       pipe_config->ips_enabled, pipe_config->double_wide);
11045
11046         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11047
11048         DRM_DEBUG_KMS("planes on this crtc\n");
11049         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11050                 struct drm_format_name_buf format_name;
11051                 intel_plane = to_intel_plane(plane);
11052                 if (intel_plane->pipe != crtc->pipe)
11053                         continue;
11054
11055                 state = to_intel_plane_state(plane->state);
11056                 fb = state->base.fb;
11057                 if (!fb) {
11058                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11059                                       plane->base.id, plane->name, state->scaler_id);
11060                         continue;
11061                 }
11062
11063                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11064                               plane->base.id, plane->name,
11065                               fb->base.id, fb->width, fb->height,
11066                               drm_get_format_name(fb->format->format, &format_name));
11067                 if (INTEL_GEN(dev_priv) >= 9)
11068                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11069                                       state->scaler_id,
11070                                       state->base.src.x1 >> 16,
11071                                       state->base.src.y1 >> 16,
11072                                       drm_rect_width(&state->base.src) >> 16,
11073                                       drm_rect_height(&state->base.src) >> 16,
11074                                       state->base.dst.x1, state->base.dst.y1,
11075                                       drm_rect_width(&state->base.dst),
11076                                       drm_rect_height(&state->base.dst));
11077         }
11078 }
11079
11080 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11081 {
11082         struct drm_device *dev = state->dev;
11083         struct drm_connector *connector;
11084         struct drm_connector_list_iter conn_iter;
11085         unsigned int used_ports = 0;
11086         unsigned int used_mst_ports = 0;
11087         bool ret = true;
11088
11089         /*
11090          * Walk the connector list instead of the encoder
11091          * list to detect the problem on ddi platforms
11092          * where there's just one encoder per digital port.
11093          */
11094         drm_connector_list_iter_begin(dev, &conn_iter);
11095         drm_for_each_connector_iter(connector, &conn_iter) {
11096                 struct drm_connector_state *connector_state;
11097                 struct intel_encoder *encoder;
11098
11099                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11100                 if (!connector_state)
11101                         connector_state = connector->state;
11102
11103                 if (!connector_state->best_encoder)
11104                         continue;
11105
11106                 encoder = to_intel_encoder(connector_state->best_encoder);
11107
11108                 WARN_ON(!connector_state->crtc);
11109
11110                 switch (encoder->type) {
11111                         unsigned int port_mask;
11112                 case INTEL_OUTPUT_DDI:
11113                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11114                                 break;
11115                         /* else: fall through */
11116                 case INTEL_OUTPUT_DP:
11117                 case INTEL_OUTPUT_HDMI:
11118                 case INTEL_OUTPUT_EDP:
11119                         port_mask = 1 << encoder->port;
11120
11121                         /* the same port mustn't appear more than once */
11122                         if (used_ports & port_mask)
11123                                 ret = false;
11124
11125                         used_ports |= port_mask;
11126                         break;
11127                 case INTEL_OUTPUT_DP_MST:
11128                         used_mst_ports |=
11129                                 1 << encoder->port;
11130                         break;
11131                 default:
11132                         break;
11133                 }
11134         }
11135         drm_connector_list_iter_end(&conn_iter);
11136
11137         /* can't mix MST and SST/HDMI on the same port */
11138         if (used_ports & used_mst_ports)
11139                 return false;
11140
11141         return ret;
11142 }
11143
11144 static void
11145 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11146 {
11147         struct drm_i915_private *dev_priv =
11148                 to_i915(crtc_state->base.crtc->dev);
11149         struct intel_crtc_scaler_state scaler_state;
11150         struct intel_dpll_hw_state dpll_hw_state;
11151         struct intel_shared_dpll *shared_dpll;
11152         struct intel_crtc_wm_state wm_state;
11153         bool force_thru, ips_force_disable;
11154
11155         /* FIXME: before the switch to atomic started, a new pipe_config was
11156          * kzalloc'd. Code that depends on any field being zero should be
11157          * fixed, so that the crtc_state can be safely duplicated. For now,
11158          * only fields that are know to not cause problems are preserved. */
11159
11160         scaler_state = crtc_state->scaler_state;
11161         shared_dpll = crtc_state->shared_dpll;
11162         dpll_hw_state = crtc_state->dpll_hw_state;
11163         force_thru = crtc_state->pch_pfit.force_thru;
11164         ips_force_disable = crtc_state->ips_force_disable;
11165         if (IS_G4X(dev_priv) ||
11166             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11167                 wm_state = crtc_state->wm;
11168
11169         /* Keep base drm_crtc_state intact, only clear our extended struct */
11170         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11171         memset(&crtc_state->base + 1, 0,
11172                sizeof(*crtc_state) - sizeof(crtc_state->base));
11173
11174         crtc_state->scaler_state = scaler_state;
11175         crtc_state->shared_dpll = shared_dpll;
11176         crtc_state->dpll_hw_state = dpll_hw_state;
11177         crtc_state->pch_pfit.force_thru = force_thru;
11178         crtc_state->ips_force_disable = ips_force_disable;
11179         if (IS_G4X(dev_priv) ||
11180             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11181                 crtc_state->wm = wm_state;
11182 }
11183
11184 static int
11185 intel_modeset_pipe_config(struct drm_crtc *crtc,
11186                           struct intel_crtc_state *pipe_config)
11187 {
11188         struct drm_atomic_state *state = pipe_config->base.state;
11189         struct intel_encoder *encoder;
11190         struct drm_connector *connector;
11191         struct drm_connector_state *connector_state;
11192         int base_bpp, ret = -EINVAL;
11193         int i;
11194         bool retry = true;
11195
11196         clear_intel_crtc_state(pipe_config);
11197
11198         pipe_config->cpu_transcoder =
11199                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11200
11201         /*
11202          * Sanitize sync polarity flags based on requested ones. If neither
11203          * positive or negative polarity is requested, treat this as meaning
11204          * negative polarity.
11205          */
11206         if (!(pipe_config->base.adjusted_mode.flags &
11207               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11208                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11209
11210         if (!(pipe_config->base.adjusted_mode.flags &
11211               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11212                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11213
11214         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11215                                              pipe_config);
11216         if (base_bpp < 0)
11217                 goto fail;
11218
11219         /*
11220          * Determine the real pipe dimensions. Note that stereo modes can
11221          * increase the actual pipe size due to the frame doubling and
11222          * insertion of additional space for blanks between the frame. This
11223          * is stored in the crtc timings. We use the requested mode to do this
11224          * computation to clearly distinguish it from the adjusted mode, which
11225          * can be changed by the connectors in the below retry loop.
11226          */
11227         drm_mode_get_hv_timing(&pipe_config->base.mode,
11228                                &pipe_config->pipe_src_w,
11229                                &pipe_config->pipe_src_h);
11230
11231         for_each_new_connector_in_state(state, connector, connector_state, i) {
11232                 if (connector_state->crtc != crtc)
11233                         continue;
11234
11235                 encoder = to_intel_encoder(connector_state->best_encoder);
11236
11237                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11238                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11239                         goto fail;
11240                 }
11241
11242                 /*
11243                  * Determine output_types before calling the .compute_config()
11244                  * hooks so that the hooks can use this information safely.
11245                  */
11246                 if (encoder->compute_output_type)
11247                         pipe_config->output_types |=
11248                                 BIT(encoder->compute_output_type(encoder, pipe_config,
11249                                                                  connector_state));
11250                 else
11251                         pipe_config->output_types |= BIT(encoder->type);
11252         }
11253
11254 encoder_retry:
11255         /* Ensure the port clock defaults are reset when retrying. */
11256         pipe_config->port_clock = 0;
11257         pipe_config->pixel_multiplier = 1;
11258
11259         /* Fill in default crtc timings, allow encoders to overwrite them. */
11260         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11261                               CRTC_STEREO_DOUBLE);
11262
11263         /* Pass our mode to the connectors and the CRTC to give them a chance to
11264          * adjust it according to limitations or connector properties, and also
11265          * a chance to reject the mode entirely.
11266          */
11267         for_each_new_connector_in_state(state, connector, connector_state, i) {
11268                 if (connector_state->crtc != crtc)
11269                         continue;
11270
11271                 encoder = to_intel_encoder(connector_state->best_encoder);
11272
11273                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
11274                         DRM_DEBUG_KMS("Encoder config failure\n");
11275                         goto fail;
11276                 }
11277         }
11278
11279         /* Set default port clock if not overwritten by the encoder. Needs to be
11280          * done afterwards in case the encoder adjusts the mode. */
11281         if (!pipe_config->port_clock)
11282                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11283                         * pipe_config->pixel_multiplier;
11284
11285         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11286         if (ret < 0) {
11287                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11288                 goto fail;
11289         }
11290
11291         if (ret == RETRY) {
11292                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11293                         ret = -EINVAL;
11294                         goto fail;
11295                 }
11296
11297                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11298                 retry = false;
11299                 goto encoder_retry;
11300         }
11301
11302         /* Dithering seems to not pass-through bits correctly when it should, so
11303          * only enable it on 6bpc panels and when its not a compliance
11304          * test requesting 6bpc video pattern.
11305          */
11306         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11307                 !pipe_config->dither_force_disable;
11308         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11309                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11310
11311 fail:
11312         return ret;
11313 }
11314
11315 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11316 {
11317         int diff;
11318
11319         if (clock1 == clock2)
11320                 return true;
11321
11322         if (!clock1 || !clock2)
11323                 return false;
11324
11325         diff = abs(clock1 - clock2);
11326
11327         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11328                 return true;
11329
11330         return false;
11331 }
11332
11333 static bool
11334 intel_compare_m_n(unsigned int m, unsigned int n,
11335                   unsigned int m2, unsigned int n2,
11336                   bool exact)
11337 {
11338         if (m == m2 && n == n2)
11339                 return true;
11340
11341         if (exact || !m || !n || !m2 || !n2)
11342                 return false;
11343
11344         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11345
11346         if (n > n2) {
11347                 while (n > n2) {
11348                         m2 <<= 1;
11349                         n2 <<= 1;
11350                 }
11351         } else if (n < n2) {
11352                 while (n < n2) {
11353                         m <<= 1;
11354                         n <<= 1;
11355                 }
11356         }
11357
11358         if (n != n2)
11359                 return false;
11360
11361         return intel_fuzzy_clock_check(m, m2);
11362 }
11363
11364 static bool
11365 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11366                        struct intel_link_m_n *m2_n2,
11367                        bool adjust)
11368 {
11369         if (m_n->tu == m2_n2->tu &&
11370             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11371                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11372             intel_compare_m_n(m_n->link_m, m_n->link_n,
11373                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11374                 if (adjust)
11375                         *m2_n2 = *m_n;
11376
11377                 return true;
11378         }
11379
11380         return false;
11381 }
11382
11383 static void __printf(3, 4)
11384 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11385 {
11386         struct va_format vaf;
11387         va_list args;
11388
11389         va_start(args, format);
11390         vaf.fmt = format;
11391         vaf.va = &args;
11392
11393         if (adjust)
11394                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11395         else
11396                 drm_err("mismatch in %s %pV", name, &vaf);
11397
11398         va_end(args);
11399 }
11400
11401 static bool
11402 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11403                           struct intel_crtc_state *current_config,
11404                           struct intel_crtc_state *pipe_config,
11405                           bool adjust)
11406 {
11407         bool ret = true;
11408         bool fixup_inherited = adjust &&
11409                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11410                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11411
11412 #define PIPE_CONF_CHECK_X(name) do { \
11413         if (current_config->name != pipe_config->name) { \
11414                 pipe_config_err(adjust, __stringify(name), \
11415                           "(expected 0x%08x, found 0x%08x)\n", \
11416                           current_config->name, \
11417                           pipe_config->name); \
11418                 ret = false; \
11419         } \
11420 } while (0)
11421
11422 #define PIPE_CONF_CHECK_I(name) do { \
11423         if (current_config->name != pipe_config->name) { \
11424                 pipe_config_err(adjust, __stringify(name), \
11425                           "(expected %i, found %i)\n", \
11426                           current_config->name, \
11427                           pipe_config->name); \
11428                 ret = false; \
11429         } \
11430 } while (0)
11431
11432 #define PIPE_CONF_CHECK_BOOL(name) do { \
11433         if (current_config->name != pipe_config->name) { \
11434                 pipe_config_err(adjust, __stringify(name), \
11435                           "(expected %s, found %s)\n", \
11436                           yesno(current_config->name), \
11437                           yesno(pipe_config->name)); \
11438                 ret = false; \
11439         } \
11440 } while (0)
11441
11442 /*
11443  * Checks state where we only read out the enabling, but not the entire
11444  * state itself (like full infoframes or ELD for audio). These states
11445  * require a full modeset on bootup to fix up.
11446  */
11447 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
11448         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11449                 PIPE_CONF_CHECK_BOOL(name); \
11450         } else { \
11451                 pipe_config_err(adjust, __stringify(name), \
11452                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11453                           yesno(current_config->name), \
11454                           yesno(pipe_config->name)); \
11455                 ret = false; \
11456         } \
11457 } while (0)
11458
11459 #define PIPE_CONF_CHECK_P(name) do { \
11460         if (current_config->name != pipe_config->name) { \
11461                 pipe_config_err(adjust, __stringify(name), \
11462                           "(expected %p, found %p)\n", \
11463                           current_config->name, \
11464                           pipe_config->name); \
11465                 ret = false; \
11466         } \
11467 } while (0)
11468
11469 #define PIPE_CONF_CHECK_M_N(name) do { \
11470         if (!intel_compare_link_m_n(&current_config->name, \
11471                                     &pipe_config->name,\
11472                                     adjust)) { \
11473                 pipe_config_err(adjust, __stringify(name), \
11474                           "(expected tu %i gmch %i/%i link %i/%i, " \
11475                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11476                           current_config->name.tu, \
11477                           current_config->name.gmch_m, \
11478                           current_config->name.gmch_n, \
11479                           current_config->name.link_m, \
11480                           current_config->name.link_n, \
11481                           pipe_config->name.tu, \
11482                           pipe_config->name.gmch_m, \
11483                           pipe_config->name.gmch_n, \
11484                           pipe_config->name.link_m, \
11485                           pipe_config->name.link_n); \
11486                 ret = false; \
11487         } \
11488 } while (0)
11489
11490 /* This is required for BDW+ where there is only one set of registers for
11491  * switching between high and low RR.
11492  * This macro can be used whenever a comparison has to be made between one
11493  * hw state and multiple sw state variables.
11494  */
11495 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
11496         if (!intel_compare_link_m_n(&current_config->name, \
11497                                     &pipe_config->name, adjust) && \
11498             !intel_compare_link_m_n(&current_config->alt_name, \
11499                                     &pipe_config->name, adjust)) { \
11500                 pipe_config_err(adjust, __stringify(name), \
11501                           "(expected tu %i gmch %i/%i link %i/%i, " \
11502                           "or tu %i gmch %i/%i link %i/%i, " \
11503                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11504                           current_config->name.tu, \
11505                           current_config->name.gmch_m, \
11506                           current_config->name.gmch_n, \
11507                           current_config->name.link_m, \
11508                           current_config->name.link_n, \
11509                           current_config->alt_name.tu, \
11510                           current_config->alt_name.gmch_m, \
11511                           current_config->alt_name.gmch_n, \
11512                           current_config->alt_name.link_m, \
11513                           current_config->alt_name.link_n, \
11514                           pipe_config->name.tu, \
11515                           pipe_config->name.gmch_m, \
11516                           pipe_config->name.gmch_n, \
11517                           pipe_config->name.link_m, \
11518                           pipe_config->name.link_n); \
11519                 ret = false; \
11520         } \
11521 } while (0)
11522
11523 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
11524         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11525                 pipe_config_err(adjust, __stringify(name), \
11526                           "(%x) (expected %i, found %i)\n", \
11527                           (mask), \
11528                           current_config->name & (mask), \
11529                           pipe_config->name & (mask)); \
11530                 ret = false; \
11531         } \
11532 } while (0)
11533
11534 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
11535         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11536                 pipe_config_err(adjust, __stringify(name), \
11537                           "(expected %i, found %i)\n", \
11538                           current_config->name, \
11539                           pipe_config->name); \
11540                 ret = false; \
11541         } \
11542 } while (0)
11543
11544 #define PIPE_CONF_QUIRK(quirk)  \
11545         ((current_config->quirks | pipe_config->quirks) & (quirk))
11546
11547         PIPE_CONF_CHECK_I(cpu_transcoder);
11548
11549         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11550         PIPE_CONF_CHECK_I(fdi_lanes);
11551         PIPE_CONF_CHECK_M_N(fdi_m_n);
11552
11553         PIPE_CONF_CHECK_I(lane_count);
11554         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11555
11556         if (INTEL_GEN(dev_priv) < 8) {
11557                 PIPE_CONF_CHECK_M_N(dp_m_n);
11558
11559                 if (current_config->has_drrs)
11560                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11561         } else
11562                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11563
11564         PIPE_CONF_CHECK_X(output_types);
11565
11566         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11567         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11568         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11569         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11570         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11571         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11572
11573         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11574         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11575         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11576         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11577         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11578         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11579
11580         PIPE_CONF_CHECK_I(pixel_multiplier);
11581         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11582         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11583             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11584                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11585
11586         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11587         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11588         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11589         PIPE_CONF_CHECK_BOOL(ycbcr420);
11590
11591         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11592
11593         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11594                               DRM_MODE_FLAG_INTERLACE);
11595
11596         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11597                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11598                                       DRM_MODE_FLAG_PHSYNC);
11599                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11600                                       DRM_MODE_FLAG_NHSYNC);
11601                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11602                                       DRM_MODE_FLAG_PVSYNC);
11603                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11604                                       DRM_MODE_FLAG_NVSYNC);
11605         }
11606
11607         PIPE_CONF_CHECK_X(gmch_pfit.control);
11608         /* pfit ratios are autocomputed by the hw on gen4+ */
11609         if (INTEL_GEN(dev_priv) < 4)
11610                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11611         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11612
11613         if (!adjust) {
11614                 PIPE_CONF_CHECK_I(pipe_src_w);
11615                 PIPE_CONF_CHECK_I(pipe_src_h);
11616
11617                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11618                 if (current_config->pch_pfit.enabled) {
11619                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11620                         PIPE_CONF_CHECK_X(pch_pfit.size);
11621                 }
11622
11623                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11624                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11625         }
11626
11627         PIPE_CONF_CHECK_BOOL(double_wide);
11628
11629         PIPE_CONF_CHECK_P(shared_dpll);
11630         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11631         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11632         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11633         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11634         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11635         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11636         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11637         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11638         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11639         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11640         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11641         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11642         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11643         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11644         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11645         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11646         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11647         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11648         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11649         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11650         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11651         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
11652         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
11653         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
11654         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
11655         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
11656         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
11657         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
11658         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
11659         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
11660         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
11661
11662         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11663         PIPE_CONF_CHECK_X(dsi_pll.div);
11664
11665         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11666                 PIPE_CONF_CHECK_I(pipe_bpp);
11667
11668         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11669         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11670
11671         PIPE_CONF_CHECK_I(min_voltage_level);
11672
11673 #undef PIPE_CONF_CHECK_X
11674 #undef PIPE_CONF_CHECK_I
11675 #undef PIPE_CONF_CHECK_BOOL
11676 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11677 #undef PIPE_CONF_CHECK_P
11678 #undef PIPE_CONF_CHECK_FLAGS
11679 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11680 #undef PIPE_CONF_QUIRK
11681
11682         return ret;
11683 }
11684
11685 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11686                                            const struct intel_crtc_state *pipe_config)
11687 {
11688         if (pipe_config->has_pch_encoder) {
11689                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11690                                                             &pipe_config->fdi_m_n);
11691                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11692
11693                 /*
11694                  * FDI already provided one idea for the dotclock.
11695                  * Yell if the encoder disagrees.
11696                  */
11697                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11698                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11699                      fdi_dotclock, dotclock);
11700         }
11701 }
11702
11703 static void verify_wm_state(struct drm_crtc *crtc,
11704                             struct drm_crtc_state *new_state)
11705 {
11706         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11707         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11708         struct skl_pipe_wm hw_wm, *sw_wm;
11709         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11710         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11711         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11712         const enum pipe pipe = intel_crtc->pipe;
11713         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11714
11715         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11716                 return;
11717
11718         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11719         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11720
11721         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11722         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11723
11724         if (INTEL_GEN(dev_priv) >= 11)
11725                 if (hw_ddb.enabled_slices != sw_ddb->enabled_slices)
11726                         DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
11727                                   sw_ddb->enabled_slices,
11728                                   hw_ddb.enabled_slices);
11729         /* planes */
11730         for_each_universal_plane(dev_priv, pipe, plane) {
11731                 hw_plane_wm = &hw_wm.planes[plane];
11732                 sw_plane_wm = &sw_wm->planes[plane];
11733
11734                 /* Watermarks */
11735                 for (level = 0; level <= max_level; level++) {
11736                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11737                                                 &sw_plane_wm->wm[level]))
11738                                 continue;
11739
11740                         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",
11741                                   pipe_name(pipe), plane + 1, level,
11742                                   sw_plane_wm->wm[level].plane_en,
11743                                   sw_plane_wm->wm[level].plane_res_b,
11744                                   sw_plane_wm->wm[level].plane_res_l,
11745                                   hw_plane_wm->wm[level].plane_en,
11746                                   hw_plane_wm->wm[level].plane_res_b,
11747                                   hw_plane_wm->wm[level].plane_res_l);
11748                 }
11749
11750                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11751                                          &sw_plane_wm->trans_wm)) {
11752                         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",
11753                                   pipe_name(pipe), plane + 1,
11754                                   sw_plane_wm->trans_wm.plane_en,
11755                                   sw_plane_wm->trans_wm.plane_res_b,
11756                                   sw_plane_wm->trans_wm.plane_res_l,
11757                                   hw_plane_wm->trans_wm.plane_en,
11758                                   hw_plane_wm->trans_wm.plane_res_b,
11759                                   hw_plane_wm->trans_wm.plane_res_l);
11760                 }
11761
11762                 /* DDB */
11763                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11764                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11765
11766                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11767                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11768                                   pipe_name(pipe), plane + 1,
11769                                   sw_ddb_entry->start, sw_ddb_entry->end,
11770                                   hw_ddb_entry->start, hw_ddb_entry->end);
11771                 }
11772         }
11773
11774         /*
11775          * cursor
11776          * If the cursor plane isn't active, we may not have updated it's ddb
11777          * allocation. In that case since the ddb allocation will be updated
11778          * once the plane becomes visible, we can skip this check
11779          */
11780         if (1) {
11781                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11782                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11783
11784                 /* Watermarks */
11785                 for (level = 0; level <= max_level; level++) {
11786                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11787                                                 &sw_plane_wm->wm[level]))
11788                                 continue;
11789
11790                         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",
11791                                   pipe_name(pipe), level,
11792                                   sw_plane_wm->wm[level].plane_en,
11793                                   sw_plane_wm->wm[level].plane_res_b,
11794                                   sw_plane_wm->wm[level].plane_res_l,
11795                                   hw_plane_wm->wm[level].plane_en,
11796                                   hw_plane_wm->wm[level].plane_res_b,
11797                                   hw_plane_wm->wm[level].plane_res_l);
11798                 }
11799
11800                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11801                                          &sw_plane_wm->trans_wm)) {
11802                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11803                                   pipe_name(pipe),
11804                                   sw_plane_wm->trans_wm.plane_en,
11805                                   sw_plane_wm->trans_wm.plane_res_b,
11806                                   sw_plane_wm->trans_wm.plane_res_l,
11807                                   hw_plane_wm->trans_wm.plane_en,
11808                                   hw_plane_wm->trans_wm.plane_res_b,
11809                                   hw_plane_wm->trans_wm.plane_res_l);
11810                 }
11811
11812                 /* DDB */
11813                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11814                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11815
11816                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11817                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11818                                   pipe_name(pipe),
11819                                   sw_ddb_entry->start, sw_ddb_entry->end,
11820                                   hw_ddb_entry->start, hw_ddb_entry->end);
11821                 }
11822         }
11823 }
11824
11825 static void
11826 verify_connector_state(struct drm_device *dev,
11827                        struct drm_atomic_state *state,
11828                        struct drm_crtc *crtc)
11829 {
11830         struct drm_connector *connector;
11831         struct drm_connector_state *new_conn_state;
11832         int i;
11833
11834         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11835                 struct drm_encoder *encoder = connector->encoder;
11836                 struct drm_crtc_state *crtc_state = NULL;
11837
11838                 if (new_conn_state->crtc != crtc)
11839                         continue;
11840
11841                 if (crtc)
11842                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11843
11844                 intel_connector_verify_state(crtc_state, new_conn_state);
11845
11846                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11847                      "connector's atomic encoder doesn't match legacy encoder\n");
11848         }
11849 }
11850
11851 static void
11852 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11853 {
11854         struct intel_encoder *encoder;
11855         struct drm_connector *connector;
11856         struct drm_connector_state *old_conn_state, *new_conn_state;
11857         int i;
11858
11859         for_each_intel_encoder(dev, encoder) {
11860                 bool enabled = false, found = false;
11861                 enum pipe pipe;
11862
11863                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11864                               encoder->base.base.id,
11865                               encoder->base.name);
11866
11867                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11868                                                    new_conn_state, i) {
11869                         if (old_conn_state->best_encoder == &encoder->base)
11870                                 found = true;
11871
11872                         if (new_conn_state->best_encoder != &encoder->base)
11873                                 continue;
11874                         found = enabled = true;
11875
11876                         I915_STATE_WARN(new_conn_state->crtc !=
11877                                         encoder->base.crtc,
11878                              "connector's crtc doesn't match encoder crtc\n");
11879                 }
11880
11881                 if (!found)
11882                         continue;
11883
11884                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11885                      "encoder's enabled state mismatch "
11886                      "(expected %i, found %i)\n",
11887                      !!encoder->base.crtc, enabled);
11888
11889                 if (!encoder->base.crtc) {
11890                         bool active;
11891
11892                         active = encoder->get_hw_state(encoder, &pipe);
11893                         I915_STATE_WARN(active,
11894                              "encoder detached but still enabled on pipe %c.\n",
11895                              pipe_name(pipe));
11896                 }
11897         }
11898 }
11899
11900 static void
11901 verify_crtc_state(struct drm_crtc *crtc,
11902                   struct drm_crtc_state *old_crtc_state,
11903                   struct drm_crtc_state *new_crtc_state)
11904 {
11905         struct drm_device *dev = crtc->dev;
11906         struct drm_i915_private *dev_priv = to_i915(dev);
11907         struct intel_encoder *encoder;
11908         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11909         struct intel_crtc_state *pipe_config, *sw_config;
11910         struct drm_atomic_state *old_state;
11911         bool active;
11912
11913         old_state = old_crtc_state->state;
11914         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11915         pipe_config = to_intel_crtc_state(old_crtc_state);
11916         memset(pipe_config, 0, sizeof(*pipe_config));
11917         pipe_config->base.crtc = crtc;
11918         pipe_config->base.state = old_state;
11919
11920         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11921
11922         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11923
11924         /* we keep both pipes enabled on 830 */
11925         if (IS_I830(dev_priv))
11926                 active = new_crtc_state->active;
11927
11928         I915_STATE_WARN(new_crtc_state->active != active,
11929              "crtc active state doesn't match with hw state "
11930              "(expected %i, found %i)\n", new_crtc_state->active, active);
11931
11932         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11933              "transitional active state does not match atomic hw state "
11934              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11935
11936         for_each_encoder_on_crtc(dev, crtc, encoder) {
11937                 enum pipe pipe;
11938
11939                 active = encoder->get_hw_state(encoder, &pipe);
11940                 I915_STATE_WARN(active != new_crtc_state->active,
11941                         "[ENCODER:%i] active %i with crtc active %i\n",
11942                         encoder->base.base.id, active, new_crtc_state->active);
11943
11944                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11945                                 "Encoder connected to wrong pipe %c\n",
11946                                 pipe_name(pipe));
11947
11948                 if (active)
11949                         encoder->get_config(encoder, pipe_config);
11950         }
11951
11952         intel_crtc_compute_pixel_rate(pipe_config);
11953
11954         if (!new_crtc_state->active)
11955                 return;
11956
11957         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11958
11959         sw_config = to_intel_crtc_state(new_crtc_state);
11960         if (!intel_pipe_config_compare(dev_priv, sw_config,
11961                                        pipe_config, false)) {
11962                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11963                 intel_dump_pipe_config(intel_crtc, pipe_config,
11964                                        "[hw state]");
11965                 intel_dump_pipe_config(intel_crtc, sw_config,
11966                                        "[sw state]");
11967         }
11968 }
11969
11970 static void
11971 intel_verify_planes(struct intel_atomic_state *state)
11972 {
11973         struct intel_plane *plane;
11974         const struct intel_plane_state *plane_state;
11975         int i;
11976
11977         for_each_new_intel_plane_in_state(state, plane,
11978                                           plane_state, i)
11979                 assert_plane(plane, plane_state->base.visible);
11980 }
11981
11982 static void
11983 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11984                          struct intel_shared_dpll *pll,
11985                          struct drm_crtc *crtc,
11986                          struct drm_crtc_state *new_state)
11987 {
11988         struct intel_dpll_hw_state dpll_hw_state;
11989         unsigned int crtc_mask;
11990         bool active;
11991
11992         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11993
11994         DRM_DEBUG_KMS("%s\n", pll->info->name);
11995
11996         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
11997
11998         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
11999                 I915_STATE_WARN(!pll->on && pll->active_mask,
12000                      "pll in active use but not on in sw tracking\n");
12001                 I915_STATE_WARN(pll->on && !pll->active_mask,
12002                      "pll is on but not used by any active crtc\n");
12003                 I915_STATE_WARN(pll->on != active,
12004                      "pll on state mismatch (expected %i, found %i)\n",
12005                      pll->on, active);
12006         }
12007
12008         if (!crtc) {
12009                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12010                                 "more active pll users than references: %x vs %x\n",
12011                                 pll->active_mask, pll->state.crtc_mask);
12012
12013                 return;
12014         }
12015
12016         crtc_mask = drm_crtc_mask(crtc);
12017
12018         if (new_state->active)
12019                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12020                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12021                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12022         else
12023                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12024                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12025                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12026
12027         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12028                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12029                         crtc_mask, pll->state.crtc_mask);
12030
12031         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12032                                           &dpll_hw_state,
12033                                           sizeof(dpll_hw_state)),
12034                         "pll hw state mismatch\n");
12035 }
12036
12037 static void
12038 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12039                          struct drm_crtc_state *old_crtc_state,
12040                          struct drm_crtc_state *new_crtc_state)
12041 {
12042         struct drm_i915_private *dev_priv = to_i915(dev);
12043         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12044         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12045
12046         if (new_state->shared_dpll)
12047                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12048
12049         if (old_state->shared_dpll &&
12050             old_state->shared_dpll != new_state->shared_dpll) {
12051                 unsigned int crtc_mask = drm_crtc_mask(crtc);
12052                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12053
12054                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12055                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12056                                 pipe_name(drm_crtc_index(crtc)));
12057                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12058                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12059                                 pipe_name(drm_crtc_index(crtc)));
12060         }
12061 }
12062
12063 static void
12064 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12065                           struct drm_atomic_state *state,
12066                           struct drm_crtc_state *old_state,
12067                           struct drm_crtc_state *new_state)
12068 {
12069         if (!needs_modeset(new_state) &&
12070             !to_intel_crtc_state(new_state)->update_pipe)
12071                 return;
12072
12073         verify_wm_state(crtc, new_state);
12074         verify_connector_state(crtc->dev, state, crtc);
12075         verify_crtc_state(crtc, old_state, new_state);
12076         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12077 }
12078
12079 static void
12080 verify_disabled_dpll_state(struct drm_device *dev)
12081 {
12082         struct drm_i915_private *dev_priv = to_i915(dev);
12083         int i;
12084
12085         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12086                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12087 }
12088
12089 static void
12090 intel_modeset_verify_disabled(struct drm_device *dev,
12091                               struct drm_atomic_state *state)
12092 {
12093         verify_encoder_state(dev, state);
12094         verify_connector_state(dev, state, NULL);
12095         verify_disabled_dpll_state(dev);
12096 }
12097
12098 static void update_scanline_offset(struct intel_crtc *crtc)
12099 {
12100         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12101
12102         /*
12103          * The scanline counter increments at the leading edge of hsync.
12104          *
12105          * On most platforms it starts counting from vtotal-1 on the
12106          * first active line. That means the scanline counter value is
12107          * always one less than what we would expect. Ie. just after
12108          * start of vblank, which also occurs at start of hsync (on the
12109          * last active line), the scanline counter will read vblank_start-1.
12110          *
12111          * On gen2 the scanline counter starts counting from 1 instead
12112          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12113          * to keep the value positive), instead of adding one.
12114          *
12115          * On HSW+ the behaviour of the scanline counter depends on the output
12116          * type. For DP ports it behaves like most other platforms, but on HDMI
12117          * there's an extra 1 line difference. So we need to add two instead of
12118          * one to the value.
12119          *
12120          * On VLV/CHV DSI the scanline counter would appear to increment
12121          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12122          * that means we can't tell whether we're in vblank or not while
12123          * we're on that particular line. We must still set scanline_offset
12124          * to 1 so that the vblank timestamps come out correct when we query
12125          * the scanline counter from within the vblank interrupt handler.
12126          * However if queried just before the start of vblank we'll get an
12127          * answer that's slightly in the future.
12128          */
12129         if (IS_GEN2(dev_priv)) {
12130                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
12131                 int vtotal;
12132
12133                 vtotal = adjusted_mode->crtc_vtotal;
12134                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12135                         vtotal /= 2;
12136
12137                 crtc->scanline_offset = vtotal - 1;
12138         } else if (HAS_DDI(dev_priv) &&
12139                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
12140                 crtc->scanline_offset = 2;
12141         } else
12142                 crtc->scanline_offset = 1;
12143 }
12144
12145 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12146 {
12147         struct drm_device *dev = state->dev;
12148         struct drm_i915_private *dev_priv = to_i915(dev);
12149         struct drm_crtc *crtc;
12150         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12151         int i;
12152
12153         if (!dev_priv->display.crtc_compute_clock)
12154                 return;
12155
12156         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12157                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12158                 struct intel_shared_dpll *old_dpll =
12159                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12160
12161                 if (!needs_modeset(new_crtc_state))
12162                         continue;
12163
12164                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12165
12166                 if (!old_dpll)
12167                         continue;
12168
12169                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12170         }
12171 }
12172
12173 /*
12174  * This implements the workaround described in the "notes" section of the mode
12175  * set sequence documentation. When going from no pipes or single pipe to
12176  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12177  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12178  */
12179 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12180 {
12181         struct drm_crtc_state *crtc_state;
12182         struct intel_crtc *intel_crtc;
12183         struct drm_crtc *crtc;
12184         struct intel_crtc_state *first_crtc_state = NULL;
12185         struct intel_crtc_state *other_crtc_state = NULL;
12186         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12187         int i;
12188
12189         /* look at all crtc's that are going to be enabled in during modeset */
12190         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12191                 intel_crtc = to_intel_crtc(crtc);
12192
12193                 if (!crtc_state->active || !needs_modeset(crtc_state))
12194                         continue;
12195
12196                 if (first_crtc_state) {
12197                         other_crtc_state = to_intel_crtc_state(crtc_state);
12198                         break;
12199                 } else {
12200                         first_crtc_state = to_intel_crtc_state(crtc_state);
12201                         first_pipe = intel_crtc->pipe;
12202                 }
12203         }
12204
12205         /* No workaround needed? */
12206         if (!first_crtc_state)
12207                 return 0;
12208
12209         /* w/a possibly needed, check how many crtc's are already enabled. */
12210         for_each_intel_crtc(state->dev, intel_crtc) {
12211                 struct intel_crtc_state *pipe_config;
12212
12213                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12214                 if (IS_ERR(pipe_config))
12215                         return PTR_ERR(pipe_config);
12216
12217                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12218
12219                 if (!pipe_config->base.active ||
12220                     needs_modeset(&pipe_config->base))
12221                         continue;
12222
12223                 /* 2 or more enabled crtcs means no need for w/a */
12224                 if (enabled_pipe != INVALID_PIPE)
12225                         return 0;
12226
12227                 enabled_pipe = intel_crtc->pipe;
12228         }
12229
12230         if (enabled_pipe != INVALID_PIPE)
12231                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12232         else if (other_crtc_state)
12233                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12234
12235         return 0;
12236 }
12237
12238 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12239 {
12240         struct drm_crtc *crtc;
12241
12242         /* Add all pipes to the state */
12243         for_each_crtc(state->dev, crtc) {
12244                 struct drm_crtc_state *crtc_state;
12245
12246                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12247                 if (IS_ERR(crtc_state))
12248                         return PTR_ERR(crtc_state);
12249         }
12250
12251         return 0;
12252 }
12253
12254 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12255 {
12256         struct drm_crtc *crtc;
12257
12258         /*
12259          * Add all pipes to the state, and force
12260          * a modeset on all the active ones.
12261          */
12262         for_each_crtc(state->dev, crtc) {
12263                 struct drm_crtc_state *crtc_state;
12264                 int ret;
12265
12266                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12267                 if (IS_ERR(crtc_state))
12268                         return PTR_ERR(crtc_state);
12269
12270                 if (!crtc_state->active || needs_modeset(crtc_state))
12271                         continue;
12272
12273                 crtc_state->mode_changed = true;
12274
12275                 ret = drm_atomic_add_affected_connectors(state, crtc);
12276                 if (ret)
12277                         return ret;
12278
12279                 ret = drm_atomic_add_affected_planes(state, crtc);
12280                 if (ret)
12281                         return ret;
12282         }
12283
12284         return 0;
12285 }
12286
12287 static int intel_modeset_checks(struct drm_atomic_state *state)
12288 {
12289         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12290         struct drm_i915_private *dev_priv = to_i915(state->dev);
12291         struct drm_crtc *crtc;
12292         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12293         int ret = 0, i;
12294
12295         if (!check_digital_port_conflicts(state)) {
12296                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12297                 return -EINVAL;
12298         }
12299
12300         intel_state->modeset = true;
12301         intel_state->active_crtcs = dev_priv->active_crtcs;
12302         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12303         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12304
12305         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12306                 if (new_crtc_state->active)
12307                         intel_state->active_crtcs |= 1 << i;
12308                 else
12309                         intel_state->active_crtcs &= ~(1 << i);
12310
12311                 if (old_crtc_state->active != new_crtc_state->active)
12312                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12313         }
12314
12315         /*
12316          * See if the config requires any additional preparation, e.g.
12317          * to adjust global state with pipes off.  We need to do this
12318          * here so we can get the modeset_pipe updated config for the new
12319          * mode set on this crtc.  For other crtcs we need to use the
12320          * adjusted_mode bits in the crtc directly.
12321          */
12322         if (dev_priv->display.modeset_calc_cdclk) {
12323                 ret = dev_priv->display.modeset_calc_cdclk(state);
12324                 if (ret < 0)
12325                         return ret;
12326
12327                 /*
12328                  * Writes to dev_priv->cdclk.logical must protected by
12329                  * holding all the crtc locks, even if we don't end up
12330                  * touching the hardware
12331                  */
12332                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12333                                         &intel_state->cdclk.logical)) {
12334                         ret = intel_lock_all_pipes(state);
12335                         if (ret < 0)
12336                                 return ret;
12337                 }
12338
12339                 /* All pipes must be switched off while we change the cdclk. */
12340                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12341                                               &intel_state->cdclk.actual)) {
12342                         ret = intel_modeset_all_pipes(state);
12343                         if (ret < 0)
12344                                 return ret;
12345                 }
12346
12347                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12348                               intel_state->cdclk.logical.cdclk,
12349                               intel_state->cdclk.actual.cdclk);
12350                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12351                               intel_state->cdclk.logical.voltage_level,
12352                               intel_state->cdclk.actual.voltage_level);
12353         } else {
12354                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12355         }
12356
12357         intel_modeset_clear_plls(state);
12358
12359         if (IS_HASWELL(dev_priv))
12360                 return haswell_mode_set_planes_workaround(state);
12361
12362         return 0;
12363 }
12364
12365 /*
12366  * Handle calculation of various watermark data at the end of the atomic check
12367  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12368  * handlers to ensure that all derived state has been updated.
12369  */
12370 static int calc_watermark_data(struct drm_atomic_state *state)
12371 {
12372         struct drm_device *dev = state->dev;
12373         struct drm_i915_private *dev_priv = to_i915(dev);
12374
12375         /* Is there platform-specific watermark information to calculate? */
12376         if (dev_priv->display.compute_global_watermarks)
12377                 return dev_priv->display.compute_global_watermarks(state);
12378
12379         return 0;
12380 }
12381
12382 /**
12383  * intel_atomic_check - validate state object
12384  * @dev: drm device
12385  * @state: state to validate
12386  */
12387 static int intel_atomic_check(struct drm_device *dev,
12388                               struct drm_atomic_state *state)
12389 {
12390         struct drm_i915_private *dev_priv = to_i915(dev);
12391         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12392         struct drm_crtc *crtc;
12393         struct drm_crtc_state *old_crtc_state, *crtc_state;
12394         int ret, i;
12395         bool any_ms = false;
12396
12397         /* Catch I915_MODE_FLAG_INHERITED */
12398         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12399                                       crtc_state, i) {
12400                 if (crtc_state->mode.private_flags !=
12401                     old_crtc_state->mode.private_flags)
12402                         crtc_state->mode_changed = true;
12403         }
12404
12405         ret = drm_atomic_helper_check_modeset(dev, state);
12406         if (ret)
12407                 return ret;
12408
12409         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12410                 struct intel_crtc_state *pipe_config =
12411                         to_intel_crtc_state(crtc_state);
12412
12413                 if (!needs_modeset(crtc_state))
12414                         continue;
12415
12416                 if (!crtc_state->enable) {
12417                         any_ms = true;
12418                         continue;
12419                 }
12420
12421                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12422                 if (ret) {
12423                         intel_dump_pipe_config(to_intel_crtc(crtc),
12424                                                pipe_config, "[failed]");
12425                         return ret;
12426                 }
12427
12428                 if (i915_modparams.fastboot &&
12429                     intel_pipe_config_compare(dev_priv,
12430                                         to_intel_crtc_state(old_crtc_state),
12431                                         pipe_config, true)) {
12432                         crtc_state->mode_changed = false;
12433                         pipe_config->update_pipe = true;
12434                 }
12435
12436                 if (needs_modeset(crtc_state))
12437                         any_ms = true;
12438
12439                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12440                                        needs_modeset(crtc_state) ?
12441                                        "[modeset]" : "[fastset]");
12442         }
12443
12444         if (any_ms) {
12445                 ret = intel_modeset_checks(state);
12446
12447                 if (ret)
12448                         return ret;
12449         } else {
12450                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12451         }
12452
12453         ret = drm_atomic_helper_check_planes(dev, state);
12454         if (ret)
12455                 return ret;
12456
12457         intel_fbc_choose_crtc(dev_priv, intel_state);
12458         return calc_watermark_data(state);
12459 }
12460
12461 static int intel_atomic_prepare_commit(struct drm_device *dev,
12462                                        struct drm_atomic_state *state)
12463 {
12464         return drm_atomic_helper_prepare_planes(dev, state);
12465 }
12466
12467 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12468 {
12469         struct drm_device *dev = crtc->base.dev;
12470
12471         if (!dev->max_vblank_count)
12472                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12473
12474         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12475 }
12476
12477 static void intel_update_crtc(struct drm_crtc *crtc,
12478                               struct drm_atomic_state *state,
12479                               struct drm_crtc_state *old_crtc_state,
12480                               struct drm_crtc_state *new_crtc_state)
12481 {
12482         struct drm_device *dev = crtc->dev;
12483         struct drm_i915_private *dev_priv = to_i915(dev);
12484         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12485         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12486         bool modeset = needs_modeset(new_crtc_state);
12487         struct intel_plane_state *new_plane_state =
12488                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
12489                                                  to_intel_plane(crtc->primary));
12490
12491         if (modeset) {
12492                 update_scanline_offset(intel_crtc);
12493                 dev_priv->display.crtc_enable(pipe_config, state);
12494
12495                 /* vblanks work again, re-enable pipe CRC. */
12496                 intel_crtc_enable_pipe_crc(intel_crtc);
12497         } else {
12498                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12499                                        pipe_config);
12500         }
12501
12502         if (new_plane_state)
12503                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
12504
12505         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12506 }
12507
12508 static void intel_update_crtcs(struct drm_atomic_state *state)
12509 {
12510         struct drm_crtc *crtc;
12511         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12512         int i;
12513
12514         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12515                 if (!new_crtc_state->active)
12516                         continue;
12517
12518                 intel_update_crtc(crtc, state, old_crtc_state,
12519                                   new_crtc_state);
12520         }
12521 }
12522
12523 static void skl_update_crtcs(struct drm_atomic_state *state)
12524 {
12525         struct drm_i915_private *dev_priv = to_i915(state->dev);
12526         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12527         struct drm_crtc *crtc;
12528         struct intel_crtc *intel_crtc;
12529         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12530         struct intel_crtc_state *cstate;
12531         unsigned int updated = 0;
12532         bool progress;
12533         enum pipe pipe;
12534         int i;
12535         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
12536         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
12537
12538         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12539
12540         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12541                 /* ignore allocations for crtc's that have been turned off. */
12542                 if (new_crtc_state->active)
12543                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12544
12545         /* If 2nd DBuf slice required, enable it here */
12546         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
12547                 icl_dbuf_slices_update(dev_priv, required_slices);
12548
12549         /*
12550          * Whenever the number of active pipes changes, we need to make sure we
12551          * update the pipes in the right order so that their ddb allocations
12552          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12553          * cause pipe underruns and other bad stuff.
12554          */
12555         do {
12556                 progress = false;
12557
12558                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12559                         bool vbl_wait = false;
12560                         unsigned int cmask = drm_crtc_mask(crtc);
12561
12562                         intel_crtc = to_intel_crtc(crtc);
12563                         cstate = to_intel_crtc_state(new_crtc_state);
12564                         pipe = intel_crtc->pipe;
12565
12566                         if (updated & cmask || !cstate->base.active)
12567                                 continue;
12568
12569                         if (skl_ddb_allocation_overlaps(dev_priv,
12570                                                         entries,
12571                                                         &cstate->wm.skl.ddb,
12572                                                         i))
12573                                 continue;
12574
12575                         updated |= cmask;
12576                         entries[i] = &cstate->wm.skl.ddb;
12577
12578                         /*
12579                          * If this is an already active pipe, it's DDB changed,
12580                          * and this isn't the last pipe that needs updating
12581                          * then we need to wait for a vblank to pass for the
12582                          * new ddb allocation to take effect.
12583                          */
12584                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12585                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12586                             !new_crtc_state->active_changed &&
12587                             intel_state->wm_results.dirty_pipes != updated)
12588                                 vbl_wait = true;
12589
12590                         intel_update_crtc(crtc, state, old_crtc_state,
12591                                           new_crtc_state);
12592
12593                         if (vbl_wait)
12594                                 intel_wait_for_vblank(dev_priv, pipe);
12595
12596                         progress = true;
12597                 }
12598         } while (progress);
12599
12600         /* If 2nd DBuf slice is no more required disable it */
12601         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
12602                 icl_dbuf_slices_update(dev_priv, required_slices);
12603 }
12604
12605 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12606 {
12607         struct intel_atomic_state *state, *next;
12608         struct llist_node *freed;
12609
12610         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12611         llist_for_each_entry_safe(state, next, freed, freed)
12612                 drm_atomic_state_put(&state->base);
12613 }
12614
12615 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12616 {
12617         struct drm_i915_private *dev_priv =
12618                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12619
12620         intel_atomic_helper_free_state(dev_priv);
12621 }
12622
12623 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12624 {
12625         struct wait_queue_entry wait_fence, wait_reset;
12626         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12627
12628         init_wait_entry(&wait_fence, 0);
12629         init_wait_entry(&wait_reset, 0);
12630         for (;;) {
12631                 prepare_to_wait(&intel_state->commit_ready.wait,
12632                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12633                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12634                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12635
12636
12637                 if (i915_sw_fence_done(&intel_state->commit_ready)
12638                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12639                         break;
12640
12641                 schedule();
12642         }
12643         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12644         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12645 }
12646
12647 static void intel_atomic_cleanup_work(struct work_struct *work)
12648 {
12649         struct drm_atomic_state *state =
12650                 container_of(work, struct drm_atomic_state, commit_work);
12651         struct drm_i915_private *i915 = to_i915(state->dev);
12652
12653         drm_atomic_helper_cleanup_planes(&i915->drm, state);
12654         drm_atomic_helper_commit_cleanup_done(state);
12655         drm_atomic_state_put(state);
12656
12657         intel_atomic_helper_free_state(i915);
12658 }
12659
12660 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12661 {
12662         struct drm_device *dev = state->dev;
12663         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12664         struct drm_i915_private *dev_priv = to_i915(dev);
12665         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12666         struct drm_crtc *crtc;
12667         struct intel_crtc_state *intel_cstate;
12668         u64 put_domains[I915_MAX_PIPES] = {};
12669         int i;
12670
12671         intel_atomic_commit_fence_wait(intel_state);
12672
12673         drm_atomic_helper_wait_for_dependencies(state);
12674
12675         if (intel_state->modeset)
12676                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12677
12678         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12679                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12680
12681                 if (needs_modeset(new_crtc_state) ||
12682                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12683
12684                         put_domains[to_intel_crtc(crtc)->pipe] =
12685                                 modeset_get_crtc_power_domains(crtc,
12686                                         to_intel_crtc_state(new_crtc_state));
12687                 }
12688
12689                 if (!needs_modeset(new_crtc_state))
12690                         continue;
12691
12692                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12693                                        to_intel_crtc_state(new_crtc_state));
12694
12695                 if (old_crtc_state->active) {
12696                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
12697
12698                         /*
12699                          * We need to disable pipe CRC before disabling the pipe,
12700                          * or we race against vblank off.
12701                          */
12702                         intel_crtc_disable_pipe_crc(intel_crtc);
12703
12704                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
12705                         intel_crtc->active = false;
12706                         intel_fbc_disable(intel_crtc);
12707                         intel_disable_shared_dpll(intel_crtc);
12708
12709                         /*
12710                          * Underruns don't always raise
12711                          * interrupts, so check manually.
12712                          */
12713                         intel_check_cpu_fifo_underruns(dev_priv);
12714                         intel_check_pch_fifo_underruns(dev_priv);
12715
12716                         if (!new_crtc_state->active) {
12717                                 /*
12718                                  * Make sure we don't call initial_watermarks
12719                                  * for ILK-style watermark updates.
12720                                  *
12721                                  * No clue what this is supposed to achieve.
12722                                  */
12723                                 if (INTEL_GEN(dev_priv) >= 9)
12724                                         dev_priv->display.initial_watermarks(intel_state,
12725                                                                              to_intel_crtc_state(new_crtc_state));
12726                         }
12727                 }
12728         }
12729
12730         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12731         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12732                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12733
12734         if (intel_state->modeset) {
12735                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12736
12737                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12738
12739                 /*
12740                  * SKL workaround: bspec recommends we disable the SAGV when we
12741                  * have more then one pipe enabled
12742                  */
12743                 if (!intel_can_enable_sagv(state))
12744                         intel_disable_sagv(dev_priv);
12745
12746                 intel_modeset_verify_disabled(dev, state);
12747         }
12748
12749         /* Complete the events for pipes that have now been disabled */
12750         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12751                 bool modeset = needs_modeset(new_crtc_state);
12752
12753                 /* Complete events for now disable pipes here. */
12754                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12755                         spin_lock_irq(&dev->event_lock);
12756                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12757                         spin_unlock_irq(&dev->event_lock);
12758
12759                         new_crtc_state->event = NULL;
12760                 }
12761         }
12762
12763         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12764         dev_priv->display.update_crtcs(state);
12765
12766         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12767          * already, but still need the state for the delayed optimization. To
12768          * fix this:
12769          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12770          * - schedule that vblank worker _before_ calling hw_done
12771          * - at the start of commit_tail, cancel it _synchrously
12772          * - switch over to the vblank wait helper in the core after that since
12773          *   we don't need out special handling any more.
12774          */
12775         drm_atomic_helper_wait_for_flip_done(dev, state);
12776
12777         /*
12778          * Now that the vblank has passed, we can go ahead and program the
12779          * optimal watermarks on platforms that need two-step watermark
12780          * programming.
12781          *
12782          * TODO: Move this (and other cleanup) to an async worker eventually.
12783          */
12784         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12785                 intel_cstate = to_intel_crtc_state(new_crtc_state);
12786
12787                 if (dev_priv->display.optimize_watermarks)
12788                         dev_priv->display.optimize_watermarks(intel_state,
12789                                                               intel_cstate);
12790         }
12791
12792         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12793                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12794
12795                 if (put_domains[i])
12796                         modeset_put_power_domains(dev_priv, put_domains[i]);
12797
12798                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12799         }
12800
12801         if (intel_state->modeset)
12802                 intel_verify_planes(intel_state);
12803
12804         if (intel_state->modeset && intel_can_enable_sagv(state))
12805                 intel_enable_sagv(dev_priv);
12806
12807         drm_atomic_helper_commit_hw_done(state);
12808
12809         if (intel_state->modeset) {
12810                 /* As one of the primary mmio accessors, KMS has a high
12811                  * likelihood of triggering bugs in unclaimed access. After we
12812                  * finish modesetting, see if an error has been flagged, and if
12813                  * so enable debugging for the next modeset - and hope we catch
12814                  * the culprit.
12815                  */
12816                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12817                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12818         }
12819
12820         /*
12821          * Defer the cleanup of the old state to a separate worker to not
12822          * impede the current task (userspace for blocking modesets) that
12823          * are executed inline. For out-of-line asynchronous modesets/flips,
12824          * deferring to a new worker seems overkill, but we would place a
12825          * schedule point (cond_resched()) here anyway to keep latencies
12826          * down.
12827          */
12828         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
12829         queue_work(system_highpri_wq, &state->commit_work);
12830 }
12831
12832 static void intel_atomic_commit_work(struct work_struct *work)
12833 {
12834         struct drm_atomic_state *state =
12835                 container_of(work, struct drm_atomic_state, commit_work);
12836
12837         intel_atomic_commit_tail(state);
12838 }
12839
12840 static int __i915_sw_fence_call
12841 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12842                           enum i915_sw_fence_notify notify)
12843 {
12844         struct intel_atomic_state *state =
12845                 container_of(fence, struct intel_atomic_state, commit_ready);
12846
12847         switch (notify) {
12848         case FENCE_COMPLETE:
12849                 /* we do blocking waits in the worker, nothing to do here */
12850                 break;
12851         case FENCE_FREE:
12852                 {
12853                         struct intel_atomic_helper *helper =
12854                                 &to_i915(state->base.dev)->atomic_helper;
12855
12856                         if (llist_add(&state->freed, &helper->free_list))
12857                                 schedule_work(&helper->free_work);
12858                         break;
12859                 }
12860         }
12861
12862         return NOTIFY_DONE;
12863 }
12864
12865 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12866 {
12867         struct drm_plane_state *old_plane_state, *new_plane_state;
12868         struct drm_plane *plane;
12869         int i;
12870
12871         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12872                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12873                                   intel_fb_obj(new_plane_state->fb),
12874                                   to_intel_plane(plane)->frontbuffer_bit);
12875 }
12876
12877 /**
12878  * intel_atomic_commit - commit validated state object
12879  * @dev: DRM device
12880  * @state: the top-level driver state object
12881  * @nonblock: nonblocking commit
12882  *
12883  * This function commits a top-level state object that has been validated
12884  * with drm_atomic_helper_check().
12885  *
12886  * RETURNS
12887  * Zero for success or -errno.
12888  */
12889 static int intel_atomic_commit(struct drm_device *dev,
12890                                struct drm_atomic_state *state,
12891                                bool nonblock)
12892 {
12893         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12894         struct drm_i915_private *dev_priv = to_i915(dev);
12895         int ret = 0;
12896
12897         drm_atomic_state_get(state);
12898         i915_sw_fence_init(&intel_state->commit_ready,
12899                            intel_atomic_commit_ready);
12900
12901         /*
12902          * The intel_legacy_cursor_update() fast path takes care
12903          * of avoiding the vblank waits for simple cursor
12904          * movement and flips. For cursor on/off and size changes,
12905          * we want to perform the vblank waits so that watermark
12906          * updates happen during the correct frames. Gen9+ have
12907          * double buffered watermarks and so shouldn't need this.
12908          *
12909          * Unset state->legacy_cursor_update before the call to
12910          * drm_atomic_helper_setup_commit() because otherwise
12911          * drm_atomic_helper_wait_for_flip_done() is a noop and
12912          * we get FIFO underruns because we didn't wait
12913          * for vblank.
12914          *
12915          * FIXME doing watermarks and fb cleanup from a vblank worker
12916          * (assuming we had any) would solve these problems.
12917          */
12918         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12919                 struct intel_crtc_state *new_crtc_state;
12920                 struct intel_crtc *crtc;
12921                 int i;
12922
12923                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12924                         if (new_crtc_state->wm.need_postvbl_update ||
12925                             new_crtc_state->update_wm_post)
12926                                 state->legacy_cursor_update = false;
12927         }
12928
12929         ret = intel_atomic_prepare_commit(dev, state);
12930         if (ret) {
12931                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12932                 i915_sw_fence_commit(&intel_state->commit_ready);
12933                 return ret;
12934         }
12935
12936         ret = drm_atomic_helper_setup_commit(state, nonblock);
12937         if (!ret)
12938                 ret = drm_atomic_helper_swap_state(state, true);
12939
12940         if (ret) {
12941                 i915_sw_fence_commit(&intel_state->commit_ready);
12942
12943                 drm_atomic_helper_cleanup_planes(dev, state);
12944                 return ret;
12945         }
12946         dev_priv->wm.distrust_bios_wm = false;
12947         intel_shared_dpll_swap_state(state);
12948         intel_atomic_track_fbs(state);
12949
12950         if (intel_state->modeset) {
12951                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12952                        sizeof(intel_state->min_cdclk));
12953                 memcpy(dev_priv->min_voltage_level,
12954                        intel_state->min_voltage_level,
12955                        sizeof(intel_state->min_voltage_level));
12956                 dev_priv->active_crtcs = intel_state->active_crtcs;
12957                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12958                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12959         }
12960
12961         drm_atomic_state_get(state);
12962         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12963
12964         i915_sw_fence_commit(&intel_state->commit_ready);
12965         if (nonblock && intel_state->modeset) {
12966                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12967         } else if (nonblock) {
12968                 queue_work(system_unbound_wq, &state->commit_work);
12969         } else {
12970                 if (intel_state->modeset)
12971                         flush_workqueue(dev_priv->modeset_wq);
12972                 intel_atomic_commit_tail(state);
12973         }
12974
12975         return 0;
12976 }
12977
12978 static const struct drm_crtc_funcs intel_crtc_funcs = {
12979         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12980         .set_config = drm_atomic_helper_set_config,
12981         .destroy = intel_crtc_destroy,
12982         .page_flip = drm_atomic_helper_page_flip,
12983         .atomic_duplicate_state = intel_crtc_duplicate_state,
12984         .atomic_destroy_state = intel_crtc_destroy_state,
12985         .set_crc_source = intel_crtc_set_crc_source,
12986         .verify_crc_source = intel_crtc_verify_crc_source,
12987         .get_crc_sources = intel_crtc_get_crc_sources,
12988 };
12989
12990 struct wait_rps_boost {
12991         struct wait_queue_entry wait;
12992
12993         struct drm_crtc *crtc;
12994         struct i915_request *request;
12995 };
12996
12997 static int do_rps_boost(struct wait_queue_entry *_wait,
12998                         unsigned mode, int sync, void *key)
12999 {
13000         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
13001         struct i915_request *rq = wait->request;
13002
13003         /*
13004          * If we missed the vblank, but the request is already running it
13005          * is reasonable to assume that it will complete before the next
13006          * vblank without our intervention, so leave RPS alone.
13007          */
13008         if (!i915_request_started(rq))
13009                 gen6_rps_boost(rq, NULL);
13010         i915_request_put(rq);
13011
13012         drm_crtc_vblank_put(wait->crtc);
13013
13014         list_del(&wait->wait.entry);
13015         kfree(wait);
13016         return 1;
13017 }
13018
13019 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
13020                                        struct dma_fence *fence)
13021 {
13022         struct wait_rps_boost *wait;
13023
13024         if (!dma_fence_is_i915(fence))
13025                 return;
13026
13027         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
13028                 return;
13029
13030         if (drm_crtc_vblank_get(crtc))
13031                 return;
13032
13033         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
13034         if (!wait) {
13035                 drm_crtc_vblank_put(crtc);
13036                 return;
13037         }
13038
13039         wait->request = to_request(dma_fence_get(fence));
13040         wait->crtc = crtc;
13041
13042         wait->wait.func = do_rps_boost;
13043         wait->wait.flags = 0;
13044
13045         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
13046 }
13047
13048 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
13049 {
13050         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
13051         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13052         struct drm_framebuffer *fb = plane_state->base.fb;
13053         struct i915_vma *vma;
13054
13055         if (plane->id == PLANE_CURSOR &&
13056             INTEL_INFO(dev_priv)->cursor_needs_physical) {
13057                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13058                 const int align = intel_cursor_alignment(dev_priv);
13059                 int err;
13060
13061                 err = i915_gem_object_attach_phys(obj, align);
13062                 if (err)
13063                         return err;
13064         }
13065
13066         vma = intel_pin_and_fence_fb_obj(fb,
13067                                          &plane_state->view,
13068                                          intel_plane_uses_fence(plane_state),
13069                                          &plane_state->flags);
13070         if (IS_ERR(vma))
13071                 return PTR_ERR(vma);
13072
13073         plane_state->vma = vma;
13074
13075         return 0;
13076 }
13077
13078 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
13079 {
13080         struct i915_vma *vma;
13081
13082         vma = fetch_and_zero(&old_plane_state->vma);
13083         if (vma)
13084                 intel_unpin_fb_vma(vma, old_plane_state->flags);
13085 }
13086
13087 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
13088 {
13089         struct i915_sched_attr attr = {
13090                 .priority = I915_PRIORITY_DISPLAY,
13091         };
13092
13093         i915_gem_object_wait_priority(obj, 0, &attr);
13094 }
13095
13096 /**
13097  * intel_prepare_plane_fb - Prepare fb for usage on plane
13098  * @plane: drm plane to prepare for
13099  * @new_state: the plane state being prepared
13100  *
13101  * Prepares a framebuffer for usage on a display plane.  Generally this
13102  * involves pinning the underlying object and updating the frontbuffer tracking
13103  * bits.  Some older platforms need special physical address handling for
13104  * cursor planes.
13105  *
13106  * Must be called with struct_mutex held.
13107  *
13108  * Returns 0 on success, negative error code on failure.
13109  */
13110 int
13111 intel_prepare_plane_fb(struct drm_plane *plane,
13112                        struct drm_plane_state *new_state)
13113 {
13114         struct intel_atomic_state *intel_state =
13115                 to_intel_atomic_state(new_state->state);
13116         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13117         struct drm_framebuffer *fb = new_state->fb;
13118         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13119         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13120         int ret;
13121
13122         if (old_obj) {
13123                 struct drm_crtc_state *crtc_state =
13124                         drm_atomic_get_new_crtc_state(new_state->state,
13125                                                       plane->state->crtc);
13126
13127                 /* Big Hammer, we also need to ensure that any pending
13128                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13129                  * current scanout is retired before unpinning the old
13130                  * framebuffer. Note that we rely on userspace rendering
13131                  * into the buffer attached to the pipe they are waiting
13132                  * on. If not, userspace generates a GPU hang with IPEHR
13133                  * point to the MI_WAIT_FOR_EVENT.
13134                  *
13135                  * This should only fail upon a hung GPU, in which case we
13136                  * can safely continue.
13137                  */
13138                 if (needs_modeset(crtc_state)) {
13139                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13140                                                               old_obj->resv, NULL,
13141                                                               false, 0,
13142                                                               GFP_KERNEL);
13143                         if (ret < 0)
13144                                 return ret;
13145                 }
13146         }
13147
13148         if (new_state->fence) { /* explicit fencing */
13149                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13150                                                     new_state->fence,
13151                                                     I915_FENCE_TIMEOUT,
13152                                                     GFP_KERNEL);
13153                 if (ret < 0)
13154                         return ret;
13155         }
13156
13157         if (!obj)
13158                 return 0;
13159
13160         ret = i915_gem_object_pin_pages(obj);
13161         if (ret)
13162                 return ret;
13163
13164         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13165         if (ret) {
13166                 i915_gem_object_unpin_pages(obj);
13167                 return ret;
13168         }
13169
13170         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
13171
13172         fb_obj_bump_render_priority(obj);
13173
13174         mutex_unlock(&dev_priv->drm.struct_mutex);
13175         i915_gem_object_unpin_pages(obj);
13176         if (ret)
13177                 return ret;
13178
13179         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13180
13181         if (!new_state->fence) { /* implicit fencing */
13182                 struct dma_fence *fence;
13183
13184                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13185                                                       obj->resv, NULL,
13186                                                       false, I915_FENCE_TIMEOUT,
13187                                                       GFP_KERNEL);
13188                 if (ret < 0)
13189                         return ret;
13190
13191                 fence = reservation_object_get_excl_rcu(obj->resv);
13192                 if (fence) {
13193                         add_rps_boost_after_vblank(new_state->crtc, fence);
13194                         dma_fence_put(fence);
13195                 }
13196         } else {
13197                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
13198         }
13199
13200         /*
13201          * We declare pageflips to be interactive and so merit a small bias
13202          * towards upclocking to deliver the frame on time. By only changing
13203          * the RPS thresholds to sample more regularly and aim for higher
13204          * clocks we can hopefully deliver low power workloads (like kodi)
13205          * that are not quite steady state without resorting to forcing
13206          * maximum clocks following a vblank miss (see do_rps_boost()).
13207          */
13208         if (!intel_state->rps_interactive) {
13209                 intel_rps_mark_interactive(dev_priv, true);
13210                 intel_state->rps_interactive = true;
13211         }
13212
13213         return 0;
13214 }
13215
13216 /**
13217  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13218  * @plane: drm plane to clean up for
13219  * @old_state: the state from the previous modeset
13220  *
13221  * Cleans up a framebuffer that has just been removed from a plane.
13222  *
13223  * Must be called with struct_mutex held.
13224  */
13225 void
13226 intel_cleanup_plane_fb(struct drm_plane *plane,
13227                        struct drm_plane_state *old_state)
13228 {
13229         struct intel_atomic_state *intel_state =
13230                 to_intel_atomic_state(old_state->state);
13231         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13232
13233         if (intel_state->rps_interactive) {
13234                 intel_rps_mark_interactive(dev_priv, false);
13235                 intel_state->rps_interactive = false;
13236         }
13237
13238         /* Should only be called after a successful intel_prepare_plane_fb()! */
13239         mutex_lock(&dev_priv->drm.struct_mutex);
13240         intel_plane_unpin_fb(to_intel_plane_state(old_state));
13241         mutex_unlock(&dev_priv->drm.struct_mutex);
13242 }
13243
13244 int
13245 skl_max_scale(const struct intel_crtc_state *crtc_state,
13246               u32 pixel_format)
13247 {
13248         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
13249         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13250         int max_scale, mult;
13251         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
13252
13253         if (!crtc_state->base.enable)
13254                 return DRM_PLANE_HELPER_NO_SCALING;
13255
13256         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13257         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13258
13259         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
13260                 max_dotclk *= 2;
13261
13262         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13263                 return DRM_PLANE_HELPER_NO_SCALING;
13264
13265         /*
13266          * skl max scale is lower of:
13267          *    close to 3 but not 3, -1 is for that purpose
13268          *            or
13269          *    cdclk/crtc_clock
13270          */
13271         mult = pixel_format == DRM_FORMAT_NV12 ? 2 : 3;
13272         tmpclk1 = (1 << 16) * mult - 1;
13273         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
13274         max_scale = min(tmpclk1, tmpclk2);
13275
13276         return max_scale;
13277 }
13278
13279 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13280                                     struct drm_crtc_state *old_crtc_state)
13281 {
13282         struct drm_device *dev = crtc->dev;
13283         struct drm_i915_private *dev_priv = to_i915(dev);
13284         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13285         struct intel_crtc_state *old_intel_cstate =
13286                 to_intel_crtc_state(old_crtc_state);
13287         struct intel_atomic_state *old_intel_state =
13288                 to_intel_atomic_state(old_crtc_state->state);
13289         struct intel_crtc_state *intel_cstate =
13290                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13291         bool modeset = needs_modeset(&intel_cstate->base);
13292
13293         if (!modeset &&
13294             (intel_cstate->base.color_mgmt_changed ||
13295              intel_cstate->update_pipe)) {
13296                 intel_color_set_csc(&intel_cstate->base);
13297                 intel_color_load_luts(&intel_cstate->base);
13298         }
13299
13300         /* Perform vblank evasion around commit operation */
13301         intel_pipe_update_start(intel_cstate);
13302
13303         if (modeset)
13304                 goto out;
13305
13306         if (intel_cstate->update_pipe)
13307                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
13308         else if (INTEL_GEN(dev_priv) >= 9)
13309                 skl_detach_scalers(intel_crtc);
13310
13311 out:
13312         if (dev_priv->display.atomic_update_watermarks)
13313                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13314                                                            intel_cstate);
13315 }
13316
13317 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
13318                                   struct intel_crtc_state *crtc_state)
13319 {
13320         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13321
13322         if (!IS_GEN2(dev_priv))
13323                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
13324
13325         if (crtc_state->has_pch_encoder) {
13326                 enum pipe pch_transcoder =
13327                         intel_crtc_pch_transcoder(crtc);
13328
13329                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13330         }
13331 }
13332
13333 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13334                                      struct drm_crtc_state *old_crtc_state)
13335 {
13336         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13337         struct intel_atomic_state *old_intel_state =
13338                 to_intel_atomic_state(old_crtc_state->state);
13339         struct intel_crtc_state *new_crtc_state =
13340                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13341
13342         intel_pipe_update_end(new_crtc_state);
13343
13344         if (new_crtc_state->update_pipe &&
13345             !needs_modeset(&new_crtc_state->base) &&
13346             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED)
13347                 intel_crtc_arm_fifo_underrun(intel_crtc, new_crtc_state);
13348 }
13349
13350 /**
13351  * intel_plane_destroy - destroy a plane
13352  * @plane: plane to destroy
13353  *
13354  * Common destruction function for all types of planes (primary, cursor,
13355  * sprite).
13356  */
13357 void intel_plane_destroy(struct drm_plane *plane)
13358 {
13359         drm_plane_cleanup(plane);
13360         kfree(to_intel_plane(plane));
13361 }
13362
13363 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
13364                                             u32 format, u64 modifier)
13365 {
13366         switch (modifier) {
13367         case DRM_FORMAT_MOD_LINEAR:
13368         case I915_FORMAT_MOD_X_TILED:
13369                 break;
13370         default:
13371                 return false;
13372         }
13373
13374         switch (format) {
13375         case DRM_FORMAT_C8:
13376         case DRM_FORMAT_RGB565:
13377         case DRM_FORMAT_XRGB1555:
13378         case DRM_FORMAT_XRGB8888:
13379                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13380                         modifier == I915_FORMAT_MOD_X_TILED;
13381         default:
13382                 return false;
13383         }
13384 }
13385
13386 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
13387                                             u32 format, u64 modifier)
13388 {
13389         switch (modifier) {
13390         case DRM_FORMAT_MOD_LINEAR:
13391         case I915_FORMAT_MOD_X_TILED:
13392                 break;
13393         default:
13394                 return false;
13395         }
13396
13397         switch (format) {
13398         case DRM_FORMAT_C8:
13399         case DRM_FORMAT_RGB565:
13400         case DRM_FORMAT_XRGB8888:
13401         case DRM_FORMAT_XBGR8888:
13402         case DRM_FORMAT_XRGB2101010:
13403         case DRM_FORMAT_XBGR2101010:
13404                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13405                         modifier == I915_FORMAT_MOD_X_TILED;
13406         default:
13407                 return false;
13408         }
13409 }
13410
13411 static bool skl_plane_format_mod_supported(struct drm_plane *_plane,
13412                                            u32 format, u64 modifier)
13413 {
13414         struct intel_plane *plane = to_intel_plane(_plane);
13415
13416         switch (modifier) {
13417         case DRM_FORMAT_MOD_LINEAR:
13418         case I915_FORMAT_MOD_X_TILED:
13419         case I915_FORMAT_MOD_Y_TILED:
13420         case I915_FORMAT_MOD_Yf_TILED:
13421                 break;
13422         case I915_FORMAT_MOD_Y_TILED_CCS:
13423         case I915_FORMAT_MOD_Yf_TILED_CCS:
13424                 if (!plane->has_ccs)
13425                         return false;
13426                 break;
13427         default:
13428                 return false;
13429         }
13430
13431         switch (format) {
13432         case DRM_FORMAT_XRGB8888:
13433         case DRM_FORMAT_XBGR8888:
13434         case DRM_FORMAT_ARGB8888:
13435         case DRM_FORMAT_ABGR8888:
13436                 if (is_ccs_modifier(modifier))
13437                         return true;
13438                 /* fall through */
13439         case DRM_FORMAT_RGB565:
13440         case DRM_FORMAT_XRGB2101010:
13441         case DRM_FORMAT_XBGR2101010:
13442         case DRM_FORMAT_YUYV:
13443         case DRM_FORMAT_YVYU:
13444         case DRM_FORMAT_UYVY:
13445         case DRM_FORMAT_VYUY:
13446         case DRM_FORMAT_NV12:
13447                 if (modifier == I915_FORMAT_MOD_Yf_TILED)
13448                         return true;
13449                 /* fall through */
13450         case DRM_FORMAT_C8:
13451                 if (modifier == DRM_FORMAT_MOD_LINEAR ||
13452                     modifier == I915_FORMAT_MOD_X_TILED ||
13453                     modifier == I915_FORMAT_MOD_Y_TILED)
13454                         return true;
13455                 /* fall through */
13456         default:
13457                 return false;
13458         }
13459 }
13460
13461 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
13462                                               u32 format, u64 modifier)
13463 {
13464         return modifier == DRM_FORMAT_MOD_LINEAR &&
13465                 format == DRM_FORMAT_ARGB8888;
13466 }
13467
13468 static struct drm_plane_funcs skl_plane_funcs = {
13469         .update_plane = drm_atomic_helper_update_plane,
13470         .disable_plane = drm_atomic_helper_disable_plane,
13471         .destroy = intel_plane_destroy,
13472         .atomic_get_property = intel_plane_atomic_get_property,
13473         .atomic_set_property = intel_plane_atomic_set_property,
13474         .atomic_duplicate_state = intel_plane_duplicate_state,
13475         .atomic_destroy_state = intel_plane_destroy_state,
13476         .format_mod_supported = skl_plane_format_mod_supported,
13477 };
13478
13479 static struct drm_plane_funcs i965_plane_funcs = {
13480         .update_plane = drm_atomic_helper_update_plane,
13481         .disable_plane = drm_atomic_helper_disable_plane,
13482         .destroy = intel_plane_destroy,
13483         .atomic_get_property = intel_plane_atomic_get_property,
13484         .atomic_set_property = intel_plane_atomic_set_property,
13485         .atomic_duplicate_state = intel_plane_duplicate_state,
13486         .atomic_destroy_state = intel_plane_destroy_state,
13487         .format_mod_supported = i965_plane_format_mod_supported,
13488 };
13489
13490 static struct drm_plane_funcs i8xx_plane_funcs = {
13491         .update_plane = drm_atomic_helper_update_plane,
13492         .disable_plane = drm_atomic_helper_disable_plane,
13493         .destroy = intel_plane_destroy,
13494         .atomic_get_property = intel_plane_atomic_get_property,
13495         .atomic_set_property = intel_plane_atomic_set_property,
13496         .atomic_duplicate_state = intel_plane_duplicate_state,
13497         .atomic_destroy_state = intel_plane_destroy_state,
13498         .format_mod_supported = i8xx_plane_format_mod_supported,
13499 };
13500
13501 static int
13502 intel_legacy_cursor_update(struct drm_plane *plane,
13503                            struct drm_crtc *crtc,
13504                            struct drm_framebuffer *fb,
13505                            int crtc_x, int crtc_y,
13506                            unsigned int crtc_w, unsigned int crtc_h,
13507                            uint32_t src_x, uint32_t src_y,
13508                            uint32_t src_w, uint32_t src_h,
13509                            struct drm_modeset_acquire_ctx *ctx)
13510 {
13511         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13512         int ret;
13513         struct drm_plane_state *old_plane_state, *new_plane_state;
13514         struct intel_plane *intel_plane = to_intel_plane(plane);
13515         struct drm_framebuffer *old_fb;
13516         struct drm_crtc_state *crtc_state = crtc->state;
13517
13518         /*
13519          * When crtc is inactive or there is a modeset pending,
13520          * wait for it to complete in the slowpath
13521          */
13522         if (!crtc_state->active || needs_modeset(crtc_state) ||
13523             to_intel_crtc_state(crtc_state)->update_pipe)
13524                 goto slow;
13525
13526         old_plane_state = plane->state;
13527         /*
13528          * Don't do an async update if there is an outstanding commit modifying
13529          * the plane.  This prevents our async update's changes from getting
13530          * overridden by a previous synchronous update's state.
13531          */
13532         if (old_plane_state->commit &&
13533             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13534                 goto slow;
13535
13536         /*
13537          * If any parameters change that may affect watermarks,
13538          * take the slowpath. Only changing fb or position should be
13539          * in the fastpath.
13540          */
13541         if (old_plane_state->crtc != crtc ||
13542             old_plane_state->src_w != src_w ||
13543             old_plane_state->src_h != src_h ||
13544             old_plane_state->crtc_w != crtc_w ||
13545             old_plane_state->crtc_h != crtc_h ||
13546             !old_plane_state->fb != !fb)
13547                 goto slow;
13548
13549         new_plane_state = intel_plane_duplicate_state(plane);
13550         if (!new_plane_state)
13551                 return -ENOMEM;
13552
13553         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13554
13555         new_plane_state->src_x = src_x;
13556         new_plane_state->src_y = src_y;
13557         new_plane_state->src_w = src_w;
13558         new_plane_state->src_h = src_h;
13559         new_plane_state->crtc_x = crtc_x;
13560         new_plane_state->crtc_y = crtc_y;
13561         new_plane_state->crtc_w = crtc_w;
13562         new_plane_state->crtc_h = crtc_h;
13563
13564         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13565                                                   to_intel_crtc_state(crtc->state), /* FIXME need a new crtc state? */
13566                                                   to_intel_plane_state(plane->state),
13567                                                   to_intel_plane_state(new_plane_state));
13568         if (ret)
13569                 goto out_free;
13570
13571         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13572         if (ret)
13573                 goto out_free;
13574
13575         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13576         if (ret)
13577                 goto out_unlock;
13578
13579         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13580
13581         old_fb = old_plane_state->fb;
13582         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13583                           intel_plane->frontbuffer_bit);
13584
13585         /* Swap plane state */
13586         plane->state = new_plane_state;
13587
13588         if (plane->state->visible) {
13589                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13590                 intel_plane->update_plane(intel_plane,
13591                                           to_intel_crtc_state(crtc->state),
13592                                           to_intel_plane_state(plane->state));
13593         } else {
13594                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13595                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13596         }
13597
13598         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13599
13600 out_unlock:
13601         mutex_unlock(&dev_priv->drm.struct_mutex);
13602 out_free:
13603         if (ret)
13604                 intel_plane_destroy_state(plane, new_plane_state);
13605         else
13606                 intel_plane_destroy_state(plane, old_plane_state);
13607         return ret;
13608
13609 slow:
13610         return drm_atomic_helper_update_plane(plane, crtc, fb,
13611                                               crtc_x, crtc_y, crtc_w, crtc_h,
13612                                               src_x, src_y, src_w, src_h, ctx);
13613 }
13614
13615 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13616         .update_plane = intel_legacy_cursor_update,
13617         .disable_plane = drm_atomic_helper_disable_plane,
13618         .destroy = intel_plane_destroy,
13619         .atomic_get_property = intel_plane_atomic_get_property,
13620         .atomic_set_property = intel_plane_atomic_set_property,
13621         .atomic_duplicate_state = intel_plane_duplicate_state,
13622         .atomic_destroy_state = intel_plane_destroy_state,
13623         .format_mod_supported = intel_cursor_format_mod_supported,
13624 };
13625
13626 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13627                                enum i9xx_plane_id i9xx_plane)
13628 {
13629         if (!HAS_FBC(dev_priv))
13630                 return false;
13631
13632         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13633                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13634         else if (IS_IVYBRIDGE(dev_priv))
13635                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13636                         i9xx_plane == PLANE_C;
13637         else if (INTEL_GEN(dev_priv) >= 4)
13638                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13639         else
13640                 return i9xx_plane == PLANE_A;
13641 }
13642
13643 static bool skl_plane_has_fbc(struct drm_i915_private *dev_priv,
13644                               enum pipe pipe, enum plane_id plane_id)
13645 {
13646         if (!HAS_FBC(dev_priv))
13647                 return false;
13648
13649         return pipe == PIPE_A && plane_id == PLANE_PRIMARY;
13650 }
13651
13652 bool skl_plane_has_planar(struct drm_i915_private *dev_priv,
13653                           enum pipe pipe, enum plane_id plane_id)
13654 {
13655         /*
13656          * FIXME: ICL requires two hardware planes for scanning out NV12
13657          * framebuffers. Do not advertize support until this is implemented.
13658          */
13659         if (INTEL_GEN(dev_priv) >= 11)
13660                 return false;
13661
13662         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
13663                 return false;
13664
13665         if (INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv) && pipe == PIPE_C)
13666                 return false;
13667
13668         if (plane_id != PLANE_PRIMARY && plane_id != PLANE_SPRITE0)
13669                 return false;
13670
13671         return true;
13672 }
13673
13674 static struct intel_plane *
13675 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13676 {
13677         struct intel_plane *primary = NULL;
13678         struct intel_plane_state *state = NULL;
13679         const struct drm_plane_funcs *plane_funcs;
13680         const uint32_t *intel_primary_formats;
13681         unsigned int supported_rotations;
13682         unsigned int num_formats;
13683         const uint64_t *modifiers;
13684         int ret;
13685
13686         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13687         if (!primary) {
13688                 ret = -ENOMEM;
13689                 goto fail;
13690         }
13691
13692         state = intel_create_plane_state(&primary->base);
13693         if (!state) {
13694                 ret = -ENOMEM;
13695                 goto fail;
13696         }
13697
13698         primary->base.state = &state->base;
13699
13700         if (INTEL_GEN(dev_priv) >= 9)
13701                 state->scaler_id = -1;
13702         primary->pipe = pipe;
13703         /*
13704          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13705          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13706          */
13707         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13708                 primary->i9xx_plane = (enum i9xx_plane_id) !pipe;
13709         else
13710                 primary->i9xx_plane = (enum i9xx_plane_id) pipe;
13711         primary->id = PLANE_PRIMARY;
13712         primary->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, primary->id);
13713
13714         if (INTEL_GEN(dev_priv) >= 9)
13715                 primary->has_fbc = skl_plane_has_fbc(dev_priv,
13716                                                      primary->pipe,
13717                                                      primary->id);
13718         else
13719                 primary->has_fbc = i9xx_plane_has_fbc(dev_priv,
13720                                                       primary->i9xx_plane);
13721
13722         if (primary->has_fbc) {
13723                 struct intel_fbc *fbc = &dev_priv->fbc;
13724
13725                 fbc->possible_framebuffer_bits |= primary->frontbuffer_bit;
13726         }
13727
13728         if (INTEL_GEN(dev_priv) >= 9) {
13729                 primary->has_ccs = skl_plane_has_ccs(dev_priv, pipe,
13730                                                      PLANE_PRIMARY);
13731
13732                 if (skl_plane_has_planar(dev_priv, pipe, PLANE_PRIMARY)) {
13733                         intel_primary_formats = skl_pri_planar_formats;
13734                         num_formats = ARRAY_SIZE(skl_pri_planar_formats);
13735                 } else {
13736                         intel_primary_formats = skl_primary_formats;
13737                         num_formats = ARRAY_SIZE(skl_primary_formats);
13738                 }
13739
13740                 if (primary->has_ccs)
13741                         modifiers = skl_format_modifiers_ccs;
13742                 else
13743                         modifiers = skl_format_modifiers_noccs;
13744
13745                 primary->max_stride = skl_plane_max_stride;
13746                 primary->update_plane = skl_update_plane;
13747                 primary->disable_plane = skl_disable_plane;
13748                 primary->get_hw_state = skl_plane_get_hw_state;
13749                 primary->check_plane = skl_plane_check;
13750
13751                 plane_funcs = &skl_plane_funcs;
13752         } else if (INTEL_GEN(dev_priv) >= 4) {
13753                 intel_primary_formats = i965_primary_formats;
13754                 num_formats = ARRAY_SIZE(i965_primary_formats);
13755                 modifiers = i9xx_format_modifiers;
13756
13757                 primary->max_stride = i9xx_plane_max_stride;
13758                 primary->update_plane = i9xx_update_plane;
13759                 primary->disable_plane = i9xx_disable_plane;
13760                 primary->get_hw_state = i9xx_plane_get_hw_state;
13761                 primary->check_plane = i9xx_plane_check;
13762
13763                 plane_funcs = &i965_plane_funcs;
13764         } else {
13765                 intel_primary_formats = i8xx_primary_formats;
13766                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13767                 modifiers = i9xx_format_modifiers;
13768
13769                 primary->max_stride = i9xx_plane_max_stride;
13770                 primary->update_plane = i9xx_update_plane;
13771                 primary->disable_plane = i9xx_disable_plane;
13772                 primary->get_hw_state = i9xx_plane_get_hw_state;
13773                 primary->check_plane = i9xx_plane_check;
13774
13775                 plane_funcs = &i8xx_plane_funcs;
13776         }
13777
13778         if (INTEL_GEN(dev_priv) >= 9)
13779                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13780                                                0, plane_funcs,
13781                                                intel_primary_formats, num_formats,
13782                                                modifiers,
13783                                                DRM_PLANE_TYPE_PRIMARY,
13784                                                "plane 1%c", pipe_name(pipe));
13785         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13786                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13787                                                0, plane_funcs,
13788                                                intel_primary_formats, num_formats,
13789                                                modifiers,
13790                                                DRM_PLANE_TYPE_PRIMARY,
13791                                                "primary %c", pipe_name(pipe));
13792         else
13793                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13794                                                0, plane_funcs,
13795                                                intel_primary_formats, num_formats,
13796                                                modifiers,
13797                                                DRM_PLANE_TYPE_PRIMARY,
13798                                                "plane %c",
13799                                                plane_name(primary->i9xx_plane));
13800         if (ret)
13801                 goto fail;
13802
13803         if (INTEL_GEN(dev_priv) >= 10) {
13804                 supported_rotations =
13805                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13806                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270 |
13807                         DRM_MODE_REFLECT_X;
13808         } else if (INTEL_GEN(dev_priv) >= 9) {
13809                 supported_rotations =
13810                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13811                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13812         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13813                 supported_rotations =
13814                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13815                         DRM_MODE_REFLECT_X;
13816         } else if (INTEL_GEN(dev_priv) >= 4) {
13817                 supported_rotations =
13818                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13819         } else {
13820                 supported_rotations = DRM_MODE_ROTATE_0;
13821         }
13822
13823         if (INTEL_GEN(dev_priv) >= 4)
13824                 drm_plane_create_rotation_property(&primary->base,
13825                                                    DRM_MODE_ROTATE_0,
13826                                                    supported_rotations);
13827
13828         if (INTEL_GEN(dev_priv) >= 9)
13829                 drm_plane_create_color_properties(&primary->base,
13830                                                   BIT(DRM_COLOR_YCBCR_BT601) |
13831                                                   BIT(DRM_COLOR_YCBCR_BT709),
13832                                                   BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
13833                                                   BIT(DRM_COLOR_YCBCR_FULL_RANGE),
13834                                                   DRM_COLOR_YCBCR_BT709,
13835                                                   DRM_COLOR_YCBCR_LIMITED_RANGE);
13836
13837         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13838
13839         return primary;
13840
13841 fail:
13842         kfree(state);
13843         kfree(primary);
13844
13845         return ERR_PTR(ret);
13846 }
13847
13848 static struct intel_plane *
13849 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13850                           enum pipe pipe)
13851 {
13852         struct intel_plane *cursor = NULL;
13853         struct intel_plane_state *state = NULL;
13854         int ret;
13855
13856         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13857         if (!cursor) {
13858                 ret = -ENOMEM;
13859                 goto fail;
13860         }
13861
13862         state = intel_create_plane_state(&cursor->base);
13863         if (!state) {
13864                 ret = -ENOMEM;
13865                 goto fail;
13866         }
13867
13868         cursor->base.state = &state->base;
13869
13870         cursor->pipe = pipe;
13871         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13872         cursor->id = PLANE_CURSOR;
13873         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13874
13875         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13876                 cursor->max_stride = i845_cursor_max_stride;
13877                 cursor->update_plane = i845_update_cursor;
13878                 cursor->disable_plane = i845_disable_cursor;
13879                 cursor->get_hw_state = i845_cursor_get_hw_state;
13880                 cursor->check_plane = i845_check_cursor;
13881         } else {
13882                 cursor->max_stride = i9xx_cursor_max_stride;
13883                 cursor->update_plane = i9xx_update_cursor;
13884                 cursor->disable_plane = i9xx_disable_cursor;
13885                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13886                 cursor->check_plane = i9xx_check_cursor;
13887         }
13888
13889         cursor->cursor.base = ~0;
13890         cursor->cursor.cntl = ~0;
13891
13892         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13893                 cursor->cursor.size = ~0;
13894
13895         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13896                                        0, &intel_cursor_plane_funcs,
13897                                        intel_cursor_formats,
13898                                        ARRAY_SIZE(intel_cursor_formats),
13899                                        cursor_format_modifiers,
13900                                        DRM_PLANE_TYPE_CURSOR,
13901                                        "cursor %c", pipe_name(pipe));
13902         if (ret)
13903                 goto fail;
13904
13905         if (INTEL_GEN(dev_priv) >= 4)
13906                 drm_plane_create_rotation_property(&cursor->base,
13907                                                    DRM_MODE_ROTATE_0,
13908                                                    DRM_MODE_ROTATE_0 |
13909                                                    DRM_MODE_ROTATE_180);
13910
13911         if (INTEL_GEN(dev_priv) >= 9)
13912                 state->scaler_id = -1;
13913
13914         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13915
13916         return cursor;
13917
13918 fail:
13919         kfree(state);
13920         kfree(cursor);
13921
13922         return ERR_PTR(ret);
13923 }
13924
13925 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13926                                     struct intel_crtc_state *crtc_state)
13927 {
13928         struct intel_crtc_scaler_state *scaler_state =
13929                 &crtc_state->scaler_state;
13930         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13931         int i;
13932
13933         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13934         if (!crtc->num_scalers)
13935                 return;
13936
13937         for (i = 0; i < crtc->num_scalers; i++) {
13938                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13939
13940                 scaler->in_use = 0;
13941                 scaler->mode = PS_SCALER_MODE_DYN;
13942         }
13943
13944         scaler_state->scaler_id = -1;
13945 }
13946
13947 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13948 {
13949         struct intel_crtc *intel_crtc;
13950         struct intel_crtc_state *crtc_state = NULL;
13951         struct intel_plane *primary = NULL;
13952         struct intel_plane *cursor = NULL;
13953         int sprite, ret;
13954
13955         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13956         if (!intel_crtc)
13957                 return -ENOMEM;
13958
13959         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13960         if (!crtc_state) {
13961                 ret = -ENOMEM;
13962                 goto fail;
13963         }
13964         intel_crtc->config = crtc_state;
13965         intel_crtc->base.state = &crtc_state->base;
13966         crtc_state->base.crtc = &intel_crtc->base;
13967
13968         primary = intel_primary_plane_create(dev_priv, pipe);
13969         if (IS_ERR(primary)) {
13970                 ret = PTR_ERR(primary);
13971                 goto fail;
13972         }
13973         intel_crtc->plane_ids_mask |= BIT(primary->id);
13974
13975         for_each_sprite(dev_priv, pipe, sprite) {
13976                 struct intel_plane *plane;
13977
13978                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13979                 if (IS_ERR(plane)) {
13980                         ret = PTR_ERR(plane);
13981                         goto fail;
13982                 }
13983                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13984         }
13985
13986         cursor = intel_cursor_plane_create(dev_priv, pipe);
13987         if (IS_ERR(cursor)) {
13988                 ret = PTR_ERR(cursor);
13989                 goto fail;
13990         }
13991         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13992
13993         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13994                                         &primary->base, &cursor->base,
13995                                         &intel_crtc_funcs,
13996                                         "pipe %c", pipe_name(pipe));
13997         if (ret)
13998                 goto fail;
13999
14000         intel_crtc->pipe = pipe;
14001
14002         /* initialize shared scalers */
14003         intel_crtc_init_scalers(intel_crtc, crtc_state);
14004
14005         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
14006                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
14007         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
14008
14009         if (INTEL_GEN(dev_priv) < 9) {
14010                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
14011
14012                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14013                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
14014                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
14015         }
14016
14017         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14018
14019         intel_color_init(&intel_crtc->base);
14020
14021         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14022
14023         return 0;
14024
14025 fail:
14026         /*
14027          * drm_mode_config_cleanup() will free up any
14028          * crtcs/planes already initialized.
14029          */
14030         kfree(crtc_state);
14031         kfree(intel_crtc);
14032
14033         return ret;
14034 }
14035
14036 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14037 {
14038         struct drm_device *dev = connector->base.dev;
14039
14040         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14041
14042         if (!connector->base.state->crtc)
14043                 return INVALID_PIPE;
14044
14045         return to_intel_crtc(connector->base.state->crtc)->pipe;
14046 }
14047
14048 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
14049                                       struct drm_file *file)
14050 {
14051         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14052         struct drm_crtc *drmmode_crtc;
14053         struct intel_crtc *crtc;
14054
14055         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
14056         if (!drmmode_crtc)
14057                 return -ENOENT;
14058
14059         crtc = to_intel_crtc(drmmode_crtc);
14060         pipe_from_crtc_id->pipe = crtc->pipe;
14061
14062         return 0;
14063 }
14064
14065 static int intel_encoder_clones(struct intel_encoder *encoder)
14066 {
14067         struct drm_device *dev = encoder->base.dev;
14068         struct intel_encoder *source_encoder;
14069         int index_mask = 0;
14070         int entry = 0;
14071
14072         for_each_intel_encoder(dev, source_encoder) {
14073                 if (encoders_cloneable(encoder, source_encoder))
14074                         index_mask |= (1 << entry);
14075
14076                 entry++;
14077         }
14078
14079         return index_mask;
14080 }
14081
14082 static bool has_edp_a(struct drm_i915_private *dev_priv)
14083 {
14084         if (!IS_MOBILE(dev_priv))
14085                 return false;
14086
14087         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14088                 return false;
14089
14090         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14091                 return false;
14092
14093         return true;
14094 }
14095
14096 static bool intel_crt_present(struct drm_i915_private *dev_priv)
14097 {
14098         if (INTEL_GEN(dev_priv) >= 9)
14099                 return false;
14100
14101         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14102                 return false;
14103
14104         if (IS_CHERRYVIEW(dev_priv))
14105                 return false;
14106
14107         if (HAS_PCH_LPT_H(dev_priv) &&
14108             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14109                 return false;
14110
14111         /* DDI E can't be used if DDI A requires 4 lanes */
14112         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14113                 return false;
14114
14115         if (!dev_priv->vbt.int_crt_support)
14116                 return false;
14117
14118         return true;
14119 }
14120
14121 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14122 {
14123         int pps_num;
14124         int pps_idx;
14125
14126         if (HAS_DDI(dev_priv))
14127                 return;
14128         /*
14129          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14130          * everywhere where registers can be write protected.
14131          */
14132         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14133                 pps_num = 2;
14134         else
14135                 pps_num = 1;
14136
14137         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14138                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14139
14140                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14141                 I915_WRITE(PP_CONTROL(pps_idx), val);
14142         }
14143 }
14144
14145 static void intel_pps_init(struct drm_i915_private *dev_priv)
14146 {
14147         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14148                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14149         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14150                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14151         else
14152                 dev_priv->pps_mmio_base = PPS_BASE;
14153
14154         intel_pps_unlock_regs_wa(dev_priv);
14155 }
14156
14157 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14158 {
14159         struct intel_encoder *encoder;
14160         bool dpd_is_edp = false;
14161
14162         intel_pps_init(dev_priv);
14163
14164         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14165                 return;
14166
14167         /*
14168          * intel_edp_init_connector() depends on this completing first, to
14169          * prevent the registeration of both eDP and LVDS and the incorrect
14170          * sharing of the PPS.
14171          */
14172         intel_lvds_init(dev_priv);
14173
14174         if (intel_crt_present(dev_priv))
14175                 intel_crt_init(dev_priv);
14176
14177         if (IS_ICELAKE(dev_priv)) {
14178                 intel_ddi_init(dev_priv, PORT_A);
14179                 intel_ddi_init(dev_priv, PORT_B);
14180                 intel_ddi_init(dev_priv, PORT_C);
14181                 intel_ddi_init(dev_priv, PORT_D);
14182                 intel_ddi_init(dev_priv, PORT_E);
14183                 intel_ddi_init(dev_priv, PORT_F);
14184         } else if (IS_GEN9_LP(dev_priv)) {
14185                 /*
14186                  * FIXME: Broxton doesn't support port detection via the
14187                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14188                  * detect the ports.
14189                  */
14190                 intel_ddi_init(dev_priv, PORT_A);
14191                 intel_ddi_init(dev_priv, PORT_B);
14192                 intel_ddi_init(dev_priv, PORT_C);
14193
14194                 vlv_dsi_init(dev_priv);
14195         } else if (HAS_DDI(dev_priv)) {
14196                 int found;
14197
14198                 /*
14199                  * Haswell uses DDI functions to detect digital outputs.
14200                  * On SKL pre-D0 the strap isn't connected, so we assume
14201                  * it's there.
14202                  */
14203                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14204                 /* WaIgnoreDDIAStrap: skl */
14205                 if (found || IS_GEN9_BC(dev_priv))
14206                         intel_ddi_init(dev_priv, PORT_A);
14207
14208                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
14209                  * register */
14210                 found = I915_READ(SFUSE_STRAP);
14211
14212                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14213                         intel_ddi_init(dev_priv, PORT_B);
14214                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14215                         intel_ddi_init(dev_priv, PORT_C);
14216                 if (found & SFUSE_STRAP_DDID_DETECTED)
14217                         intel_ddi_init(dev_priv, PORT_D);
14218                 if (found & SFUSE_STRAP_DDIF_DETECTED)
14219                         intel_ddi_init(dev_priv, PORT_F);
14220                 /*
14221                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14222                  */
14223                 if (IS_GEN9_BC(dev_priv) &&
14224                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14225                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14226                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14227                         intel_ddi_init(dev_priv, PORT_E);
14228
14229         } else if (HAS_PCH_SPLIT(dev_priv)) {
14230                 int found;
14231                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14232
14233                 if (has_edp_a(dev_priv))
14234                         intel_dp_init(dev_priv, DP_A, PORT_A);
14235
14236                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14237                         /* PCH SDVOB multiplex with HDMIB */
14238                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14239                         if (!found)
14240                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14241                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14242                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14243                 }
14244
14245                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14246                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14247
14248                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14249                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14250
14251                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14252                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14253
14254                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14255                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14256         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14257                 bool has_edp, has_port;
14258
14259                 /*
14260                  * The DP_DETECTED bit is the latched state of the DDC
14261                  * SDA pin at boot. However since eDP doesn't require DDC
14262                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14263                  * eDP ports may have been muxed to an alternate function.
14264                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14265                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14266                  * detect eDP ports.
14267                  *
14268                  * Sadly the straps seem to be missing sometimes even for HDMI
14269                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14270                  * and VBT for the presence of the port. Additionally we can't
14271                  * trust the port type the VBT declares as we've seen at least
14272                  * HDMI ports that the VBT claim are DP or eDP.
14273                  */
14274                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14275                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14276                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14277                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14278                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14279                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14280
14281                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14282                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14283                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14284                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14285                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14286                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14287
14288                 if (IS_CHERRYVIEW(dev_priv)) {
14289                         /*
14290                          * eDP not supported on port D,
14291                          * so no need to worry about it
14292                          */
14293                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14294                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14295                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14296                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14297                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14298                 }
14299
14300                 vlv_dsi_init(dev_priv);
14301         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
14302                 bool found = false;
14303
14304                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14305                         DRM_DEBUG_KMS("probing SDVOB\n");
14306                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14307                         if (!found && IS_G4X(dev_priv)) {
14308                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14309                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14310                         }
14311
14312                         if (!found && IS_G4X(dev_priv))
14313                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14314                 }
14315
14316                 /* Before G4X SDVOC doesn't have its own detect register */
14317
14318                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14319                         DRM_DEBUG_KMS("probing SDVOC\n");
14320                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14321                 }
14322
14323                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14324
14325                         if (IS_G4X(dev_priv)) {
14326                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14327                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14328                         }
14329                         if (IS_G4X(dev_priv))
14330                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14331                 }
14332
14333                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14334                         intel_dp_init(dev_priv, DP_D, PORT_D);
14335         } else if (IS_GEN2(dev_priv))
14336                 intel_dvo_init(dev_priv);
14337
14338         if (SUPPORTS_TV(dev_priv))
14339                 intel_tv_init(dev_priv);
14340
14341         intel_psr_init(dev_priv);
14342
14343         for_each_intel_encoder(&dev_priv->drm, encoder) {
14344                 encoder->base.possible_crtcs = encoder->crtc_mask;
14345                 encoder->base.possible_clones =
14346                         intel_encoder_clones(encoder);
14347         }
14348
14349         intel_init_pch_refclk(dev_priv);
14350
14351         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14352 }
14353
14354 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14355 {
14356         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14357         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14358
14359         drm_framebuffer_cleanup(fb);
14360
14361         i915_gem_object_lock(obj);
14362         WARN_ON(!obj->framebuffer_references--);
14363         i915_gem_object_unlock(obj);
14364
14365         i915_gem_object_put(obj);
14366
14367         kfree(intel_fb);
14368 }
14369
14370 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14371                                                 struct drm_file *file,
14372                                                 unsigned int *handle)
14373 {
14374         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14375
14376         if (obj->userptr.mm) {
14377                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14378                 return -EINVAL;
14379         }
14380
14381         return drm_gem_handle_create(file, &obj->base, handle);
14382 }
14383
14384 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14385                                         struct drm_file *file,
14386                                         unsigned flags, unsigned color,
14387                                         struct drm_clip_rect *clips,
14388                                         unsigned num_clips)
14389 {
14390         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14391
14392         i915_gem_object_flush_if_display(obj);
14393         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14394
14395         return 0;
14396 }
14397
14398 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14399         .destroy = intel_user_framebuffer_destroy,
14400         .create_handle = intel_user_framebuffer_create_handle,
14401         .dirty = intel_user_framebuffer_dirty,
14402 };
14403
14404 static
14405 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14406                          uint64_t fb_modifier, uint32_t pixel_format)
14407 {
14408         struct intel_crtc *crtc;
14409         struct intel_plane *plane;
14410
14411         /*
14412          * We assume the primary plane for pipe A has
14413          * the highest stride limits of them all.
14414          */
14415         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
14416         plane = to_intel_plane(crtc->base.primary);
14417
14418         return plane->max_stride(plane, pixel_format, fb_modifier,
14419                                  DRM_MODE_ROTATE_0);
14420 }
14421
14422 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14423                                   struct drm_i915_gem_object *obj,
14424                                   struct drm_mode_fb_cmd2 *mode_cmd)
14425 {
14426         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14427         struct drm_framebuffer *fb = &intel_fb->base;
14428         struct drm_format_name_buf format_name;
14429         u32 pitch_limit;
14430         unsigned int tiling, stride;
14431         int ret = -EINVAL;
14432         int i;
14433
14434         i915_gem_object_lock(obj);
14435         obj->framebuffer_references++;
14436         tiling = i915_gem_object_get_tiling(obj);
14437         stride = i915_gem_object_get_stride(obj);
14438         i915_gem_object_unlock(obj);
14439
14440         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14441                 /*
14442                  * If there's a fence, enforce that
14443                  * the fb modifier and tiling mode match.
14444                  */
14445                 if (tiling != I915_TILING_NONE &&
14446                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14447                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14448                         goto err;
14449                 }
14450         } else {
14451                 if (tiling == I915_TILING_X) {
14452                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14453                 } else if (tiling == I915_TILING_Y) {
14454                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14455                         goto err;
14456                 }
14457         }
14458
14459         /* Passed in modifier sanity checking. */
14460         switch (mode_cmd->modifier[0]) {
14461         case I915_FORMAT_MOD_Y_TILED_CCS:
14462         case I915_FORMAT_MOD_Yf_TILED_CCS:
14463                 switch (mode_cmd->pixel_format) {
14464                 case DRM_FORMAT_XBGR8888:
14465                 case DRM_FORMAT_ABGR8888:
14466                 case DRM_FORMAT_XRGB8888:
14467                 case DRM_FORMAT_ARGB8888:
14468                         break;
14469                 default:
14470                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
14471                         goto err;
14472                 }
14473                 /* fall through */
14474         case I915_FORMAT_MOD_Y_TILED:
14475         case I915_FORMAT_MOD_Yf_TILED:
14476                 if (INTEL_GEN(dev_priv) < 9) {
14477                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14478                                       mode_cmd->modifier[0]);
14479                         goto err;
14480                 }
14481         case DRM_FORMAT_MOD_LINEAR:
14482         case I915_FORMAT_MOD_X_TILED:
14483                 break;
14484         default:
14485                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14486                               mode_cmd->modifier[0]);
14487                 goto err;
14488         }
14489
14490         /*
14491          * gen2/3 display engine uses the fence if present,
14492          * so the tiling mode must match the fb modifier exactly.
14493          */
14494         if (INTEL_GEN(dev_priv) < 4 &&
14495             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14496                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14497                 goto err;
14498         }
14499
14500         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14501                                            mode_cmd->pixel_format);
14502         if (mode_cmd->pitches[0] > pitch_limit) {
14503                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14504                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14505                               "tiled" : "linear",
14506                               mode_cmd->pitches[0], pitch_limit);
14507                 goto err;
14508         }
14509
14510         /*
14511          * If there's a fence, enforce that
14512          * the fb pitch and fence stride match.
14513          */
14514         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14515                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14516                               mode_cmd->pitches[0], stride);
14517                 goto err;
14518         }
14519
14520         /* Reject formats not supported by any plane early. */
14521         switch (mode_cmd->pixel_format) {
14522         case DRM_FORMAT_C8:
14523         case DRM_FORMAT_RGB565:
14524         case DRM_FORMAT_XRGB8888:
14525         case DRM_FORMAT_ARGB8888:
14526                 break;
14527         case DRM_FORMAT_XRGB1555:
14528                 if (INTEL_GEN(dev_priv) > 3) {
14529                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14530                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14531                         goto err;
14532                 }
14533                 break;
14534         case DRM_FORMAT_ABGR8888:
14535                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14536                     INTEL_GEN(dev_priv) < 9) {
14537                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14538                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14539                         goto err;
14540                 }
14541                 break;
14542         case DRM_FORMAT_XBGR8888:
14543         case DRM_FORMAT_XRGB2101010:
14544         case DRM_FORMAT_XBGR2101010:
14545                 if (INTEL_GEN(dev_priv) < 4) {
14546                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14547                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14548                         goto err;
14549                 }
14550                 break;
14551         case DRM_FORMAT_ABGR2101010:
14552                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14553                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14554                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14555                         goto err;
14556                 }
14557                 break;
14558         case DRM_FORMAT_YUYV:
14559         case DRM_FORMAT_UYVY:
14560         case DRM_FORMAT_YVYU:
14561         case DRM_FORMAT_VYUY:
14562                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14563                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14564                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14565                         goto err;
14566                 }
14567                 break;
14568         case DRM_FORMAT_NV12:
14569                 if (INTEL_GEN(dev_priv) < 9 || IS_SKYLAKE(dev_priv) ||
14570                     IS_BROXTON(dev_priv) || INTEL_GEN(dev_priv) >= 11) {
14571                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14572                                       drm_get_format_name(mode_cmd->pixel_format,
14573                                                           &format_name));
14574                         goto err;
14575                 }
14576                 break;
14577         default:
14578                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14579                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14580                 goto err;
14581         }
14582
14583         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14584         if (mode_cmd->offsets[0] != 0)
14585                 goto err;
14586
14587         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14588
14589         if (fb->format->format == DRM_FORMAT_NV12 &&
14590             (fb->width < SKL_MIN_YUV_420_SRC_W ||
14591              fb->height < SKL_MIN_YUV_420_SRC_H ||
14592              (fb->width % 4) != 0 || (fb->height % 4) != 0)) {
14593                 DRM_DEBUG_KMS("src dimensions not correct for NV12\n");
14594                 return -EINVAL;
14595         }
14596
14597         for (i = 0; i < fb->format->num_planes; i++) {
14598                 u32 stride_alignment;
14599
14600                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14601                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14602                         goto err;
14603                 }
14604
14605                 stride_alignment = intel_fb_stride_alignment(fb, i);
14606
14607                 /*
14608                  * Display WA #0531: skl,bxt,kbl,glk
14609                  *
14610                  * Render decompression and plane width > 3840
14611                  * combined with horizontal panning requires the
14612                  * plane stride to be a multiple of 4. We'll just
14613                  * require the entire fb to accommodate that to avoid
14614                  * potential runtime errors at plane configuration time.
14615                  */
14616                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14617                     is_ccs_modifier(fb->modifier))
14618                         stride_alignment *= 4;
14619
14620                 if (fb->pitches[i] & (stride_alignment - 1)) {
14621                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14622                                       i, fb->pitches[i], stride_alignment);
14623                         goto err;
14624                 }
14625
14626                 fb->obj[i] = &obj->base;
14627         }
14628
14629         ret = intel_fill_fb_info(dev_priv, fb);
14630         if (ret)
14631                 goto err;
14632
14633         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14634         if (ret) {
14635                 DRM_ERROR("framebuffer init failed %d\n", ret);
14636                 goto err;
14637         }
14638
14639         return 0;
14640
14641 err:
14642         i915_gem_object_lock(obj);
14643         obj->framebuffer_references--;
14644         i915_gem_object_unlock(obj);
14645         return ret;
14646 }
14647
14648 static struct drm_framebuffer *
14649 intel_user_framebuffer_create(struct drm_device *dev,
14650                               struct drm_file *filp,
14651                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14652 {
14653         struct drm_framebuffer *fb;
14654         struct drm_i915_gem_object *obj;
14655         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14656
14657         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14658         if (!obj)
14659                 return ERR_PTR(-ENOENT);
14660
14661         fb = intel_framebuffer_create(obj, &mode_cmd);
14662         if (IS_ERR(fb))
14663                 i915_gem_object_put(obj);
14664
14665         return fb;
14666 }
14667
14668 static void intel_atomic_state_free(struct drm_atomic_state *state)
14669 {
14670         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14671
14672         drm_atomic_state_default_release(state);
14673
14674         i915_sw_fence_fini(&intel_state->commit_ready);
14675
14676         kfree(state);
14677 }
14678
14679 static enum drm_mode_status
14680 intel_mode_valid(struct drm_device *dev,
14681                  const struct drm_display_mode *mode)
14682 {
14683         struct drm_i915_private *dev_priv = to_i915(dev);
14684         int hdisplay_max, htotal_max;
14685         int vdisplay_max, vtotal_max;
14686
14687         /*
14688          * Can't reject DBLSCAN here because Xorg ddxen can add piles
14689          * of DBLSCAN modes to the output's mode list when they detect
14690          * the scaling mode property on the connector. And they don't
14691          * ask the kernel to validate those modes in any way until
14692          * modeset time at which point the client gets a protocol error.
14693          * So in order to not upset those clients we silently ignore the
14694          * DBLSCAN flag on such connectors. For other connectors we will
14695          * reject modes with the DBLSCAN flag in encoder->compute_config().
14696          * And we always reject DBLSCAN modes in connector->mode_valid()
14697          * as we never want such modes on the connector's mode list.
14698          */
14699
14700         if (mode->vscan > 1)
14701                 return MODE_NO_VSCAN;
14702
14703         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14704                 return MODE_H_ILLEGAL;
14705
14706         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14707                            DRM_MODE_FLAG_NCSYNC |
14708                            DRM_MODE_FLAG_PCSYNC))
14709                 return MODE_HSYNC;
14710
14711         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14712                            DRM_MODE_FLAG_PIXMUX |
14713                            DRM_MODE_FLAG_CLKDIV2))
14714                 return MODE_BAD;
14715
14716         if (INTEL_GEN(dev_priv) >= 9 ||
14717             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
14718                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
14719                 vdisplay_max = 4096;
14720                 htotal_max = 8192;
14721                 vtotal_max = 8192;
14722         } else if (INTEL_GEN(dev_priv) >= 3) {
14723                 hdisplay_max = 4096;
14724                 vdisplay_max = 4096;
14725                 htotal_max = 8192;
14726                 vtotal_max = 8192;
14727         } else {
14728                 hdisplay_max = 2048;
14729                 vdisplay_max = 2048;
14730                 htotal_max = 4096;
14731                 vtotal_max = 4096;
14732         }
14733
14734         if (mode->hdisplay > hdisplay_max ||
14735             mode->hsync_start > htotal_max ||
14736             mode->hsync_end > htotal_max ||
14737             mode->htotal > htotal_max)
14738                 return MODE_H_ILLEGAL;
14739
14740         if (mode->vdisplay > vdisplay_max ||
14741             mode->vsync_start > vtotal_max ||
14742             mode->vsync_end > vtotal_max ||
14743             mode->vtotal > vtotal_max)
14744                 return MODE_V_ILLEGAL;
14745
14746         return MODE_OK;
14747 }
14748
14749 static const struct drm_mode_config_funcs intel_mode_funcs = {
14750         .fb_create = intel_user_framebuffer_create,
14751         .get_format_info = intel_get_format_info,
14752         .output_poll_changed = intel_fbdev_output_poll_changed,
14753         .mode_valid = intel_mode_valid,
14754         .atomic_check = intel_atomic_check,
14755         .atomic_commit = intel_atomic_commit,
14756         .atomic_state_alloc = intel_atomic_state_alloc,
14757         .atomic_state_clear = intel_atomic_state_clear,
14758         .atomic_state_free = intel_atomic_state_free,
14759 };
14760
14761 /**
14762  * intel_init_display_hooks - initialize the display modesetting hooks
14763  * @dev_priv: device private
14764  */
14765 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14766 {
14767         intel_init_cdclk_hooks(dev_priv);
14768
14769         if (INTEL_GEN(dev_priv) >= 9) {
14770                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14771                 dev_priv->display.get_initial_plane_config =
14772                         skylake_get_initial_plane_config;
14773                 dev_priv->display.crtc_compute_clock =
14774                         haswell_crtc_compute_clock;
14775                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14776                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14777         } else if (HAS_DDI(dev_priv)) {
14778                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14779                 dev_priv->display.get_initial_plane_config =
14780                         i9xx_get_initial_plane_config;
14781                 dev_priv->display.crtc_compute_clock =
14782                         haswell_crtc_compute_clock;
14783                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14784                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14785         } else if (HAS_PCH_SPLIT(dev_priv)) {
14786                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14787                 dev_priv->display.get_initial_plane_config =
14788                         i9xx_get_initial_plane_config;
14789                 dev_priv->display.crtc_compute_clock =
14790                         ironlake_crtc_compute_clock;
14791                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14792                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14793         } else if (IS_CHERRYVIEW(dev_priv)) {
14794                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14795                 dev_priv->display.get_initial_plane_config =
14796                         i9xx_get_initial_plane_config;
14797                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14798                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14799                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14800         } else if (IS_VALLEYVIEW(dev_priv)) {
14801                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14802                 dev_priv->display.get_initial_plane_config =
14803                         i9xx_get_initial_plane_config;
14804                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14805                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14806                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14807         } else if (IS_G4X(dev_priv)) {
14808                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14809                 dev_priv->display.get_initial_plane_config =
14810                         i9xx_get_initial_plane_config;
14811                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14812                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14813                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14814         } else if (IS_PINEVIEW(dev_priv)) {
14815                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14816                 dev_priv->display.get_initial_plane_config =
14817                         i9xx_get_initial_plane_config;
14818                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14819                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14820                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14821         } else if (!IS_GEN2(dev_priv)) {
14822                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14823                 dev_priv->display.get_initial_plane_config =
14824                         i9xx_get_initial_plane_config;
14825                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14826                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14827                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14828         } else {
14829                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14830                 dev_priv->display.get_initial_plane_config =
14831                         i9xx_get_initial_plane_config;
14832                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14833                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14834                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14835         }
14836
14837         if (IS_GEN5(dev_priv)) {
14838                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14839         } else if (IS_GEN6(dev_priv)) {
14840                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14841         } else if (IS_IVYBRIDGE(dev_priv)) {
14842                 /* FIXME: detect B0+ stepping and use auto training */
14843                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14844         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14845                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14846         }
14847
14848         if (INTEL_GEN(dev_priv) >= 9)
14849                 dev_priv->display.update_crtcs = skl_update_crtcs;
14850         else
14851                 dev_priv->display.update_crtcs = intel_update_crtcs;
14852 }
14853
14854 /*
14855  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14856  */
14857 static void quirk_ssc_force_disable(struct drm_device *dev)
14858 {
14859         struct drm_i915_private *dev_priv = to_i915(dev);
14860         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14861         DRM_INFO("applying lvds SSC disable quirk\n");
14862 }
14863
14864 /*
14865  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14866  * brightness value
14867  */
14868 static void quirk_invert_brightness(struct drm_device *dev)
14869 {
14870         struct drm_i915_private *dev_priv = to_i915(dev);
14871         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14872         DRM_INFO("applying inverted panel brightness quirk\n");
14873 }
14874
14875 /* Some VBT's incorrectly indicate no backlight is present */
14876 static void quirk_backlight_present(struct drm_device *dev)
14877 {
14878         struct drm_i915_private *dev_priv = to_i915(dev);
14879         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14880         DRM_INFO("applying backlight present quirk\n");
14881 }
14882
14883 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14884  * which is 300 ms greater than eDP spec T12 min.
14885  */
14886 static void quirk_increase_t12_delay(struct drm_device *dev)
14887 {
14888         struct drm_i915_private *dev_priv = to_i915(dev);
14889
14890         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14891         DRM_INFO("Applying T12 delay quirk\n");
14892 }
14893
14894 /*
14895  * GeminiLake NUC HDMI outputs require additional off time
14896  * this allows the onboard retimer to correctly sync to signal
14897  */
14898 static void quirk_increase_ddi_disabled_time(struct drm_device *dev)
14899 {
14900         struct drm_i915_private *dev_priv = to_i915(dev);
14901
14902         dev_priv->quirks |= QUIRK_INCREASE_DDI_DISABLED_TIME;
14903         DRM_INFO("Applying Increase DDI Disabled quirk\n");
14904 }
14905
14906 struct intel_quirk {
14907         int device;
14908         int subsystem_vendor;
14909         int subsystem_device;
14910         void (*hook)(struct drm_device *dev);
14911 };
14912
14913 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14914 struct intel_dmi_quirk {
14915         void (*hook)(struct drm_device *dev);
14916         const struct dmi_system_id (*dmi_id_list)[];
14917 };
14918
14919 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14920 {
14921         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14922         return 1;
14923 }
14924
14925 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14926         {
14927                 .dmi_id_list = &(const struct dmi_system_id[]) {
14928                         {
14929                                 .callback = intel_dmi_reverse_brightness,
14930                                 .ident = "NCR Corporation",
14931                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14932                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14933                                 },
14934                         },
14935                         { }  /* terminating entry */
14936                 },
14937                 .hook = quirk_invert_brightness,
14938         },
14939 };
14940
14941 static struct intel_quirk intel_quirks[] = {
14942         /* Lenovo U160 cannot use SSC on LVDS */
14943         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14944
14945         /* Sony Vaio Y cannot use SSC on LVDS */
14946         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14947
14948         /* Acer Aspire 5734Z must invert backlight brightness */
14949         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14950
14951         /* Acer/eMachines G725 */
14952         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14953
14954         /* Acer/eMachines e725 */
14955         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14956
14957         /* Acer/Packard Bell NCL20 */
14958         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14959
14960         /* Acer Aspire 4736Z */
14961         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14962
14963         /* Acer Aspire 5336 */
14964         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14965
14966         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14967         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14968
14969         /* Acer C720 Chromebook (Core i3 4005U) */
14970         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14971
14972         /* Apple Macbook 2,1 (Core 2 T7400) */
14973         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14974
14975         /* Apple Macbook 4,1 */
14976         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14977
14978         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14979         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14980
14981         /* HP Chromebook 14 (Celeron 2955U) */
14982         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14983
14984         /* Dell Chromebook 11 */
14985         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14986
14987         /* Dell Chromebook 11 (2015 version) */
14988         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14989
14990         /* Toshiba Satellite P50-C-18C */
14991         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14992
14993         /* GeminiLake NUC */
14994         { 0x3185, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14995         { 0x3184, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14996         /* ASRock ITX*/
14997         { 0x3185, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14998         { 0x3184, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14999 };
15000
15001 static void intel_init_quirks(struct drm_device *dev)
15002 {
15003         struct pci_dev *d = dev->pdev;
15004         int i;
15005
15006         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15007                 struct intel_quirk *q = &intel_quirks[i];
15008
15009                 if (d->device == q->device &&
15010                     (d->subsystem_vendor == q->subsystem_vendor ||
15011                      q->subsystem_vendor == PCI_ANY_ID) &&
15012                     (d->subsystem_device == q->subsystem_device ||
15013                      q->subsystem_device == PCI_ANY_ID))
15014                         q->hook(dev);
15015         }
15016         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15017                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15018                         intel_dmi_quirks[i].hook(dev);
15019         }
15020 }
15021
15022 /* Disable the VGA plane that we never use */
15023 static void i915_disable_vga(struct drm_i915_private *dev_priv)
15024 {
15025         struct pci_dev *pdev = dev_priv->drm.pdev;
15026         u8 sr1;
15027         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15028
15029         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15030         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
15031         outb(SR01, VGA_SR_INDEX);
15032         sr1 = inb(VGA_SR_DATA);
15033         outb(sr1 | 1<<5, VGA_SR_DATA);
15034         vga_put(pdev, VGA_RSRC_LEGACY_IO);
15035         udelay(300);
15036
15037         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15038         POSTING_READ(vga_reg);
15039 }
15040
15041 void intel_modeset_init_hw(struct drm_device *dev)
15042 {
15043         struct drm_i915_private *dev_priv = to_i915(dev);
15044
15045         intel_update_cdclk(dev_priv);
15046         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
15047         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
15048 }
15049
15050 /*
15051  * Calculate what we think the watermarks should be for the state we've read
15052  * out of the hardware and then immediately program those watermarks so that
15053  * we ensure the hardware settings match our internal state.
15054  *
15055  * We can calculate what we think WM's should be by creating a duplicate of the
15056  * current state (which was constructed during hardware readout) and running it
15057  * through the atomic check code to calculate new watermark values in the
15058  * state object.
15059  */
15060 static void sanitize_watermarks(struct drm_device *dev)
15061 {
15062         struct drm_i915_private *dev_priv = to_i915(dev);
15063         struct drm_atomic_state *state;
15064         struct intel_atomic_state *intel_state;
15065         struct drm_crtc *crtc;
15066         struct drm_crtc_state *cstate;
15067         struct drm_modeset_acquire_ctx ctx;
15068         int ret;
15069         int i;
15070
15071         /* Only supported on platforms that use atomic watermark design */
15072         if (!dev_priv->display.optimize_watermarks)
15073                 return;
15074
15075         /*
15076          * We need to hold connection_mutex before calling duplicate_state so
15077          * that the connector loop is protected.
15078          */
15079         drm_modeset_acquire_init(&ctx, 0);
15080 retry:
15081         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15082         if (ret == -EDEADLK) {
15083                 drm_modeset_backoff(&ctx);
15084                 goto retry;
15085         } else if (WARN_ON(ret)) {
15086                 goto fail;
15087         }
15088
15089         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15090         if (WARN_ON(IS_ERR(state)))
15091                 goto fail;
15092
15093         intel_state = to_intel_atomic_state(state);
15094
15095         /*
15096          * Hardware readout is the only time we don't want to calculate
15097          * intermediate watermarks (since we don't trust the current
15098          * watermarks).
15099          */
15100         if (!HAS_GMCH_DISPLAY(dev_priv))
15101                 intel_state->skip_intermediate_wm = true;
15102
15103         ret = intel_atomic_check(dev, state);
15104         if (ret) {
15105                 /*
15106                  * If we fail here, it means that the hardware appears to be
15107                  * programmed in a way that shouldn't be possible, given our
15108                  * understanding of watermark requirements.  This might mean a
15109                  * mistake in the hardware readout code or a mistake in the
15110                  * watermark calculations for a given platform.  Raise a WARN
15111                  * so that this is noticeable.
15112                  *
15113                  * If this actually happens, we'll have to just leave the
15114                  * BIOS-programmed watermarks untouched and hope for the best.
15115                  */
15116                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15117                 goto put_state;
15118         }
15119
15120         /* Write calculated watermark values back */
15121         for_each_new_crtc_in_state(state, crtc, cstate, i) {
15122                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15123
15124                 cs->wm.need_postvbl_update = true;
15125                 dev_priv->display.optimize_watermarks(intel_state, cs);
15126
15127                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
15128         }
15129
15130 put_state:
15131         drm_atomic_state_put(state);
15132 fail:
15133         drm_modeset_drop_locks(&ctx);
15134         drm_modeset_acquire_fini(&ctx);
15135 }
15136
15137 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
15138 {
15139         if (IS_GEN5(dev_priv)) {
15140                 u32 fdi_pll_clk =
15141                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
15142
15143                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
15144         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
15145                 dev_priv->fdi_pll_freq = 270000;
15146         } else {
15147                 return;
15148         }
15149
15150         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
15151 }
15152
15153 static int intel_initial_commit(struct drm_device *dev)
15154 {
15155         struct drm_atomic_state *state = NULL;
15156         struct drm_modeset_acquire_ctx ctx;
15157         struct drm_crtc *crtc;
15158         struct drm_crtc_state *crtc_state;
15159         int ret = 0;
15160
15161         state = drm_atomic_state_alloc(dev);
15162         if (!state)
15163                 return -ENOMEM;
15164
15165         drm_modeset_acquire_init(&ctx, 0);
15166
15167 retry:
15168         state->acquire_ctx = &ctx;
15169
15170         drm_for_each_crtc(crtc, dev) {
15171                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
15172                 if (IS_ERR(crtc_state)) {
15173                         ret = PTR_ERR(crtc_state);
15174                         goto out;
15175                 }
15176
15177                 if (crtc_state->active) {
15178                         ret = drm_atomic_add_affected_planes(state, crtc);
15179                         if (ret)
15180                                 goto out;
15181                 }
15182         }
15183
15184         ret = drm_atomic_commit(state);
15185
15186 out:
15187         if (ret == -EDEADLK) {
15188                 drm_atomic_state_clear(state);
15189                 drm_modeset_backoff(&ctx);
15190                 goto retry;
15191         }
15192
15193         drm_atomic_state_put(state);
15194
15195         drm_modeset_drop_locks(&ctx);
15196         drm_modeset_acquire_fini(&ctx);
15197
15198         return ret;
15199 }
15200
15201 int intel_modeset_init(struct drm_device *dev)
15202 {
15203         struct drm_i915_private *dev_priv = to_i915(dev);
15204         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15205         enum pipe pipe;
15206         struct intel_crtc *crtc;
15207         int ret;
15208
15209         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15210
15211         drm_mode_config_init(dev);
15212
15213         dev->mode_config.min_width = 0;
15214         dev->mode_config.min_height = 0;
15215
15216         dev->mode_config.preferred_depth = 24;
15217         dev->mode_config.prefer_shadow = 1;
15218
15219         dev->mode_config.allow_fb_modifiers = true;
15220
15221         dev->mode_config.funcs = &intel_mode_funcs;
15222
15223         init_llist_head(&dev_priv->atomic_helper.free_list);
15224         INIT_WORK(&dev_priv->atomic_helper.free_work,
15225                   intel_atomic_helper_free_state_worker);
15226
15227         intel_init_quirks(dev);
15228
15229         intel_init_pm(dev_priv);
15230
15231         /*
15232          * There may be no VBT; and if the BIOS enabled SSC we can
15233          * just keep using it to avoid unnecessary flicker.  Whereas if the
15234          * BIOS isn't using it, don't assume it will work even if the VBT
15235          * indicates as much.
15236          */
15237         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15238                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15239                                             DREF_SSC1_ENABLE);
15240
15241                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15242                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15243                                      bios_lvds_use_ssc ? "en" : "dis",
15244                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15245                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15246                 }
15247         }
15248
15249         /* maximum framebuffer dimensions */
15250         if (IS_GEN2(dev_priv)) {
15251                 dev->mode_config.max_width = 2048;
15252                 dev->mode_config.max_height = 2048;
15253         } else if (IS_GEN3(dev_priv)) {
15254                 dev->mode_config.max_width = 4096;
15255                 dev->mode_config.max_height = 4096;
15256         } else {
15257                 dev->mode_config.max_width = 8192;
15258                 dev->mode_config.max_height = 8192;
15259         }
15260
15261         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15262                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15263                 dev->mode_config.cursor_height = 1023;
15264         } else if (IS_GEN2(dev_priv)) {
15265                 dev->mode_config.cursor_width = 64;
15266                 dev->mode_config.cursor_height = 64;
15267         } else {
15268                 dev->mode_config.cursor_width = 256;
15269                 dev->mode_config.cursor_height = 256;
15270         }
15271
15272         dev->mode_config.fb_base = ggtt->gmadr.start;
15273
15274         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15275                       INTEL_INFO(dev_priv)->num_pipes,
15276                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15277
15278         for_each_pipe(dev_priv, pipe) {
15279                 ret = intel_crtc_init(dev_priv, pipe);
15280                 if (ret) {
15281                         drm_mode_config_cleanup(dev);
15282                         return ret;
15283                 }
15284         }
15285
15286         intel_shared_dpll_init(dev);
15287         intel_update_fdi_pll_freq(dev_priv);
15288
15289         intel_update_czclk(dev_priv);
15290         intel_modeset_init_hw(dev);
15291
15292         if (dev_priv->max_cdclk_freq == 0)
15293                 intel_update_max_cdclk(dev_priv);
15294
15295         /* Just disable it once at startup */
15296         i915_disable_vga(dev_priv);
15297         intel_setup_outputs(dev_priv);
15298
15299         drm_modeset_lock_all(dev);
15300         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15301         drm_modeset_unlock_all(dev);
15302
15303         for_each_intel_crtc(dev, crtc) {
15304                 struct intel_initial_plane_config plane_config = {};
15305
15306                 if (!crtc->active)
15307                         continue;
15308
15309                 /*
15310                  * Note that reserving the BIOS fb up front prevents us
15311                  * from stuffing other stolen allocations like the ring
15312                  * on top.  This prevents some ugliness at boot time, and
15313                  * can even allow for smooth boot transitions if the BIOS
15314                  * fb is large enough for the active pipe configuration.
15315                  */
15316                 dev_priv->display.get_initial_plane_config(crtc,
15317                                                            &plane_config);
15318
15319                 /*
15320                  * If the fb is shared between multiple heads, we'll
15321                  * just get the first one.
15322                  */
15323                 intel_find_initial_plane_obj(crtc, &plane_config);
15324         }
15325
15326         /*
15327          * Make sure hardware watermarks really match the state we read out.
15328          * Note that we need to do this after reconstructing the BIOS fb's
15329          * since the watermark calculation done here will use pstate->fb.
15330          */
15331         if (!HAS_GMCH_DISPLAY(dev_priv))
15332                 sanitize_watermarks(dev);
15333
15334         /*
15335          * Force all active planes to recompute their states. So that on
15336          * mode_setcrtc after probe, all the intel_plane_state variables
15337          * are already calculated and there is no assert_plane warnings
15338          * during bootup.
15339          */
15340         ret = intel_initial_commit(dev);
15341         if (ret)
15342                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15343
15344         return 0;
15345 }
15346
15347 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15348 {
15349         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15350         /* 640x480@60Hz, ~25175 kHz */
15351         struct dpll clock = {
15352                 .m1 = 18,
15353                 .m2 = 7,
15354                 .p1 = 13,
15355                 .p2 = 4,
15356                 .n = 2,
15357         };
15358         u32 dpll, fp;
15359         int i;
15360
15361         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15362
15363         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15364                       pipe_name(pipe), clock.vco, clock.dot);
15365
15366         fp = i9xx_dpll_compute_fp(&clock);
15367         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
15368                 DPLL_VGA_MODE_DIS |
15369                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15370                 PLL_P2_DIVIDE_BY_4 |
15371                 PLL_REF_INPUT_DREFCLK |
15372                 DPLL_VCO_ENABLE;
15373
15374         I915_WRITE(FP0(pipe), fp);
15375         I915_WRITE(FP1(pipe), fp);
15376
15377         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15378         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15379         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15380         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15381         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15382         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15383         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15384
15385         /*
15386          * Apparently we need to have VGA mode enabled prior to changing
15387          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15388          * dividers, even though the register value does change.
15389          */
15390         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15391         I915_WRITE(DPLL(pipe), dpll);
15392
15393         /* Wait for the clocks to stabilize. */
15394         POSTING_READ(DPLL(pipe));
15395         udelay(150);
15396
15397         /* The pixel multiplier can only be updated once the
15398          * DPLL is enabled and the clocks are stable.
15399          *
15400          * So write it again.
15401          */
15402         I915_WRITE(DPLL(pipe), dpll);
15403
15404         /* We do this three times for luck */
15405         for (i = 0; i < 3 ; i++) {
15406                 I915_WRITE(DPLL(pipe), dpll);
15407                 POSTING_READ(DPLL(pipe));
15408                 udelay(150); /* wait for warmup */
15409         }
15410
15411         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15412         POSTING_READ(PIPECONF(pipe));
15413
15414         intel_wait_for_pipe_scanline_moving(crtc);
15415 }
15416
15417 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15418 {
15419         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15420
15421         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15422                       pipe_name(pipe));
15423
15424         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15425         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15426         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15427         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15428         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
15429
15430         I915_WRITE(PIPECONF(pipe), 0);
15431         POSTING_READ(PIPECONF(pipe));
15432
15433         intel_wait_for_pipe_scanline_stopped(crtc);
15434
15435         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15436         POSTING_READ(DPLL(pipe));
15437 }
15438
15439 static bool intel_plane_mapping_ok(struct intel_crtc *crtc,
15440                                    struct intel_plane *plane)
15441 {
15442         enum pipe pipe;
15443
15444         if (!plane->get_hw_state(plane, &pipe))
15445                 return true;
15446
15447         return pipe == crtc->pipe;
15448 }
15449
15450 static void
15451 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15452 {
15453         struct intel_crtc *crtc;
15454
15455         if (INTEL_GEN(dev_priv) >= 4)
15456                 return;
15457
15458         for_each_intel_crtc(&dev_priv->drm, crtc) {
15459                 struct intel_plane *plane =
15460                         to_intel_plane(crtc->base.primary);
15461
15462                 if (intel_plane_mapping_ok(crtc, plane))
15463                         continue;
15464
15465                 DRM_DEBUG_KMS("%s attached to the wrong pipe, disabling plane\n",
15466                               plane->base.name);
15467                 intel_plane_disable_noatomic(crtc, plane);
15468         }
15469 }
15470
15471 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15472 {
15473         struct drm_device *dev = crtc->base.dev;
15474         struct intel_encoder *encoder;
15475
15476         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15477                 return true;
15478
15479         return false;
15480 }
15481
15482 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15483 {
15484         struct drm_device *dev = encoder->base.dev;
15485         struct intel_connector *connector;
15486
15487         for_each_connector_on_encoder(dev, &encoder->base, connector)
15488                 return connector;
15489
15490         return NULL;
15491 }
15492
15493 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15494                               enum pipe pch_transcoder)
15495 {
15496         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15497                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15498 }
15499
15500 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15501                                 struct drm_modeset_acquire_ctx *ctx)
15502 {
15503         struct drm_device *dev = crtc->base.dev;
15504         struct drm_i915_private *dev_priv = to_i915(dev);
15505         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15506
15507         /* Clear any frame start delays used for debugging left by the BIOS */
15508         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15509                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15510
15511                 I915_WRITE(reg,
15512                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15513         }
15514
15515         /* restore vblank interrupts to correct state */
15516         drm_crtc_vblank_reset(&crtc->base);
15517         if (crtc->active) {
15518                 struct intel_plane *plane;
15519
15520                 drm_crtc_vblank_on(&crtc->base);
15521
15522                 /* Disable everything but the primary plane */
15523                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15524                         const struct intel_plane_state *plane_state =
15525                                 to_intel_plane_state(plane->base.state);
15526
15527                         if (plane_state->base.visible &&
15528                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15529                                 intel_plane_disable_noatomic(crtc, plane);
15530                 }
15531         }
15532
15533         /* Adjust the state of the output pipe according to whether we
15534          * have active connectors/encoders. */
15535         if (crtc->active && !intel_crtc_has_encoders(crtc))
15536                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15537
15538         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15539                 /*
15540                  * We start out with underrun reporting disabled to avoid races.
15541                  * For correct bookkeeping mark this on active crtcs.
15542                  *
15543                  * Also on gmch platforms we dont have any hardware bits to
15544                  * disable the underrun reporting. Which means we need to start
15545                  * out with underrun reporting disabled also on inactive pipes,
15546                  * since otherwise we'll complain about the garbage we read when
15547                  * e.g. coming up after runtime pm.
15548                  *
15549                  * No protection against concurrent access is required - at
15550                  * worst a fifo underrun happens which also sets this to false.
15551                  */
15552                 crtc->cpu_fifo_underrun_disabled = true;
15553                 /*
15554                  * We track the PCH trancoder underrun reporting state
15555                  * within the crtc. With crtc for pipe A housing the underrun
15556                  * reporting state for PCH transcoder A, crtc for pipe B housing
15557                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15558                  * and marking underrun reporting as disabled for the non-existing
15559                  * PCH transcoders B and C would prevent enabling the south
15560                  * error interrupt (see cpt_can_enable_serr_int()).
15561                  */
15562                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15563                         crtc->pch_fifo_underrun_disabled = true;
15564         }
15565 }
15566
15567 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15568 {
15569         struct intel_connector *connector;
15570
15571         /* We need to check both for a crtc link (meaning that the
15572          * encoder is active and trying to read from a pipe) and the
15573          * pipe itself being active. */
15574         bool has_active_crtc = encoder->base.crtc &&
15575                 to_intel_crtc(encoder->base.crtc)->active;
15576
15577         connector = intel_encoder_find_connector(encoder);
15578         if (connector && !has_active_crtc) {
15579                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15580                               encoder->base.base.id,
15581                               encoder->base.name);
15582
15583                 /* Connector is active, but has no active pipe. This is
15584                  * fallout from our resume register restoring. Disable
15585                  * the encoder manually again. */
15586                 if (encoder->base.crtc) {
15587                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15588
15589                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15590                                       encoder->base.base.id,
15591                                       encoder->base.name);
15592                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15593                         if (encoder->post_disable)
15594                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15595                 }
15596                 encoder->base.crtc = NULL;
15597
15598                 /* Inconsistent output/port/pipe state happens presumably due to
15599                  * a bug in one of the get_hw_state functions. Or someplace else
15600                  * in our code, like the register restore mess on resume. Clamp
15601                  * things to off as a safer default. */
15602
15603                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15604                 connector->base.encoder = NULL;
15605         }
15606
15607         /* notify opregion of the sanitized encoder state */
15608         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
15609 }
15610
15611 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15612 {
15613         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15614
15615         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15616                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15617                 i915_disable_vga(dev_priv);
15618         }
15619 }
15620
15621 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15622 {
15623         /* This function can be called both from intel_modeset_setup_hw_state or
15624          * at a very early point in our resume sequence, where the power well
15625          * structures are not yet restored. Since this function is at a very
15626          * paranoid "someone might have enabled VGA while we were not looking"
15627          * level, just check if the power well is enabled instead of trying to
15628          * follow the "don't touch the power well if we don't need it" policy
15629          * the rest of the driver uses. */
15630         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15631                 return;
15632
15633         i915_redisable_vga_power_on(dev_priv);
15634
15635         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15636 }
15637
15638 /* FIXME read out full plane state for all planes */
15639 static void readout_plane_state(struct intel_crtc *crtc)
15640 {
15641         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15642         struct intel_crtc_state *crtc_state =
15643                 to_intel_crtc_state(crtc->base.state);
15644         struct intel_plane *plane;
15645
15646         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
15647                 struct intel_plane_state *plane_state =
15648                         to_intel_plane_state(plane->base.state);
15649                 enum pipe pipe;
15650                 bool visible;
15651
15652                 visible = plane->get_hw_state(plane, &pipe);
15653
15654                 intel_set_plane_visible(crtc_state, plane_state, visible);
15655         }
15656 }
15657
15658 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15659 {
15660         struct drm_i915_private *dev_priv = to_i915(dev);
15661         enum pipe pipe;
15662         struct intel_crtc *crtc;
15663         struct intel_encoder *encoder;
15664         struct intel_connector *connector;
15665         struct drm_connector_list_iter conn_iter;
15666         int i;
15667
15668         dev_priv->active_crtcs = 0;
15669
15670         for_each_intel_crtc(dev, crtc) {
15671                 struct intel_crtc_state *crtc_state =
15672                         to_intel_crtc_state(crtc->base.state);
15673
15674                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15675                 memset(crtc_state, 0, sizeof(*crtc_state));
15676                 crtc_state->base.crtc = &crtc->base;
15677
15678                 crtc_state->base.active = crtc_state->base.enable =
15679                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15680
15681                 crtc->base.enabled = crtc_state->base.enable;
15682                 crtc->active = crtc_state->base.active;
15683
15684                 if (crtc_state->base.active)
15685                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15686
15687                 readout_plane_state(crtc);
15688
15689                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15690                               crtc->base.base.id, crtc->base.name,
15691                               enableddisabled(crtc_state->base.active));
15692         }
15693
15694         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15695                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15696
15697                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15698                                                         &pll->state.hw_state);
15699                 pll->state.crtc_mask = 0;
15700                 for_each_intel_crtc(dev, crtc) {
15701                         struct intel_crtc_state *crtc_state =
15702                                 to_intel_crtc_state(crtc->base.state);
15703
15704                         if (crtc_state->base.active &&
15705                             crtc_state->shared_dpll == pll)
15706                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15707                 }
15708                 pll->active_mask = pll->state.crtc_mask;
15709
15710                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15711                               pll->info->name, pll->state.crtc_mask, pll->on);
15712         }
15713
15714         for_each_intel_encoder(dev, encoder) {
15715                 pipe = 0;
15716
15717                 if (encoder->get_hw_state(encoder, &pipe)) {
15718                         struct intel_crtc_state *crtc_state;
15719
15720                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15721                         crtc_state = to_intel_crtc_state(crtc->base.state);
15722
15723                         encoder->base.crtc = &crtc->base;
15724                         encoder->get_config(encoder, crtc_state);
15725                 } else {
15726                         encoder->base.crtc = NULL;
15727                 }
15728
15729                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15730                               encoder->base.base.id, encoder->base.name,
15731                               enableddisabled(encoder->base.crtc),
15732                               pipe_name(pipe));
15733         }
15734
15735         drm_connector_list_iter_begin(dev, &conn_iter);
15736         for_each_intel_connector_iter(connector, &conn_iter) {
15737                 if (connector->get_hw_state(connector)) {
15738                         connector->base.dpms = DRM_MODE_DPMS_ON;
15739
15740                         encoder = connector->encoder;
15741                         connector->base.encoder = &encoder->base;
15742
15743                         if (encoder->base.crtc &&
15744                             encoder->base.crtc->state->active) {
15745                                 /*
15746                                  * This has to be done during hardware readout
15747                                  * because anything calling .crtc_disable may
15748                                  * rely on the connector_mask being accurate.
15749                                  */
15750                                 encoder->base.crtc->state->connector_mask |=
15751                                         drm_connector_mask(&connector->base);
15752                                 encoder->base.crtc->state->encoder_mask |=
15753                                         drm_encoder_mask(&encoder->base);
15754                         }
15755
15756                 } else {
15757                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15758                         connector->base.encoder = NULL;
15759                 }
15760                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15761                               connector->base.base.id, connector->base.name,
15762                               enableddisabled(connector->base.encoder));
15763         }
15764         drm_connector_list_iter_end(&conn_iter);
15765
15766         for_each_intel_crtc(dev, crtc) {
15767                 struct intel_crtc_state *crtc_state =
15768                         to_intel_crtc_state(crtc->base.state);
15769                 int min_cdclk = 0;
15770
15771                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15772                 if (crtc_state->base.active) {
15773                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15774                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
15775                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
15776                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15777                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15778
15779                         /*
15780                          * The initial mode needs to be set in order to keep
15781                          * the atomic core happy. It wants a valid mode if the
15782                          * crtc's enabled, so we do the above call.
15783                          *
15784                          * But we don't set all the derived state fully, hence
15785                          * set a flag to indicate that a full recalculation is
15786                          * needed on the next commit.
15787                          */
15788                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15789
15790                         intel_crtc_compute_pixel_rate(crtc_state);
15791
15792                         if (dev_priv->display.modeset_calc_cdclk) {
15793                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15794                                 if (WARN_ON(min_cdclk < 0))
15795                                         min_cdclk = 0;
15796                         }
15797
15798                         drm_calc_timestamping_constants(&crtc->base,
15799                                                         &crtc_state->base.adjusted_mode);
15800                         update_scanline_offset(crtc);
15801                 }
15802
15803                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15804                 dev_priv->min_voltage_level[crtc->pipe] =
15805                         crtc_state->min_voltage_level;
15806
15807                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15808         }
15809 }
15810
15811 static void
15812 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15813 {
15814         struct intel_encoder *encoder;
15815
15816         for_each_intel_encoder(&dev_priv->drm, encoder) {
15817                 u64 get_domains;
15818                 enum intel_display_power_domain domain;
15819                 struct intel_crtc_state *crtc_state;
15820
15821                 if (!encoder->get_power_domains)
15822                         continue;
15823
15824                 /*
15825                  * MST-primary and inactive encoders don't have a crtc state
15826                  * and neither of these require any power domain references.
15827                  */
15828                 if (!encoder->base.crtc)
15829                         continue;
15830
15831                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
15832                 get_domains = encoder->get_power_domains(encoder, crtc_state);
15833                 for_each_power_domain(domain, get_domains)
15834                         intel_display_power_get(dev_priv, domain);
15835         }
15836 }
15837
15838 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15839 {
15840         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15841         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15842                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15843                            DARBF_GATING_DIS);
15844
15845         if (IS_HASWELL(dev_priv)) {
15846                 /*
15847                  * WaRsPkgCStateDisplayPMReq:hsw
15848                  * System hang if this isn't done before disabling all planes!
15849                  */
15850                 I915_WRITE(CHICKEN_PAR1_1,
15851                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15852         }
15853 }
15854
15855 /* Scan out the current hw modeset state,
15856  * and sanitizes it to the current state
15857  */
15858 static void
15859 intel_modeset_setup_hw_state(struct drm_device *dev,
15860                              struct drm_modeset_acquire_ctx *ctx)
15861 {
15862         struct drm_i915_private *dev_priv = to_i915(dev);
15863         enum pipe pipe;
15864         struct intel_crtc *crtc;
15865         struct intel_encoder *encoder;
15866         int i;
15867
15868         intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
15869
15870         intel_early_display_was(dev_priv);
15871         intel_modeset_readout_hw_state(dev);
15872
15873         /* HW state is read out, now we need to sanitize this mess. */
15874         get_encoder_power_domains(dev_priv);
15875
15876         intel_sanitize_plane_mapping(dev_priv);
15877
15878         for_each_intel_encoder(dev, encoder) {
15879                 intel_sanitize_encoder(encoder);
15880         }
15881
15882         for_each_pipe(dev_priv, pipe) {
15883                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15884
15885                 intel_sanitize_crtc(crtc, ctx);
15886                 intel_dump_pipe_config(crtc, crtc->config,
15887                                        "[setup_hw_state]");
15888         }
15889
15890         intel_modeset_update_connector_atomic_state(dev);
15891
15892         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15893                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15894
15895                 if (!pll->on || pll->active_mask)
15896                         continue;
15897
15898                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
15899                               pll->info->name);
15900
15901                 pll->info->funcs->disable(dev_priv, pll);
15902                 pll->on = false;
15903         }
15904
15905         if (IS_G4X(dev_priv)) {
15906                 g4x_wm_get_hw_state(dev);
15907                 g4x_wm_sanitize(dev_priv);
15908         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15909                 vlv_wm_get_hw_state(dev);
15910                 vlv_wm_sanitize(dev_priv);
15911         } else if (INTEL_GEN(dev_priv) >= 9) {
15912                 skl_wm_get_hw_state(dev);
15913         } else if (HAS_PCH_SPLIT(dev_priv)) {
15914                 ilk_wm_get_hw_state(dev);
15915         }
15916
15917         for_each_intel_crtc(dev, crtc) {
15918                 u64 put_domains;
15919
15920                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15921                 if (WARN_ON(put_domains))
15922                         modeset_put_power_domains(dev_priv, put_domains);
15923         }
15924
15925         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT);
15926
15927         intel_fbc_init_pipe_state(dev_priv);
15928 }
15929
15930 void intel_display_resume(struct drm_device *dev)
15931 {
15932         struct drm_i915_private *dev_priv = to_i915(dev);
15933         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15934         struct drm_modeset_acquire_ctx ctx;
15935         int ret;
15936
15937         dev_priv->modeset_restore_state = NULL;
15938         if (state)
15939                 state->acquire_ctx = &ctx;
15940
15941         drm_modeset_acquire_init(&ctx, 0);
15942
15943         while (1) {
15944                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15945                 if (ret != -EDEADLK)
15946                         break;
15947
15948                 drm_modeset_backoff(&ctx);
15949         }
15950
15951         if (!ret)
15952                 ret = __intel_display_resume(dev, state, &ctx);
15953
15954         intel_enable_ipc(dev_priv);
15955         drm_modeset_drop_locks(&ctx);
15956         drm_modeset_acquire_fini(&ctx);
15957
15958         if (ret)
15959                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15960         if (state)
15961                 drm_atomic_state_put(state);
15962 }
15963
15964 int intel_connector_register(struct drm_connector *connector)
15965 {
15966         struct intel_connector *intel_connector = to_intel_connector(connector);
15967         int ret;
15968
15969         ret = intel_backlight_device_register(intel_connector);
15970         if (ret)
15971                 goto err;
15972
15973         return 0;
15974
15975 err:
15976         return ret;
15977 }
15978
15979 void intel_connector_unregister(struct drm_connector *connector)
15980 {
15981         struct intel_connector *intel_connector = to_intel_connector(connector);
15982
15983         intel_backlight_device_unregister(intel_connector);
15984         intel_panel_destroy_backlight(connector);
15985 }
15986
15987 static void intel_hpd_poll_fini(struct drm_device *dev)
15988 {
15989         struct intel_connector *connector;
15990         struct drm_connector_list_iter conn_iter;
15991
15992         /* Kill all the work that may have been queued by hpd. */
15993         drm_connector_list_iter_begin(dev, &conn_iter);
15994         for_each_intel_connector_iter(connector, &conn_iter) {
15995                 if (connector->modeset_retry_work.func)
15996                         cancel_work_sync(&connector->modeset_retry_work);
15997                 if (connector->hdcp_shim) {
15998                         cancel_delayed_work_sync(&connector->hdcp_check_work);
15999                         cancel_work_sync(&connector->hdcp_prop_work);
16000                 }
16001         }
16002         drm_connector_list_iter_end(&conn_iter);
16003 }
16004
16005 void intel_modeset_cleanup(struct drm_device *dev)
16006 {
16007         struct drm_i915_private *dev_priv = to_i915(dev);
16008
16009         flush_workqueue(dev_priv->modeset_wq);
16010
16011         flush_work(&dev_priv->atomic_helper.free_work);
16012         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
16013
16014         /*
16015          * Interrupts and polling as the first thing to avoid creating havoc.
16016          * Too much stuff here (turning of connectors, ...) would
16017          * experience fancy races otherwise.
16018          */
16019         intel_irq_uninstall(dev_priv);
16020
16021         /*
16022          * Due to the hpd irq storm handling the hotplug work can re-arm the
16023          * poll handlers. Hence disable polling after hpd handling is shut down.
16024          */
16025         intel_hpd_poll_fini(dev);
16026
16027         /* poll work can call into fbdev, hence clean that up afterwards */
16028         intel_fbdev_fini(dev_priv);
16029
16030         intel_unregister_dsm_handler();
16031
16032         intel_fbc_global_disable(dev_priv);
16033
16034         /* flush any delayed tasks or pending work */
16035         flush_scheduled_work();
16036
16037         drm_mode_config_cleanup(dev);
16038
16039         intel_cleanup_overlay(dev_priv);
16040
16041         intel_teardown_gmbus(dev_priv);
16042
16043         destroy_workqueue(dev_priv->modeset_wq);
16044 }
16045
16046 void intel_connector_attach_encoder(struct intel_connector *connector,
16047                                     struct intel_encoder *encoder)
16048 {
16049         connector->encoder = encoder;
16050         drm_connector_attach_encoder(&connector->base, &encoder->base);
16051 }
16052
16053 /*
16054  * set vga decode state - true == enable VGA decode
16055  */
16056 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
16057 {
16058         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16059         u16 gmch_ctrl;
16060
16061         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16062                 DRM_ERROR("failed to read control word\n");
16063                 return -EIO;
16064         }
16065
16066         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16067                 return 0;
16068
16069         if (state)
16070                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16071         else
16072                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16073
16074         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16075                 DRM_ERROR("failed to write control word\n");
16076                 return -EIO;
16077         }
16078
16079         return 0;
16080 }
16081
16082 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
16083
16084 struct intel_display_error_state {
16085
16086         u32 power_well_driver;
16087
16088         int num_transcoders;
16089
16090         struct intel_cursor_error_state {
16091                 u32 control;
16092                 u32 position;
16093                 u32 base;
16094                 u32 size;
16095         } cursor[I915_MAX_PIPES];
16096
16097         struct intel_pipe_error_state {
16098                 bool power_domain_on;
16099                 u32 source;
16100                 u32 stat;
16101         } pipe[I915_MAX_PIPES];
16102
16103         struct intel_plane_error_state {
16104                 u32 control;
16105                 u32 stride;
16106                 u32 size;
16107                 u32 pos;
16108                 u32 addr;
16109                 u32 surface;
16110                 u32 tile_offset;
16111         } plane[I915_MAX_PIPES];
16112
16113         struct intel_transcoder_error_state {
16114                 bool power_domain_on;
16115                 enum transcoder cpu_transcoder;
16116
16117                 u32 conf;
16118
16119                 u32 htotal;
16120                 u32 hblank;
16121                 u32 hsync;
16122                 u32 vtotal;
16123                 u32 vblank;
16124                 u32 vsync;
16125         } transcoder[4];
16126 };
16127
16128 struct intel_display_error_state *
16129 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16130 {
16131         struct intel_display_error_state *error;
16132         int transcoders[] = {
16133                 TRANSCODER_A,
16134                 TRANSCODER_B,
16135                 TRANSCODER_C,
16136                 TRANSCODER_EDP,
16137         };
16138         int i;
16139
16140         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16141                 return NULL;
16142
16143         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16144         if (error == NULL)
16145                 return NULL;
16146
16147         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16148                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
16149
16150         for_each_pipe(dev_priv, i) {
16151                 error->pipe[i].power_domain_on =
16152                         __intel_display_power_is_enabled(dev_priv,
16153                                                          POWER_DOMAIN_PIPE(i));
16154                 if (!error->pipe[i].power_domain_on)
16155                         continue;
16156
16157                 error->cursor[i].control = I915_READ(CURCNTR(i));
16158                 error->cursor[i].position = I915_READ(CURPOS(i));
16159                 error->cursor[i].base = I915_READ(CURBASE(i));
16160
16161                 error->plane[i].control = I915_READ(DSPCNTR(i));
16162                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16163                 if (INTEL_GEN(dev_priv) <= 3) {
16164                         error->plane[i].size = I915_READ(DSPSIZE(i));
16165                         error->plane[i].pos = I915_READ(DSPPOS(i));
16166                 }
16167                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16168                         error->plane[i].addr = I915_READ(DSPADDR(i));
16169                 if (INTEL_GEN(dev_priv) >= 4) {
16170                         error->plane[i].surface = I915_READ(DSPSURF(i));
16171                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16172                 }
16173
16174                 error->pipe[i].source = I915_READ(PIPESRC(i));
16175
16176                 if (HAS_GMCH_DISPLAY(dev_priv))
16177                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16178         }
16179
16180         /* Note: this does not include DSI transcoders. */
16181         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16182         if (HAS_DDI(dev_priv))
16183                 error->num_transcoders++; /* Account for eDP. */
16184
16185         for (i = 0; i < error->num_transcoders; i++) {
16186                 enum transcoder cpu_transcoder = transcoders[i];
16187
16188                 error->transcoder[i].power_domain_on =
16189                         __intel_display_power_is_enabled(dev_priv,
16190                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16191                 if (!error->transcoder[i].power_domain_on)
16192                         continue;
16193
16194                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16195
16196                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16197                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16198                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16199                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16200                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16201                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16202                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16203         }
16204
16205         return error;
16206 }
16207
16208 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16209
16210 void
16211 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16212                                 struct intel_display_error_state *error)
16213 {
16214         struct drm_i915_private *dev_priv = m->i915;
16215         int i;
16216
16217         if (!error)
16218                 return;
16219
16220         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16221         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16222                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16223                            error->power_well_driver);
16224         for_each_pipe(dev_priv, i) {
16225                 err_printf(m, "Pipe [%d]:\n", i);
16226                 err_printf(m, "  Power: %s\n",
16227                            onoff(error->pipe[i].power_domain_on));
16228                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16229                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16230
16231                 err_printf(m, "Plane [%d]:\n", i);
16232                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16233                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16234                 if (INTEL_GEN(dev_priv) <= 3) {
16235                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16236                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16237                 }
16238                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16239                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16240                 if (INTEL_GEN(dev_priv) >= 4) {
16241                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16242                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16243                 }
16244
16245                 err_printf(m, "Cursor [%d]:\n", i);
16246                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16247                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16248                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16249         }
16250
16251         for (i = 0; i < error->num_transcoders; i++) {
16252                 err_printf(m, "CPU transcoder: %s\n",
16253                            transcoder_name(error->transcoder[i].cpu_transcoder));
16254                 err_printf(m, "  Power: %s\n",
16255                            onoff(error->transcoder[i].power_domain_on));
16256                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16257                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16258                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16259                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16260                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16261                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16262                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16263         }
16264 }
16265
16266 #endif