]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/gpu/drm/i915/intel_display.c
c24bc848ac6c4600ea4f456f9b35feee9d6b9d1c
[linux.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "i915_gem_clflush.h"
41 #include "intel_dsi.h"
42 #include "i915_trace.h"
43 #include <drm/drm_atomic.h>
44 #include <drm/drm_atomic_helper.h>
45 #include <drm/drm_dp_helper.h>
46 #include <drm/drm_crtc_helper.h>
47 #include <drm/drm_plane_helper.h>
48 #include <drm/drm_rect.h>
49 #include <drm/drm_atomic_uapi.h>
50 #include <linux/dma_remapping.h>
51 #include <linux/reservation.h>
52
53 /* Primary plane formats for gen <= 3 */
54 static const uint32_t i8xx_primary_formats[] = {
55         DRM_FORMAT_C8,
56         DRM_FORMAT_RGB565,
57         DRM_FORMAT_XRGB1555,
58         DRM_FORMAT_XRGB8888,
59 };
60
61 /* Primary plane formats for gen >= 4 */
62 static const uint32_t i965_primary_formats[] = {
63         DRM_FORMAT_C8,
64         DRM_FORMAT_RGB565,
65         DRM_FORMAT_XRGB8888,
66         DRM_FORMAT_XBGR8888,
67         DRM_FORMAT_XRGB2101010,
68         DRM_FORMAT_XBGR2101010,
69 };
70
71 static const uint64_t i9xx_format_modifiers[] = {
72         I915_FORMAT_MOD_X_TILED,
73         DRM_FORMAT_MOD_LINEAR,
74         DRM_FORMAT_MOD_INVALID
75 };
76
77 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 plane)
1921 {
1922         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1923         unsigned int cpp = fb->format->cpp[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 (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 (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 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, plane);
1975 }
1976
1977 /* Return the tile dimensions in pixel units */
1978 static void intel_tile_dims(const struct drm_framebuffer *fb, int plane,
1979                             unsigned int *tile_width,
1980                             unsigned int *tile_height)
1981 {
1982         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, plane);
1983         unsigned int cpp = fb->format->cpp[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 plane, unsigned int height)
1992 {
1993         unsigned int tile_height = intel_tile_height(fb, 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 plane)
2048 {
2049         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2050
2051         /* AUX_DIST needs only 4K alignment */
2052         if (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                            unsigned int rotation,
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_ggtt_view view;
2091         struct i915_vma *vma;
2092         unsigned int pinctl;
2093         u32 alignment;
2094
2095         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2096
2097         alignment = intel_surf_alignment(fb, 0);
2098
2099         intel_fill_fb_ggtt_view(&view, fb, rotation);
2100
2101         /* Note that the w/a also requires 64 PTE of padding following the
2102          * bo. We currently fill all unused PTE with the shadow page and so
2103          * we should always have valid PTE following the scanout preventing
2104          * the VT-d warning.
2105          */
2106         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2107                 alignment = 256 * 1024;
2108
2109         /*
2110          * Global gtt pte registers are special registers which actually forward
2111          * writes to a chunk of system memory. Which means that there is no risk
2112          * that the register values disappear as soon as we call
2113          * intel_runtime_pm_put(), so it is correct to wrap only the
2114          * pin/unpin/fence and not more.
2115          */
2116         intel_runtime_pm_get(dev_priv);
2117
2118         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2119
2120         pinctl = 0;
2121
2122         /* Valleyview is definitely limited to scanning out the first
2123          * 512MiB. Lets presume this behaviour was inherited from the
2124          * g4x display engine and that all earlier gen are similarly
2125          * limited. Testing suggests that it is a little more
2126          * complicated than this. For example, Cherryview appears quite
2127          * happy to scanout from anywhere within its global aperture.
2128          */
2129         if (HAS_GMCH_DISPLAY(dev_priv))
2130                 pinctl |= PIN_MAPPABLE;
2131
2132         vma = i915_gem_object_pin_to_display_plane(obj,
2133                                                    alignment, &view, pinctl);
2134         if (IS_ERR(vma))
2135                 goto err;
2136
2137         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2138                 int ret;
2139
2140                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2141                  * fence, whereas 965+ only requires a fence if using
2142                  * framebuffer compression.  For simplicity, we always, when
2143                  * possible, install a fence as the cost is not that onerous.
2144                  *
2145                  * If we fail to fence the tiled scanout, then either the
2146                  * modeset will reject the change (which is highly unlikely as
2147                  * the affected systems, all but one, do not have unmappable
2148                  * space) or we will not be able to enable full powersaving
2149                  * techniques (also likely not to apply due to various limits
2150                  * FBC and the like impose on the size of the buffer, which
2151                  * presumably we violated anyway with this unmappable buffer).
2152                  * Anyway, it is presumably better to stumble onwards with
2153                  * something and try to run the system in a "less than optimal"
2154                  * mode that matches the user configuration.
2155                  */
2156                 ret = i915_vma_pin_fence(vma);
2157                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2158                         i915_gem_object_unpin_from_display_plane(vma);
2159                         vma = ERR_PTR(ret);
2160                         goto err;
2161                 }
2162
2163                 if (ret == 0 && vma->fence)
2164                         *out_flags |= PLANE_HAS_FENCE;
2165         }
2166
2167         i915_vma_get(vma);
2168 err:
2169         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2170
2171         intel_runtime_pm_put(dev_priv);
2172         return vma;
2173 }
2174
2175 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2176 {
2177         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2178
2179         if (flags & PLANE_HAS_FENCE)
2180                 i915_vma_unpin_fence(vma);
2181         i915_gem_object_unpin_from_display_plane(vma);
2182         i915_vma_put(vma);
2183 }
2184
2185 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2186                           unsigned int rotation)
2187 {
2188         if (drm_rotation_90_or_270(rotation))
2189                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2190         else
2191                 return fb->pitches[plane];
2192 }
2193
2194 /*
2195  * Convert the x/y offsets into a linear offset.
2196  * Only valid with 0/180 degree rotation, which is fine since linear
2197  * offset is only used with linear buffers on pre-hsw and tiled buffers
2198  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2199  */
2200 u32 intel_fb_xy_to_linear(int x, int y,
2201                           const struct intel_plane_state *state,
2202                           int plane)
2203 {
2204         const struct drm_framebuffer *fb = state->base.fb;
2205         unsigned int cpp = fb->format->cpp[plane];
2206         unsigned int pitch = fb->pitches[plane];
2207
2208         return y * pitch + x * cpp;
2209 }
2210
2211 /*
2212  * Add the x/y offsets derived from fb->offsets[] to the user
2213  * specified plane src x/y offsets. The resulting x/y offsets
2214  * specify the start of scanout from the beginning of the gtt mapping.
2215  */
2216 void intel_add_fb_offsets(int *x, int *y,
2217                           const struct intel_plane_state *state,
2218                           int plane)
2219
2220 {
2221         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2222         unsigned int rotation = state->base.rotation;
2223
2224         if (drm_rotation_90_or_270(rotation)) {
2225                 *x += intel_fb->rotated[plane].x;
2226                 *y += intel_fb->rotated[plane].y;
2227         } else {
2228                 *x += intel_fb->normal[plane].x;
2229                 *y += intel_fb->normal[plane].y;
2230         }
2231 }
2232
2233 static u32 __intel_adjust_tile_offset(int *x, int *y,
2234                                       unsigned int tile_width,
2235                                       unsigned int tile_height,
2236                                       unsigned int tile_size,
2237                                       unsigned int pitch_tiles,
2238                                       u32 old_offset,
2239                                       u32 new_offset)
2240 {
2241         unsigned int pitch_pixels = pitch_tiles * tile_width;
2242         unsigned int tiles;
2243
2244         WARN_ON(old_offset & (tile_size - 1));
2245         WARN_ON(new_offset & (tile_size - 1));
2246         WARN_ON(new_offset > old_offset);
2247
2248         tiles = (old_offset - new_offset) / tile_size;
2249
2250         *y += tiles / pitch_tiles * tile_height;
2251         *x += tiles % pitch_tiles * tile_width;
2252
2253         /* minimize x in case it got needlessly big */
2254         *y += *x / pitch_pixels * tile_height;
2255         *x %= pitch_pixels;
2256
2257         return new_offset;
2258 }
2259
2260 static u32 _intel_adjust_tile_offset(int *x, int *y,
2261                                      const struct drm_framebuffer *fb, int plane,
2262                                      unsigned int rotation,
2263                                      u32 old_offset, u32 new_offset)
2264 {
2265         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2266         unsigned int cpp = fb->format->cpp[plane];
2267         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2268
2269         WARN_ON(new_offset > old_offset);
2270
2271         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2272                 unsigned int tile_size, tile_width, tile_height;
2273                 unsigned int pitch_tiles;
2274
2275                 tile_size = intel_tile_size(dev_priv);
2276                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2277
2278                 if (drm_rotation_90_or_270(rotation)) {
2279                         pitch_tiles = pitch / tile_height;
2280                         swap(tile_width, tile_height);
2281                 } else {
2282                         pitch_tiles = pitch / (tile_width * cpp);
2283                 }
2284
2285                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2286                                            tile_size, pitch_tiles,
2287                                            old_offset, new_offset);
2288         } else {
2289                 old_offset += *y * pitch + *x * cpp;
2290
2291                 *y = (old_offset - new_offset) / pitch;
2292                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2293         }
2294
2295         return new_offset;
2296 }
2297
2298 /*
2299  * Adjust the tile offset by moving the difference into
2300  * the x/y offsets.
2301  */
2302 static u32 intel_adjust_tile_offset(int *x, int *y,
2303                                     const struct intel_plane_state *state, int plane,
2304                                     u32 old_offset, u32 new_offset)
2305 {
2306         return _intel_adjust_tile_offset(x, y, state->base.fb, plane,
2307                                          state->base.rotation,
2308                                          old_offset, new_offset);
2309 }
2310
2311 /*
2312  * Computes the linear 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_tile_offset(const struct drm_i915_private *dev_priv,
2326                                       int *x, int *y,
2327                                       const struct drm_framebuffer *fb, int plane,
2328                                       unsigned int pitch,
2329                                       unsigned int rotation,
2330                                       u32 alignment)
2331 {
2332         uint64_t fb_modifier = fb->modifier;
2333         unsigned int cpp = fb->format->cpp[plane];
2334         u32 offset, offset_aligned;
2335
2336         if (alignment)
2337                 alignment--;
2338
2339         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2340                 unsigned int tile_size, tile_width, tile_height;
2341                 unsigned int tile_rows, tiles, pitch_tiles;
2342
2343                 tile_size = intel_tile_size(dev_priv);
2344                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2345
2346                 if (drm_rotation_90_or_270(rotation)) {
2347                         pitch_tiles = pitch / tile_height;
2348                         swap(tile_width, tile_height);
2349                 } else {
2350                         pitch_tiles = pitch / (tile_width * cpp);
2351                 }
2352
2353                 tile_rows = *y / tile_height;
2354                 *y %= tile_height;
2355
2356                 tiles = *x / tile_width;
2357                 *x %= tile_width;
2358
2359                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2360                 offset_aligned = offset & ~alignment;
2361
2362                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2363                                            tile_size, pitch_tiles,
2364                                            offset, offset_aligned);
2365         } else {
2366                 offset = *y * pitch + *x * cpp;
2367                 offset_aligned = offset & ~alignment;
2368
2369                 *y = (offset & alignment) / pitch;
2370                 *x = ((offset & alignment) - *y * pitch) / cpp;
2371         }
2372
2373         return offset_aligned;
2374 }
2375
2376 u32 intel_compute_tile_offset(int *x, int *y,
2377                               const struct intel_plane_state *state,
2378                               int plane)
2379 {
2380         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2381         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2382         const struct drm_framebuffer *fb = state->base.fb;
2383         unsigned int rotation = state->base.rotation;
2384         int pitch = intel_fb_pitch(fb, plane, rotation);
2385         u32 alignment;
2386
2387         if (intel_plane->id == PLANE_CURSOR)
2388                 alignment = intel_cursor_alignment(dev_priv);
2389         else
2390                 alignment = intel_surf_alignment(fb, plane);
2391
2392         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2393                                           rotation, alignment);
2394 }
2395
2396 /* Convert the fb->offset[] into x/y offsets */
2397 static int intel_fb_offset_to_xy(int *x, int *y,
2398                                  const struct drm_framebuffer *fb, int plane)
2399 {
2400         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2401
2402         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2403             fb->offsets[plane] % intel_tile_size(dev_priv))
2404                 return -EINVAL;
2405
2406         *x = 0;
2407         *y = 0;
2408
2409         _intel_adjust_tile_offset(x, y,
2410                                   fb, plane, DRM_MODE_ROTATE_0,
2411                                   fb->offsets[plane], 0);
2412
2413         return 0;
2414 }
2415
2416 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2417 {
2418         switch (fb_modifier) {
2419         case I915_FORMAT_MOD_X_TILED:
2420                 return I915_TILING_X;
2421         case I915_FORMAT_MOD_Y_TILED:
2422         case I915_FORMAT_MOD_Y_TILED_CCS:
2423                 return I915_TILING_Y;
2424         default:
2425                 return I915_TILING_NONE;
2426         }
2427 }
2428
2429 /*
2430  * From the Sky Lake PRM:
2431  * "The Color Control Surface (CCS) contains the compression status of
2432  *  the cache-line pairs. The compression state of the cache-line pair
2433  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2434  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2435  *  cache-line-pairs. CCS is always Y tiled."
2436  *
2437  * Since cache line pairs refers to horizontally adjacent cache lines,
2438  * each cache line in the CCS corresponds to an area of 32x16 cache
2439  * lines on the main surface. Since each pixel is 4 bytes, this gives
2440  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2441  * main surface.
2442  */
2443 static const struct drm_format_info ccs_formats[] = {
2444         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2445         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2446         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2447         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2448 };
2449
2450 static const struct drm_format_info *
2451 lookup_format_info(const struct drm_format_info formats[],
2452                    int num_formats, u32 format)
2453 {
2454         int i;
2455
2456         for (i = 0; i < num_formats; i++) {
2457                 if (formats[i].format == format)
2458                         return &formats[i];
2459         }
2460
2461         return NULL;
2462 }
2463
2464 static const struct drm_format_info *
2465 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2466 {
2467         switch (cmd->modifier[0]) {
2468         case I915_FORMAT_MOD_Y_TILED_CCS:
2469         case I915_FORMAT_MOD_Yf_TILED_CCS:
2470                 return lookup_format_info(ccs_formats,
2471                                           ARRAY_SIZE(ccs_formats),
2472                                           cmd->pixel_format);
2473         default:
2474                 return NULL;
2475         }
2476 }
2477
2478 static int
2479 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2480                    struct drm_framebuffer *fb)
2481 {
2482         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2483         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2484         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2485         u32 gtt_offset_rotated = 0;
2486         unsigned int max_size = 0;
2487         int i, num_planes = fb->format->num_planes;
2488         unsigned int tile_size = intel_tile_size(dev_priv);
2489
2490         for (i = 0; i < num_planes; i++) {
2491                 unsigned int width, height;
2492                 unsigned int cpp, size;
2493                 u32 offset;
2494                 int x, y;
2495                 int ret;
2496
2497                 cpp = fb->format->cpp[i];
2498                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2499                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2500
2501                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2502                 if (ret) {
2503                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2504                                       i, fb->offsets[i]);
2505                         return ret;
2506                 }
2507
2508                 if ((fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2509                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) && i == 1) {
2510                         int hsub = fb->format->hsub;
2511                         int vsub = fb->format->vsub;
2512                         int tile_width, tile_height;
2513                         int main_x, main_y;
2514                         int ccs_x, ccs_y;
2515
2516                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2517                         tile_width *= hsub;
2518                         tile_height *= vsub;
2519
2520                         ccs_x = (x * hsub) % tile_width;
2521                         ccs_y = (y * vsub) % tile_height;
2522                         main_x = intel_fb->normal[0].x % tile_width;
2523                         main_y = intel_fb->normal[0].y % tile_height;
2524
2525                         /*
2526                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2527                          * x/y offsets must match between CCS and the main surface.
2528                          */
2529                         if (main_x != ccs_x || main_y != ccs_y) {
2530                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2531                                               main_x, main_y,
2532                                               ccs_x, ccs_y,
2533                                               intel_fb->normal[0].x,
2534                                               intel_fb->normal[0].y,
2535                                               x, y);
2536                                 return -EINVAL;
2537                         }
2538                 }
2539
2540                 /*
2541                  * The fence (if used) is aligned to the start of the object
2542                  * so having the framebuffer wrap around across the edge of the
2543                  * fenced region doesn't really work. We have no API to configure
2544                  * the fence start offset within the object (nor could we probably
2545                  * on gen2/3). So it's just easier if we just require that the
2546                  * fb layout agrees with the fence layout. We already check that the
2547                  * fb stride matches the fence stride elsewhere.
2548                  */
2549                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2550                     (x + width) * cpp > fb->pitches[i]) {
2551                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2552                                       i, fb->offsets[i]);
2553                         return -EINVAL;
2554                 }
2555
2556                 /*
2557                  * First pixel of the framebuffer from
2558                  * the start of the normal gtt mapping.
2559                  */
2560                 intel_fb->normal[i].x = x;
2561                 intel_fb->normal[i].y = y;
2562
2563                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2564                                                     fb, i, fb->pitches[i],
2565                                                     DRM_MODE_ROTATE_0, tile_size);
2566                 offset /= tile_size;
2567
2568                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2569                         unsigned int tile_width, tile_height;
2570                         unsigned int pitch_tiles;
2571                         struct drm_rect r;
2572
2573                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2574
2575                         rot_info->plane[i].offset = offset;
2576                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2577                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2578                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2579
2580                         intel_fb->rotated[i].pitch =
2581                                 rot_info->plane[i].height * tile_height;
2582
2583                         /* how many tiles does this plane need */
2584                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2585                         /*
2586                          * If the plane isn't horizontally tile aligned,
2587                          * we need one more tile.
2588                          */
2589                         if (x != 0)
2590                                 size++;
2591
2592                         /* rotate the x/y offsets to match the GTT view */
2593                         r.x1 = x;
2594                         r.y1 = y;
2595                         r.x2 = x + width;
2596                         r.y2 = y + height;
2597                         drm_rect_rotate(&r,
2598                                         rot_info->plane[i].width * tile_width,
2599                                         rot_info->plane[i].height * tile_height,
2600                                         DRM_MODE_ROTATE_270);
2601                         x = r.x1;
2602                         y = r.y1;
2603
2604                         /* rotate the tile dimensions to match the GTT view */
2605                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2606                         swap(tile_width, tile_height);
2607
2608                         /*
2609                          * We only keep the x/y offsets, so push all of the
2610                          * gtt offset into the x/y offsets.
2611                          */
2612                         __intel_adjust_tile_offset(&x, &y,
2613                                                    tile_width, tile_height,
2614                                                    tile_size, pitch_tiles,
2615                                                    gtt_offset_rotated * tile_size, 0);
2616
2617                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2618
2619                         /*
2620                          * First pixel of the framebuffer from
2621                          * the start of the rotated gtt mapping.
2622                          */
2623                         intel_fb->rotated[i].x = x;
2624                         intel_fb->rotated[i].y = y;
2625                 } else {
2626                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2627                                             x * cpp, tile_size);
2628                 }
2629
2630                 /* how many tiles in total needed in the bo */
2631                 max_size = max(max_size, offset + size);
2632         }
2633
2634         if (max_size * tile_size > obj->base.size) {
2635                 DRM_DEBUG_KMS("fb too big for bo (need %u bytes, have %zu bytes)\n",
2636                               max_size * tile_size, obj->base.size);
2637                 return -EINVAL;
2638         }
2639
2640         return 0;
2641 }
2642
2643 static int i9xx_format_to_fourcc(int format)
2644 {
2645         switch (format) {
2646         case DISPPLANE_8BPP:
2647                 return DRM_FORMAT_C8;
2648         case DISPPLANE_BGRX555:
2649                 return DRM_FORMAT_XRGB1555;
2650         case DISPPLANE_BGRX565:
2651                 return DRM_FORMAT_RGB565;
2652         default:
2653         case DISPPLANE_BGRX888:
2654                 return DRM_FORMAT_XRGB8888;
2655         case DISPPLANE_RGBX888:
2656                 return DRM_FORMAT_XBGR8888;
2657         case DISPPLANE_BGRX101010:
2658                 return DRM_FORMAT_XRGB2101010;
2659         case DISPPLANE_RGBX101010:
2660                 return DRM_FORMAT_XBGR2101010;
2661         }
2662 }
2663
2664 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2665 {
2666         switch (format) {
2667         case PLANE_CTL_FORMAT_RGB_565:
2668                 return DRM_FORMAT_RGB565;
2669         case PLANE_CTL_FORMAT_NV12:
2670                 return DRM_FORMAT_NV12;
2671         default:
2672         case PLANE_CTL_FORMAT_XRGB_8888:
2673                 if (rgb_order) {
2674                         if (alpha)
2675                                 return DRM_FORMAT_ABGR8888;
2676                         else
2677                                 return DRM_FORMAT_XBGR8888;
2678                 } else {
2679                         if (alpha)
2680                                 return DRM_FORMAT_ARGB8888;
2681                         else
2682                                 return DRM_FORMAT_XRGB8888;
2683                 }
2684         case PLANE_CTL_FORMAT_XRGB_2101010:
2685                 if (rgb_order)
2686                         return DRM_FORMAT_XBGR2101010;
2687                 else
2688                         return DRM_FORMAT_XRGB2101010;
2689         }
2690 }
2691
2692 static bool
2693 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2694                               struct intel_initial_plane_config *plane_config)
2695 {
2696         struct drm_device *dev = crtc->base.dev;
2697         struct drm_i915_private *dev_priv = to_i915(dev);
2698         struct drm_i915_gem_object *obj = NULL;
2699         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2700         struct drm_framebuffer *fb = &plane_config->fb->base;
2701         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2702         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2703                                     PAGE_SIZE);
2704
2705         size_aligned -= base_aligned;
2706
2707         if (plane_config->size == 0)
2708                 return false;
2709
2710         /* If the FB is too big, just don't use it since fbdev is not very
2711          * important and we should probably use that space with FBC or other
2712          * features. */
2713         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2714                 return false;
2715
2716         mutex_lock(&dev->struct_mutex);
2717         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2718                                                              base_aligned,
2719                                                              base_aligned,
2720                                                              size_aligned);
2721         mutex_unlock(&dev->struct_mutex);
2722         if (!obj)
2723                 return false;
2724
2725         if (plane_config->tiling == I915_TILING_X)
2726                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2727
2728         mode_cmd.pixel_format = fb->format->format;
2729         mode_cmd.width = fb->width;
2730         mode_cmd.height = fb->height;
2731         mode_cmd.pitches[0] = fb->pitches[0];
2732         mode_cmd.modifier[0] = fb->modifier;
2733         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2734
2735         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2736                 DRM_DEBUG_KMS("intel fb init failed\n");
2737                 goto out_unref_obj;
2738         }
2739
2740
2741         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2742         return true;
2743
2744 out_unref_obj:
2745         i915_gem_object_put(obj);
2746         return false;
2747 }
2748
2749 static void
2750 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2751                         struct intel_plane_state *plane_state,
2752                         bool visible)
2753 {
2754         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2755
2756         plane_state->base.visible = visible;
2757
2758         /* FIXME pre-g4x don't work like this */
2759         if (visible) {
2760                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
2761                 crtc_state->active_planes |= BIT(plane->id);
2762         } else {
2763                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
2764                 crtc_state->active_planes &= ~BIT(plane->id);
2765         }
2766
2767         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2768                       crtc_state->base.crtc->name,
2769                       crtc_state->active_planes);
2770 }
2771
2772 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2773                                          struct intel_plane *plane)
2774 {
2775         struct intel_crtc_state *crtc_state =
2776                 to_intel_crtc_state(crtc->base.state);
2777         struct intel_plane_state *plane_state =
2778                 to_intel_plane_state(plane->base.state);
2779
2780         intel_set_plane_visible(crtc_state, plane_state, false);
2781
2782         if (plane->id == PLANE_PRIMARY)
2783                 intel_pre_disable_primary_noatomic(&crtc->base);
2784
2785         trace_intel_disable_plane(&plane->base, crtc);
2786         plane->disable_plane(plane, crtc);
2787 }
2788
2789 static void
2790 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2791                              struct intel_initial_plane_config *plane_config)
2792 {
2793         struct drm_device *dev = intel_crtc->base.dev;
2794         struct drm_i915_private *dev_priv = to_i915(dev);
2795         struct drm_crtc *c;
2796         struct drm_i915_gem_object *obj;
2797         struct drm_plane *primary = intel_crtc->base.primary;
2798         struct drm_plane_state *plane_state = primary->state;
2799         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2800         struct intel_plane *intel_plane = to_intel_plane(primary);
2801         struct intel_plane_state *intel_state =
2802                 to_intel_plane_state(plane_state);
2803         struct drm_framebuffer *fb;
2804
2805         if (!plane_config->fb)
2806                 return;
2807
2808         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2809                 fb = &plane_config->fb->base;
2810                 goto valid_fb;
2811         }
2812
2813         kfree(plane_config->fb);
2814
2815         /*
2816          * Failed to alloc the obj, check to see if we should share
2817          * an fb with another CRTC instead
2818          */
2819         for_each_crtc(dev, c) {
2820                 struct intel_plane_state *state;
2821
2822                 if (c == &intel_crtc->base)
2823                         continue;
2824
2825                 if (!to_intel_crtc(c)->active)
2826                         continue;
2827
2828                 state = to_intel_plane_state(c->primary->state);
2829                 if (!state->vma)
2830                         continue;
2831
2832                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2833                         fb = state->base.fb;
2834                         drm_framebuffer_get(fb);
2835                         goto valid_fb;
2836                 }
2837         }
2838
2839         /*
2840          * We've failed to reconstruct the BIOS FB.  Current display state
2841          * indicates that the primary plane is visible, but has a NULL FB,
2842          * which will lead to problems later if we don't fix it up.  The
2843          * simplest solution is to just disable the primary plane now and
2844          * pretend the BIOS never had it enabled.
2845          */
2846         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2847
2848         return;
2849
2850 valid_fb:
2851         mutex_lock(&dev->struct_mutex);
2852         intel_state->vma =
2853                 intel_pin_and_fence_fb_obj(fb,
2854                                            primary->state->rotation,
2855                                            intel_plane_uses_fence(intel_state),
2856                                            &intel_state->flags);
2857         mutex_unlock(&dev->struct_mutex);
2858         if (IS_ERR(intel_state->vma)) {
2859                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2860                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2861
2862                 intel_state->vma = NULL;
2863                 drm_framebuffer_put(fb);
2864                 return;
2865         }
2866
2867         obj = intel_fb_obj(fb);
2868         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
2869
2870         plane_state->src_x = 0;
2871         plane_state->src_y = 0;
2872         plane_state->src_w = fb->width << 16;
2873         plane_state->src_h = fb->height << 16;
2874
2875         plane_state->crtc_x = 0;
2876         plane_state->crtc_y = 0;
2877         plane_state->crtc_w = fb->width;
2878         plane_state->crtc_h = fb->height;
2879
2880         intel_state->base.src = drm_plane_state_src(plane_state);
2881         intel_state->base.dst = drm_plane_state_dest(plane_state);
2882
2883         if (i915_gem_object_is_tiled(obj))
2884                 dev_priv->preserve_bios_swizzle = true;
2885
2886         plane_state->fb = fb;
2887         plane_state->crtc = &intel_crtc->base;
2888
2889         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2890                                 to_intel_plane_state(plane_state),
2891                                 true);
2892
2893         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2894                   &obj->frontbuffer_bits);
2895 }
2896
2897 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2898                                unsigned int rotation)
2899 {
2900         int cpp = fb->format->cpp[plane];
2901
2902         switch (fb->modifier) {
2903         case DRM_FORMAT_MOD_LINEAR:
2904         case I915_FORMAT_MOD_X_TILED:
2905                 switch (cpp) {
2906                 case 8:
2907                         return 4096;
2908                 case 4:
2909                 case 2:
2910                 case 1:
2911                         return 8192;
2912                 default:
2913                         MISSING_CASE(cpp);
2914                         break;
2915                 }
2916                 break;
2917         case I915_FORMAT_MOD_Y_TILED_CCS:
2918         case I915_FORMAT_MOD_Yf_TILED_CCS:
2919                 /* FIXME AUX plane? */
2920         case I915_FORMAT_MOD_Y_TILED:
2921         case I915_FORMAT_MOD_Yf_TILED:
2922                 switch (cpp) {
2923                 case 8:
2924                         return 2048;
2925                 case 4:
2926                         return 4096;
2927                 case 2:
2928                 case 1:
2929                         return 8192;
2930                 default:
2931                         MISSING_CASE(cpp);
2932                         break;
2933                 }
2934                 break;
2935         default:
2936                 MISSING_CASE(fb->modifier);
2937         }
2938
2939         return 2048;
2940 }
2941
2942 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2943                                            int main_x, int main_y, u32 main_offset)
2944 {
2945         const struct drm_framebuffer *fb = plane_state->base.fb;
2946         int hsub = fb->format->hsub;
2947         int vsub = fb->format->vsub;
2948         int aux_x = plane_state->aux.x;
2949         int aux_y = plane_state->aux.y;
2950         u32 aux_offset = plane_state->aux.offset;
2951         u32 alignment = intel_surf_alignment(fb, 1);
2952
2953         while (aux_offset >= main_offset && aux_y <= main_y) {
2954                 int x, y;
2955
2956                 if (aux_x == main_x && aux_y == main_y)
2957                         break;
2958
2959                 if (aux_offset == 0)
2960                         break;
2961
2962                 x = aux_x / hsub;
2963                 y = aux_y / vsub;
2964                 aux_offset = intel_adjust_tile_offset(&x, &y, plane_state, 1,
2965                                                       aux_offset, aux_offset - alignment);
2966                 aux_x = x * hsub + aux_x % hsub;
2967                 aux_y = y * vsub + aux_y % vsub;
2968         }
2969
2970         if (aux_x != main_x || aux_y != main_y)
2971                 return false;
2972
2973         plane_state->aux.offset = aux_offset;
2974         plane_state->aux.x = aux_x;
2975         plane_state->aux.y = aux_y;
2976
2977         return true;
2978 }
2979
2980 static int skl_check_main_surface(const struct intel_crtc_state *crtc_state,
2981                                   struct intel_plane_state *plane_state)
2982 {
2983         struct drm_i915_private *dev_priv =
2984                 to_i915(plane_state->base.plane->dev);
2985         const struct drm_framebuffer *fb = plane_state->base.fb;
2986         unsigned int rotation = plane_state->base.rotation;
2987         int x = plane_state->base.src.x1 >> 16;
2988         int y = plane_state->base.src.y1 >> 16;
2989         int w = drm_rect_width(&plane_state->base.src) >> 16;
2990         int h = drm_rect_height(&plane_state->base.src) >> 16;
2991         int dst_x = plane_state->base.dst.x1;
2992         int pipe_src_w = crtc_state->pipe_src_w;
2993         int max_width = skl_max_plane_width(fb, 0, rotation);
2994         int max_height = 4096;
2995         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2996
2997         if (w > max_width || h > max_height) {
2998                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2999                               w, h, max_width, max_height);
3000                 return -EINVAL;
3001         }
3002
3003         /*
3004          * Display WA #1175: cnl,glk
3005          * Planes other than the cursor may cause FIFO underflow and display
3006          * corruption if starting less than 4 pixels from the right edge of
3007          * the screen.
3008          * Besides the above WA fix the similar problem, where planes other
3009          * than the cursor ending less than 4 pixels from the left edge of the
3010          * screen may cause FIFO underflow and display corruption.
3011          */
3012         if ((IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
3013             (dst_x + w < 4 || dst_x > pipe_src_w - 4)) {
3014                 DRM_DEBUG_KMS("requested plane X %s position %d invalid (valid range %d-%d)\n",
3015                               dst_x + w < 4 ? "end" : "start",
3016                               dst_x + w < 4 ? dst_x + w : dst_x,
3017                               4, pipe_src_w - 4);
3018                 return -ERANGE;
3019         }
3020
3021         intel_add_fb_offsets(&x, &y, plane_state, 0);
3022         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
3023         alignment = intel_surf_alignment(fb, 0);
3024
3025         /*
3026          * AUX surface offset is specified as the distance from the
3027          * main surface offset, and it must be non-negative. Make
3028          * sure that is what we will get.
3029          */
3030         if (offset > aux_offset)
3031                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3032                                                   offset, aux_offset & ~(alignment - 1));
3033
3034         /*
3035          * When using an X-tiled surface, the plane blows up
3036          * if the x offset + width exceed the stride.
3037          *
3038          * TODO: linear and Y-tiled seem fine, Yf untested,
3039          */
3040         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3041                 int cpp = fb->format->cpp[0];
3042
3043                 while ((x + w) * cpp > fb->pitches[0]) {
3044                         if (offset == 0) {
3045                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3046                                 return -EINVAL;
3047                         }
3048
3049                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3050                                                           offset, offset - alignment);
3051                 }
3052         }
3053
3054         /*
3055          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3056          * they match with the main surface x/y offsets.
3057          */
3058         if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3059             fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3060                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3061                         if (offset == 0)
3062                                 break;
3063
3064                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3065                                                           offset, offset - alignment);
3066                 }
3067
3068                 if (x != plane_state->aux.x || y != plane_state->aux.y) {
3069                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3070                         return -EINVAL;
3071                 }
3072         }
3073
3074         plane_state->main.offset = offset;
3075         plane_state->main.x = x;
3076         plane_state->main.y = y;
3077
3078         return 0;
3079 }
3080
3081 static int
3082 skl_check_nv12_surface(const struct intel_crtc_state *crtc_state,
3083                        struct intel_plane_state *plane_state)
3084 {
3085         /* Display WA #1106 */
3086         if (plane_state->base.rotation !=
3087             (DRM_MODE_REFLECT_X | DRM_MODE_ROTATE_90) &&
3088             plane_state->base.rotation != DRM_MODE_ROTATE_270)
3089                 return 0;
3090
3091         /*
3092          * src coordinates are rotated here.
3093          * We check height but report it as width
3094          */
3095         if (((drm_rect_height(&plane_state->base.src) >> 16) % 4) != 0) {
3096                 DRM_DEBUG_KMS("src width must be multiple "
3097                               "of 4 for rotated NV12\n");
3098                 return -EINVAL;
3099         }
3100
3101         return 0;
3102 }
3103
3104 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3105 {
3106         const struct drm_framebuffer *fb = plane_state->base.fb;
3107         unsigned int rotation = plane_state->base.rotation;
3108         int max_width = skl_max_plane_width(fb, 1, rotation);
3109         int max_height = 4096;
3110         int x = plane_state->base.src.x1 >> 17;
3111         int y = plane_state->base.src.y1 >> 17;
3112         int w = drm_rect_width(&plane_state->base.src) >> 17;
3113         int h = drm_rect_height(&plane_state->base.src) >> 17;
3114         u32 offset;
3115
3116         intel_add_fb_offsets(&x, &y, plane_state, 1);
3117         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3118
3119         /* FIXME not quite sure how/if these apply to the chroma plane */
3120         if (w > max_width || h > max_height) {
3121                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3122                               w, h, max_width, max_height);
3123                 return -EINVAL;
3124         }
3125
3126         plane_state->aux.offset = offset;
3127         plane_state->aux.x = x;
3128         plane_state->aux.y = y;
3129
3130         return 0;
3131 }
3132
3133 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3134 {
3135         const struct drm_framebuffer *fb = plane_state->base.fb;
3136         int src_x = plane_state->base.src.x1 >> 16;
3137         int src_y = plane_state->base.src.y1 >> 16;
3138         int hsub = fb->format->hsub;
3139         int vsub = fb->format->vsub;
3140         int x = src_x / hsub;
3141         int y = src_y / vsub;
3142         u32 offset;
3143
3144         if (plane_state->base.rotation & ~(DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180)) {
3145                 DRM_DEBUG_KMS("RC support only with 0/180 degree rotation %x\n",
3146                               plane_state->base.rotation);
3147                 return -EINVAL;
3148         }
3149
3150         intel_add_fb_offsets(&x, &y, plane_state, 1);
3151         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3152
3153         plane_state->aux.offset = offset;
3154         plane_state->aux.x = x * hsub + src_x % hsub;
3155         plane_state->aux.y = y * vsub + src_y % vsub;
3156
3157         return 0;
3158 }
3159
3160 int skl_check_plane_surface(const struct intel_crtc_state *crtc_state,
3161                             struct intel_plane_state *plane_state)
3162 {
3163         const struct drm_framebuffer *fb = plane_state->base.fb;
3164         unsigned int rotation = plane_state->base.rotation;
3165         int ret;
3166
3167         if (rotation & DRM_MODE_REFLECT_X &&
3168             fb->modifier == DRM_FORMAT_MOD_LINEAR) {
3169                 DRM_DEBUG_KMS("horizontal flip is not supported with linear surface formats\n");
3170                 return -EINVAL;
3171         }
3172
3173         if (!plane_state->base.visible)
3174                 return 0;
3175
3176         /* Rotate src coordinates to match rotated GTT view */
3177         if (drm_rotation_90_or_270(rotation))
3178                 drm_rect_rotate(&plane_state->base.src,
3179                                 fb->width << 16, fb->height << 16,
3180                                 DRM_MODE_ROTATE_270);
3181
3182         /*
3183          * Handle the AUX surface first since
3184          * the main surface setup depends on it.
3185          */
3186         if (fb->format->format == DRM_FORMAT_NV12) {
3187                 ret = skl_check_nv12_surface(crtc_state, plane_state);
3188                 if (ret)
3189                         return ret;
3190                 ret = skl_check_nv12_aux_surface(plane_state);
3191                 if (ret)
3192                         return ret;
3193         } else if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3194                    fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3195                 ret = skl_check_ccs_aux_surface(plane_state);
3196                 if (ret)
3197                         return ret;
3198         } else {
3199                 plane_state->aux.offset = ~0xfff;
3200                 plane_state->aux.x = 0;
3201                 plane_state->aux.y = 0;
3202         }
3203
3204         ret = skl_check_main_surface(crtc_state, plane_state);
3205         if (ret)
3206                 return ret;
3207
3208         return 0;
3209 }
3210
3211 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3212                           const struct intel_plane_state *plane_state)
3213 {
3214         struct drm_i915_private *dev_priv =
3215                 to_i915(plane_state->base.plane->dev);
3216         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3217         const struct drm_framebuffer *fb = plane_state->base.fb;
3218         unsigned int rotation = plane_state->base.rotation;
3219         u32 dspcntr;
3220
3221         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3222
3223         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3224             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3225                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3226
3227         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3228                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3229
3230         if (INTEL_GEN(dev_priv) < 5)
3231                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3232
3233         switch (fb->format->format) {
3234         case DRM_FORMAT_C8:
3235                 dspcntr |= DISPPLANE_8BPP;
3236                 break;
3237         case DRM_FORMAT_XRGB1555:
3238                 dspcntr |= DISPPLANE_BGRX555;
3239                 break;
3240         case DRM_FORMAT_RGB565:
3241                 dspcntr |= DISPPLANE_BGRX565;
3242                 break;
3243         case DRM_FORMAT_XRGB8888:
3244                 dspcntr |= DISPPLANE_BGRX888;
3245                 break;
3246         case DRM_FORMAT_XBGR8888:
3247                 dspcntr |= DISPPLANE_RGBX888;
3248                 break;
3249         case DRM_FORMAT_XRGB2101010:
3250                 dspcntr |= DISPPLANE_BGRX101010;
3251                 break;
3252         case DRM_FORMAT_XBGR2101010:
3253                 dspcntr |= DISPPLANE_RGBX101010;
3254                 break;
3255         default:
3256                 MISSING_CASE(fb->format->format);
3257                 return 0;
3258         }
3259
3260         if (INTEL_GEN(dev_priv) >= 4 &&
3261             fb->modifier == I915_FORMAT_MOD_X_TILED)
3262                 dspcntr |= DISPPLANE_TILED;
3263
3264         if (rotation & DRM_MODE_ROTATE_180)
3265                 dspcntr |= DISPPLANE_ROTATE_180;
3266
3267         if (rotation & DRM_MODE_REFLECT_X)
3268                 dspcntr |= DISPPLANE_MIRROR;
3269
3270         return dspcntr;
3271 }
3272
3273 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3274 {
3275         struct drm_i915_private *dev_priv =
3276                 to_i915(plane_state->base.plane->dev);
3277         int src_x = plane_state->base.src.x1 >> 16;
3278         int src_y = plane_state->base.src.y1 >> 16;
3279         u32 offset;
3280
3281         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3282
3283         if (INTEL_GEN(dev_priv) >= 4)
3284                 offset = intel_compute_tile_offset(&src_x, &src_y,
3285                                                    plane_state, 0);
3286         else
3287                 offset = 0;
3288
3289         /* HSW/BDW do this automagically in hardware */
3290         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3291                 unsigned int rotation = plane_state->base.rotation;
3292                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3293                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3294
3295                 if (rotation & DRM_MODE_ROTATE_180) {
3296                         src_x += src_w - 1;
3297                         src_y += src_h - 1;
3298                 } else if (rotation & DRM_MODE_REFLECT_X) {
3299                         src_x += src_w - 1;
3300                 }
3301         }
3302
3303         plane_state->main.offset = offset;
3304         plane_state->main.x = src_x;
3305         plane_state->main.y = src_y;
3306
3307         return 0;
3308 }
3309
3310 static void i9xx_update_plane(struct intel_plane *plane,
3311                               const struct intel_crtc_state *crtc_state,
3312                               const struct intel_plane_state *plane_state)
3313 {
3314         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3315         const struct drm_framebuffer *fb = plane_state->base.fb;
3316         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3317         u32 linear_offset;
3318         u32 dspcntr = plane_state->ctl;
3319         i915_reg_t reg = DSPCNTR(i9xx_plane);
3320         int x = plane_state->main.x;
3321         int y = plane_state->main.y;
3322         unsigned long irqflags;
3323         u32 dspaddr_offset;
3324
3325         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3326
3327         if (INTEL_GEN(dev_priv) >= 4)
3328                 dspaddr_offset = plane_state->main.offset;
3329         else
3330                 dspaddr_offset = linear_offset;
3331
3332         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3333
3334         if (INTEL_GEN(dev_priv) < 4) {
3335                 /* pipesrc and dspsize control the size that is scaled from,
3336                  * which should always be the user's requested size.
3337                  */
3338                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3339                               ((crtc_state->pipe_src_h - 1) << 16) |
3340                               (crtc_state->pipe_src_w - 1));
3341                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3342         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3343                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3344                               ((crtc_state->pipe_src_h - 1) << 16) |
3345                               (crtc_state->pipe_src_w - 1));
3346                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3347                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3348         }
3349
3350         I915_WRITE_FW(reg, dspcntr);
3351
3352         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), fb->pitches[0]);
3353         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3354                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3355                               intel_plane_ggtt_offset(plane_state) +
3356                               dspaddr_offset);
3357                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3358         } else if (INTEL_GEN(dev_priv) >= 4) {
3359                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3360                               intel_plane_ggtt_offset(plane_state) +
3361                               dspaddr_offset);
3362                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3363                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3364         } else {
3365                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3366                               intel_plane_ggtt_offset(plane_state) +
3367                               dspaddr_offset);
3368         }
3369         POSTING_READ_FW(reg);
3370
3371         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3372 }
3373
3374 static void i9xx_disable_plane(struct intel_plane *plane,
3375                                struct intel_crtc *crtc)
3376 {
3377         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3378         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3379         unsigned long irqflags;
3380
3381         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3382
3383         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3384         if (INTEL_GEN(dev_priv) >= 4)
3385                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3386         else
3387                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3388         POSTING_READ_FW(DSPCNTR(i9xx_plane));
3389
3390         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3391 }
3392
3393 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3394                                     enum pipe *pipe)
3395 {
3396         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3397         enum intel_display_power_domain power_domain;
3398         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3399         bool ret;
3400         u32 val;
3401
3402         /*
3403          * Not 100% correct for planes that can move between pipes,
3404          * but that's only the case for gen2-4 which don't have any
3405          * display power wells.
3406          */
3407         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3408         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3409                 return false;
3410
3411         val = I915_READ(DSPCNTR(i9xx_plane));
3412
3413         ret = val & DISPLAY_PLANE_ENABLE;
3414
3415         if (INTEL_GEN(dev_priv) >= 5)
3416                 *pipe = plane->pipe;
3417         else
3418                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3419                         DISPPLANE_SEL_PIPE_SHIFT;
3420
3421         intel_display_power_put(dev_priv, power_domain);
3422
3423         return ret;
3424 }
3425
3426 static u32
3427 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int plane)
3428 {
3429         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3430                 return 64;
3431         else
3432                 return intel_tile_width_bytes(fb, plane);
3433 }
3434
3435 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3436 {
3437         struct drm_device *dev = intel_crtc->base.dev;
3438         struct drm_i915_private *dev_priv = to_i915(dev);
3439
3440         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3441         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3442         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3443 }
3444
3445 /*
3446  * This function detaches (aka. unbinds) unused scalers in hardware
3447  */
3448 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3449 {
3450         struct intel_crtc_scaler_state *scaler_state;
3451         int i;
3452
3453         scaler_state = &intel_crtc->config->scaler_state;
3454
3455         /* loop through and disable scalers that aren't in use */
3456         for (i = 0; i < intel_crtc->num_scalers; i++) {
3457                 if (!scaler_state->scalers[i].in_use)
3458                         skl_detach_scaler(intel_crtc, i);
3459         }
3460 }
3461
3462 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3463                      unsigned int rotation)
3464 {
3465         u32 stride;
3466
3467         if (plane >= fb->format->num_planes)
3468                 return 0;
3469
3470         stride = intel_fb_pitch(fb, plane, rotation);
3471
3472         /*
3473          * The stride is either expressed as a multiple of 64 bytes chunks for
3474          * linear buffers or in number of tiles for tiled buffers.
3475          */
3476         if (drm_rotation_90_or_270(rotation))
3477                 stride /= intel_tile_height(fb, plane);
3478         else
3479                 stride /= intel_fb_stride_alignment(fb, plane);
3480
3481         return stride;
3482 }
3483
3484 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3485 {
3486         switch (pixel_format) {
3487         case DRM_FORMAT_C8:
3488                 return PLANE_CTL_FORMAT_INDEXED;
3489         case DRM_FORMAT_RGB565:
3490                 return PLANE_CTL_FORMAT_RGB_565;
3491         case DRM_FORMAT_XBGR8888:
3492         case DRM_FORMAT_ABGR8888:
3493                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3494         case DRM_FORMAT_XRGB8888:
3495         case DRM_FORMAT_ARGB8888:
3496                 return PLANE_CTL_FORMAT_XRGB_8888;
3497         case DRM_FORMAT_XRGB2101010:
3498                 return PLANE_CTL_FORMAT_XRGB_2101010;
3499         case DRM_FORMAT_XBGR2101010:
3500                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3501         case DRM_FORMAT_YUYV:
3502                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3503         case DRM_FORMAT_YVYU:
3504                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3505         case DRM_FORMAT_UYVY:
3506                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3507         case DRM_FORMAT_VYUY:
3508                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3509         case DRM_FORMAT_NV12:
3510                 return PLANE_CTL_FORMAT_NV12;
3511         default:
3512                 MISSING_CASE(pixel_format);
3513         }
3514
3515         return 0;
3516 }
3517
3518 /*
3519  * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3520  * to be already pre-multiplied. We need to add a knob (or a different
3521  * DRM_FORMAT) for user-space to configure that.
3522  */
3523 static u32 skl_plane_ctl_alpha(uint32_t pixel_format)
3524 {
3525         switch (pixel_format) {
3526         case DRM_FORMAT_ABGR8888:
3527         case DRM_FORMAT_ARGB8888:
3528                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3529         default:
3530                 return PLANE_CTL_ALPHA_DISABLE;
3531         }
3532 }
3533
3534 static u32 glk_plane_color_ctl_alpha(uint32_t pixel_format)
3535 {
3536         switch (pixel_format) {
3537         case DRM_FORMAT_ABGR8888:
3538         case DRM_FORMAT_ARGB8888:
3539                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3540         default:
3541                 return PLANE_COLOR_ALPHA_DISABLE;
3542         }
3543 }
3544
3545 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3546 {
3547         switch (fb_modifier) {
3548         case DRM_FORMAT_MOD_LINEAR:
3549                 break;
3550         case I915_FORMAT_MOD_X_TILED:
3551                 return PLANE_CTL_TILED_X;
3552         case I915_FORMAT_MOD_Y_TILED:
3553                 return PLANE_CTL_TILED_Y;
3554         case I915_FORMAT_MOD_Y_TILED_CCS:
3555                 return PLANE_CTL_TILED_Y | PLANE_CTL_DECOMPRESSION_ENABLE;
3556         case I915_FORMAT_MOD_Yf_TILED:
3557                 return PLANE_CTL_TILED_YF;
3558         case I915_FORMAT_MOD_Yf_TILED_CCS:
3559                 return PLANE_CTL_TILED_YF | PLANE_CTL_DECOMPRESSION_ENABLE;
3560         default:
3561                 MISSING_CASE(fb_modifier);
3562         }
3563
3564         return 0;
3565 }
3566
3567 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3568 {
3569         switch (rotate) {
3570         case DRM_MODE_ROTATE_0:
3571                 break;
3572         /*
3573          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3574          * while i915 HW rotation is clockwise, thats why this swapping.
3575          */
3576         case DRM_MODE_ROTATE_90:
3577                 return PLANE_CTL_ROTATE_270;
3578         case DRM_MODE_ROTATE_180:
3579                 return PLANE_CTL_ROTATE_180;
3580         case DRM_MODE_ROTATE_270:
3581                 return PLANE_CTL_ROTATE_90;
3582         default:
3583                 MISSING_CASE(rotate);
3584         }
3585
3586         return 0;
3587 }
3588
3589 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3590 {
3591         switch (reflect) {
3592         case 0:
3593                 break;
3594         case DRM_MODE_REFLECT_X:
3595                 return PLANE_CTL_FLIP_HORIZONTAL;
3596         case DRM_MODE_REFLECT_Y:
3597         default:
3598                 MISSING_CASE(reflect);
3599         }
3600
3601         return 0;
3602 }
3603
3604 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3605                   const struct intel_plane_state *plane_state)
3606 {
3607         struct drm_i915_private *dev_priv =
3608                 to_i915(plane_state->base.plane->dev);
3609         const struct drm_framebuffer *fb = plane_state->base.fb;
3610         unsigned int rotation = plane_state->base.rotation;
3611         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3612         u32 plane_ctl;
3613
3614         plane_ctl = PLANE_CTL_ENABLE;
3615
3616         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3617                 plane_ctl |= skl_plane_ctl_alpha(fb->format->format);
3618                 plane_ctl |=
3619                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3620                         PLANE_CTL_PIPE_CSC_ENABLE |
3621                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3622
3623                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3624                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3625
3626                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3627                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3628         }
3629
3630         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3631         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3632         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3633
3634         if (INTEL_GEN(dev_priv) >= 10)
3635                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3636                                                 DRM_MODE_REFLECT_MASK);
3637
3638         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3639                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3640         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3641                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3642
3643         return plane_ctl;
3644 }
3645
3646 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3647                         const struct intel_plane_state *plane_state)
3648 {
3649         struct drm_i915_private *dev_priv =
3650                 to_i915(plane_state->base.plane->dev);
3651         const struct drm_framebuffer *fb = plane_state->base.fb;
3652         u32 plane_color_ctl = 0;
3653
3654         if (INTEL_GEN(dev_priv) < 11) {
3655                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3656                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3657         }
3658         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3659         plane_color_ctl |= glk_plane_color_ctl_alpha(fb->format->format);
3660
3661         if (fb->format->is_yuv) {
3662                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3663                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3664                 else
3665                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3666
3667                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3668                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3669         }
3670
3671         return plane_color_ctl;
3672 }
3673
3674 static int
3675 __intel_display_resume(struct drm_device *dev,
3676                        struct drm_atomic_state *state,
3677                        struct drm_modeset_acquire_ctx *ctx)
3678 {
3679         struct drm_crtc_state *crtc_state;
3680         struct drm_crtc *crtc;
3681         int i, ret;
3682
3683         intel_modeset_setup_hw_state(dev, ctx);
3684         i915_redisable_vga(to_i915(dev));
3685
3686         if (!state)
3687                 return 0;
3688
3689         /*
3690          * We've duplicated the state, pointers to the old state are invalid.
3691          *
3692          * Don't attempt to use the old state until we commit the duplicated state.
3693          */
3694         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3695                 /*
3696                  * Force recalculation even if we restore
3697                  * current state. With fast modeset this may not result
3698                  * in a modeset when the state is compatible.
3699                  */
3700                 crtc_state->mode_changed = true;
3701         }
3702
3703         /* ignore any reset values/BIOS leftovers in the WM registers */
3704         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3705                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3706
3707         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3708
3709         WARN_ON(ret == -EDEADLK);
3710         return ret;
3711 }
3712
3713 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3714 {
3715         return intel_has_gpu_reset(dev_priv) &&
3716                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3717 }
3718
3719 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3720 {
3721         struct drm_device *dev = &dev_priv->drm;
3722         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3723         struct drm_atomic_state *state;
3724         int ret;
3725
3726         /* reset doesn't touch the display */
3727         if (!i915_modparams.force_reset_modeset_test &&
3728             !gpu_reset_clobbers_display(dev_priv))
3729                 return;
3730
3731         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3732         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3733         wake_up_all(&dev_priv->gpu_error.wait_queue);
3734
3735         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3736                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3737                 i915_gem_set_wedged(dev_priv);
3738         }
3739
3740         /*
3741          * Need mode_config.mutex so that we don't
3742          * trample ongoing ->detect() and whatnot.
3743          */
3744         mutex_lock(&dev->mode_config.mutex);
3745         drm_modeset_acquire_init(ctx, 0);
3746         while (1) {
3747                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3748                 if (ret != -EDEADLK)
3749                         break;
3750
3751                 drm_modeset_backoff(ctx);
3752         }
3753         /*
3754          * Disabling the crtcs gracefully seems nicer. Also the
3755          * g33 docs say we should at least disable all the planes.
3756          */
3757         state = drm_atomic_helper_duplicate_state(dev, ctx);
3758         if (IS_ERR(state)) {
3759                 ret = PTR_ERR(state);
3760                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3761                 return;
3762         }
3763
3764         ret = drm_atomic_helper_disable_all(dev, ctx);
3765         if (ret) {
3766                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3767                 drm_atomic_state_put(state);
3768                 return;
3769         }
3770
3771         dev_priv->modeset_restore_state = state;
3772         state->acquire_ctx = ctx;
3773 }
3774
3775 void intel_finish_reset(struct drm_i915_private *dev_priv)
3776 {
3777         struct drm_device *dev = &dev_priv->drm;
3778         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3779         struct drm_atomic_state *state;
3780         int ret;
3781
3782         /* reset doesn't touch the display */
3783         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
3784                 return;
3785
3786         state = fetch_and_zero(&dev_priv->modeset_restore_state);
3787         if (!state)
3788                 goto unlock;
3789
3790         /* reset doesn't touch the display */
3791         if (!gpu_reset_clobbers_display(dev_priv)) {
3792                 /* for testing only restore the display */
3793                 ret = __intel_display_resume(dev, state, ctx);
3794                 if (ret)
3795                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3796         } else {
3797                 /*
3798                  * The display has been reset as well,
3799                  * so need a full re-initialization.
3800                  */
3801                 intel_runtime_pm_disable_interrupts(dev_priv);
3802                 intel_runtime_pm_enable_interrupts(dev_priv);
3803
3804                 intel_pps_unlock_regs_wa(dev_priv);
3805                 intel_modeset_init_hw(dev);
3806                 intel_init_clock_gating(dev_priv);
3807
3808                 spin_lock_irq(&dev_priv->irq_lock);
3809                 if (dev_priv->display.hpd_irq_setup)
3810                         dev_priv->display.hpd_irq_setup(dev_priv);
3811                 spin_unlock_irq(&dev_priv->irq_lock);
3812
3813                 ret = __intel_display_resume(dev, state, ctx);
3814                 if (ret)
3815                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3816
3817                 intel_hpd_init(dev_priv);
3818         }
3819
3820         drm_atomic_state_put(state);
3821 unlock:
3822         drm_modeset_drop_locks(ctx);
3823         drm_modeset_acquire_fini(ctx);
3824         mutex_unlock(&dev->mode_config.mutex);
3825
3826         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3827 }
3828
3829 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3830                                      const struct intel_crtc_state *new_crtc_state)
3831 {
3832         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3833         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3834
3835         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3836         crtc->base.mode = new_crtc_state->base.mode;
3837
3838         /*
3839          * Update pipe size and adjust fitter if needed: the reason for this is
3840          * that in compute_mode_changes we check the native mode (not the pfit
3841          * mode) to see if we can flip rather than do a full mode set. In the
3842          * fastboot case, we'll flip, but if we don't update the pipesrc and
3843          * pfit state, we'll end up with a big fb scanned out into the wrong
3844          * sized surface.
3845          */
3846
3847         I915_WRITE(PIPESRC(crtc->pipe),
3848                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3849                    (new_crtc_state->pipe_src_h - 1));
3850
3851         /* on skylake this is done by detaching scalers */
3852         if (INTEL_GEN(dev_priv) >= 9) {
3853                 skl_detach_scalers(crtc);
3854
3855                 if (new_crtc_state->pch_pfit.enabled)
3856                         skylake_pfit_enable(crtc);
3857         } else if (HAS_PCH_SPLIT(dev_priv)) {
3858                 if (new_crtc_state->pch_pfit.enabled)
3859                         ironlake_pfit_enable(crtc);
3860                 else if (old_crtc_state->pch_pfit.enabled)
3861                         ironlake_pfit_disable(crtc, true);
3862         }
3863 }
3864
3865 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3866 {
3867         struct drm_device *dev = crtc->base.dev;
3868         struct drm_i915_private *dev_priv = to_i915(dev);
3869         int pipe = crtc->pipe;
3870         i915_reg_t reg;
3871         u32 temp;
3872
3873         /* enable normal train */
3874         reg = FDI_TX_CTL(pipe);
3875         temp = I915_READ(reg);
3876         if (IS_IVYBRIDGE(dev_priv)) {
3877                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3878                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3879         } else {
3880                 temp &= ~FDI_LINK_TRAIN_NONE;
3881                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3882         }
3883         I915_WRITE(reg, temp);
3884
3885         reg = FDI_RX_CTL(pipe);
3886         temp = I915_READ(reg);
3887         if (HAS_PCH_CPT(dev_priv)) {
3888                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3889                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3890         } else {
3891                 temp &= ~FDI_LINK_TRAIN_NONE;
3892                 temp |= FDI_LINK_TRAIN_NONE;
3893         }
3894         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3895
3896         /* wait one idle pattern time */
3897         POSTING_READ(reg);
3898         udelay(1000);
3899
3900         /* IVB wants error correction enabled */
3901         if (IS_IVYBRIDGE(dev_priv))
3902                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3903                            FDI_FE_ERRC_ENABLE);
3904 }
3905
3906 /* The FDI link training functions for ILK/Ibexpeak. */
3907 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3908                                     const struct intel_crtc_state *crtc_state)
3909 {
3910         struct drm_device *dev = crtc->base.dev;
3911         struct drm_i915_private *dev_priv = to_i915(dev);
3912         int pipe = crtc->pipe;
3913         i915_reg_t reg;
3914         u32 temp, tries;
3915
3916         /* FDI needs bits from pipe first */
3917         assert_pipe_enabled(dev_priv, pipe);
3918
3919         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3920            for train result */
3921         reg = FDI_RX_IMR(pipe);
3922         temp = I915_READ(reg);
3923         temp &= ~FDI_RX_SYMBOL_LOCK;
3924         temp &= ~FDI_RX_BIT_LOCK;
3925         I915_WRITE(reg, temp);
3926         I915_READ(reg);
3927         udelay(150);
3928
3929         /* enable CPU FDI TX and PCH FDI RX */
3930         reg = FDI_TX_CTL(pipe);
3931         temp = I915_READ(reg);
3932         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3933         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3934         temp &= ~FDI_LINK_TRAIN_NONE;
3935         temp |= FDI_LINK_TRAIN_PATTERN_1;
3936         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3937
3938         reg = FDI_RX_CTL(pipe);
3939         temp = I915_READ(reg);
3940         temp &= ~FDI_LINK_TRAIN_NONE;
3941         temp |= FDI_LINK_TRAIN_PATTERN_1;
3942         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3943
3944         POSTING_READ(reg);
3945         udelay(150);
3946
3947         /* Ironlake workaround, enable clock pointer after FDI enable*/
3948         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3949         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3950                    FDI_RX_PHASE_SYNC_POINTER_EN);
3951
3952         reg = FDI_RX_IIR(pipe);
3953         for (tries = 0; tries < 5; tries++) {
3954                 temp = I915_READ(reg);
3955                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3956
3957                 if ((temp & FDI_RX_BIT_LOCK)) {
3958                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3959                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3960                         break;
3961                 }
3962         }
3963         if (tries == 5)
3964                 DRM_ERROR("FDI train 1 fail!\n");
3965
3966         /* Train 2 */
3967         reg = FDI_TX_CTL(pipe);
3968         temp = I915_READ(reg);
3969         temp &= ~FDI_LINK_TRAIN_NONE;
3970         temp |= FDI_LINK_TRAIN_PATTERN_2;
3971         I915_WRITE(reg, temp);
3972
3973         reg = FDI_RX_CTL(pipe);
3974         temp = I915_READ(reg);
3975         temp &= ~FDI_LINK_TRAIN_NONE;
3976         temp |= FDI_LINK_TRAIN_PATTERN_2;
3977         I915_WRITE(reg, temp);
3978
3979         POSTING_READ(reg);
3980         udelay(150);
3981
3982         reg = FDI_RX_IIR(pipe);
3983         for (tries = 0; tries < 5; tries++) {
3984                 temp = I915_READ(reg);
3985                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3986
3987                 if (temp & FDI_RX_SYMBOL_LOCK) {
3988                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3989                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3990                         break;
3991                 }
3992         }
3993         if (tries == 5)
3994                 DRM_ERROR("FDI train 2 fail!\n");
3995
3996         DRM_DEBUG_KMS("FDI train done\n");
3997
3998 }
3999
4000 static const int snb_b_fdi_train_param[] = {
4001         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4002         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4003         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4004         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4005 };
4006
4007 /* The FDI link training functions for SNB/Cougarpoint. */
4008 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4009                                 const struct intel_crtc_state *crtc_state)
4010 {
4011         struct drm_device *dev = crtc->base.dev;
4012         struct drm_i915_private *dev_priv = to_i915(dev);
4013         int pipe = crtc->pipe;
4014         i915_reg_t reg;
4015         u32 temp, i, retry;
4016
4017         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4018            for train result */
4019         reg = FDI_RX_IMR(pipe);
4020         temp = I915_READ(reg);
4021         temp &= ~FDI_RX_SYMBOL_LOCK;
4022         temp &= ~FDI_RX_BIT_LOCK;
4023         I915_WRITE(reg, temp);
4024
4025         POSTING_READ(reg);
4026         udelay(150);
4027
4028         /* enable CPU FDI TX and PCH FDI RX */
4029         reg = FDI_TX_CTL(pipe);
4030         temp = I915_READ(reg);
4031         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4032         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4033         temp &= ~FDI_LINK_TRAIN_NONE;
4034         temp |= FDI_LINK_TRAIN_PATTERN_1;
4035         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4036         /* SNB-B */
4037         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4038         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4039
4040         I915_WRITE(FDI_RX_MISC(pipe),
4041                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4042
4043         reg = FDI_RX_CTL(pipe);
4044         temp = I915_READ(reg);
4045         if (HAS_PCH_CPT(dev_priv)) {
4046                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4047                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4048         } else {
4049                 temp &= ~FDI_LINK_TRAIN_NONE;
4050                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4051         }
4052         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4053
4054         POSTING_READ(reg);
4055         udelay(150);
4056
4057         for (i = 0; i < 4; i++) {
4058                 reg = FDI_TX_CTL(pipe);
4059                 temp = I915_READ(reg);
4060                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4061                 temp |= snb_b_fdi_train_param[i];
4062                 I915_WRITE(reg, temp);
4063
4064                 POSTING_READ(reg);
4065                 udelay(500);
4066
4067                 for (retry = 0; retry < 5; retry++) {
4068                         reg = FDI_RX_IIR(pipe);
4069                         temp = I915_READ(reg);
4070                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4071                         if (temp & FDI_RX_BIT_LOCK) {
4072                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4073                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4074                                 break;
4075                         }
4076                         udelay(50);
4077                 }
4078                 if (retry < 5)
4079                         break;
4080         }
4081         if (i == 4)
4082                 DRM_ERROR("FDI train 1 fail!\n");
4083
4084         /* Train 2 */
4085         reg = FDI_TX_CTL(pipe);
4086         temp = I915_READ(reg);
4087         temp &= ~FDI_LINK_TRAIN_NONE;
4088         temp |= FDI_LINK_TRAIN_PATTERN_2;
4089         if (IS_GEN6(dev_priv)) {
4090                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4091                 /* SNB-B */
4092                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4093         }
4094         I915_WRITE(reg, temp);
4095
4096         reg = FDI_RX_CTL(pipe);
4097         temp = I915_READ(reg);
4098         if (HAS_PCH_CPT(dev_priv)) {
4099                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4100                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4101         } else {
4102                 temp &= ~FDI_LINK_TRAIN_NONE;
4103                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4104         }
4105         I915_WRITE(reg, temp);
4106
4107         POSTING_READ(reg);
4108         udelay(150);
4109
4110         for (i = 0; i < 4; i++) {
4111                 reg = FDI_TX_CTL(pipe);
4112                 temp = I915_READ(reg);
4113                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4114                 temp |= snb_b_fdi_train_param[i];
4115                 I915_WRITE(reg, temp);
4116
4117                 POSTING_READ(reg);
4118                 udelay(500);
4119
4120                 for (retry = 0; retry < 5; retry++) {
4121                         reg = FDI_RX_IIR(pipe);
4122                         temp = I915_READ(reg);
4123                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4124                         if (temp & FDI_RX_SYMBOL_LOCK) {
4125                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4126                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4127                                 break;
4128                         }
4129                         udelay(50);
4130                 }
4131                 if (retry < 5)
4132                         break;
4133         }
4134         if (i == 4)
4135                 DRM_ERROR("FDI train 2 fail!\n");
4136
4137         DRM_DEBUG_KMS("FDI train done.\n");
4138 }
4139
4140 /* Manual link training for Ivy Bridge A0 parts */
4141 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4142                                       const struct intel_crtc_state *crtc_state)
4143 {
4144         struct drm_device *dev = crtc->base.dev;
4145         struct drm_i915_private *dev_priv = to_i915(dev);
4146         int pipe = crtc->pipe;
4147         i915_reg_t reg;
4148         u32 temp, i, j;
4149
4150         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4151            for train result */
4152         reg = FDI_RX_IMR(pipe);
4153         temp = I915_READ(reg);
4154         temp &= ~FDI_RX_SYMBOL_LOCK;
4155         temp &= ~FDI_RX_BIT_LOCK;
4156         I915_WRITE(reg, temp);
4157
4158         POSTING_READ(reg);
4159         udelay(150);
4160
4161         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4162                       I915_READ(FDI_RX_IIR(pipe)));
4163
4164         /* Try each vswing and preemphasis setting twice before moving on */
4165         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4166                 /* disable first in case we need to retry */
4167                 reg = FDI_TX_CTL(pipe);
4168                 temp = I915_READ(reg);
4169                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4170                 temp &= ~FDI_TX_ENABLE;
4171                 I915_WRITE(reg, temp);
4172
4173                 reg = FDI_RX_CTL(pipe);
4174                 temp = I915_READ(reg);
4175                 temp &= ~FDI_LINK_TRAIN_AUTO;
4176                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4177                 temp &= ~FDI_RX_ENABLE;
4178                 I915_WRITE(reg, temp);
4179
4180                 /* enable CPU FDI TX and PCH FDI RX */
4181                 reg = FDI_TX_CTL(pipe);
4182                 temp = I915_READ(reg);
4183                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4184                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4185                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4186                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4187                 temp |= snb_b_fdi_train_param[j/2];
4188                 temp |= FDI_COMPOSITE_SYNC;
4189                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4190
4191                 I915_WRITE(FDI_RX_MISC(pipe),
4192                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4193
4194                 reg = FDI_RX_CTL(pipe);
4195                 temp = I915_READ(reg);
4196                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4197                 temp |= FDI_COMPOSITE_SYNC;
4198                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4199
4200                 POSTING_READ(reg);
4201                 udelay(1); /* should be 0.5us */
4202
4203                 for (i = 0; i < 4; i++) {
4204                         reg = FDI_RX_IIR(pipe);
4205                         temp = I915_READ(reg);
4206                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4207
4208                         if (temp & FDI_RX_BIT_LOCK ||
4209                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4210                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4211                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4212                                               i);
4213                                 break;
4214                         }
4215                         udelay(1); /* should be 0.5us */
4216                 }
4217                 if (i == 4) {
4218                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4219                         continue;
4220                 }
4221
4222                 /* Train 2 */
4223                 reg = FDI_TX_CTL(pipe);
4224                 temp = I915_READ(reg);
4225                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4226                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4227                 I915_WRITE(reg, temp);
4228
4229                 reg = FDI_RX_CTL(pipe);
4230                 temp = I915_READ(reg);
4231                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4232                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4233                 I915_WRITE(reg, temp);
4234
4235                 POSTING_READ(reg);
4236                 udelay(2); /* should be 1.5us */
4237
4238                 for (i = 0; i < 4; i++) {
4239                         reg = FDI_RX_IIR(pipe);
4240                         temp = I915_READ(reg);
4241                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4242
4243                         if (temp & FDI_RX_SYMBOL_LOCK ||
4244                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4245                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4246                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4247                                               i);
4248                                 goto train_done;
4249                         }
4250                         udelay(2); /* should be 1.5us */
4251                 }
4252                 if (i == 4)
4253                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4254         }
4255
4256 train_done:
4257         DRM_DEBUG_KMS("FDI train done.\n");
4258 }
4259
4260 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4261 {
4262         struct drm_device *dev = intel_crtc->base.dev;
4263         struct drm_i915_private *dev_priv = to_i915(dev);
4264         int pipe = intel_crtc->pipe;
4265         i915_reg_t reg;
4266         u32 temp;
4267
4268         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4269         reg = FDI_RX_CTL(pipe);
4270         temp = I915_READ(reg);
4271         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4272         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4273         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4274         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4275
4276         POSTING_READ(reg);
4277         udelay(200);
4278
4279         /* Switch from Rawclk to PCDclk */
4280         temp = I915_READ(reg);
4281         I915_WRITE(reg, temp | FDI_PCDCLK);
4282
4283         POSTING_READ(reg);
4284         udelay(200);
4285
4286         /* Enable CPU FDI TX PLL, always on for Ironlake */
4287         reg = FDI_TX_CTL(pipe);
4288         temp = I915_READ(reg);
4289         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4290                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4291
4292                 POSTING_READ(reg);
4293                 udelay(100);
4294         }
4295 }
4296
4297 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4298 {
4299         struct drm_device *dev = intel_crtc->base.dev;
4300         struct drm_i915_private *dev_priv = to_i915(dev);
4301         int pipe = intel_crtc->pipe;
4302         i915_reg_t reg;
4303         u32 temp;
4304
4305         /* Switch from PCDclk to Rawclk */
4306         reg = FDI_RX_CTL(pipe);
4307         temp = I915_READ(reg);
4308         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4309
4310         /* Disable CPU FDI TX PLL */
4311         reg = FDI_TX_CTL(pipe);
4312         temp = I915_READ(reg);
4313         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4314
4315         POSTING_READ(reg);
4316         udelay(100);
4317
4318         reg = FDI_RX_CTL(pipe);
4319         temp = I915_READ(reg);
4320         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4321
4322         /* Wait for the clocks to turn off. */
4323         POSTING_READ(reg);
4324         udelay(100);
4325 }
4326
4327 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4328 {
4329         struct drm_device *dev = crtc->dev;
4330         struct drm_i915_private *dev_priv = to_i915(dev);
4331         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4332         int pipe = intel_crtc->pipe;
4333         i915_reg_t reg;
4334         u32 temp;
4335
4336         /* disable CPU FDI tx and PCH FDI rx */
4337         reg = FDI_TX_CTL(pipe);
4338         temp = I915_READ(reg);
4339         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4340         POSTING_READ(reg);
4341
4342         reg = FDI_RX_CTL(pipe);
4343         temp = I915_READ(reg);
4344         temp &= ~(0x7 << 16);
4345         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4346         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4347
4348         POSTING_READ(reg);
4349         udelay(100);
4350
4351         /* Ironlake workaround, disable clock pointer after downing FDI */
4352         if (HAS_PCH_IBX(dev_priv))
4353                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4354
4355         /* still set train pattern 1 */
4356         reg = FDI_TX_CTL(pipe);
4357         temp = I915_READ(reg);
4358         temp &= ~FDI_LINK_TRAIN_NONE;
4359         temp |= FDI_LINK_TRAIN_PATTERN_1;
4360         I915_WRITE(reg, temp);
4361
4362         reg = FDI_RX_CTL(pipe);
4363         temp = I915_READ(reg);
4364         if (HAS_PCH_CPT(dev_priv)) {
4365                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4366                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4367         } else {
4368                 temp &= ~FDI_LINK_TRAIN_NONE;
4369                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4370         }
4371         /* BPC in FDI rx is consistent with that in PIPECONF */
4372         temp &= ~(0x07 << 16);
4373         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4374         I915_WRITE(reg, temp);
4375
4376         POSTING_READ(reg);
4377         udelay(100);
4378 }
4379
4380 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4381 {
4382         struct drm_crtc *crtc;
4383         bool cleanup_done;
4384
4385         drm_for_each_crtc(crtc, &dev_priv->drm) {
4386                 struct drm_crtc_commit *commit;
4387                 spin_lock(&crtc->commit_lock);
4388                 commit = list_first_entry_or_null(&crtc->commit_list,
4389                                                   struct drm_crtc_commit, commit_entry);
4390                 cleanup_done = commit ?
4391                         try_wait_for_completion(&commit->cleanup_done) : true;
4392                 spin_unlock(&crtc->commit_lock);
4393
4394                 if (cleanup_done)
4395                         continue;
4396
4397                 drm_crtc_wait_one_vblank(crtc);
4398
4399                 return true;
4400         }
4401
4402         return false;
4403 }
4404
4405 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4406 {
4407         u32 temp;
4408
4409         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4410
4411         mutex_lock(&dev_priv->sb_lock);
4412
4413         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4414         temp |= SBI_SSCCTL_DISABLE;
4415         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4416
4417         mutex_unlock(&dev_priv->sb_lock);
4418 }
4419
4420 /* Program iCLKIP clock to the desired frequency */
4421 static void lpt_program_iclkip(struct intel_crtc *crtc)
4422 {
4423         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4424         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4425         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4426         u32 temp;
4427
4428         lpt_disable_iclkip(dev_priv);
4429
4430         /* The iCLK virtual clock root frequency is in MHz,
4431          * but the adjusted_mode->crtc_clock in in KHz. To get the
4432          * divisors, it is necessary to divide one by another, so we
4433          * convert the virtual clock precision to KHz here for higher
4434          * precision.
4435          */
4436         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4437                 u32 iclk_virtual_root_freq = 172800 * 1000;
4438                 u32 iclk_pi_range = 64;
4439                 u32 desired_divisor;
4440
4441                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4442                                                     clock << auxdiv);
4443                 divsel = (desired_divisor / iclk_pi_range) - 2;
4444                 phaseinc = desired_divisor % iclk_pi_range;
4445
4446                 /*
4447                  * Near 20MHz is a corner case which is
4448                  * out of range for the 7-bit divisor
4449                  */
4450                 if (divsel <= 0x7f)
4451                         break;
4452         }
4453
4454         /* This should not happen with any sane values */
4455         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4456                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4457         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4458                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4459
4460         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4461                         clock,
4462                         auxdiv,
4463                         divsel,
4464                         phasedir,
4465                         phaseinc);
4466
4467         mutex_lock(&dev_priv->sb_lock);
4468
4469         /* Program SSCDIVINTPHASE6 */
4470         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4471         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4472         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4473         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4474         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4475         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4476         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4477         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4478
4479         /* Program SSCAUXDIV */
4480         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4481         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4482         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4483         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4484
4485         /* Enable modulator and associated divider */
4486         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4487         temp &= ~SBI_SSCCTL_DISABLE;
4488         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4489
4490         mutex_unlock(&dev_priv->sb_lock);
4491
4492         /* Wait for initialization time */
4493         udelay(24);
4494
4495         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4496 }
4497
4498 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4499 {
4500         u32 divsel, phaseinc, auxdiv;
4501         u32 iclk_virtual_root_freq = 172800 * 1000;
4502         u32 iclk_pi_range = 64;
4503         u32 desired_divisor;
4504         u32 temp;
4505
4506         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4507                 return 0;
4508
4509         mutex_lock(&dev_priv->sb_lock);
4510
4511         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4512         if (temp & SBI_SSCCTL_DISABLE) {
4513                 mutex_unlock(&dev_priv->sb_lock);
4514                 return 0;
4515         }
4516
4517         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4518         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4519                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4520         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4521                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4522
4523         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4524         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4525                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4526
4527         mutex_unlock(&dev_priv->sb_lock);
4528
4529         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4530
4531         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4532                                  desired_divisor << auxdiv);
4533 }
4534
4535 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4536                                                 enum pipe pch_transcoder)
4537 {
4538         struct drm_device *dev = crtc->base.dev;
4539         struct drm_i915_private *dev_priv = to_i915(dev);
4540         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4541
4542         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4543                    I915_READ(HTOTAL(cpu_transcoder)));
4544         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4545                    I915_READ(HBLANK(cpu_transcoder)));
4546         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4547                    I915_READ(HSYNC(cpu_transcoder)));
4548
4549         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4550                    I915_READ(VTOTAL(cpu_transcoder)));
4551         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4552                    I915_READ(VBLANK(cpu_transcoder)));
4553         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4554                    I915_READ(VSYNC(cpu_transcoder)));
4555         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4556                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4557 }
4558
4559 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4560 {
4561         struct drm_i915_private *dev_priv = to_i915(dev);
4562         uint32_t temp;
4563
4564         temp = I915_READ(SOUTH_CHICKEN1);
4565         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4566                 return;
4567
4568         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4569         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4570
4571         temp &= ~FDI_BC_BIFURCATION_SELECT;
4572         if (enable)
4573                 temp |= FDI_BC_BIFURCATION_SELECT;
4574
4575         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4576         I915_WRITE(SOUTH_CHICKEN1, temp);
4577         POSTING_READ(SOUTH_CHICKEN1);
4578 }
4579
4580 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4581 {
4582         struct drm_device *dev = intel_crtc->base.dev;
4583
4584         switch (intel_crtc->pipe) {
4585         case PIPE_A:
4586                 break;
4587         case PIPE_B:
4588                 if (intel_crtc->config->fdi_lanes > 2)
4589                         cpt_set_fdi_bc_bifurcation(dev, false);
4590                 else
4591                         cpt_set_fdi_bc_bifurcation(dev, true);
4592
4593                 break;
4594         case PIPE_C:
4595                 cpt_set_fdi_bc_bifurcation(dev, true);
4596
4597                 break;
4598         default:
4599                 BUG();
4600         }
4601 }
4602
4603 /*
4604  * Finds the encoder associated with the given CRTC. This can only be
4605  * used when we know that the CRTC isn't feeding multiple encoders!
4606  */
4607 static struct intel_encoder *
4608 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
4609                            const struct intel_crtc_state *crtc_state)
4610 {
4611         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4612         const struct drm_connector_state *connector_state;
4613         const struct drm_connector *connector;
4614         struct intel_encoder *encoder = NULL;
4615         int num_encoders = 0;
4616         int i;
4617
4618         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
4619                 if (connector_state->crtc != &crtc->base)
4620                         continue;
4621
4622                 encoder = to_intel_encoder(connector_state->best_encoder);
4623                 num_encoders++;
4624         }
4625
4626         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
4627              num_encoders, pipe_name(crtc->pipe));
4628
4629         return encoder;
4630 }
4631
4632 /*
4633  * Enable PCH resources required for PCH ports:
4634  *   - PCH PLLs
4635  *   - FDI training & RX/TX
4636  *   - update transcoder timings
4637  *   - DP transcoding bits
4638  *   - transcoder
4639  */
4640 static void ironlake_pch_enable(const struct intel_atomic_state *state,
4641                                 const struct intel_crtc_state *crtc_state)
4642 {
4643         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4644         struct drm_device *dev = crtc->base.dev;
4645         struct drm_i915_private *dev_priv = to_i915(dev);
4646         int pipe = crtc->pipe;
4647         u32 temp;
4648
4649         assert_pch_transcoder_disabled(dev_priv, pipe);
4650
4651         if (IS_IVYBRIDGE(dev_priv))
4652                 ivybridge_update_fdi_bc_bifurcation(crtc);
4653
4654         /* Write the TU size bits before fdi link training, so that error
4655          * detection works. */
4656         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4657                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4658
4659         /* For PCH output, training FDI link */
4660         dev_priv->display.fdi_link_train(crtc, crtc_state);
4661
4662         /* We need to program the right clock selection before writing the pixel
4663          * mutliplier into the DPLL. */
4664         if (HAS_PCH_CPT(dev_priv)) {
4665                 u32 sel;
4666
4667                 temp = I915_READ(PCH_DPLL_SEL);
4668                 temp |= TRANS_DPLL_ENABLE(pipe);
4669                 sel = TRANS_DPLLB_SEL(pipe);
4670                 if (crtc_state->shared_dpll ==
4671                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4672                         temp |= sel;
4673                 else
4674                         temp &= ~sel;
4675                 I915_WRITE(PCH_DPLL_SEL, temp);
4676         }
4677
4678         /* XXX: pch pll's can be enabled any time before we enable the PCH
4679          * transcoder, and we actually should do this to not upset any PCH
4680          * transcoder that already use the clock when we share it.
4681          *
4682          * Note that enable_shared_dpll tries to do the right thing, but
4683          * get_shared_dpll unconditionally resets the pll - we need that to have
4684          * the right LVDS enable sequence. */
4685         intel_enable_shared_dpll(crtc);
4686
4687         /* set transcoder timing, panel must allow it */
4688         assert_panel_unlocked(dev_priv, pipe);
4689         ironlake_pch_transcoder_set_timings(crtc, pipe);
4690
4691         intel_fdi_normal_train(crtc);
4692
4693         /* For PCH DP, enable TRANS_DP_CTL */
4694         if (HAS_PCH_CPT(dev_priv) &&
4695             intel_crtc_has_dp_encoder(crtc_state)) {
4696                 const struct drm_display_mode *adjusted_mode =
4697                         &crtc_state->base.adjusted_mode;
4698                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4699                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4700                 enum port port;
4701
4702                 temp = I915_READ(reg);
4703                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4704                           TRANS_DP_SYNC_MASK |
4705                           TRANS_DP_BPC_MASK);
4706                 temp |= TRANS_DP_OUTPUT_ENABLE;
4707                 temp |= bpc << 9; /* same format but at 11:9 */
4708
4709                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4710                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4711                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4712                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4713
4714                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
4715                 WARN_ON(port < PORT_B || port > PORT_D);
4716                 temp |= TRANS_DP_PORT_SEL(port);
4717
4718                 I915_WRITE(reg, temp);
4719         }
4720
4721         ironlake_enable_pch_transcoder(dev_priv, pipe);
4722 }
4723
4724 static void lpt_pch_enable(const struct intel_atomic_state *state,
4725                            const struct intel_crtc_state *crtc_state)
4726 {
4727         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4728         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4729         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4730
4731         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4732
4733         lpt_program_iclkip(crtc);
4734
4735         /* Set transcoder timing. */
4736         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4737
4738         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4739 }
4740
4741 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4742 {
4743         struct drm_i915_private *dev_priv = to_i915(dev);
4744         i915_reg_t dslreg = PIPEDSL(pipe);
4745         u32 temp;
4746
4747         temp = I915_READ(dslreg);
4748         udelay(500);
4749         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4750                 if (wait_for(I915_READ(dslreg) != temp, 5))
4751                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4752         }
4753 }
4754
4755 /*
4756  * The hardware phase 0.0 refers to the center of the pixel.
4757  * We want to start from the top/left edge which is phase
4758  * -0.5. That matches how the hardware calculates the scaling
4759  * factors (from top-left of the first pixel to bottom-right
4760  * of the last pixel, as opposed to the pixel centers).
4761  *
4762  * For 4:2:0 subsampled chroma planes we obviously have to
4763  * adjust that so that the chroma sample position lands in
4764  * the right spot.
4765  *
4766  * Note that for packed YCbCr 4:2:2 formats there is no way to
4767  * control chroma siting. The hardware simply replicates the
4768  * chroma samples for both of the luma samples, and thus we don't
4769  * actually get the expected MPEG2 chroma siting convention :(
4770  * The same behaviour is observed on pre-SKL platforms as well.
4771  */
4772 u16 skl_scaler_calc_phase(int sub, bool chroma_cosited)
4773 {
4774         int phase = -0x8000;
4775         u16 trip = 0;
4776
4777         if (chroma_cosited)
4778                 phase += (sub - 1) * 0x8000 / sub;
4779
4780         if (phase < 0)
4781                 phase = 0x10000 + phase;
4782         else
4783                 trip = PS_PHASE_TRIP;
4784
4785         return ((phase >> 2) & PS_PHASE_MASK) | trip;
4786 }
4787
4788 static int
4789 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4790                   unsigned int scaler_user, int *scaler_id,
4791                   int src_w, int src_h, int dst_w, int dst_h,
4792                   bool plane_scaler_check,
4793                   uint32_t pixel_format)
4794 {
4795         struct intel_crtc_scaler_state *scaler_state =
4796                 &crtc_state->scaler_state;
4797         struct intel_crtc *intel_crtc =
4798                 to_intel_crtc(crtc_state->base.crtc);
4799         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4800         const struct drm_display_mode *adjusted_mode =
4801                 &crtc_state->base.adjusted_mode;
4802         int need_scaling;
4803
4804         /*
4805          * Src coordinates are already rotated by 270 degrees for
4806          * the 90/270 degree plane rotation cases (to match the
4807          * GTT mapping), hence no need to account for rotation here.
4808          */
4809         need_scaling = src_w != dst_w || src_h != dst_h;
4810
4811         if (plane_scaler_check)
4812                 if (pixel_format == DRM_FORMAT_NV12)
4813                         need_scaling = true;
4814
4815         if (crtc_state->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4816                 need_scaling = true;
4817
4818         /*
4819          * Scaling/fitting not supported in IF-ID mode in GEN9+
4820          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4821          * Once NV12 is enabled, handle it here while allocating scaler
4822          * for NV12.
4823          */
4824         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4825             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4826                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4827                 return -EINVAL;
4828         }
4829
4830         /*
4831          * if plane is being disabled or scaler is no more required or force detach
4832          *  - free scaler binded to this plane/crtc
4833          *  - in order to do this, update crtc->scaler_usage
4834          *
4835          * Here scaler state in crtc_state is set free so that
4836          * scaler can be assigned to other user. Actual register
4837          * update to free the scaler is done in plane/panel-fit programming.
4838          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4839          */
4840         if (force_detach || !need_scaling) {
4841                 if (*scaler_id >= 0) {
4842                         scaler_state->scaler_users &= ~(1 << scaler_user);
4843                         scaler_state->scalers[*scaler_id].in_use = 0;
4844
4845                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4846                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4847                                 intel_crtc->pipe, scaler_user, *scaler_id,
4848                                 scaler_state->scaler_users);
4849                         *scaler_id = -1;
4850                 }
4851                 return 0;
4852         }
4853
4854         if (plane_scaler_check && pixel_format == DRM_FORMAT_NV12 &&
4855             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
4856                 DRM_DEBUG_KMS("NV12: src dimensions not met\n");
4857                 return -EINVAL;
4858         }
4859
4860         /* range checks */
4861         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4862             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4863             (IS_GEN11(dev_priv) &&
4864              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
4865               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
4866             (!IS_GEN11(dev_priv) &&
4867              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4868               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
4869                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4870                         "size is out of scaler range\n",
4871                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4872                 return -EINVAL;
4873         }
4874
4875         /* mark this plane as a scaler user in crtc_state */
4876         scaler_state->scaler_users |= (1 << scaler_user);
4877         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4878                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4879                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4880                 scaler_state->scaler_users);
4881
4882         return 0;
4883 }
4884
4885 /**
4886  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4887  *
4888  * @state: crtc's scaler state
4889  *
4890  * Return
4891  *     0 - scaler_usage updated successfully
4892  *    error - requested scaling cannot be supported or other error condition
4893  */
4894 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4895 {
4896         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4897
4898         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4899                                  &state->scaler_state.scaler_id,
4900                                  state->pipe_src_w, state->pipe_src_h,
4901                                  adjusted_mode->crtc_hdisplay,
4902                                  adjusted_mode->crtc_vdisplay, false, 0);
4903 }
4904
4905 /**
4906  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4907  * @crtc_state: crtc's scaler state
4908  * @plane_state: atomic plane state to update
4909  *
4910  * Return
4911  *     0 - scaler_usage updated successfully
4912  *    error - requested scaling cannot be supported or other error condition
4913  */
4914 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4915                                    struct intel_plane_state *plane_state)
4916 {
4917
4918         struct intel_plane *intel_plane =
4919                 to_intel_plane(plane_state->base.plane);
4920         struct drm_framebuffer *fb = plane_state->base.fb;
4921         int ret;
4922
4923         bool force_detach = !fb || !plane_state->base.visible;
4924
4925         ret = skl_update_scaler(crtc_state, force_detach,
4926                                 drm_plane_index(&intel_plane->base),
4927                                 &plane_state->scaler_id,
4928                                 drm_rect_width(&plane_state->base.src) >> 16,
4929                                 drm_rect_height(&plane_state->base.src) >> 16,
4930                                 drm_rect_width(&plane_state->base.dst),
4931                                 drm_rect_height(&plane_state->base.dst),
4932                                 fb ? true : false, fb ? fb->format->format : 0);
4933
4934         if (ret || plane_state->scaler_id < 0)
4935                 return ret;
4936
4937         /* check colorkey */
4938         if (plane_state->ckey.flags) {
4939                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4940                               intel_plane->base.base.id,
4941                               intel_plane->base.name);
4942                 return -EINVAL;
4943         }
4944
4945         /* Check src format */
4946         switch (fb->format->format) {
4947         case DRM_FORMAT_RGB565:
4948         case DRM_FORMAT_XBGR8888:
4949         case DRM_FORMAT_XRGB8888:
4950         case DRM_FORMAT_ABGR8888:
4951         case DRM_FORMAT_ARGB8888:
4952         case DRM_FORMAT_XRGB2101010:
4953         case DRM_FORMAT_XBGR2101010:
4954         case DRM_FORMAT_YUYV:
4955         case DRM_FORMAT_YVYU:
4956         case DRM_FORMAT_UYVY:
4957         case DRM_FORMAT_VYUY:
4958         case DRM_FORMAT_NV12:
4959                 break;
4960         default:
4961                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4962                               intel_plane->base.base.id, intel_plane->base.name,
4963                               fb->base.id, fb->format->format);
4964                 return -EINVAL;
4965         }
4966
4967         return 0;
4968 }
4969
4970 static void skylake_scaler_disable(struct intel_crtc *crtc)
4971 {
4972         int i;
4973
4974         for (i = 0; i < crtc->num_scalers; i++)
4975                 skl_detach_scaler(crtc, i);
4976 }
4977
4978 static void skylake_pfit_enable(struct intel_crtc *crtc)
4979 {
4980         struct drm_device *dev = crtc->base.dev;
4981         struct drm_i915_private *dev_priv = to_i915(dev);
4982         int pipe = crtc->pipe;
4983         struct intel_crtc_scaler_state *scaler_state =
4984                 &crtc->config->scaler_state;
4985
4986         if (crtc->config->pch_pfit.enabled) {
4987                 u16 uv_rgb_hphase, uv_rgb_vphase;
4988                 int id;
4989
4990                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4991                         return;
4992
4993                 uv_rgb_hphase = skl_scaler_calc_phase(1, false);
4994                 uv_rgb_vphase = skl_scaler_calc_phase(1, false);
4995
4996                 id = scaler_state->scaler_id;
4997                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4998                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4999                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5000                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5001                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5002                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5003                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
5004                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
5005         }
5006 }
5007
5008 static void ironlake_pfit_enable(struct intel_crtc *crtc)
5009 {
5010         struct drm_device *dev = crtc->base.dev;
5011         struct drm_i915_private *dev_priv = to_i915(dev);
5012         int pipe = crtc->pipe;
5013
5014         if (crtc->config->pch_pfit.enabled) {
5015                 /* Force use of hard-coded filter coefficients
5016                  * as some pre-programmed values are broken,
5017                  * e.g. x201.
5018                  */
5019                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5020                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5021                                                  PF_PIPE_SEL_IVB(pipe));
5022                 else
5023                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5024                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
5025                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
5026         }
5027 }
5028
5029 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5030 {
5031         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5032         struct drm_device *dev = crtc->base.dev;
5033         struct drm_i915_private *dev_priv = to_i915(dev);
5034
5035         if (!crtc_state->ips_enabled)
5036                 return;
5037
5038         /*
5039          * We can only enable IPS after we enable a plane and wait for a vblank
5040          * This function is called from post_plane_update, which is run after
5041          * a vblank wait.
5042          */
5043         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5044
5045         if (IS_BROADWELL(dev_priv)) {
5046                 mutex_lock(&dev_priv->pcu_lock);
5047                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5048                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5049                 mutex_unlock(&dev_priv->pcu_lock);
5050                 /* Quoting Art Runyan: "its not safe to expect any particular
5051                  * value in IPS_CTL bit 31 after enabling IPS through the
5052                  * mailbox." Moreover, the mailbox may return a bogus state,
5053                  * so we need to just enable it and continue on.
5054                  */
5055         } else {
5056                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5057                 /* The bit only becomes 1 in the next vblank, so this wait here
5058                  * is essentially intel_wait_for_vblank. If we don't have this
5059                  * and don't wait for vblanks until the end of crtc_enable, then
5060                  * the HW state readout code will complain that the expected
5061                  * IPS_CTL value is not the one we read. */
5062                 if (intel_wait_for_register(dev_priv,
5063                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5064                                             50))
5065                         DRM_ERROR("Timed out waiting for IPS enable\n");
5066         }
5067 }
5068
5069 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5070 {
5071         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5072         struct drm_device *dev = crtc->base.dev;
5073         struct drm_i915_private *dev_priv = to_i915(dev);
5074
5075         if (!crtc_state->ips_enabled)
5076                 return;
5077
5078         if (IS_BROADWELL(dev_priv)) {
5079                 mutex_lock(&dev_priv->pcu_lock);
5080                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5081                 mutex_unlock(&dev_priv->pcu_lock);
5082                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
5083                 if (intel_wait_for_register(dev_priv,
5084                                             IPS_CTL, IPS_ENABLE, 0,
5085                                             42))
5086                         DRM_ERROR("Timed out waiting for IPS disable\n");
5087         } else {
5088                 I915_WRITE(IPS_CTL, 0);
5089                 POSTING_READ(IPS_CTL);
5090         }
5091
5092         /* We need to wait for a vblank before we can disable the plane. */
5093         intel_wait_for_vblank(dev_priv, crtc->pipe);
5094 }
5095
5096 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5097 {
5098         if (intel_crtc->overlay) {
5099                 struct drm_device *dev = intel_crtc->base.dev;
5100
5101                 mutex_lock(&dev->struct_mutex);
5102                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5103                 mutex_unlock(&dev->struct_mutex);
5104         }
5105
5106         /* Let userspace switch the overlay on again. In most cases userspace
5107          * has to recompute where to put it anyway.
5108          */
5109 }
5110
5111 /**
5112  * intel_post_enable_primary - Perform operations after enabling primary plane
5113  * @crtc: the CRTC whose primary plane was just enabled
5114  * @new_crtc_state: the enabling state
5115  *
5116  * Performs potentially sleeping operations that must be done after the primary
5117  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5118  * called due to an explicit primary plane update, or due to an implicit
5119  * re-enable that is caused when a sprite plane is updated to no longer
5120  * completely hide the primary plane.
5121  */
5122 static void
5123 intel_post_enable_primary(struct drm_crtc *crtc,
5124                           const struct intel_crtc_state *new_crtc_state)
5125 {
5126         struct drm_device *dev = crtc->dev;
5127         struct drm_i915_private *dev_priv = to_i915(dev);
5128         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5129         int pipe = intel_crtc->pipe;
5130
5131         /*
5132          * Gen2 reports pipe underruns whenever all planes are disabled.
5133          * So don't enable underrun reporting before at least some planes
5134          * are enabled.
5135          * FIXME: Need to fix the logic to work when we turn off all planes
5136          * but leave the pipe running.
5137          */
5138         if (IS_GEN2(dev_priv))
5139                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5140
5141         /* Underruns don't always raise interrupts, so check manually. */
5142         intel_check_cpu_fifo_underruns(dev_priv);
5143         intel_check_pch_fifo_underruns(dev_priv);
5144 }
5145
5146 /* FIXME get rid of this and use pre_plane_update */
5147 static void
5148 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5149 {
5150         struct drm_device *dev = crtc->dev;
5151         struct drm_i915_private *dev_priv = to_i915(dev);
5152         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5153         int pipe = intel_crtc->pipe;
5154
5155         /*
5156          * Gen2 reports pipe underruns whenever all planes are disabled.
5157          * So disable underrun reporting before all the planes get disabled.
5158          */
5159         if (IS_GEN2(dev_priv))
5160                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5161
5162         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5163
5164         /*
5165          * Vblank time updates from the shadow to live plane control register
5166          * are blocked if the memory self-refresh mode is active at that
5167          * moment. So to make sure the plane gets truly disabled, disable
5168          * first the self-refresh mode. The self-refresh enable bit in turn
5169          * will be checked/applied by the HW only at the next frame start
5170          * event which is after the vblank start event, so we need to have a
5171          * wait-for-vblank between disabling the plane and the pipe.
5172          */
5173         if (HAS_GMCH_DISPLAY(dev_priv) &&
5174             intel_set_memory_cxsr(dev_priv, false))
5175                 intel_wait_for_vblank(dev_priv, pipe);
5176 }
5177
5178 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5179                                        const struct intel_crtc_state *new_crtc_state)
5180 {
5181         if (!old_crtc_state->ips_enabled)
5182                 return false;
5183
5184         if (needs_modeset(&new_crtc_state->base))
5185                 return true;
5186
5187         return !new_crtc_state->ips_enabled;
5188 }
5189
5190 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5191                                        const struct intel_crtc_state *new_crtc_state)
5192 {
5193         if (!new_crtc_state->ips_enabled)
5194                 return false;
5195
5196         if (needs_modeset(&new_crtc_state->base))
5197                 return true;
5198
5199         /*
5200          * We can't read out IPS on broadwell, assume the worst and
5201          * forcibly enable IPS on the first fastset.
5202          */
5203         if (new_crtc_state->update_pipe &&
5204             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5205                 return true;
5206
5207         return !old_crtc_state->ips_enabled;
5208 }
5209
5210 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5211                           const struct intel_crtc_state *crtc_state)
5212 {
5213         if (!crtc_state->nv12_planes)
5214                 return false;
5215
5216         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
5217                 return false;
5218
5219         if ((INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv)) ||
5220             IS_CANNONLAKE(dev_priv))
5221                 return true;
5222
5223         return false;
5224 }
5225
5226 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5227 {
5228         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5229         struct drm_device *dev = crtc->base.dev;
5230         struct drm_i915_private *dev_priv = to_i915(dev);
5231         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5232         struct intel_crtc_state *pipe_config =
5233                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5234                                                 crtc);
5235         struct drm_plane *primary = crtc->base.primary;
5236         struct drm_plane_state *old_primary_state =
5237                 drm_atomic_get_old_plane_state(old_state, primary);
5238
5239         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5240
5241         if (pipe_config->update_wm_post && pipe_config->base.active)
5242                 intel_update_watermarks(crtc);
5243
5244         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5245                 hsw_enable_ips(pipe_config);
5246
5247         if (old_primary_state) {
5248                 struct drm_plane_state *new_primary_state =
5249                         drm_atomic_get_new_plane_state(old_state, primary);
5250
5251                 intel_fbc_post_update(crtc);
5252
5253                 if (new_primary_state->visible &&
5254                     (needs_modeset(&pipe_config->base) ||
5255                      !old_primary_state->visible))
5256                         intel_post_enable_primary(&crtc->base, pipe_config);
5257         }
5258
5259         /* Display WA 827 */
5260         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5261             !needs_nv12_wa(dev_priv, pipe_config)) {
5262                 skl_wa_clkgate(dev_priv, crtc->pipe, false);
5263                 skl_wa_528(dev_priv, crtc->pipe, false);
5264         }
5265 }
5266
5267 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5268                                    struct intel_crtc_state *pipe_config)
5269 {
5270         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5271         struct drm_device *dev = crtc->base.dev;
5272         struct drm_i915_private *dev_priv = to_i915(dev);
5273         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5274         struct drm_plane *primary = crtc->base.primary;
5275         struct drm_plane_state *old_primary_state =
5276                 drm_atomic_get_old_plane_state(old_state, primary);
5277         bool modeset = needs_modeset(&pipe_config->base);
5278         struct intel_atomic_state *old_intel_state =
5279                 to_intel_atomic_state(old_state);
5280
5281         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5282                 hsw_disable_ips(old_crtc_state);
5283
5284         if (old_primary_state) {
5285                 struct intel_plane_state *new_primary_state =
5286                         intel_atomic_get_new_plane_state(old_intel_state,
5287                                                          to_intel_plane(primary));
5288
5289                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5290                 /*
5291                  * Gen2 reports pipe underruns whenever all planes are disabled.
5292                  * So disable underrun reporting before all the planes get disabled.
5293                  */
5294                 if (IS_GEN2(dev_priv) && old_primary_state->visible &&
5295                     (modeset || !new_primary_state->base.visible))
5296                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5297         }
5298
5299         /* Display WA 827 */
5300         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5301             needs_nv12_wa(dev_priv, pipe_config)) {
5302                 skl_wa_clkgate(dev_priv, crtc->pipe, true);
5303                 skl_wa_528(dev_priv, crtc->pipe, true);
5304         }
5305
5306         /*
5307          * Vblank time updates from the shadow to live plane control register
5308          * are blocked if the memory self-refresh mode is active at that
5309          * moment. So to make sure the plane gets truly disabled, disable
5310          * first the self-refresh mode. The self-refresh enable bit in turn
5311          * will be checked/applied by the HW only at the next frame start
5312          * event which is after the vblank start event, so we need to have a
5313          * wait-for-vblank between disabling the plane and the pipe.
5314          */
5315         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5316             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5317                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5318
5319         /*
5320          * IVB workaround: must disable low power watermarks for at least
5321          * one frame before enabling scaling.  LP watermarks can be re-enabled
5322          * when scaling is disabled.
5323          *
5324          * WaCxSRDisabledForSpriteScaling:ivb
5325          */
5326         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5327                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5328
5329         /*
5330          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5331          * watermark programming here.
5332          */
5333         if (needs_modeset(&pipe_config->base))
5334                 return;
5335
5336         /*
5337          * For platforms that support atomic watermarks, program the
5338          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5339          * will be the intermediate values that are safe for both pre- and
5340          * post- vblank; when vblank happens, the 'active' values will be set
5341          * to the final 'target' values and we'll do this again to get the
5342          * optimal watermarks.  For gen9+ platforms, the values we program here
5343          * will be the final target values which will get automatically latched
5344          * at vblank time; no further programming will be necessary.
5345          *
5346          * If a platform hasn't been transitioned to atomic watermarks yet,
5347          * we'll continue to update watermarks the old way, if flags tell
5348          * us to.
5349          */
5350         if (dev_priv->display.initial_watermarks != NULL)
5351                 dev_priv->display.initial_watermarks(old_intel_state,
5352                                                      pipe_config);
5353         else if (pipe_config->update_wm_pre)
5354                 intel_update_watermarks(crtc);
5355 }
5356
5357 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5358 {
5359         struct drm_device *dev = crtc->dev;
5360         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5361         struct drm_plane *p;
5362         int pipe = intel_crtc->pipe;
5363
5364         intel_crtc_dpms_overlay_disable(intel_crtc);
5365
5366         drm_for_each_plane_mask(p, dev, plane_mask)
5367                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5368
5369         /*
5370          * FIXME: Once we grow proper nuclear flip support out of this we need
5371          * to compute the mask of flip planes precisely. For the time being
5372          * consider this a flip to a NULL plane.
5373          */
5374         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5375 }
5376
5377 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5378                                           struct intel_crtc_state *crtc_state,
5379                                           struct drm_atomic_state *old_state)
5380 {
5381         struct drm_connector_state *conn_state;
5382         struct drm_connector *conn;
5383         int i;
5384
5385         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5386                 struct intel_encoder *encoder =
5387                         to_intel_encoder(conn_state->best_encoder);
5388
5389                 if (conn_state->crtc != crtc)
5390                         continue;
5391
5392                 if (encoder->pre_pll_enable)
5393                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5394         }
5395 }
5396
5397 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5398                                       struct intel_crtc_state *crtc_state,
5399                                       struct drm_atomic_state *old_state)
5400 {
5401         struct drm_connector_state *conn_state;
5402         struct drm_connector *conn;
5403         int i;
5404
5405         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5406                 struct intel_encoder *encoder =
5407                         to_intel_encoder(conn_state->best_encoder);
5408
5409                 if (conn_state->crtc != crtc)
5410                         continue;
5411
5412                 if (encoder->pre_enable)
5413                         encoder->pre_enable(encoder, crtc_state, conn_state);
5414         }
5415 }
5416
5417 static void intel_encoders_enable(struct drm_crtc *crtc,
5418                                   struct intel_crtc_state *crtc_state,
5419                                   struct drm_atomic_state *old_state)
5420 {
5421         struct drm_connector_state *conn_state;
5422         struct drm_connector *conn;
5423         int i;
5424
5425         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5426                 struct intel_encoder *encoder =
5427                         to_intel_encoder(conn_state->best_encoder);
5428
5429                 if (conn_state->crtc != crtc)
5430                         continue;
5431
5432                 encoder->enable(encoder, crtc_state, conn_state);
5433                 intel_opregion_notify_encoder(encoder, true);
5434         }
5435 }
5436
5437 static void intel_encoders_disable(struct drm_crtc *crtc,
5438                                    struct intel_crtc_state *old_crtc_state,
5439                                    struct drm_atomic_state *old_state)
5440 {
5441         struct drm_connector_state *old_conn_state;
5442         struct drm_connector *conn;
5443         int i;
5444
5445         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5446                 struct intel_encoder *encoder =
5447                         to_intel_encoder(old_conn_state->best_encoder);
5448
5449                 if (old_conn_state->crtc != crtc)
5450                         continue;
5451
5452                 intel_opregion_notify_encoder(encoder, false);
5453                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5454         }
5455 }
5456
5457 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5458                                         struct intel_crtc_state *old_crtc_state,
5459                                         struct drm_atomic_state *old_state)
5460 {
5461         struct drm_connector_state *old_conn_state;
5462         struct drm_connector *conn;
5463         int i;
5464
5465         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5466                 struct intel_encoder *encoder =
5467                         to_intel_encoder(old_conn_state->best_encoder);
5468
5469                 if (old_conn_state->crtc != crtc)
5470                         continue;
5471
5472                 if (encoder->post_disable)
5473                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5474         }
5475 }
5476
5477 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5478                                             struct intel_crtc_state *old_crtc_state,
5479                                             struct drm_atomic_state *old_state)
5480 {
5481         struct drm_connector_state *old_conn_state;
5482         struct drm_connector *conn;
5483         int i;
5484
5485         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5486                 struct intel_encoder *encoder =
5487                         to_intel_encoder(old_conn_state->best_encoder);
5488
5489                 if (old_conn_state->crtc != crtc)
5490                         continue;
5491
5492                 if (encoder->post_pll_disable)
5493                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5494         }
5495 }
5496
5497 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5498                                  struct drm_atomic_state *old_state)
5499 {
5500         struct drm_crtc *crtc = pipe_config->base.crtc;
5501         struct drm_device *dev = crtc->dev;
5502         struct drm_i915_private *dev_priv = to_i915(dev);
5503         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5504         int pipe = intel_crtc->pipe;
5505         struct intel_atomic_state *old_intel_state =
5506                 to_intel_atomic_state(old_state);
5507
5508         if (WARN_ON(intel_crtc->active))
5509                 return;
5510
5511         /*
5512          * Sometimes spurious CPU pipe underruns happen during FDI
5513          * training, at least with VGA+HDMI cloning. Suppress them.
5514          *
5515          * On ILK we get an occasional spurious CPU pipe underruns
5516          * between eDP port A enable and vdd enable. Also PCH port
5517          * enable seems to result in the occasional CPU pipe underrun.
5518          *
5519          * Spurious PCH underruns also occur during PCH enabling.
5520          */
5521         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5522         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5523
5524         if (intel_crtc->config->has_pch_encoder)
5525                 intel_prepare_shared_dpll(intel_crtc);
5526
5527         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5528                 intel_dp_set_m_n(intel_crtc, M1_N1);
5529
5530         intel_set_pipe_timings(intel_crtc);
5531         intel_set_pipe_src_size(intel_crtc);
5532
5533         if (intel_crtc->config->has_pch_encoder) {
5534                 intel_cpu_transcoder_set_m_n(intel_crtc,
5535                                      &intel_crtc->config->fdi_m_n, NULL);
5536         }
5537
5538         ironlake_set_pipeconf(crtc);
5539
5540         intel_crtc->active = true;
5541
5542         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5543
5544         if (intel_crtc->config->has_pch_encoder) {
5545                 /* Note: FDI PLL enabling _must_ be done before we enable the
5546                  * cpu pipes, hence this is separate from all the other fdi/pch
5547                  * enabling. */
5548                 ironlake_fdi_pll_enable(intel_crtc);
5549         } else {
5550                 assert_fdi_tx_disabled(dev_priv, pipe);
5551                 assert_fdi_rx_disabled(dev_priv, pipe);
5552         }
5553
5554         ironlake_pfit_enable(intel_crtc);
5555
5556         /*
5557          * On ILK+ LUT must be loaded before the pipe is running but with
5558          * clocks enabled
5559          */
5560         intel_color_load_luts(&pipe_config->base);
5561
5562         if (dev_priv->display.initial_watermarks != NULL)
5563                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5564         intel_enable_pipe(pipe_config);
5565
5566         if (intel_crtc->config->has_pch_encoder)
5567                 ironlake_pch_enable(old_intel_state, pipe_config);
5568
5569         assert_vblank_disabled(crtc);
5570         drm_crtc_vblank_on(crtc);
5571
5572         intel_encoders_enable(crtc, pipe_config, old_state);
5573
5574         if (HAS_PCH_CPT(dev_priv))
5575                 cpt_verify_modeset(dev, intel_crtc->pipe);
5576
5577         /*
5578          * Must wait for vblank to avoid spurious PCH FIFO underruns.
5579          * And a second vblank wait is needed at least on ILK with
5580          * some interlaced HDMI modes. Let's do the double wait always
5581          * in case there are more corner cases we don't know about.
5582          */
5583         if (intel_crtc->config->has_pch_encoder) {
5584                 intel_wait_for_vblank(dev_priv, pipe);
5585                 intel_wait_for_vblank(dev_priv, pipe);
5586         }
5587         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5588         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5589 }
5590
5591 /* IPS only exists on ULT machines and is tied to pipe A. */
5592 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5593 {
5594         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5595 }
5596
5597 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5598                                             enum pipe pipe, bool apply)
5599 {
5600         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5601         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5602
5603         if (apply)
5604                 val |= mask;
5605         else
5606                 val &= ~mask;
5607
5608         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5609 }
5610
5611 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5612 {
5613         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5614         enum pipe pipe = crtc->pipe;
5615         uint32_t val;
5616
5617         val = MBUS_DBOX_BW_CREDIT(1) | MBUS_DBOX_A_CREDIT(2);
5618
5619         /* Program B credit equally to all pipes */
5620         val |= MBUS_DBOX_B_CREDIT(24 / INTEL_INFO(dev_priv)->num_pipes);
5621
5622         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5623 }
5624
5625 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5626                                 struct drm_atomic_state *old_state)
5627 {
5628         struct drm_crtc *crtc = pipe_config->base.crtc;
5629         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5630         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5631         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5632         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5633         struct intel_atomic_state *old_intel_state =
5634                 to_intel_atomic_state(old_state);
5635         bool psl_clkgate_wa;
5636         u32 pipe_chicken;
5637
5638         if (WARN_ON(intel_crtc->active))
5639                 return;
5640
5641         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5642
5643         if (intel_crtc->config->shared_dpll)
5644                 intel_enable_shared_dpll(intel_crtc);
5645
5646         if (INTEL_GEN(dev_priv) >= 11)
5647                 icl_map_plls_to_ports(crtc, pipe_config, old_state);
5648
5649         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5650
5651         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5652                 intel_dp_set_m_n(intel_crtc, M1_N1);
5653
5654         if (!transcoder_is_dsi(cpu_transcoder))
5655                 intel_set_pipe_timings(intel_crtc);
5656
5657         intel_set_pipe_src_size(intel_crtc);
5658
5659         if (cpu_transcoder != TRANSCODER_EDP &&
5660             !transcoder_is_dsi(cpu_transcoder)) {
5661                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5662                            intel_crtc->config->pixel_multiplier - 1);
5663         }
5664
5665         if (intel_crtc->config->has_pch_encoder) {
5666                 intel_cpu_transcoder_set_m_n(intel_crtc,
5667                                      &intel_crtc->config->fdi_m_n, NULL);
5668         }
5669
5670         if (!transcoder_is_dsi(cpu_transcoder))
5671                 haswell_set_pipeconf(crtc);
5672
5673         haswell_set_pipemisc(crtc);
5674
5675         intel_color_set_csc(&pipe_config->base);
5676
5677         intel_crtc->active = true;
5678
5679         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5680         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5681                          intel_crtc->config->pch_pfit.enabled;
5682         if (psl_clkgate_wa)
5683                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5684
5685         if (INTEL_GEN(dev_priv) >= 9)
5686                 skylake_pfit_enable(intel_crtc);
5687         else
5688                 ironlake_pfit_enable(intel_crtc);
5689
5690         /*
5691          * On ILK+ LUT must be loaded before the pipe is running but with
5692          * clocks enabled
5693          */
5694         intel_color_load_luts(&pipe_config->base);
5695
5696         /*
5697          * Display WA #1153: enable hardware to bypass the alpha math
5698          * and rounding for per-pixel values 00 and 0xff
5699          */
5700         if (INTEL_GEN(dev_priv) >= 11) {
5701                 pipe_chicken = I915_READ(PIPE_CHICKEN(pipe));
5702                 if (!(pipe_chicken & PER_PIXEL_ALPHA_BYPASS_EN))
5703                         I915_WRITE_FW(PIPE_CHICKEN(pipe),
5704                                       pipe_chicken | PER_PIXEL_ALPHA_BYPASS_EN);
5705         }
5706
5707         intel_ddi_set_pipe_settings(pipe_config);
5708         if (!transcoder_is_dsi(cpu_transcoder))
5709                 intel_ddi_enable_transcoder_func(pipe_config);
5710
5711         if (dev_priv->display.initial_watermarks != NULL)
5712                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5713
5714         if (INTEL_GEN(dev_priv) >= 11)
5715                 icl_pipe_mbus_enable(intel_crtc);
5716
5717         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5718         if (!transcoder_is_dsi(cpu_transcoder))
5719                 intel_enable_pipe(pipe_config);
5720
5721         if (intel_crtc->config->has_pch_encoder)
5722                 lpt_pch_enable(old_intel_state, pipe_config);
5723
5724         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5725                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5726
5727         assert_vblank_disabled(crtc);
5728         drm_crtc_vblank_on(crtc);
5729
5730         intel_encoders_enable(crtc, pipe_config, old_state);
5731
5732         if (psl_clkgate_wa) {
5733                 intel_wait_for_vblank(dev_priv, pipe);
5734                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5735         }
5736
5737         /* If we change the relative order between pipe/planes enabling, we need
5738          * to change the workaround. */
5739         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5740         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5741                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5742                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5743         }
5744 }
5745
5746 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5747 {
5748         struct drm_device *dev = crtc->base.dev;
5749         struct drm_i915_private *dev_priv = to_i915(dev);
5750         int pipe = crtc->pipe;
5751
5752         /* To avoid upsetting the power well on haswell only disable the pfit if
5753          * it's in use. The hw state code will make sure we get this right. */
5754         if (force || crtc->config->pch_pfit.enabled) {
5755                 I915_WRITE(PF_CTL(pipe), 0);
5756                 I915_WRITE(PF_WIN_POS(pipe), 0);
5757                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5758         }
5759 }
5760
5761 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5762                                   struct drm_atomic_state *old_state)
5763 {
5764         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5765         struct drm_device *dev = crtc->dev;
5766         struct drm_i915_private *dev_priv = to_i915(dev);
5767         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5768         int pipe = intel_crtc->pipe;
5769
5770         /*
5771          * Sometimes spurious CPU pipe underruns happen when the
5772          * pipe is already disabled, but FDI RX/TX is still enabled.
5773          * Happens at least with VGA+HDMI cloning. Suppress them.
5774          */
5775         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5776         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5777
5778         intel_encoders_disable(crtc, old_crtc_state, old_state);
5779
5780         drm_crtc_vblank_off(crtc);
5781         assert_vblank_disabled(crtc);
5782
5783         intel_disable_pipe(old_crtc_state);
5784
5785         ironlake_pfit_disable(intel_crtc, false);
5786
5787         if (intel_crtc->config->has_pch_encoder)
5788                 ironlake_fdi_disable(crtc);
5789
5790         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5791
5792         if (intel_crtc->config->has_pch_encoder) {
5793                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5794
5795                 if (HAS_PCH_CPT(dev_priv)) {
5796                         i915_reg_t reg;
5797                         u32 temp;
5798
5799                         /* disable TRANS_DP_CTL */
5800                         reg = TRANS_DP_CTL(pipe);
5801                         temp = I915_READ(reg);
5802                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5803                                   TRANS_DP_PORT_SEL_MASK);
5804                         temp |= TRANS_DP_PORT_SEL_NONE;
5805                         I915_WRITE(reg, temp);
5806
5807                         /* disable DPLL_SEL */
5808                         temp = I915_READ(PCH_DPLL_SEL);
5809                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5810                         I915_WRITE(PCH_DPLL_SEL, temp);
5811                 }
5812
5813                 ironlake_fdi_pll_disable(intel_crtc);
5814         }
5815
5816         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5817         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5818 }
5819
5820 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5821                                  struct drm_atomic_state *old_state)
5822 {
5823         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5824         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5825         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5826         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
5827
5828         intel_encoders_disable(crtc, old_crtc_state, old_state);
5829
5830         drm_crtc_vblank_off(crtc);
5831         assert_vblank_disabled(crtc);
5832
5833         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5834         if (!transcoder_is_dsi(cpu_transcoder))
5835                 intel_disable_pipe(old_crtc_state);
5836
5837         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
5838                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
5839
5840         if (!transcoder_is_dsi(cpu_transcoder))
5841                 intel_ddi_disable_transcoder_func(old_crtc_state);
5842
5843         if (INTEL_GEN(dev_priv) >= 9)
5844                 skylake_scaler_disable(intel_crtc);
5845         else
5846                 ironlake_pfit_disable(intel_crtc, false);
5847
5848         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5849
5850         if (INTEL_GEN(dev_priv) >= 11)
5851                 icl_unmap_plls_to_ports(crtc, old_crtc_state, old_state);
5852 }
5853
5854 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5855 {
5856         struct drm_device *dev = crtc->base.dev;
5857         struct drm_i915_private *dev_priv = to_i915(dev);
5858         struct intel_crtc_state *pipe_config = crtc->config;
5859
5860         if (!pipe_config->gmch_pfit.control)
5861                 return;
5862
5863         /*
5864          * The panel fitter should only be adjusted whilst the pipe is disabled,
5865          * according to register description and PRM.
5866          */
5867         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5868         assert_pipe_disabled(dev_priv, crtc->pipe);
5869
5870         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5871         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5872
5873         /* Border color in case we don't scale up to the full screen. Black by
5874          * default, change to something else for debugging. */
5875         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5876 }
5877
5878 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
5879 {
5880         if (IS_ICELAKE(dev_priv))
5881                 return port >= PORT_C && port <= PORT_F;
5882
5883         return false;
5884 }
5885
5886 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
5887 {
5888         if (!intel_port_is_tc(dev_priv, port))
5889                 return PORT_TC_NONE;
5890
5891         return port - PORT_C;
5892 }
5893
5894 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5895 {
5896         switch (port) {
5897         case PORT_A:
5898                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5899         case PORT_B:
5900                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5901         case PORT_C:
5902                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5903         case PORT_D:
5904                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5905         case PORT_E:
5906                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5907         case PORT_F:
5908                 return POWER_DOMAIN_PORT_DDI_F_LANES;
5909         default:
5910                 MISSING_CASE(port);
5911                 return POWER_DOMAIN_PORT_OTHER;
5912         }
5913 }
5914
5915 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5916                                   struct intel_crtc_state *crtc_state)
5917 {
5918         struct drm_device *dev = crtc->dev;
5919         struct drm_i915_private *dev_priv = to_i915(dev);
5920         struct drm_encoder *encoder;
5921         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5922         enum pipe pipe = intel_crtc->pipe;
5923         u64 mask;
5924         enum transcoder transcoder = crtc_state->cpu_transcoder;
5925
5926         if (!crtc_state->base.active)
5927                 return 0;
5928
5929         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
5930         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
5931         if (crtc_state->pch_pfit.enabled ||
5932             crtc_state->pch_pfit.force_thru)
5933                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5934
5935         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5936                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5937
5938                 mask |= BIT_ULL(intel_encoder->power_domain);
5939         }
5940
5941         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5942                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
5943
5944         if (crtc_state->shared_dpll)
5945                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5946
5947         return mask;
5948 }
5949
5950 static u64
5951 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5952                                struct intel_crtc_state *crtc_state)
5953 {
5954         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5955         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5956         enum intel_display_power_domain domain;
5957         u64 domains, new_domains, old_domains;
5958
5959         old_domains = intel_crtc->enabled_power_domains;
5960         intel_crtc->enabled_power_domains = new_domains =
5961                 get_crtc_power_domains(crtc, crtc_state);
5962
5963         domains = new_domains & ~old_domains;
5964
5965         for_each_power_domain(domain, domains)
5966                 intel_display_power_get(dev_priv, domain);
5967
5968         return old_domains & ~new_domains;
5969 }
5970
5971 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5972                                       u64 domains)
5973 {
5974         enum intel_display_power_domain domain;
5975
5976         for_each_power_domain(domain, domains)
5977                 intel_display_power_put(dev_priv, domain);
5978 }
5979
5980 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5981                                    struct drm_atomic_state *old_state)
5982 {
5983         struct intel_atomic_state *old_intel_state =
5984                 to_intel_atomic_state(old_state);
5985         struct drm_crtc *crtc = pipe_config->base.crtc;
5986         struct drm_device *dev = crtc->dev;
5987         struct drm_i915_private *dev_priv = to_i915(dev);
5988         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5989         int pipe = intel_crtc->pipe;
5990
5991         if (WARN_ON(intel_crtc->active))
5992                 return;
5993
5994         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5995                 intel_dp_set_m_n(intel_crtc, M1_N1);
5996
5997         intel_set_pipe_timings(intel_crtc);
5998         intel_set_pipe_src_size(intel_crtc);
5999
6000         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6001                 struct drm_i915_private *dev_priv = to_i915(dev);
6002
6003                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6004                 I915_WRITE(CHV_CANVAS(pipe), 0);
6005         }
6006
6007         i9xx_set_pipeconf(intel_crtc);
6008
6009         intel_crtc->active = true;
6010
6011         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6012
6013         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6014
6015         if (IS_CHERRYVIEW(dev_priv)) {
6016                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6017                 chv_enable_pll(intel_crtc, intel_crtc->config);
6018         } else {
6019                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6020                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6021         }
6022
6023         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6024
6025         i9xx_pfit_enable(intel_crtc);
6026
6027         intel_color_load_luts(&pipe_config->base);
6028
6029         dev_priv->display.initial_watermarks(old_intel_state,
6030                                              pipe_config);
6031         intel_enable_pipe(pipe_config);
6032
6033         assert_vblank_disabled(crtc);
6034         drm_crtc_vblank_on(crtc);
6035
6036         intel_encoders_enable(crtc, pipe_config, old_state);
6037 }
6038
6039 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6040 {
6041         struct drm_device *dev = crtc->base.dev;
6042         struct drm_i915_private *dev_priv = to_i915(dev);
6043
6044         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6045         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6046 }
6047
6048 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6049                              struct drm_atomic_state *old_state)
6050 {
6051         struct intel_atomic_state *old_intel_state =
6052                 to_intel_atomic_state(old_state);
6053         struct drm_crtc *crtc = pipe_config->base.crtc;
6054         struct drm_device *dev = crtc->dev;
6055         struct drm_i915_private *dev_priv = to_i915(dev);
6056         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6057         enum pipe pipe = intel_crtc->pipe;
6058
6059         if (WARN_ON(intel_crtc->active))
6060                 return;
6061
6062         i9xx_set_pll_dividers(intel_crtc);
6063
6064         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6065                 intel_dp_set_m_n(intel_crtc, M1_N1);
6066
6067         intel_set_pipe_timings(intel_crtc);
6068         intel_set_pipe_src_size(intel_crtc);
6069
6070         i9xx_set_pipeconf(intel_crtc);
6071
6072         intel_crtc->active = true;
6073
6074         if (!IS_GEN2(dev_priv))
6075                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6076
6077         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6078
6079         i9xx_enable_pll(intel_crtc, pipe_config);
6080
6081         i9xx_pfit_enable(intel_crtc);
6082
6083         intel_color_load_luts(&pipe_config->base);
6084
6085         if (dev_priv->display.initial_watermarks != NULL)
6086                 dev_priv->display.initial_watermarks(old_intel_state,
6087                                                      intel_crtc->config);
6088         else
6089                 intel_update_watermarks(intel_crtc);
6090         intel_enable_pipe(pipe_config);
6091
6092         assert_vblank_disabled(crtc);
6093         drm_crtc_vblank_on(crtc);
6094
6095         intel_encoders_enable(crtc, pipe_config, old_state);
6096 }
6097
6098 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6099 {
6100         struct drm_device *dev = crtc->base.dev;
6101         struct drm_i915_private *dev_priv = to_i915(dev);
6102
6103         if (!crtc->config->gmch_pfit.control)
6104                 return;
6105
6106         assert_pipe_disabled(dev_priv, crtc->pipe);
6107
6108         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
6109                          I915_READ(PFIT_CONTROL));
6110         I915_WRITE(PFIT_CONTROL, 0);
6111 }
6112
6113 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6114                               struct drm_atomic_state *old_state)
6115 {
6116         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6117         struct drm_device *dev = crtc->dev;
6118         struct drm_i915_private *dev_priv = to_i915(dev);
6119         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6120         int pipe = intel_crtc->pipe;
6121
6122         /*
6123          * On gen2 planes are double buffered but the pipe isn't, so we must
6124          * wait for planes to fully turn off before disabling the pipe.
6125          */
6126         if (IS_GEN2(dev_priv))
6127                 intel_wait_for_vblank(dev_priv, pipe);
6128
6129         intel_encoders_disable(crtc, old_crtc_state, old_state);
6130
6131         drm_crtc_vblank_off(crtc);
6132         assert_vblank_disabled(crtc);
6133
6134         intel_disable_pipe(old_crtc_state);
6135
6136         i9xx_pfit_disable(intel_crtc);
6137
6138         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6139
6140         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6141                 if (IS_CHERRYVIEW(dev_priv))
6142                         chv_disable_pll(dev_priv, pipe);
6143                 else if (IS_VALLEYVIEW(dev_priv))
6144                         vlv_disable_pll(dev_priv, pipe);
6145                 else
6146                         i9xx_disable_pll(intel_crtc);
6147         }
6148
6149         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6150
6151         if (!IS_GEN2(dev_priv))
6152                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6153
6154         if (!dev_priv->display.initial_watermarks)
6155                 intel_update_watermarks(intel_crtc);
6156
6157         /* clock the pipe down to 640x480@60 to potentially save power */
6158         if (IS_I830(dev_priv))
6159                 i830_enable_pipe(dev_priv, pipe);
6160 }
6161
6162 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6163                                         struct drm_modeset_acquire_ctx *ctx)
6164 {
6165         struct intel_encoder *encoder;
6166         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6167         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6168         enum intel_display_power_domain domain;
6169         struct intel_plane *plane;
6170         u64 domains;
6171         struct drm_atomic_state *state;
6172         struct intel_crtc_state *crtc_state;
6173         int ret;
6174
6175         if (!intel_crtc->active)
6176                 return;
6177
6178         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6179                 const struct intel_plane_state *plane_state =
6180                         to_intel_plane_state(plane->base.state);
6181
6182                 if (plane_state->base.visible)
6183                         intel_plane_disable_noatomic(intel_crtc, plane);
6184         }
6185
6186         state = drm_atomic_state_alloc(crtc->dev);
6187         if (!state) {
6188                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6189                               crtc->base.id, crtc->name);
6190                 return;
6191         }
6192
6193         state->acquire_ctx = ctx;
6194
6195         /* Everything's already locked, -EDEADLK can't happen. */
6196         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6197         ret = drm_atomic_add_affected_connectors(state, crtc);
6198
6199         WARN_ON(IS_ERR(crtc_state) || ret);
6200
6201         dev_priv->display.crtc_disable(crtc_state, state);
6202
6203         drm_atomic_state_put(state);
6204
6205         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6206                       crtc->base.id, crtc->name);
6207
6208         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6209         crtc->state->active = false;
6210         intel_crtc->active = false;
6211         crtc->enabled = false;
6212         crtc->state->connector_mask = 0;
6213         crtc->state->encoder_mask = 0;
6214
6215         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6216                 encoder->base.crtc = NULL;
6217
6218         intel_fbc_disable(intel_crtc);
6219         intel_update_watermarks(intel_crtc);
6220         intel_disable_shared_dpll(intel_crtc);
6221
6222         domains = intel_crtc->enabled_power_domains;
6223         for_each_power_domain(domain, domains)
6224                 intel_display_power_put(dev_priv, domain);
6225         intel_crtc->enabled_power_domains = 0;
6226
6227         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6228         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6229         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6230 }
6231
6232 /*
6233  * turn all crtc's off, but do not adjust state
6234  * This has to be paired with a call to intel_modeset_setup_hw_state.
6235  */
6236 int intel_display_suspend(struct drm_device *dev)
6237 {
6238         struct drm_i915_private *dev_priv = to_i915(dev);
6239         struct drm_atomic_state *state;
6240         int ret;
6241
6242         state = drm_atomic_helper_suspend(dev);
6243         ret = PTR_ERR_OR_ZERO(state);
6244         if (ret)
6245                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6246         else
6247                 dev_priv->modeset_restore_state = state;
6248         return ret;
6249 }
6250
6251 void intel_encoder_destroy(struct drm_encoder *encoder)
6252 {
6253         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6254
6255         drm_encoder_cleanup(encoder);
6256         kfree(intel_encoder);
6257 }
6258
6259 /* Cross check the actual hw state with our own modeset state tracking (and it's
6260  * internal consistency). */
6261 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6262                                          struct drm_connector_state *conn_state)
6263 {
6264         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6265
6266         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6267                       connector->base.base.id,
6268                       connector->base.name);
6269
6270         if (connector->get_hw_state(connector)) {
6271                 struct intel_encoder *encoder = connector->encoder;
6272
6273                 I915_STATE_WARN(!crtc_state,
6274                          "connector enabled without attached crtc\n");
6275
6276                 if (!crtc_state)
6277                         return;
6278
6279                 I915_STATE_WARN(!crtc_state->active,
6280                       "connector is active, but attached crtc isn't\n");
6281
6282                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6283                         return;
6284
6285                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6286                         "atomic encoder doesn't match attached encoder\n");
6287
6288                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6289                         "attached encoder crtc differs from connector crtc\n");
6290         } else {
6291                 I915_STATE_WARN(crtc_state && crtc_state->active,
6292                         "attached crtc is active, but connector isn't\n");
6293                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6294                         "best encoder set without crtc!\n");
6295         }
6296 }
6297
6298 int intel_connector_init(struct intel_connector *connector)
6299 {
6300         struct intel_digital_connector_state *conn_state;
6301
6302         /*
6303          * Allocate enough memory to hold intel_digital_connector_state,
6304          * This might be a few bytes too many, but for connectors that don't
6305          * need it we'll free the state and allocate a smaller one on the first
6306          * succesful commit anyway.
6307          */
6308         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
6309         if (!conn_state)
6310                 return -ENOMEM;
6311
6312         __drm_atomic_helper_connector_reset(&connector->base,
6313                                             &conn_state->base);
6314
6315         return 0;
6316 }
6317
6318 struct intel_connector *intel_connector_alloc(void)
6319 {
6320         struct intel_connector *connector;
6321
6322         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6323         if (!connector)
6324                 return NULL;
6325
6326         if (intel_connector_init(connector) < 0) {
6327                 kfree(connector);
6328                 return NULL;
6329         }
6330
6331         return connector;
6332 }
6333
6334 /*
6335  * Free the bits allocated by intel_connector_alloc.
6336  * This should only be used after intel_connector_alloc has returned
6337  * successfully, and before drm_connector_init returns successfully.
6338  * Otherwise the destroy callbacks for the connector and the state should
6339  * take care of proper cleanup/free
6340  */
6341 void intel_connector_free(struct intel_connector *connector)
6342 {
6343         kfree(to_intel_digital_connector_state(connector->base.state));
6344         kfree(connector);
6345 }
6346
6347 /* Simple connector->get_hw_state implementation for encoders that support only
6348  * one connector and no cloning and hence the encoder state determines the state
6349  * of the connector. */
6350 bool intel_connector_get_hw_state(struct intel_connector *connector)
6351 {
6352         enum pipe pipe = 0;
6353         struct intel_encoder *encoder = connector->encoder;
6354
6355         return encoder->get_hw_state(encoder, &pipe);
6356 }
6357
6358 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6359 {
6360         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6361                 return crtc_state->fdi_lanes;
6362
6363         return 0;
6364 }
6365
6366 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6367                                      struct intel_crtc_state *pipe_config)
6368 {
6369         struct drm_i915_private *dev_priv = to_i915(dev);
6370         struct drm_atomic_state *state = pipe_config->base.state;
6371         struct intel_crtc *other_crtc;
6372         struct intel_crtc_state *other_crtc_state;
6373
6374         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6375                       pipe_name(pipe), pipe_config->fdi_lanes);
6376         if (pipe_config->fdi_lanes > 4) {
6377                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6378                               pipe_name(pipe), pipe_config->fdi_lanes);
6379                 return -EINVAL;
6380         }
6381
6382         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6383                 if (pipe_config->fdi_lanes > 2) {
6384                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6385                                       pipe_config->fdi_lanes);
6386                         return -EINVAL;
6387                 } else {
6388                         return 0;
6389                 }
6390         }
6391
6392         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6393                 return 0;
6394
6395         /* Ivybridge 3 pipe is really complicated */
6396         switch (pipe) {
6397         case PIPE_A:
6398                 return 0;
6399         case PIPE_B:
6400                 if (pipe_config->fdi_lanes <= 2)
6401                         return 0;
6402
6403                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6404                 other_crtc_state =
6405                         intel_atomic_get_crtc_state(state, other_crtc);
6406                 if (IS_ERR(other_crtc_state))
6407                         return PTR_ERR(other_crtc_state);
6408
6409                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6410                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6411                                       pipe_name(pipe), pipe_config->fdi_lanes);
6412                         return -EINVAL;
6413                 }
6414                 return 0;
6415         case PIPE_C:
6416                 if (pipe_config->fdi_lanes > 2) {
6417                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6418                                       pipe_name(pipe), pipe_config->fdi_lanes);
6419                         return -EINVAL;
6420                 }
6421
6422                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6423                 other_crtc_state =
6424                         intel_atomic_get_crtc_state(state, other_crtc);
6425                 if (IS_ERR(other_crtc_state))
6426                         return PTR_ERR(other_crtc_state);
6427
6428                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6429                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6430                         return -EINVAL;
6431                 }
6432                 return 0;
6433         default:
6434                 BUG();
6435         }
6436 }
6437
6438 #define RETRY 1
6439 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6440                                        struct intel_crtc_state *pipe_config)
6441 {
6442         struct drm_device *dev = intel_crtc->base.dev;
6443         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6444         int lane, link_bw, fdi_dotclock, ret;
6445         bool needs_recompute = false;
6446
6447 retry:
6448         /* FDI is a binary signal running at ~2.7GHz, encoding
6449          * each output octet as 10 bits. The actual frequency
6450          * is stored as a divider into a 100MHz clock, and the
6451          * mode pixel clock is stored in units of 1KHz.
6452          * Hence the bw of each lane in terms of the mode signal
6453          * is:
6454          */
6455         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6456
6457         fdi_dotclock = adjusted_mode->crtc_clock;
6458
6459         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6460                                            pipe_config->pipe_bpp);
6461
6462         pipe_config->fdi_lanes = lane;
6463
6464         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6465                                link_bw, &pipe_config->fdi_m_n, false);
6466
6467         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6468         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6469                 pipe_config->pipe_bpp -= 2*3;
6470                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6471                               pipe_config->pipe_bpp);
6472                 needs_recompute = true;
6473                 pipe_config->bw_constrained = true;
6474
6475                 goto retry;
6476         }
6477
6478         if (needs_recompute)
6479                 return RETRY;
6480
6481         return ret;
6482 }
6483
6484 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6485 {
6486         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6487         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6488
6489         /* IPS only exists on ULT machines and is tied to pipe A. */
6490         if (!hsw_crtc_supports_ips(crtc))
6491                 return false;
6492
6493         if (!i915_modparams.enable_ips)
6494                 return false;
6495
6496         if (crtc_state->pipe_bpp > 24)
6497                 return false;
6498
6499         /*
6500          * We compare against max which means we must take
6501          * the increased cdclk requirement into account when
6502          * calculating the new cdclk.
6503          *
6504          * Should measure whether using a lower cdclk w/o IPS
6505          */
6506         if (IS_BROADWELL(dev_priv) &&
6507             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6508                 return false;
6509
6510         return true;
6511 }
6512
6513 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6514 {
6515         struct drm_i915_private *dev_priv =
6516                 to_i915(crtc_state->base.crtc->dev);
6517         struct intel_atomic_state *intel_state =
6518                 to_intel_atomic_state(crtc_state->base.state);
6519
6520         if (!hsw_crtc_state_ips_capable(crtc_state))
6521                 return false;
6522
6523         if (crtc_state->ips_force_disable)
6524                 return false;
6525
6526         /* IPS should be fine as long as at least one plane is enabled. */
6527         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6528                 return false;
6529
6530         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6531         if (IS_BROADWELL(dev_priv) &&
6532             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6533                 return false;
6534
6535         return true;
6536 }
6537
6538 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6539 {
6540         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6541
6542         /* GDG double wide on either pipe, otherwise pipe A only */
6543         return INTEL_GEN(dev_priv) < 4 &&
6544                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6545 }
6546
6547 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6548 {
6549         uint32_t pixel_rate;
6550
6551         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6552
6553         /*
6554          * We only use IF-ID interlacing. If we ever use
6555          * PF-ID we'll need to adjust the pixel_rate here.
6556          */
6557
6558         if (pipe_config->pch_pfit.enabled) {
6559                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6560                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6561
6562                 pipe_w = pipe_config->pipe_src_w;
6563                 pipe_h = pipe_config->pipe_src_h;
6564
6565                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6566                 pfit_h = pfit_size & 0xFFFF;
6567                 if (pipe_w < pfit_w)
6568                         pipe_w = pfit_w;
6569                 if (pipe_h < pfit_h)
6570                         pipe_h = pfit_h;
6571
6572                 if (WARN_ON(!pfit_w || !pfit_h))
6573                         return pixel_rate;
6574
6575                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6576                                      pfit_w * pfit_h);
6577         }
6578
6579         return pixel_rate;
6580 }
6581
6582 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6583 {
6584         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6585
6586         if (HAS_GMCH_DISPLAY(dev_priv))
6587                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6588                 crtc_state->pixel_rate =
6589                         crtc_state->base.adjusted_mode.crtc_clock;
6590         else
6591                 crtc_state->pixel_rate =
6592                         ilk_pipe_pixel_rate(crtc_state);
6593 }
6594
6595 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6596                                      struct intel_crtc_state *pipe_config)
6597 {
6598         struct drm_device *dev = crtc->base.dev;
6599         struct drm_i915_private *dev_priv = to_i915(dev);
6600         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6601         int clock_limit = dev_priv->max_dotclk_freq;
6602
6603         if (INTEL_GEN(dev_priv) < 4) {
6604                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6605
6606                 /*
6607                  * Enable double wide mode when the dot clock
6608                  * is > 90% of the (display) core speed.
6609                  */
6610                 if (intel_crtc_supports_double_wide(crtc) &&
6611                     adjusted_mode->crtc_clock > clock_limit) {
6612                         clock_limit = dev_priv->max_dotclk_freq;
6613                         pipe_config->double_wide = true;
6614                 }
6615         }
6616
6617         if (adjusted_mode->crtc_clock > clock_limit) {
6618                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6619                               adjusted_mode->crtc_clock, clock_limit,
6620                               yesno(pipe_config->double_wide));
6621                 return -EINVAL;
6622         }
6623
6624         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6625                 /*
6626                  * There is only one pipe CSC unit per pipe, and we need that
6627                  * for output conversion from RGB->YCBCR. So if CTM is already
6628                  * applied we can't support YCBCR420 output.
6629                  */
6630                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6631                 return -EINVAL;
6632         }
6633
6634         /*
6635          * Pipe horizontal size must be even in:
6636          * - DVO ganged mode
6637          * - LVDS dual channel mode
6638          * - Double wide pipe
6639          */
6640         if (pipe_config->pipe_src_w & 1) {
6641                 if (pipe_config->double_wide) {
6642                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6643                         return -EINVAL;
6644                 }
6645
6646                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6647                     intel_is_dual_link_lvds(dev)) {
6648                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6649                         return -EINVAL;
6650                 }
6651         }
6652
6653         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6654          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6655          */
6656         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6657                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6658                 return -EINVAL;
6659
6660         intel_crtc_compute_pixel_rate(pipe_config);
6661
6662         if (pipe_config->has_pch_encoder)
6663                 return ironlake_fdi_compute_config(crtc, pipe_config);
6664
6665         return 0;
6666 }
6667
6668 static void
6669 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6670 {
6671         while (*num > DATA_LINK_M_N_MASK ||
6672                *den > DATA_LINK_M_N_MASK) {
6673                 *num >>= 1;
6674                 *den >>= 1;
6675         }
6676 }
6677
6678 static void compute_m_n(unsigned int m, unsigned int n,
6679                         uint32_t *ret_m, uint32_t *ret_n,
6680                         bool reduce_m_n)
6681 {
6682         /*
6683          * Reduce M/N as much as possible without loss in precision. Several DP
6684          * dongles in particular seem to be fussy about too large *link* M/N
6685          * values. The passed in values are more likely to have the least
6686          * significant bits zero than M after rounding below, so do this first.
6687          */
6688         if (reduce_m_n) {
6689                 while ((m & 1) == 0 && (n & 1) == 0) {
6690                         m >>= 1;
6691                         n >>= 1;
6692                 }
6693         }
6694
6695         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6696         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6697         intel_reduce_m_n_ratio(ret_m, ret_n);
6698 }
6699
6700 void
6701 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6702                        int pixel_clock, int link_clock,
6703                        struct intel_link_m_n *m_n,
6704                        bool reduce_m_n)
6705 {
6706         m_n->tu = 64;
6707
6708         compute_m_n(bits_per_pixel * pixel_clock,
6709                     link_clock * nlanes * 8,
6710                     &m_n->gmch_m, &m_n->gmch_n,
6711                     reduce_m_n);
6712
6713         compute_m_n(pixel_clock, link_clock,
6714                     &m_n->link_m, &m_n->link_n,
6715                     reduce_m_n);
6716 }
6717
6718 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6719 {
6720         if (i915_modparams.panel_use_ssc >= 0)
6721                 return i915_modparams.panel_use_ssc != 0;
6722         return dev_priv->vbt.lvds_use_ssc
6723                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6724 }
6725
6726 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6727 {
6728         return (1 << dpll->n) << 16 | dpll->m2;
6729 }
6730
6731 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6732 {
6733         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6734 }
6735
6736 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6737                                      struct intel_crtc_state *crtc_state,
6738                                      struct dpll *reduced_clock)
6739 {
6740         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6741         u32 fp, fp2 = 0;
6742
6743         if (IS_PINEVIEW(dev_priv)) {
6744                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6745                 if (reduced_clock)
6746                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6747         } else {
6748                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6749                 if (reduced_clock)
6750                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6751         }
6752
6753         crtc_state->dpll_hw_state.fp0 = fp;
6754
6755         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6756             reduced_clock) {
6757                 crtc_state->dpll_hw_state.fp1 = fp2;
6758         } else {
6759                 crtc_state->dpll_hw_state.fp1 = fp;
6760         }
6761 }
6762
6763 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6764                 pipe)
6765 {
6766         u32 reg_val;
6767
6768         /*
6769          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6770          * and set it to a reasonable value instead.
6771          */
6772         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6773         reg_val &= 0xffffff00;
6774         reg_val |= 0x00000030;
6775         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6776
6777         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6778         reg_val &= 0x00ffffff;
6779         reg_val |= 0x8c000000;
6780         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6781
6782         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6783         reg_val &= 0xffffff00;
6784         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6785
6786         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6787         reg_val &= 0x00ffffff;
6788         reg_val |= 0xb0000000;
6789         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6790 }
6791
6792 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6793                                          struct intel_link_m_n *m_n)
6794 {
6795         struct drm_device *dev = crtc->base.dev;
6796         struct drm_i915_private *dev_priv = to_i915(dev);
6797         int pipe = crtc->pipe;
6798
6799         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6800         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6801         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6802         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6803 }
6804
6805 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6806                                          struct intel_link_m_n *m_n,
6807                                          struct intel_link_m_n *m2_n2)
6808 {
6809         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6810         int pipe = crtc->pipe;
6811         enum transcoder transcoder = crtc->config->cpu_transcoder;
6812
6813         if (INTEL_GEN(dev_priv) >= 5) {
6814                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6815                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6816                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6817                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6818                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6819                  * for gen < 8) and if DRRS is supported (to make sure the
6820                  * registers are not unnecessarily accessed).
6821                  */
6822                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6823                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6824                         I915_WRITE(PIPE_DATA_M2(transcoder),
6825                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6826                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6827                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6828                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6829                 }
6830         } else {
6831                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6832                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6833                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6834                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6835         }
6836 }
6837
6838 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6839 {
6840         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6841
6842         if (m_n == M1_N1) {
6843                 dp_m_n = &crtc->config->dp_m_n;
6844                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6845         } else if (m_n == M2_N2) {
6846
6847                 /*
6848                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6849                  * needs to be programmed into M1_N1.
6850                  */
6851                 dp_m_n = &crtc->config->dp_m2_n2;
6852         } else {
6853                 DRM_ERROR("Unsupported divider value\n");
6854                 return;
6855         }
6856
6857         if (crtc->config->has_pch_encoder)
6858                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6859         else
6860                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6861 }
6862
6863 static void vlv_compute_dpll(struct intel_crtc *crtc,
6864                              struct intel_crtc_state *pipe_config)
6865 {
6866         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6867                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6868         if (crtc->pipe != PIPE_A)
6869                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6870
6871         /* DPLL not used with DSI, but still need the rest set up */
6872         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6873                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6874                         DPLL_EXT_BUFFER_ENABLE_VLV;
6875
6876         pipe_config->dpll_hw_state.dpll_md =
6877                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6878 }
6879
6880 static void chv_compute_dpll(struct intel_crtc *crtc,
6881                              struct intel_crtc_state *pipe_config)
6882 {
6883         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6884                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6885         if (crtc->pipe != PIPE_A)
6886                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6887
6888         /* DPLL not used with DSI, but still need the rest set up */
6889         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6890                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6891
6892         pipe_config->dpll_hw_state.dpll_md =
6893                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6894 }
6895
6896 static void vlv_prepare_pll(struct intel_crtc *crtc,
6897                             const struct intel_crtc_state *pipe_config)
6898 {
6899         struct drm_device *dev = crtc->base.dev;
6900         struct drm_i915_private *dev_priv = to_i915(dev);
6901         enum pipe pipe = crtc->pipe;
6902         u32 mdiv;
6903         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6904         u32 coreclk, reg_val;
6905
6906         /* Enable Refclk */
6907         I915_WRITE(DPLL(pipe),
6908                    pipe_config->dpll_hw_state.dpll &
6909                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6910
6911         /* No need to actually set up the DPLL with DSI */
6912         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6913                 return;
6914
6915         mutex_lock(&dev_priv->sb_lock);
6916
6917         bestn = pipe_config->dpll.n;
6918         bestm1 = pipe_config->dpll.m1;
6919         bestm2 = pipe_config->dpll.m2;
6920         bestp1 = pipe_config->dpll.p1;
6921         bestp2 = pipe_config->dpll.p2;
6922
6923         /* See eDP HDMI DPIO driver vbios notes doc */
6924
6925         /* PLL B needs special handling */
6926         if (pipe == PIPE_B)
6927                 vlv_pllb_recal_opamp(dev_priv, pipe);
6928
6929         /* Set up Tx target for periodic Rcomp update */
6930         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6931
6932         /* Disable target IRef on PLL */
6933         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6934         reg_val &= 0x00ffffff;
6935         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6936
6937         /* Disable fast lock */
6938         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6939
6940         /* Set idtafcrecal before PLL is enabled */
6941         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6942         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6943         mdiv |= ((bestn << DPIO_N_SHIFT));
6944         mdiv |= (1 << DPIO_K_SHIFT);
6945
6946         /*
6947          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6948          * but we don't support that).
6949          * Note: don't use the DAC post divider as it seems unstable.
6950          */
6951         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6952         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6953
6954         mdiv |= DPIO_ENABLE_CALIBRATION;
6955         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6956
6957         /* Set HBR and RBR LPF coefficients */
6958         if (pipe_config->port_clock == 162000 ||
6959             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6960             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6961                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6962                                  0x009f0003);
6963         else
6964                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6965                                  0x00d0000f);
6966
6967         if (intel_crtc_has_dp_encoder(pipe_config)) {
6968                 /* Use SSC source */
6969                 if (pipe == PIPE_A)
6970                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6971                                          0x0df40000);
6972                 else
6973                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6974                                          0x0df70000);
6975         } else { /* HDMI or VGA */
6976                 /* Use bend source */
6977                 if (pipe == PIPE_A)
6978                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6979                                          0x0df70000);
6980                 else
6981                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6982                                          0x0df40000);
6983         }
6984
6985         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6986         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6987         if (intel_crtc_has_dp_encoder(crtc->config))
6988                 coreclk |= 0x01000000;
6989         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6990
6991         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6992         mutex_unlock(&dev_priv->sb_lock);
6993 }
6994
6995 static void chv_prepare_pll(struct intel_crtc *crtc,
6996                             const struct intel_crtc_state *pipe_config)
6997 {
6998         struct drm_device *dev = crtc->base.dev;
6999         struct drm_i915_private *dev_priv = to_i915(dev);
7000         enum pipe pipe = crtc->pipe;
7001         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7002         u32 loopfilter, tribuf_calcntr;
7003         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7004         u32 dpio_val;
7005         int vco;
7006
7007         /* Enable Refclk and SSC */
7008         I915_WRITE(DPLL(pipe),
7009                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7010
7011         /* No need to actually set up the DPLL with DSI */
7012         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7013                 return;
7014
7015         bestn = pipe_config->dpll.n;
7016         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7017         bestm1 = pipe_config->dpll.m1;
7018         bestm2 = pipe_config->dpll.m2 >> 22;
7019         bestp1 = pipe_config->dpll.p1;
7020         bestp2 = pipe_config->dpll.p2;
7021         vco = pipe_config->dpll.vco;
7022         dpio_val = 0;
7023         loopfilter = 0;
7024
7025         mutex_lock(&dev_priv->sb_lock);
7026
7027         /* p1 and p2 divider */
7028         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7029                         5 << DPIO_CHV_S1_DIV_SHIFT |
7030                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7031                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7032                         1 << DPIO_CHV_K_DIV_SHIFT);
7033
7034         /* Feedback post-divider - m2 */
7035         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7036
7037         /* Feedback refclk divider - n and m1 */
7038         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7039                         DPIO_CHV_M1_DIV_BY_2 |
7040                         1 << DPIO_CHV_N_DIV_SHIFT);
7041
7042         /* M2 fraction division */
7043         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7044
7045         /* M2 fraction division enable */
7046         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7047         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7048         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7049         if (bestm2_frac)
7050                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7051         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7052
7053         /* Program digital lock detect threshold */
7054         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7055         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7056                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7057         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7058         if (!bestm2_frac)
7059                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7060         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7061
7062         /* Loop filter */
7063         if (vco == 5400000) {
7064                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7065                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7066                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7067                 tribuf_calcntr = 0x9;
7068         } else if (vco <= 6200000) {
7069                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7070                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7071                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7072                 tribuf_calcntr = 0x9;
7073         } else if (vco <= 6480000) {
7074                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7075                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7076                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7077                 tribuf_calcntr = 0x8;
7078         } else {
7079                 /* Not supported. Apply the same limits as in the max case */
7080                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7081                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7082                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7083                 tribuf_calcntr = 0;
7084         }
7085         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7086
7087         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7088         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7089         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7090         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7091
7092         /* AFC Recal */
7093         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7094                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7095                         DPIO_AFC_RECAL);
7096
7097         mutex_unlock(&dev_priv->sb_lock);
7098 }
7099
7100 /**
7101  * vlv_force_pll_on - forcibly enable just the PLL
7102  * @dev_priv: i915 private structure
7103  * @pipe: pipe PLL to enable
7104  * @dpll: PLL configuration
7105  *
7106  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7107  * in cases where we need the PLL enabled even when @pipe is not going to
7108  * be enabled.
7109  */
7110 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7111                      const struct dpll *dpll)
7112 {
7113         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7114         struct intel_crtc_state *pipe_config;
7115
7116         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7117         if (!pipe_config)
7118                 return -ENOMEM;
7119
7120         pipe_config->base.crtc = &crtc->base;
7121         pipe_config->pixel_multiplier = 1;
7122         pipe_config->dpll = *dpll;
7123
7124         if (IS_CHERRYVIEW(dev_priv)) {
7125                 chv_compute_dpll(crtc, pipe_config);
7126                 chv_prepare_pll(crtc, pipe_config);
7127                 chv_enable_pll(crtc, pipe_config);
7128         } else {
7129                 vlv_compute_dpll(crtc, pipe_config);
7130                 vlv_prepare_pll(crtc, pipe_config);
7131                 vlv_enable_pll(crtc, pipe_config);
7132         }
7133
7134         kfree(pipe_config);
7135
7136         return 0;
7137 }
7138
7139 /**
7140  * vlv_force_pll_off - forcibly disable just the PLL
7141  * @dev_priv: i915 private structure
7142  * @pipe: pipe PLL to disable
7143  *
7144  * Disable the PLL for @pipe. To be used in cases where we need
7145  * the PLL enabled even when @pipe is not going to be enabled.
7146  */
7147 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7148 {
7149         if (IS_CHERRYVIEW(dev_priv))
7150                 chv_disable_pll(dev_priv, pipe);
7151         else
7152                 vlv_disable_pll(dev_priv, pipe);
7153 }
7154
7155 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7156                               struct intel_crtc_state *crtc_state,
7157                               struct dpll *reduced_clock)
7158 {
7159         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7160         u32 dpll;
7161         struct dpll *clock = &crtc_state->dpll;
7162
7163         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7164
7165         dpll = DPLL_VGA_MODE_DIS;
7166
7167         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7168                 dpll |= DPLLB_MODE_LVDS;
7169         else
7170                 dpll |= DPLLB_MODE_DAC_SERIAL;
7171
7172         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7173             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7174                 dpll |= (crtc_state->pixel_multiplier - 1)
7175                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7176         }
7177
7178         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7179             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7180                 dpll |= DPLL_SDVO_HIGH_SPEED;
7181
7182         if (intel_crtc_has_dp_encoder(crtc_state))
7183                 dpll |= DPLL_SDVO_HIGH_SPEED;
7184
7185         /* compute bitmask from p1 value */
7186         if (IS_PINEVIEW(dev_priv))
7187                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7188         else {
7189                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7190                 if (IS_G4X(dev_priv) && reduced_clock)
7191                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7192         }
7193         switch (clock->p2) {
7194         case 5:
7195                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7196                 break;
7197         case 7:
7198                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7199                 break;
7200         case 10:
7201                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7202                 break;
7203         case 14:
7204                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7205                 break;
7206         }
7207         if (INTEL_GEN(dev_priv) >= 4)
7208                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7209
7210         if (crtc_state->sdvo_tv_clock)
7211                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7212         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7213                  intel_panel_use_ssc(dev_priv))
7214                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7215         else
7216                 dpll |= PLL_REF_INPUT_DREFCLK;
7217
7218         dpll |= DPLL_VCO_ENABLE;
7219         crtc_state->dpll_hw_state.dpll = dpll;
7220
7221         if (INTEL_GEN(dev_priv) >= 4) {
7222                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7223                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7224                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7225         }
7226 }
7227
7228 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7229                               struct intel_crtc_state *crtc_state,
7230                               struct dpll *reduced_clock)
7231 {
7232         struct drm_device *dev = crtc->base.dev;
7233         struct drm_i915_private *dev_priv = to_i915(dev);
7234         u32 dpll;
7235         struct dpll *clock = &crtc_state->dpll;
7236
7237         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7238
7239         dpll = DPLL_VGA_MODE_DIS;
7240
7241         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7242                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7243         } else {
7244                 if (clock->p1 == 2)
7245                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7246                 else
7247                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7248                 if (clock->p2 == 4)
7249                         dpll |= PLL_P2_DIVIDE_BY_4;
7250         }
7251
7252         if (!IS_I830(dev_priv) &&
7253             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7254                 dpll |= DPLL_DVO_2X_MODE;
7255
7256         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7257             intel_panel_use_ssc(dev_priv))
7258                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7259         else
7260                 dpll |= PLL_REF_INPUT_DREFCLK;
7261
7262         dpll |= DPLL_VCO_ENABLE;
7263         crtc_state->dpll_hw_state.dpll = dpll;
7264 }
7265
7266 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7267 {
7268         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7269         enum pipe pipe = intel_crtc->pipe;
7270         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7271         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7272         uint32_t crtc_vtotal, crtc_vblank_end;
7273         int vsyncshift = 0;
7274
7275         /* We need to be careful not to changed the adjusted mode, for otherwise
7276          * the hw state checker will get angry at the mismatch. */
7277         crtc_vtotal = adjusted_mode->crtc_vtotal;
7278         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7279
7280         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7281                 /* the chip adds 2 halflines automatically */
7282                 crtc_vtotal -= 1;
7283                 crtc_vblank_end -= 1;
7284
7285                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7286                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7287                 else
7288                         vsyncshift = adjusted_mode->crtc_hsync_start -
7289                                 adjusted_mode->crtc_htotal / 2;
7290                 if (vsyncshift < 0)
7291                         vsyncshift += adjusted_mode->crtc_htotal;
7292         }
7293
7294         if (INTEL_GEN(dev_priv) > 3)
7295                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7296
7297         I915_WRITE(HTOTAL(cpu_transcoder),
7298                    (adjusted_mode->crtc_hdisplay - 1) |
7299                    ((adjusted_mode->crtc_htotal - 1) << 16));
7300         I915_WRITE(HBLANK(cpu_transcoder),
7301                    (adjusted_mode->crtc_hblank_start - 1) |
7302                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7303         I915_WRITE(HSYNC(cpu_transcoder),
7304                    (adjusted_mode->crtc_hsync_start - 1) |
7305                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7306
7307         I915_WRITE(VTOTAL(cpu_transcoder),
7308                    (adjusted_mode->crtc_vdisplay - 1) |
7309                    ((crtc_vtotal - 1) << 16));
7310         I915_WRITE(VBLANK(cpu_transcoder),
7311                    (adjusted_mode->crtc_vblank_start - 1) |
7312                    ((crtc_vblank_end - 1) << 16));
7313         I915_WRITE(VSYNC(cpu_transcoder),
7314                    (adjusted_mode->crtc_vsync_start - 1) |
7315                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7316
7317         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7318          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7319          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7320          * bits. */
7321         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7322             (pipe == PIPE_B || pipe == PIPE_C))
7323                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7324
7325 }
7326
7327 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7328 {
7329         struct drm_device *dev = intel_crtc->base.dev;
7330         struct drm_i915_private *dev_priv = to_i915(dev);
7331         enum pipe pipe = intel_crtc->pipe;
7332
7333         /* pipesrc controls the size that is scaled from, which should
7334          * always be the user's requested size.
7335          */
7336         I915_WRITE(PIPESRC(pipe),
7337                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7338                    (intel_crtc->config->pipe_src_h - 1));
7339 }
7340
7341 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7342                                    struct intel_crtc_state *pipe_config)
7343 {
7344         struct drm_device *dev = crtc->base.dev;
7345         struct drm_i915_private *dev_priv = to_i915(dev);
7346         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7347         uint32_t tmp;
7348
7349         tmp = I915_READ(HTOTAL(cpu_transcoder));
7350         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7351         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7352         tmp = I915_READ(HBLANK(cpu_transcoder));
7353         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7354         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7355         tmp = I915_READ(HSYNC(cpu_transcoder));
7356         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7357         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7358
7359         tmp = I915_READ(VTOTAL(cpu_transcoder));
7360         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7361         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7362         tmp = I915_READ(VBLANK(cpu_transcoder));
7363         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7364         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7365         tmp = I915_READ(VSYNC(cpu_transcoder));
7366         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7367         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7368
7369         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7370                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7371                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7372                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7373         }
7374 }
7375
7376 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7377                                     struct intel_crtc_state *pipe_config)
7378 {
7379         struct drm_device *dev = crtc->base.dev;
7380         struct drm_i915_private *dev_priv = to_i915(dev);
7381         u32 tmp;
7382
7383         tmp = I915_READ(PIPESRC(crtc->pipe));
7384         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7385         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7386
7387         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7388         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7389 }
7390
7391 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7392                                  struct intel_crtc_state *pipe_config)
7393 {
7394         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7395         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7396         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7397         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7398
7399         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7400         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7401         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7402         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7403
7404         mode->flags = pipe_config->base.adjusted_mode.flags;
7405         mode->type = DRM_MODE_TYPE_DRIVER;
7406
7407         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7408
7409         mode->hsync = drm_mode_hsync(mode);
7410         mode->vrefresh = drm_mode_vrefresh(mode);
7411         drm_mode_set_name(mode);
7412 }
7413
7414 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7415 {
7416         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7417         uint32_t pipeconf;
7418
7419         pipeconf = 0;
7420
7421         /* we keep both pipes enabled on 830 */
7422         if (IS_I830(dev_priv))
7423                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7424
7425         if (intel_crtc->config->double_wide)
7426                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7427
7428         /* only g4x and later have fancy bpc/dither controls */
7429         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7430             IS_CHERRYVIEW(dev_priv)) {
7431                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7432                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7433                         pipeconf |= PIPECONF_DITHER_EN |
7434                                     PIPECONF_DITHER_TYPE_SP;
7435
7436                 switch (intel_crtc->config->pipe_bpp) {
7437                 case 18:
7438                         pipeconf |= PIPECONF_6BPC;
7439                         break;
7440                 case 24:
7441                         pipeconf |= PIPECONF_8BPC;
7442                         break;
7443                 case 30:
7444                         pipeconf |= PIPECONF_10BPC;
7445                         break;
7446                 default:
7447                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7448                         BUG();
7449                 }
7450         }
7451
7452         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7453                 if (INTEL_GEN(dev_priv) < 4 ||
7454                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7455                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7456                 else
7457                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7458         } else
7459                 pipeconf |= PIPECONF_PROGRESSIVE;
7460
7461         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7462              intel_crtc->config->limited_color_range)
7463                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7464
7465         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7466         POSTING_READ(PIPECONF(intel_crtc->pipe));
7467 }
7468
7469 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7470                                    struct intel_crtc_state *crtc_state)
7471 {
7472         struct drm_device *dev = crtc->base.dev;
7473         struct drm_i915_private *dev_priv = to_i915(dev);
7474         const struct intel_limit *limit;
7475         int refclk = 48000;
7476
7477         memset(&crtc_state->dpll_hw_state, 0,
7478                sizeof(crtc_state->dpll_hw_state));
7479
7480         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7481                 if (intel_panel_use_ssc(dev_priv)) {
7482                         refclk = dev_priv->vbt.lvds_ssc_freq;
7483                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7484                 }
7485
7486                 limit = &intel_limits_i8xx_lvds;
7487         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7488                 limit = &intel_limits_i8xx_dvo;
7489         } else {
7490                 limit = &intel_limits_i8xx_dac;
7491         }
7492
7493         if (!crtc_state->clock_set &&
7494             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7495                                  refclk, NULL, &crtc_state->dpll)) {
7496                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7497                 return -EINVAL;
7498         }
7499
7500         i8xx_compute_dpll(crtc, crtc_state, NULL);
7501
7502         return 0;
7503 }
7504
7505 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7506                                   struct intel_crtc_state *crtc_state)
7507 {
7508         struct drm_device *dev = crtc->base.dev;
7509         struct drm_i915_private *dev_priv = to_i915(dev);
7510         const struct intel_limit *limit;
7511         int refclk = 96000;
7512
7513         memset(&crtc_state->dpll_hw_state, 0,
7514                sizeof(crtc_state->dpll_hw_state));
7515
7516         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7517                 if (intel_panel_use_ssc(dev_priv)) {
7518                         refclk = dev_priv->vbt.lvds_ssc_freq;
7519                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7520                 }
7521
7522                 if (intel_is_dual_link_lvds(dev))
7523                         limit = &intel_limits_g4x_dual_channel_lvds;
7524                 else
7525                         limit = &intel_limits_g4x_single_channel_lvds;
7526         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7527                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7528                 limit = &intel_limits_g4x_hdmi;
7529         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7530                 limit = &intel_limits_g4x_sdvo;
7531         } else {
7532                 /* The option is for other outputs */
7533                 limit = &intel_limits_i9xx_sdvo;
7534         }
7535
7536         if (!crtc_state->clock_set &&
7537             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7538                                 refclk, NULL, &crtc_state->dpll)) {
7539                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7540                 return -EINVAL;
7541         }
7542
7543         i9xx_compute_dpll(crtc, crtc_state, NULL);
7544
7545         return 0;
7546 }
7547
7548 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7549                                   struct intel_crtc_state *crtc_state)
7550 {
7551         struct drm_device *dev = crtc->base.dev;
7552         struct drm_i915_private *dev_priv = to_i915(dev);
7553         const struct intel_limit *limit;
7554         int refclk = 96000;
7555
7556         memset(&crtc_state->dpll_hw_state, 0,
7557                sizeof(crtc_state->dpll_hw_state));
7558
7559         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7560                 if (intel_panel_use_ssc(dev_priv)) {
7561                         refclk = dev_priv->vbt.lvds_ssc_freq;
7562                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7563                 }
7564
7565                 limit = &intel_limits_pineview_lvds;
7566         } else {
7567                 limit = &intel_limits_pineview_sdvo;
7568         }
7569
7570         if (!crtc_state->clock_set &&
7571             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7572                                 refclk, NULL, &crtc_state->dpll)) {
7573                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7574                 return -EINVAL;
7575         }
7576
7577         i9xx_compute_dpll(crtc, crtc_state, NULL);
7578
7579         return 0;
7580 }
7581
7582 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7583                                    struct intel_crtc_state *crtc_state)
7584 {
7585         struct drm_device *dev = crtc->base.dev;
7586         struct drm_i915_private *dev_priv = to_i915(dev);
7587         const struct intel_limit *limit;
7588         int refclk = 96000;
7589
7590         memset(&crtc_state->dpll_hw_state, 0,
7591                sizeof(crtc_state->dpll_hw_state));
7592
7593         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7594                 if (intel_panel_use_ssc(dev_priv)) {
7595                         refclk = dev_priv->vbt.lvds_ssc_freq;
7596                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7597                 }
7598
7599                 limit = &intel_limits_i9xx_lvds;
7600         } else {
7601                 limit = &intel_limits_i9xx_sdvo;
7602         }
7603
7604         if (!crtc_state->clock_set &&
7605             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7606                                  refclk, NULL, &crtc_state->dpll)) {
7607                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7608                 return -EINVAL;
7609         }
7610
7611         i9xx_compute_dpll(crtc, crtc_state, NULL);
7612
7613         return 0;
7614 }
7615
7616 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7617                                   struct intel_crtc_state *crtc_state)
7618 {
7619         int refclk = 100000;
7620         const struct intel_limit *limit = &intel_limits_chv;
7621
7622         memset(&crtc_state->dpll_hw_state, 0,
7623                sizeof(crtc_state->dpll_hw_state));
7624
7625         if (!crtc_state->clock_set &&
7626             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7627                                 refclk, NULL, &crtc_state->dpll)) {
7628                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7629                 return -EINVAL;
7630         }
7631
7632         chv_compute_dpll(crtc, crtc_state);
7633
7634         return 0;
7635 }
7636
7637 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7638                                   struct intel_crtc_state *crtc_state)
7639 {
7640         int refclk = 100000;
7641         const struct intel_limit *limit = &intel_limits_vlv;
7642
7643         memset(&crtc_state->dpll_hw_state, 0,
7644                sizeof(crtc_state->dpll_hw_state));
7645
7646         if (!crtc_state->clock_set &&
7647             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7648                                 refclk, NULL, &crtc_state->dpll)) {
7649                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7650                 return -EINVAL;
7651         }
7652
7653         vlv_compute_dpll(crtc, crtc_state);
7654
7655         return 0;
7656 }
7657
7658 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7659                                  struct intel_crtc_state *pipe_config)
7660 {
7661         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7662         uint32_t tmp;
7663
7664         if (INTEL_GEN(dev_priv) <= 3 &&
7665             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7666                 return;
7667
7668         tmp = I915_READ(PFIT_CONTROL);
7669         if (!(tmp & PFIT_ENABLE))
7670                 return;
7671
7672         /* Check whether the pfit is attached to our pipe. */
7673         if (INTEL_GEN(dev_priv) < 4) {
7674                 if (crtc->pipe != PIPE_B)
7675                         return;
7676         } else {
7677                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7678                         return;
7679         }
7680
7681         pipe_config->gmch_pfit.control = tmp;
7682         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7683 }
7684
7685 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7686                                struct intel_crtc_state *pipe_config)
7687 {
7688         struct drm_device *dev = crtc->base.dev;
7689         struct drm_i915_private *dev_priv = to_i915(dev);
7690         int pipe = pipe_config->cpu_transcoder;
7691         struct dpll clock;
7692         u32 mdiv;
7693         int refclk = 100000;
7694
7695         /* In case of DSI, DPLL will not be used */
7696         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7697                 return;
7698
7699         mutex_lock(&dev_priv->sb_lock);
7700         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7701         mutex_unlock(&dev_priv->sb_lock);
7702
7703         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7704         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7705         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7706         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7707         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7708
7709         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7710 }
7711
7712 static void
7713 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7714                               struct intel_initial_plane_config *plane_config)
7715 {
7716         struct drm_device *dev = crtc->base.dev;
7717         struct drm_i915_private *dev_priv = to_i915(dev);
7718         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7719         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7720         enum pipe pipe;
7721         u32 val, base, offset;
7722         int fourcc, pixel_format;
7723         unsigned int aligned_height;
7724         struct drm_framebuffer *fb;
7725         struct intel_framebuffer *intel_fb;
7726
7727         if (!plane->get_hw_state(plane, &pipe))
7728                 return;
7729
7730         WARN_ON(pipe != crtc->pipe);
7731
7732         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7733         if (!intel_fb) {
7734                 DRM_DEBUG_KMS("failed to alloc fb\n");
7735                 return;
7736         }
7737
7738         fb = &intel_fb->base;
7739
7740         fb->dev = dev;
7741
7742         val = I915_READ(DSPCNTR(i9xx_plane));
7743
7744         if (INTEL_GEN(dev_priv) >= 4) {
7745                 if (val & DISPPLANE_TILED) {
7746                         plane_config->tiling = I915_TILING_X;
7747                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7748                 }
7749         }
7750
7751         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7752         fourcc = i9xx_format_to_fourcc(pixel_format);
7753         fb->format = drm_format_info(fourcc);
7754
7755         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7756                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7757                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7758         } else if (INTEL_GEN(dev_priv) >= 4) {
7759                 if (plane_config->tiling)
7760                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7761                 else
7762                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7763                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7764         } else {
7765                 base = I915_READ(DSPADDR(i9xx_plane));
7766         }
7767         plane_config->base = base;
7768
7769         val = I915_READ(PIPESRC(pipe));
7770         fb->width = ((val >> 16) & 0xfff) + 1;
7771         fb->height = ((val >> 0) & 0xfff) + 1;
7772
7773         val = I915_READ(DSPSTRIDE(i9xx_plane));
7774         fb->pitches[0] = val & 0xffffffc0;
7775
7776         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7777
7778         plane_config->size = fb->pitches[0] * aligned_height;
7779
7780         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7781                       crtc->base.name, plane->base.name, fb->width, fb->height,
7782                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7783                       plane_config->size);
7784
7785         plane_config->fb = intel_fb;
7786 }
7787
7788 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7789                                struct intel_crtc_state *pipe_config)
7790 {
7791         struct drm_device *dev = crtc->base.dev;
7792         struct drm_i915_private *dev_priv = to_i915(dev);
7793         int pipe = pipe_config->cpu_transcoder;
7794         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7795         struct dpll clock;
7796         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7797         int refclk = 100000;
7798
7799         /* In case of DSI, DPLL will not be used */
7800         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7801                 return;
7802
7803         mutex_lock(&dev_priv->sb_lock);
7804         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7805         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7806         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7807         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7808         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7809         mutex_unlock(&dev_priv->sb_lock);
7810
7811         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7812         clock.m2 = (pll_dw0 & 0xff) << 22;
7813         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7814                 clock.m2 |= pll_dw2 & 0x3fffff;
7815         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7816         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7817         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7818
7819         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7820 }
7821
7822 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7823                                  struct intel_crtc_state *pipe_config)
7824 {
7825         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7826         enum intel_display_power_domain power_domain;
7827         uint32_t tmp;
7828         bool ret;
7829
7830         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7831         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7832                 return false;
7833
7834         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7835         pipe_config->shared_dpll = NULL;
7836
7837         ret = false;
7838
7839         tmp = I915_READ(PIPECONF(crtc->pipe));
7840         if (!(tmp & PIPECONF_ENABLE))
7841                 goto out;
7842
7843         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7844             IS_CHERRYVIEW(dev_priv)) {
7845                 switch (tmp & PIPECONF_BPC_MASK) {
7846                 case PIPECONF_6BPC:
7847                         pipe_config->pipe_bpp = 18;
7848                         break;
7849                 case PIPECONF_8BPC:
7850                         pipe_config->pipe_bpp = 24;
7851                         break;
7852                 case PIPECONF_10BPC:
7853                         pipe_config->pipe_bpp = 30;
7854                         break;
7855                 default:
7856                         break;
7857                 }
7858         }
7859
7860         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7861             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7862                 pipe_config->limited_color_range = true;
7863
7864         if (INTEL_GEN(dev_priv) < 4)
7865                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7866
7867         intel_get_pipe_timings(crtc, pipe_config);
7868         intel_get_pipe_src_size(crtc, pipe_config);
7869
7870         i9xx_get_pfit_config(crtc, pipe_config);
7871
7872         if (INTEL_GEN(dev_priv) >= 4) {
7873                 /* No way to read it out on pipes B and C */
7874                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7875                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7876                 else
7877                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7878                 pipe_config->pixel_multiplier =
7879                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7880                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7881                 pipe_config->dpll_hw_state.dpll_md = tmp;
7882         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7883                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7884                 tmp = I915_READ(DPLL(crtc->pipe));
7885                 pipe_config->pixel_multiplier =
7886                         ((tmp & SDVO_MULTIPLIER_MASK)
7887                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7888         } else {
7889                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7890                  * port and will be fixed up in the encoder->get_config
7891                  * function. */
7892                 pipe_config->pixel_multiplier = 1;
7893         }
7894         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7895         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7896                 /*
7897                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7898                  * on 830. Filter it out here so that we don't
7899                  * report errors due to that.
7900                  */
7901                 if (IS_I830(dev_priv))
7902                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7903
7904                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7905                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7906         } else {
7907                 /* Mask out read-only status bits. */
7908                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7909                                                      DPLL_PORTC_READY_MASK |
7910                                                      DPLL_PORTB_READY_MASK);
7911         }
7912
7913         if (IS_CHERRYVIEW(dev_priv))
7914                 chv_crtc_clock_get(crtc, pipe_config);
7915         else if (IS_VALLEYVIEW(dev_priv))
7916                 vlv_crtc_clock_get(crtc, pipe_config);
7917         else
7918                 i9xx_crtc_clock_get(crtc, pipe_config);
7919
7920         /*
7921          * Normally the dotclock is filled in by the encoder .get_config()
7922          * but in case the pipe is enabled w/o any ports we need a sane
7923          * default.
7924          */
7925         pipe_config->base.adjusted_mode.crtc_clock =
7926                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7927
7928         ret = true;
7929
7930 out:
7931         intel_display_power_put(dev_priv, power_domain);
7932
7933         return ret;
7934 }
7935
7936 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7937 {
7938         struct intel_encoder *encoder;
7939         int i;
7940         u32 val, final;
7941         bool has_lvds = false;
7942         bool has_cpu_edp = false;
7943         bool has_panel = false;
7944         bool has_ck505 = false;
7945         bool can_ssc = false;
7946         bool using_ssc_source = false;
7947
7948         /* We need to take the global config into account */
7949         for_each_intel_encoder(&dev_priv->drm, encoder) {
7950                 switch (encoder->type) {
7951                 case INTEL_OUTPUT_LVDS:
7952                         has_panel = true;
7953                         has_lvds = true;
7954                         break;
7955                 case INTEL_OUTPUT_EDP:
7956                         has_panel = true;
7957                         if (encoder->port == PORT_A)
7958                                 has_cpu_edp = true;
7959                         break;
7960                 default:
7961                         break;
7962                 }
7963         }
7964
7965         if (HAS_PCH_IBX(dev_priv)) {
7966                 has_ck505 = dev_priv->vbt.display_clock_mode;
7967                 can_ssc = has_ck505;
7968         } else {
7969                 has_ck505 = false;
7970                 can_ssc = true;
7971         }
7972
7973         /* Check if any DPLLs are using the SSC source */
7974         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7975                 u32 temp = I915_READ(PCH_DPLL(i));
7976
7977                 if (!(temp & DPLL_VCO_ENABLE))
7978                         continue;
7979
7980                 if ((temp & PLL_REF_INPUT_MASK) ==
7981                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7982                         using_ssc_source = true;
7983                         break;
7984                 }
7985         }
7986
7987         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7988                       has_panel, has_lvds, has_ck505, using_ssc_source);
7989
7990         /* Ironlake: try to setup display ref clock before DPLL
7991          * enabling. This is only under driver's control after
7992          * PCH B stepping, previous chipset stepping should be
7993          * ignoring this setting.
7994          */
7995         val = I915_READ(PCH_DREF_CONTROL);
7996
7997         /* As we must carefully and slowly disable/enable each source in turn,
7998          * compute the final state we want first and check if we need to
7999          * make any changes at all.
8000          */
8001         final = val;
8002         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8003         if (has_ck505)
8004                 final |= DREF_NONSPREAD_CK505_ENABLE;
8005         else
8006                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8007
8008         final &= ~DREF_SSC_SOURCE_MASK;
8009         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8010         final &= ~DREF_SSC1_ENABLE;
8011
8012         if (has_panel) {
8013                 final |= DREF_SSC_SOURCE_ENABLE;
8014
8015                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8016                         final |= DREF_SSC1_ENABLE;
8017
8018                 if (has_cpu_edp) {
8019                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8020                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8021                         else
8022                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8023                 } else
8024                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8025         } else if (using_ssc_source) {
8026                 final |= DREF_SSC_SOURCE_ENABLE;
8027                 final |= DREF_SSC1_ENABLE;
8028         }
8029
8030         if (final == val)
8031                 return;
8032
8033         /* Always enable nonspread source */
8034         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8035
8036         if (has_ck505)
8037                 val |= DREF_NONSPREAD_CK505_ENABLE;
8038         else
8039                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8040
8041         if (has_panel) {
8042                 val &= ~DREF_SSC_SOURCE_MASK;
8043                 val |= DREF_SSC_SOURCE_ENABLE;
8044
8045                 /* SSC must be turned on before enabling the CPU output  */
8046                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8047                         DRM_DEBUG_KMS("Using SSC on panel\n");
8048                         val |= DREF_SSC1_ENABLE;
8049                 } else
8050                         val &= ~DREF_SSC1_ENABLE;
8051
8052                 /* Get SSC going before enabling the outputs */
8053                 I915_WRITE(PCH_DREF_CONTROL, val);
8054                 POSTING_READ(PCH_DREF_CONTROL);
8055                 udelay(200);
8056
8057                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8058
8059                 /* Enable CPU source on CPU attached eDP */
8060                 if (has_cpu_edp) {
8061                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8062                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8063                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8064                         } else
8065                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8066                 } else
8067                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8068
8069                 I915_WRITE(PCH_DREF_CONTROL, val);
8070                 POSTING_READ(PCH_DREF_CONTROL);
8071                 udelay(200);
8072         } else {
8073                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8074
8075                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8076
8077                 /* Turn off CPU output */
8078                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8079
8080                 I915_WRITE(PCH_DREF_CONTROL, val);
8081                 POSTING_READ(PCH_DREF_CONTROL);
8082                 udelay(200);
8083
8084                 if (!using_ssc_source) {
8085                         DRM_DEBUG_KMS("Disabling SSC source\n");
8086
8087                         /* Turn off the SSC source */
8088                         val &= ~DREF_SSC_SOURCE_MASK;
8089                         val |= DREF_SSC_SOURCE_DISABLE;
8090
8091                         /* Turn off SSC1 */
8092                         val &= ~DREF_SSC1_ENABLE;
8093
8094                         I915_WRITE(PCH_DREF_CONTROL, val);
8095                         POSTING_READ(PCH_DREF_CONTROL);
8096                         udelay(200);
8097                 }
8098         }
8099
8100         BUG_ON(val != final);
8101 }
8102
8103 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8104 {
8105         uint32_t tmp;
8106
8107         tmp = I915_READ(SOUTH_CHICKEN2);
8108         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8109         I915_WRITE(SOUTH_CHICKEN2, tmp);
8110
8111         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8112                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8113                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8114
8115         tmp = I915_READ(SOUTH_CHICKEN2);
8116         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8117         I915_WRITE(SOUTH_CHICKEN2, tmp);
8118
8119         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8120                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8121                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8122 }
8123
8124 /* WaMPhyProgramming:hsw */
8125 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8126 {
8127         uint32_t tmp;
8128
8129         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8130         tmp &= ~(0xFF << 24);
8131         tmp |= (0x12 << 24);
8132         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8133
8134         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8135         tmp |= (1 << 11);
8136         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8137
8138         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8139         tmp |= (1 << 11);
8140         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8141
8142         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8143         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8144         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8145
8146         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8147         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8148         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8149
8150         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8151         tmp &= ~(7 << 13);
8152         tmp |= (5 << 13);
8153         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8154
8155         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8156         tmp &= ~(7 << 13);
8157         tmp |= (5 << 13);
8158         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8159
8160         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8161         tmp &= ~0xFF;
8162         tmp |= 0x1C;
8163         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8164
8165         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8166         tmp &= ~0xFF;
8167         tmp |= 0x1C;
8168         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8169
8170         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8171         tmp &= ~(0xFF << 16);
8172         tmp |= (0x1C << 16);
8173         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8174
8175         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8176         tmp &= ~(0xFF << 16);
8177         tmp |= (0x1C << 16);
8178         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8179
8180         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8181         tmp |= (1 << 27);
8182         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8183
8184         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8185         tmp |= (1 << 27);
8186         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8187
8188         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8189         tmp &= ~(0xF << 28);
8190         tmp |= (4 << 28);
8191         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8192
8193         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8194         tmp &= ~(0xF << 28);
8195         tmp |= (4 << 28);
8196         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8197 }
8198
8199 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8200  * Programming" based on the parameters passed:
8201  * - Sequence to enable CLKOUT_DP
8202  * - Sequence to enable CLKOUT_DP without spread
8203  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8204  */
8205 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8206                                  bool with_spread, bool with_fdi)
8207 {
8208         uint32_t reg, tmp;
8209
8210         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8211                 with_spread = true;
8212         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8213             with_fdi, "LP PCH doesn't have FDI\n"))
8214                 with_fdi = false;
8215
8216         mutex_lock(&dev_priv->sb_lock);
8217
8218         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8219         tmp &= ~SBI_SSCCTL_DISABLE;
8220         tmp |= SBI_SSCCTL_PATHALT;
8221         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8222
8223         udelay(24);
8224
8225         if (with_spread) {
8226                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8227                 tmp &= ~SBI_SSCCTL_PATHALT;
8228                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8229
8230                 if (with_fdi) {
8231                         lpt_reset_fdi_mphy(dev_priv);
8232                         lpt_program_fdi_mphy(dev_priv);
8233                 }
8234         }
8235
8236         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8237         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8238         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8239         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8240
8241         mutex_unlock(&dev_priv->sb_lock);
8242 }
8243
8244 /* Sequence to disable CLKOUT_DP */
8245 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8246 {
8247         uint32_t reg, tmp;
8248
8249         mutex_lock(&dev_priv->sb_lock);
8250
8251         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8252         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8253         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8254         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8255
8256         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8257         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8258                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8259                         tmp |= SBI_SSCCTL_PATHALT;
8260                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8261                         udelay(32);
8262                 }
8263                 tmp |= SBI_SSCCTL_DISABLE;
8264                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8265         }
8266
8267         mutex_unlock(&dev_priv->sb_lock);
8268 }
8269
8270 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8271
8272 static const uint16_t sscdivintphase[] = {
8273         [BEND_IDX( 50)] = 0x3B23,
8274         [BEND_IDX( 45)] = 0x3B23,
8275         [BEND_IDX( 40)] = 0x3C23,
8276         [BEND_IDX( 35)] = 0x3C23,
8277         [BEND_IDX( 30)] = 0x3D23,
8278         [BEND_IDX( 25)] = 0x3D23,
8279         [BEND_IDX( 20)] = 0x3E23,
8280         [BEND_IDX( 15)] = 0x3E23,
8281         [BEND_IDX( 10)] = 0x3F23,
8282         [BEND_IDX(  5)] = 0x3F23,
8283         [BEND_IDX(  0)] = 0x0025,
8284         [BEND_IDX( -5)] = 0x0025,
8285         [BEND_IDX(-10)] = 0x0125,
8286         [BEND_IDX(-15)] = 0x0125,
8287         [BEND_IDX(-20)] = 0x0225,
8288         [BEND_IDX(-25)] = 0x0225,
8289         [BEND_IDX(-30)] = 0x0325,
8290         [BEND_IDX(-35)] = 0x0325,
8291         [BEND_IDX(-40)] = 0x0425,
8292         [BEND_IDX(-45)] = 0x0425,
8293         [BEND_IDX(-50)] = 0x0525,
8294 };
8295
8296 /*
8297  * Bend CLKOUT_DP
8298  * steps -50 to 50 inclusive, in steps of 5
8299  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8300  * change in clock period = -(steps / 10) * 5.787 ps
8301  */
8302 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8303 {
8304         uint32_t tmp;
8305         int idx = BEND_IDX(steps);
8306
8307         if (WARN_ON(steps % 5 != 0))
8308                 return;
8309
8310         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8311                 return;
8312
8313         mutex_lock(&dev_priv->sb_lock);
8314
8315         if (steps % 10 != 0)
8316                 tmp = 0xAAAAAAAB;
8317         else
8318                 tmp = 0x00000000;
8319         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8320
8321         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8322         tmp &= 0xffff0000;
8323         tmp |= sscdivintphase[idx];
8324         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8325
8326         mutex_unlock(&dev_priv->sb_lock);
8327 }
8328
8329 #undef BEND_IDX
8330
8331 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8332 {
8333         struct intel_encoder *encoder;
8334         bool has_vga = false;
8335
8336         for_each_intel_encoder(&dev_priv->drm, encoder) {
8337                 switch (encoder->type) {
8338                 case INTEL_OUTPUT_ANALOG:
8339                         has_vga = true;
8340                         break;
8341                 default:
8342                         break;
8343                 }
8344         }
8345
8346         if (has_vga) {
8347                 lpt_bend_clkout_dp(dev_priv, 0);
8348                 lpt_enable_clkout_dp(dev_priv, true, true);
8349         } else {
8350                 lpt_disable_clkout_dp(dev_priv);
8351         }
8352 }
8353
8354 /*
8355  * Initialize reference clocks when the driver loads
8356  */
8357 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8358 {
8359         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8360                 ironlake_init_pch_refclk(dev_priv);
8361         else if (HAS_PCH_LPT(dev_priv))
8362                 lpt_init_pch_refclk(dev_priv);
8363 }
8364
8365 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8366 {
8367         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8368         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8369         int pipe = intel_crtc->pipe;
8370         uint32_t val;
8371
8372         val = 0;
8373
8374         switch (intel_crtc->config->pipe_bpp) {
8375         case 18:
8376                 val |= PIPECONF_6BPC;
8377                 break;
8378         case 24:
8379                 val |= PIPECONF_8BPC;
8380                 break;
8381         case 30:
8382                 val |= PIPECONF_10BPC;
8383                 break;
8384         case 36:
8385                 val |= PIPECONF_12BPC;
8386                 break;
8387         default:
8388                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8389                 BUG();
8390         }
8391
8392         if (intel_crtc->config->dither)
8393                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8394
8395         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8396                 val |= PIPECONF_INTERLACED_ILK;
8397         else
8398                 val |= PIPECONF_PROGRESSIVE;
8399
8400         if (intel_crtc->config->limited_color_range)
8401                 val |= PIPECONF_COLOR_RANGE_SELECT;
8402
8403         I915_WRITE(PIPECONF(pipe), val);
8404         POSTING_READ(PIPECONF(pipe));
8405 }
8406
8407 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8408 {
8409         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8410         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8411         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8412         u32 val = 0;
8413
8414         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8415                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8416
8417         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8418                 val |= PIPECONF_INTERLACED_ILK;
8419         else
8420                 val |= PIPECONF_PROGRESSIVE;
8421
8422         I915_WRITE(PIPECONF(cpu_transcoder), val);
8423         POSTING_READ(PIPECONF(cpu_transcoder));
8424 }
8425
8426 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8427 {
8428         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8429         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8430         struct intel_crtc_state *config = intel_crtc->config;
8431
8432         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8433                 u32 val = 0;
8434
8435                 switch (intel_crtc->config->pipe_bpp) {
8436                 case 18:
8437                         val |= PIPEMISC_DITHER_6_BPC;
8438                         break;
8439                 case 24:
8440                         val |= PIPEMISC_DITHER_8_BPC;
8441                         break;
8442                 case 30:
8443                         val |= PIPEMISC_DITHER_10_BPC;
8444                         break;
8445                 case 36:
8446                         val |= PIPEMISC_DITHER_12_BPC;
8447                         break;
8448                 default:
8449                         /* Case prevented by pipe_config_set_bpp. */
8450                         BUG();
8451                 }
8452
8453                 if (intel_crtc->config->dither)
8454                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8455
8456                 if (config->ycbcr420) {
8457                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8458                                 PIPEMISC_YUV420_ENABLE |
8459                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8460                 }
8461
8462                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8463         }
8464 }
8465
8466 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8467 {
8468         /*
8469          * Account for spread spectrum to avoid
8470          * oversubscribing the link. Max center spread
8471          * is 2.5%; use 5% for safety's sake.
8472          */
8473         u32 bps = target_clock * bpp * 21 / 20;
8474         return DIV_ROUND_UP(bps, link_bw * 8);
8475 }
8476
8477 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8478 {
8479         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8480 }
8481
8482 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8483                                   struct intel_crtc_state *crtc_state,
8484                                   struct dpll *reduced_clock)
8485 {
8486         struct drm_crtc *crtc = &intel_crtc->base;
8487         struct drm_device *dev = crtc->dev;
8488         struct drm_i915_private *dev_priv = to_i915(dev);
8489         u32 dpll, fp, fp2;
8490         int factor;
8491
8492         /* Enable autotuning of the PLL clock (if permissible) */
8493         factor = 21;
8494         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8495                 if ((intel_panel_use_ssc(dev_priv) &&
8496                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8497                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8498                         factor = 25;
8499         } else if (crtc_state->sdvo_tv_clock)
8500                 factor = 20;
8501
8502         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8503
8504         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8505                 fp |= FP_CB_TUNE;
8506
8507         if (reduced_clock) {
8508                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8509
8510                 if (reduced_clock->m < factor * reduced_clock->n)
8511                         fp2 |= FP_CB_TUNE;
8512         } else {
8513                 fp2 = fp;
8514         }
8515
8516         dpll = 0;
8517
8518         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8519                 dpll |= DPLLB_MODE_LVDS;
8520         else
8521                 dpll |= DPLLB_MODE_DAC_SERIAL;
8522
8523         dpll |= (crtc_state->pixel_multiplier - 1)
8524                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8525
8526         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8527             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8528                 dpll |= DPLL_SDVO_HIGH_SPEED;
8529
8530         if (intel_crtc_has_dp_encoder(crtc_state))
8531                 dpll |= DPLL_SDVO_HIGH_SPEED;
8532
8533         /*
8534          * The high speed IO clock is only really required for
8535          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8536          * possible to share the DPLL between CRT and HDMI. Enabling
8537          * the clock needlessly does no real harm, except use up a
8538          * bit of power potentially.
8539          *
8540          * We'll limit this to IVB with 3 pipes, since it has only two
8541          * DPLLs and so DPLL sharing is the only way to get three pipes
8542          * driving PCH ports at the same time. On SNB we could do this,
8543          * and potentially avoid enabling the second DPLL, but it's not
8544          * clear if it''s a win or loss power wise. No point in doing
8545          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8546          */
8547         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8548             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8549                 dpll |= DPLL_SDVO_HIGH_SPEED;
8550
8551         /* compute bitmask from p1 value */
8552         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8553         /* also FPA1 */
8554         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8555
8556         switch (crtc_state->dpll.p2) {
8557         case 5:
8558                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8559                 break;
8560         case 7:
8561                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8562                 break;
8563         case 10:
8564                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8565                 break;
8566         case 14:
8567                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8568                 break;
8569         }
8570
8571         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8572             intel_panel_use_ssc(dev_priv))
8573                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8574         else
8575                 dpll |= PLL_REF_INPUT_DREFCLK;
8576
8577         dpll |= DPLL_VCO_ENABLE;
8578
8579         crtc_state->dpll_hw_state.dpll = dpll;
8580         crtc_state->dpll_hw_state.fp0 = fp;
8581         crtc_state->dpll_hw_state.fp1 = fp2;
8582 }
8583
8584 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8585                                        struct intel_crtc_state *crtc_state)
8586 {
8587         struct drm_device *dev = crtc->base.dev;
8588         struct drm_i915_private *dev_priv = to_i915(dev);
8589         const struct intel_limit *limit;
8590         int refclk = 120000;
8591
8592         memset(&crtc_state->dpll_hw_state, 0,
8593                sizeof(crtc_state->dpll_hw_state));
8594
8595         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8596         if (!crtc_state->has_pch_encoder)
8597                 return 0;
8598
8599         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8600                 if (intel_panel_use_ssc(dev_priv)) {
8601                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8602                                       dev_priv->vbt.lvds_ssc_freq);
8603                         refclk = dev_priv->vbt.lvds_ssc_freq;
8604                 }
8605
8606                 if (intel_is_dual_link_lvds(dev)) {
8607                         if (refclk == 100000)
8608                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8609                         else
8610                                 limit = &intel_limits_ironlake_dual_lvds;
8611                 } else {
8612                         if (refclk == 100000)
8613                                 limit = &intel_limits_ironlake_single_lvds_100m;
8614                         else
8615                                 limit = &intel_limits_ironlake_single_lvds;
8616                 }
8617         } else {
8618                 limit = &intel_limits_ironlake_dac;
8619         }
8620
8621         if (!crtc_state->clock_set &&
8622             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8623                                 refclk, NULL, &crtc_state->dpll)) {
8624                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8625                 return -EINVAL;
8626         }
8627
8628         ironlake_compute_dpll(crtc, crtc_state, NULL);
8629
8630         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8631                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8632                                  pipe_name(crtc->pipe));
8633                 return -EINVAL;
8634         }
8635
8636         return 0;
8637 }
8638
8639 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8640                                          struct intel_link_m_n *m_n)
8641 {
8642         struct drm_device *dev = crtc->base.dev;
8643         struct drm_i915_private *dev_priv = to_i915(dev);
8644         enum pipe pipe = crtc->pipe;
8645
8646         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8647         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8648         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8649                 & ~TU_SIZE_MASK;
8650         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8651         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8652                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8653 }
8654
8655 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8656                                          enum transcoder transcoder,
8657                                          struct intel_link_m_n *m_n,
8658                                          struct intel_link_m_n *m2_n2)
8659 {
8660         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8661         enum pipe pipe = crtc->pipe;
8662
8663         if (INTEL_GEN(dev_priv) >= 5) {
8664                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8665                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8666                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8667                         & ~TU_SIZE_MASK;
8668                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8669                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8670                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8671                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8672                  * gen < 8) and if DRRS is supported (to make sure the
8673                  * registers are not unnecessarily read).
8674                  */
8675                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8676                         crtc->config->has_drrs) {
8677                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8678                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8679                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8680                                         & ~TU_SIZE_MASK;
8681                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8682                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8683                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8684                 }
8685         } else {
8686                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8687                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8688                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8689                         & ~TU_SIZE_MASK;
8690                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8691                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8692                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8693         }
8694 }
8695
8696 void intel_dp_get_m_n(struct intel_crtc *crtc,
8697                       struct intel_crtc_state *pipe_config)
8698 {
8699         if (pipe_config->has_pch_encoder)
8700                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8701         else
8702                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8703                                              &pipe_config->dp_m_n,
8704                                              &pipe_config->dp_m2_n2);
8705 }
8706
8707 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8708                                         struct intel_crtc_state *pipe_config)
8709 {
8710         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8711                                      &pipe_config->fdi_m_n, NULL);
8712 }
8713
8714 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8715                                     struct intel_crtc_state *pipe_config)
8716 {
8717         struct drm_device *dev = crtc->base.dev;
8718         struct drm_i915_private *dev_priv = to_i915(dev);
8719         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8720         uint32_t ps_ctrl = 0;
8721         int id = -1;
8722         int i;
8723
8724         /* find scaler attached to this pipe */
8725         for (i = 0; i < crtc->num_scalers; i++) {
8726                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8727                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8728                         id = i;
8729                         pipe_config->pch_pfit.enabled = true;
8730                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8731                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8732                         break;
8733                 }
8734         }
8735
8736         scaler_state->scaler_id = id;
8737         if (id >= 0) {
8738                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8739         } else {
8740                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8741         }
8742 }
8743
8744 static void
8745 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8746                                  struct intel_initial_plane_config *plane_config)
8747 {
8748         struct drm_device *dev = crtc->base.dev;
8749         struct drm_i915_private *dev_priv = to_i915(dev);
8750         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8751         enum plane_id plane_id = plane->id;
8752         enum pipe pipe;
8753         u32 val, base, offset, stride_mult, tiling, alpha;
8754         int fourcc, pixel_format;
8755         unsigned int aligned_height;
8756         struct drm_framebuffer *fb;
8757         struct intel_framebuffer *intel_fb;
8758
8759         if (!plane->get_hw_state(plane, &pipe))
8760                 return;
8761
8762         WARN_ON(pipe != crtc->pipe);
8763
8764         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8765         if (!intel_fb) {
8766                 DRM_DEBUG_KMS("failed to alloc fb\n");
8767                 return;
8768         }
8769
8770         fb = &intel_fb->base;
8771
8772         fb->dev = dev;
8773
8774         val = I915_READ(PLANE_CTL(pipe, plane_id));
8775
8776         if (INTEL_GEN(dev_priv) >= 11)
8777                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8778         else
8779                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8780
8781         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8782                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8783                 alpha &= PLANE_COLOR_ALPHA_MASK;
8784         } else {
8785                 alpha = val & PLANE_CTL_ALPHA_MASK;
8786         }
8787
8788         fourcc = skl_format_to_fourcc(pixel_format,
8789                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8790         fb->format = drm_format_info(fourcc);
8791
8792         tiling = val & PLANE_CTL_TILED_MASK;
8793         switch (tiling) {
8794         case PLANE_CTL_TILED_LINEAR:
8795                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8796                 break;
8797         case PLANE_CTL_TILED_X:
8798                 plane_config->tiling = I915_TILING_X;
8799                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8800                 break;
8801         case PLANE_CTL_TILED_Y:
8802                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8803                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8804                 else
8805                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8806                 break;
8807         case PLANE_CTL_TILED_YF:
8808                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8809                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8810                 else
8811                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8812                 break;
8813         default:
8814                 MISSING_CASE(tiling);
8815                 goto error;
8816         }
8817
8818         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8819         plane_config->base = base;
8820
8821         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8822
8823         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8824         fb->height = ((val >> 16) & 0xfff) + 1;
8825         fb->width = ((val >> 0) & 0x1fff) + 1;
8826
8827         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8828         stride_mult = intel_fb_stride_alignment(fb, 0);
8829         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8830
8831         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8832
8833         plane_config->size = fb->pitches[0] * aligned_height;
8834
8835         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8836                       crtc->base.name, plane->base.name, fb->width, fb->height,
8837                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8838                       plane_config->size);
8839
8840         plane_config->fb = intel_fb;
8841         return;
8842
8843 error:
8844         kfree(intel_fb);
8845 }
8846
8847 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8848                                      struct intel_crtc_state *pipe_config)
8849 {
8850         struct drm_device *dev = crtc->base.dev;
8851         struct drm_i915_private *dev_priv = to_i915(dev);
8852         uint32_t tmp;
8853
8854         tmp = I915_READ(PF_CTL(crtc->pipe));
8855
8856         if (tmp & PF_ENABLE) {
8857                 pipe_config->pch_pfit.enabled = true;
8858                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8859                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8860
8861                 /* We currently do not free assignements of panel fitters on
8862                  * ivb/hsw (since we don't use the higher upscaling modes which
8863                  * differentiates them) so just WARN about this case for now. */
8864                 if (IS_GEN7(dev_priv)) {
8865                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8866                                 PF_PIPE_SEL_IVB(crtc->pipe));
8867                 }
8868         }
8869 }
8870
8871 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8872                                      struct intel_crtc_state *pipe_config)
8873 {
8874         struct drm_device *dev = crtc->base.dev;
8875         struct drm_i915_private *dev_priv = to_i915(dev);
8876         enum intel_display_power_domain power_domain;
8877         uint32_t tmp;
8878         bool ret;
8879
8880         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8881         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8882                 return false;
8883
8884         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8885         pipe_config->shared_dpll = NULL;
8886
8887         ret = false;
8888         tmp = I915_READ(PIPECONF(crtc->pipe));
8889         if (!(tmp & PIPECONF_ENABLE))
8890                 goto out;
8891
8892         switch (tmp & PIPECONF_BPC_MASK) {
8893         case PIPECONF_6BPC:
8894                 pipe_config->pipe_bpp = 18;
8895                 break;
8896         case PIPECONF_8BPC:
8897                 pipe_config->pipe_bpp = 24;
8898                 break;
8899         case PIPECONF_10BPC:
8900                 pipe_config->pipe_bpp = 30;
8901                 break;
8902         case PIPECONF_12BPC:
8903                 pipe_config->pipe_bpp = 36;
8904                 break;
8905         default:
8906                 break;
8907         }
8908
8909         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8910                 pipe_config->limited_color_range = true;
8911
8912         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8913                 struct intel_shared_dpll *pll;
8914                 enum intel_dpll_id pll_id;
8915
8916                 pipe_config->has_pch_encoder = true;
8917
8918                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8919                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8920                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8921
8922                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8923
8924                 if (HAS_PCH_IBX(dev_priv)) {
8925                         /*
8926                          * The pipe->pch transcoder and pch transcoder->pll
8927                          * mapping is fixed.
8928                          */
8929                         pll_id = (enum intel_dpll_id) crtc->pipe;
8930                 } else {
8931                         tmp = I915_READ(PCH_DPLL_SEL);
8932                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8933                                 pll_id = DPLL_ID_PCH_PLL_B;
8934                         else
8935                                 pll_id= DPLL_ID_PCH_PLL_A;
8936                 }
8937
8938                 pipe_config->shared_dpll =
8939                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8940                 pll = pipe_config->shared_dpll;
8941
8942                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
8943                                                 &pipe_config->dpll_hw_state));
8944
8945                 tmp = pipe_config->dpll_hw_state.dpll;
8946                 pipe_config->pixel_multiplier =
8947                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8948                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8949
8950                 ironlake_pch_clock_get(crtc, pipe_config);
8951         } else {
8952                 pipe_config->pixel_multiplier = 1;
8953         }
8954
8955         intel_get_pipe_timings(crtc, pipe_config);
8956         intel_get_pipe_src_size(crtc, pipe_config);
8957
8958         ironlake_get_pfit_config(crtc, pipe_config);
8959
8960         ret = true;
8961
8962 out:
8963         intel_display_power_put(dev_priv, power_domain);
8964
8965         return ret;
8966 }
8967
8968 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8969 {
8970         struct drm_device *dev = &dev_priv->drm;
8971         struct intel_crtc *crtc;
8972
8973         for_each_intel_crtc(dev, crtc)
8974                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8975                      pipe_name(crtc->pipe));
8976
8977         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL)),
8978                         "Display power well on\n");
8979         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8980         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8981         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8982         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8983         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8984              "CPU PWM1 enabled\n");
8985         if (IS_HASWELL(dev_priv))
8986                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8987                      "CPU PWM2 enabled\n");
8988         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8989              "PCH PWM1 enabled\n");
8990         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8991              "Utility pin enabled\n");
8992         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8993
8994         /*
8995          * In theory we can still leave IRQs enabled, as long as only the HPD
8996          * interrupts remain enabled. We used to check for that, but since it's
8997          * gen-specific and since we only disable LCPLL after we fully disable
8998          * the interrupts, the check below should be enough.
8999          */
9000         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9001 }
9002
9003 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9004 {
9005         if (IS_HASWELL(dev_priv))
9006                 return I915_READ(D_COMP_HSW);
9007         else
9008                 return I915_READ(D_COMP_BDW);
9009 }
9010
9011 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9012 {
9013         if (IS_HASWELL(dev_priv)) {
9014                 mutex_lock(&dev_priv->pcu_lock);
9015                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9016                                             val))
9017                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
9018                 mutex_unlock(&dev_priv->pcu_lock);
9019         } else {
9020                 I915_WRITE(D_COMP_BDW, val);
9021                 POSTING_READ(D_COMP_BDW);
9022         }
9023 }
9024
9025 /*
9026  * This function implements pieces of two sequences from BSpec:
9027  * - Sequence for display software to disable LCPLL
9028  * - Sequence for display software to allow package C8+
9029  * The steps implemented here are just the steps that actually touch the LCPLL
9030  * register. Callers should take care of disabling all the display engine
9031  * functions, doing the mode unset, fixing interrupts, etc.
9032  */
9033 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9034                               bool switch_to_fclk, bool allow_power_down)
9035 {
9036         uint32_t val;
9037
9038         assert_can_disable_lcpll(dev_priv);
9039
9040         val = I915_READ(LCPLL_CTL);
9041
9042         if (switch_to_fclk) {
9043                 val |= LCPLL_CD_SOURCE_FCLK;
9044                 I915_WRITE(LCPLL_CTL, val);
9045
9046                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9047                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9048                         DRM_ERROR("Switching to FCLK failed\n");
9049
9050                 val = I915_READ(LCPLL_CTL);
9051         }
9052
9053         val |= LCPLL_PLL_DISABLE;
9054         I915_WRITE(LCPLL_CTL, val);
9055         POSTING_READ(LCPLL_CTL);
9056
9057         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9058                 DRM_ERROR("LCPLL still locked\n");
9059
9060         val = hsw_read_dcomp(dev_priv);
9061         val |= D_COMP_COMP_DISABLE;
9062         hsw_write_dcomp(dev_priv, val);
9063         ndelay(100);
9064
9065         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9066                      1))
9067                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9068
9069         if (allow_power_down) {
9070                 val = I915_READ(LCPLL_CTL);
9071                 val |= LCPLL_POWER_DOWN_ALLOW;
9072                 I915_WRITE(LCPLL_CTL, val);
9073                 POSTING_READ(LCPLL_CTL);
9074         }
9075 }
9076
9077 /*
9078  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9079  * source.
9080  */
9081 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9082 {
9083         uint32_t val;
9084
9085         val = I915_READ(LCPLL_CTL);
9086
9087         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9088                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9089                 return;
9090
9091         /*
9092          * Make sure we're not on PC8 state before disabling PC8, otherwise
9093          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9094          */
9095         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9096
9097         if (val & LCPLL_POWER_DOWN_ALLOW) {
9098                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9099                 I915_WRITE(LCPLL_CTL, val);
9100                 POSTING_READ(LCPLL_CTL);
9101         }
9102
9103         val = hsw_read_dcomp(dev_priv);
9104         val |= D_COMP_COMP_FORCE;
9105         val &= ~D_COMP_COMP_DISABLE;
9106         hsw_write_dcomp(dev_priv, val);
9107
9108         val = I915_READ(LCPLL_CTL);
9109         val &= ~LCPLL_PLL_DISABLE;
9110         I915_WRITE(LCPLL_CTL, val);
9111
9112         if (intel_wait_for_register(dev_priv,
9113                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9114                                     5))
9115                 DRM_ERROR("LCPLL not locked yet\n");
9116
9117         if (val & LCPLL_CD_SOURCE_FCLK) {
9118                 val = I915_READ(LCPLL_CTL);
9119                 val &= ~LCPLL_CD_SOURCE_FCLK;
9120                 I915_WRITE(LCPLL_CTL, val);
9121
9122                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9123                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9124                         DRM_ERROR("Switching back to LCPLL failed\n");
9125         }
9126
9127         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9128
9129         intel_update_cdclk(dev_priv);
9130         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
9131 }
9132
9133 /*
9134  * Package states C8 and deeper are really deep PC states that can only be
9135  * reached when all the devices on the system allow it, so even if the graphics
9136  * device allows PC8+, it doesn't mean the system will actually get to these
9137  * states. Our driver only allows PC8+ when going into runtime PM.
9138  *
9139  * The requirements for PC8+ are that all the outputs are disabled, the power
9140  * well is disabled and most interrupts are disabled, and these are also
9141  * requirements for runtime PM. When these conditions are met, we manually do
9142  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9143  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9144  * hang the machine.
9145  *
9146  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9147  * the state of some registers, so when we come back from PC8+ we need to
9148  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9149  * need to take care of the registers kept by RC6. Notice that this happens even
9150  * if we don't put the device in PCI D3 state (which is what currently happens
9151  * because of the runtime PM support).
9152  *
9153  * For more, read "Display Sequences for Package C8" on the hardware
9154  * documentation.
9155  */
9156 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9157 {
9158         uint32_t val;
9159
9160         DRM_DEBUG_KMS("Enabling package C8+\n");
9161
9162         if (HAS_PCH_LPT_LP(dev_priv)) {
9163                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9164                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9165                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9166         }
9167
9168         lpt_disable_clkout_dp(dev_priv);
9169         hsw_disable_lcpll(dev_priv, true, true);
9170 }
9171
9172 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9173 {
9174         uint32_t val;
9175
9176         DRM_DEBUG_KMS("Disabling package C8+\n");
9177
9178         hsw_restore_lcpll(dev_priv);
9179         lpt_init_pch_refclk(dev_priv);
9180
9181         if (HAS_PCH_LPT_LP(dev_priv)) {
9182                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9183                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9184                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9185         }
9186 }
9187
9188 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9189                                       struct intel_crtc_state *crtc_state)
9190 {
9191         struct intel_atomic_state *state =
9192                 to_intel_atomic_state(crtc_state->base.state);
9193
9194         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9195                 struct intel_encoder *encoder =
9196                         intel_get_crtc_new_encoder(state, crtc_state);
9197
9198                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9199                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9200                                          pipe_name(crtc->pipe));
9201                         return -EINVAL;
9202                 }
9203         }
9204
9205         return 0;
9206 }
9207
9208 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9209                                    enum port port,
9210                                    struct intel_crtc_state *pipe_config)
9211 {
9212         enum intel_dpll_id id;
9213         u32 temp;
9214
9215         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9216         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9217
9218         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9219                 return;
9220
9221         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9222 }
9223
9224 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9225                                 enum port port,
9226                                 struct intel_crtc_state *pipe_config)
9227 {
9228         enum intel_dpll_id id;
9229         u32 temp;
9230
9231         /* TODO: TBT pll not implemented. */
9232         switch (port) {
9233         case PORT_A:
9234         case PORT_B:
9235                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9236                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9237                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9238
9239                 if (WARN_ON(id != DPLL_ID_ICL_DPLL0 && id != DPLL_ID_ICL_DPLL1))
9240                         return;
9241                 break;
9242         case PORT_C:
9243                 id = DPLL_ID_ICL_MGPLL1;
9244                 break;
9245         case PORT_D:
9246                 id = DPLL_ID_ICL_MGPLL2;
9247                 break;
9248         case PORT_E:
9249                 id = DPLL_ID_ICL_MGPLL3;
9250                 break;
9251         case PORT_F:
9252                 id = DPLL_ID_ICL_MGPLL4;
9253                 break;
9254         default:
9255                 MISSING_CASE(port);
9256                 return;
9257         }
9258
9259         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9260 }
9261
9262 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9263                                 enum port port,
9264                                 struct intel_crtc_state *pipe_config)
9265 {
9266         enum intel_dpll_id id;
9267
9268         switch (port) {
9269         case PORT_A:
9270                 id = DPLL_ID_SKL_DPLL0;
9271                 break;
9272         case PORT_B:
9273                 id = DPLL_ID_SKL_DPLL1;
9274                 break;
9275         case PORT_C:
9276                 id = DPLL_ID_SKL_DPLL2;
9277                 break;
9278         default:
9279                 DRM_ERROR("Incorrect port type\n");
9280                 return;
9281         }
9282
9283         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9284 }
9285
9286 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9287                                 enum port port,
9288                                 struct intel_crtc_state *pipe_config)
9289 {
9290         enum intel_dpll_id id;
9291         u32 temp;
9292
9293         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9294         id = temp >> (port * 3 + 1);
9295
9296         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9297                 return;
9298
9299         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9300 }
9301
9302 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9303                                 enum port port,
9304                                 struct intel_crtc_state *pipe_config)
9305 {
9306         enum intel_dpll_id id;
9307         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9308
9309         switch (ddi_pll_sel) {
9310         case PORT_CLK_SEL_WRPLL1:
9311                 id = DPLL_ID_WRPLL1;
9312                 break;
9313         case PORT_CLK_SEL_WRPLL2:
9314                 id = DPLL_ID_WRPLL2;
9315                 break;
9316         case PORT_CLK_SEL_SPLL:
9317                 id = DPLL_ID_SPLL;
9318                 break;
9319         case PORT_CLK_SEL_LCPLL_810:
9320                 id = DPLL_ID_LCPLL_810;
9321                 break;
9322         case PORT_CLK_SEL_LCPLL_1350:
9323                 id = DPLL_ID_LCPLL_1350;
9324                 break;
9325         case PORT_CLK_SEL_LCPLL_2700:
9326                 id = DPLL_ID_LCPLL_2700;
9327                 break;
9328         default:
9329                 MISSING_CASE(ddi_pll_sel);
9330                 /* fall through */
9331         case PORT_CLK_SEL_NONE:
9332                 return;
9333         }
9334
9335         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9336 }
9337
9338 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9339                                      struct intel_crtc_state *pipe_config,
9340                                      u64 *power_domain_mask)
9341 {
9342         struct drm_device *dev = crtc->base.dev;
9343         struct drm_i915_private *dev_priv = to_i915(dev);
9344         enum intel_display_power_domain power_domain;
9345         u32 tmp;
9346
9347         /*
9348          * The pipe->transcoder mapping is fixed with the exception of the eDP
9349          * transcoder handled below.
9350          */
9351         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9352
9353         /*
9354          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9355          * consistency and less surprising code; it's in always on power).
9356          */
9357         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9358         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9359                 enum pipe trans_edp_pipe;
9360                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9361                 default:
9362                         WARN(1, "unknown pipe linked to edp transcoder\n");
9363                         /* fall through */
9364                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9365                 case TRANS_DDI_EDP_INPUT_A_ON:
9366                         trans_edp_pipe = PIPE_A;
9367                         break;
9368                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9369                         trans_edp_pipe = PIPE_B;
9370                         break;
9371                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9372                         trans_edp_pipe = PIPE_C;
9373                         break;
9374                 }
9375
9376                 if (trans_edp_pipe == crtc->pipe)
9377                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9378         }
9379
9380         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9381         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9382                 return false;
9383         *power_domain_mask |= BIT_ULL(power_domain);
9384
9385         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9386
9387         return tmp & PIPECONF_ENABLE;
9388 }
9389
9390 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9391                                          struct intel_crtc_state *pipe_config,
9392                                          u64 *power_domain_mask)
9393 {
9394         struct drm_device *dev = crtc->base.dev;
9395         struct drm_i915_private *dev_priv = to_i915(dev);
9396         enum intel_display_power_domain power_domain;
9397         enum port port;
9398         enum transcoder cpu_transcoder;
9399         u32 tmp;
9400
9401         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9402                 if (port == PORT_A)
9403                         cpu_transcoder = TRANSCODER_DSI_A;
9404                 else
9405                         cpu_transcoder = TRANSCODER_DSI_C;
9406
9407                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9408                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9409                         continue;
9410                 *power_domain_mask |= BIT_ULL(power_domain);
9411
9412                 /*
9413                  * The PLL needs to be enabled with a valid divider
9414                  * configuration, otherwise accessing DSI registers will hang
9415                  * the machine. See BSpec North Display Engine
9416                  * registers/MIPI[BXT]. We can break out here early, since we
9417                  * need the same DSI PLL to be enabled for both DSI ports.
9418                  */
9419                 if (!bxt_dsi_pll_is_enabled(dev_priv))
9420                         break;
9421
9422                 /* XXX: this works for video mode only */
9423                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9424                 if (!(tmp & DPI_ENABLE))
9425                         continue;
9426
9427                 tmp = I915_READ(MIPI_CTRL(port));
9428                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9429                         continue;
9430
9431                 pipe_config->cpu_transcoder = cpu_transcoder;
9432                 break;
9433         }
9434
9435         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9436 }
9437
9438 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9439                                        struct intel_crtc_state *pipe_config)
9440 {
9441         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9442         struct intel_shared_dpll *pll;
9443         enum port port;
9444         uint32_t tmp;
9445
9446         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9447
9448         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9449
9450         if (IS_ICELAKE(dev_priv))
9451                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
9452         else if (IS_CANNONLAKE(dev_priv))
9453                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9454         else if (IS_GEN9_BC(dev_priv))
9455                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9456         else if (IS_GEN9_LP(dev_priv))
9457                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9458         else
9459                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9460
9461         pll = pipe_config->shared_dpll;
9462         if (pll) {
9463                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9464                                                 &pipe_config->dpll_hw_state));
9465         }
9466
9467         /*
9468          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9469          * DDI E. So just check whether this pipe is wired to DDI E and whether
9470          * the PCH transcoder is on.
9471          */
9472         if (INTEL_GEN(dev_priv) < 9 &&
9473             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9474                 pipe_config->has_pch_encoder = true;
9475
9476                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9477                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9478                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9479
9480                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9481         }
9482 }
9483
9484 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9485                                     struct intel_crtc_state *pipe_config)
9486 {
9487         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9488         enum intel_display_power_domain power_domain;
9489         u64 power_domain_mask;
9490         bool active;
9491
9492         intel_crtc_init_scalers(crtc, pipe_config);
9493
9494         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9495         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9496                 return false;
9497         power_domain_mask = BIT_ULL(power_domain);
9498
9499         pipe_config->shared_dpll = NULL;
9500
9501         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9502
9503         if (IS_GEN9_LP(dev_priv) &&
9504             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9505                 WARN_ON(active);
9506                 active = true;
9507         }
9508
9509         if (!active)
9510                 goto out;
9511
9512         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9513                 haswell_get_ddi_port_state(crtc, pipe_config);
9514                 intel_get_pipe_timings(crtc, pipe_config);
9515         }
9516
9517         intel_get_pipe_src_size(crtc, pipe_config);
9518
9519         pipe_config->gamma_mode =
9520                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9521
9522         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
9523                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9524                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9525
9526                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10) {
9527                         bool blend_mode_420 = tmp &
9528                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9529
9530                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9531                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9532                             pipe_config->ycbcr420 != blend_mode_420)
9533                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9534                 } else if (clrspace_yuv) {
9535                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9536                 }
9537         }
9538
9539         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9540         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9541                 power_domain_mask |= BIT_ULL(power_domain);
9542                 if (INTEL_GEN(dev_priv) >= 9)
9543                         skylake_get_pfit_config(crtc, pipe_config);
9544                 else
9545                         ironlake_get_pfit_config(crtc, pipe_config);
9546         }
9547
9548         if (hsw_crtc_supports_ips(crtc)) {
9549                 if (IS_HASWELL(dev_priv))
9550                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9551                 else {
9552                         /*
9553                          * We cannot readout IPS state on broadwell, set to
9554                          * true so we can set it to a defined state on first
9555                          * commit.
9556                          */
9557                         pipe_config->ips_enabled = true;
9558                 }
9559         }
9560
9561         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9562             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9563                 pipe_config->pixel_multiplier =
9564                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9565         } else {
9566                 pipe_config->pixel_multiplier = 1;
9567         }
9568
9569 out:
9570         for_each_power_domain(power_domain, power_domain_mask)
9571                 intel_display_power_put(dev_priv, power_domain);
9572
9573         return active;
9574 }
9575
9576 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9577 {
9578         struct drm_i915_private *dev_priv =
9579                 to_i915(plane_state->base.plane->dev);
9580         const struct drm_framebuffer *fb = plane_state->base.fb;
9581         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9582         u32 base;
9583
9584         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9585                 base = obj->phys_handle->busaddr;
9586         else
9587                 base = intel_plane_ggtt_offset(plane_state);
9588
9589         base += plane_state->main.offset;
9590
9591         /* ILK+ do this automagically */
9592         if (HAS_GMCH_DISPLAY(dev_priv) &&
9593             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9594                 base += (plane_state->base.crtc_h *
9595                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9596
9597         return base;
9598 }
9599
9600 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9601 {
9602         int x = plane_state->base.crtc_x;
9603         int y = plane_state->base.crtc_y;
9604         u32 pos = 0;
9605
9606         if (x < 0) {
9607                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9608                 x = -x;
9609         }
9610         pos |= x << CURSOR_X_SHIFT;
9611
9612         if (y < 0) {
9613                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9614                 y = -y;
9615         }
9616         pos |= y << CURSOR_Y_SHIFT;
9617
9618         return pos;
9619 }
9620
9621 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9622 {
9623         const struct drm_mode_config *config =
9624                 &plane_state->base.plane->dev->mode_config;
9625         int width = plane_state->base.crtc_w;
9626         int height = plane_state->base.crtc_h;
9627
9628         return width > 0 && width <= config->cursor_width &&
9629                 height > 0 && height <= config->cursor_height;
9630 }
9631
9632 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9633                               struct intel_plane_state *plane_state)
9634 {
9635         const struct drm_framebuffer *fb = plane_state->base.fb;
9636         int src_x, src_y;
9637         u32 offset;
9638         int ret;
9639
9640         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9641                                                   &crtc_state->base,
9642                                                   DRM_PLANE_HELPER_NO_SCALING,
9643                                                   DRM_PLANE_HELPER_NO_SCALING,
9644                                                   true, true);
9645         if (ret)
9646                 return ret;
9647
9648         if (!fb)
9649                 return 0;
9650
9651         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9652                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9653                 return -EINVAL;
9654         }
9655
9656         src_x = plane_state->base.src_x >> 16;
9657         src_y = plane_state->base.src_y >> 16;
9658
9659         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9660         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9661
9662         if (src_x != 0 || src_y != 0) {
9663                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9664                 return -EINVAL;
9665         }
9666
9667         plane_state->main.offset = offset;
9668
9669         return 0;
9670 }
9671
9672 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9673                            const struct intel_plane_state *plane_state)
9674 {
9675         const struct drm_framebuffer *fb = plane_state->base.fb;
9676
9677         return CURSOR_ENABLE |
9678                 CURSOR_GAMMA_ENABLE |
9679                 CURSOR_FORMAT_ARGB |
9680                 CURSOR_STRIDE(fb->pitches[0]);
9681 }
9682
9683 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9684 {
9685         int width = plane_state->base.crtc_w;
9686
9687         /*
9688          * 845g/865g are only limited by the width of their cursors,
9689          * the height is arbitrary up to the precision of the register.
9690          */
9691         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9692 }
9693
9694 static int i845_check_cursor(struct intel_plane *plane,
9695                              struct intel_crtc_state *crtc_state,
9696                              struct intel_plane_state *plane_state)
9697 {
9698         const struct drm_framebuffer *fb = plane_state->base.fb;
9699         int ret;
9700
9701         ret = intel_check_cursor(crtc_state, plane_state);
9702         if (ret)
9703                 return ret;
9704
9705         /* if we want to turn off the cursor ignore width and height */
9706         if (!fb)
9707                 return 0;
9708
9709         /* Check for which cursor types we support */
9710         if (!i845_cursor_size_ok(plane_state)) {
9711                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9712                           plane_state->base.crtc_w,
9713                           plane_state->base.crtc_h);
9714                 return -EINVAL;
9715         }
9716
9717         switch (fb->pitches[0]) {
9718         case 256:
9719         case 512:
9720         case 1024:
9721         case 2048:
9722                 break;
9723         default:
9724                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9725                               fb->pitches[0]);
9726                 return -EINVAL;
9727         }
9728
9729         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9730
9731         return 0;
9732 }
9733
9734 static void i845_update_cursor(struct intel_plane *plane,
9735                                const struct intel_crtc_state *crtc_state,
9736                                const struct intel_plane_state *plane_state)
9737 {
9738         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9739         u32 cntl = 0, base = 0, pos = 0, size = 0;
9740         unsigned long irqflags;
9741
9742         if (plane_state && plane_state->base.visible) {
9743                 unsigned int width = plane_state->base.crtc_w;
9744                 unsigned int height = plane_state->base.crtc_h;
9745
9746                 cntl = plane_state->ctl;
9747                 size = (height << 12) | width;
9748
9749                 base = intel_cursor_base(plane_state);
9750                 pos = intel_cursor_position(plane_state);
9751         }
9752
9753         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9754
9755         /* On these chipsets we can only modify the base/size/stride
9756          * whilst the cursor is disabled.
9757          */
9758         if (plane->cursor.base != base ||
9759             plane->cursor.size != size ||
9760             plane->cursor.cntl != cntl) {
9761                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9762                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9763                 I915_WRITE_FW(CURSIZE, size);
9764                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9765                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9766
9767                 plane->cursor.base = base;
9768                 plane->cursor.size = size;
9769                 plane->cursor.cntl = cntl;
9770         } else {
9771                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9772         }
9773
9774         POSTING_READ_FW(CURCNTR(PIPE_A));
9775
9776         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9777 }
9778
9779 static void i845_disable_cursor(struct intel_plane *plane,
9780                                 struct intel_crtc *crtc)
9781 {
9782         i845_update_cursor(plane, NULL, NULL);
9783 }
9784
9785 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
9786                                      enum pipe *pipe)
9787 {
9788         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9789         enum intel_display_power_domain power_domain;
9790         bool ret;
9791
9792         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9793         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9794                 return false;
9795
9796         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9797
9798         *pipe = PIPE_A;
9799
9800         intel_display_power_put(dev_priv, power_domain);
9801
9802         return ret;
9803 }
9804
9805 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9806                            const struct intel_plane_state *plane_state)
9807 {
9808         struct drm_i915_private *dev_priv =
9809                 to_i915(plane_state->base.plane->dev);
9810         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9811         u32 cntl = 0;
9812
9813         if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
9814                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
9815
9816         if (INTEL_GEN(dev_priv) <= 10) {
9817                 cntl |= MCURSOR_GAMMA_ENABLE;
9818
9819                 if (HAS_DDI(dev_priv))
9820                         cntl |= MCURSOR_PIPE_CSC_ENABLE;
9821         }
9822
9823         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
9824                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9825
9826         switch (plane_state->base.crtc_w) {
9827         case 64:
9828                 cntl |= MCURSOR_MODE_64_ARGB_AX;
9829                 break;
9830         case 128:
9831                 cntl |= MCURSOR_MODE_128_ARGB_AX;
9832                 break;
9833         case 256:
9834                 cntl |= MCURSOR_MODE_256_ARGB_AX;
9835                 break;
9836         default:
9837                 MISSING_CASE(plane_state->base.crtc_w);
9838                 return 0;
9839         }
9840
9841         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9842                 cntl |= MCURSOR_ROTATE_180;
9843
9844         return cntl;
9845 }
9846
9847 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9848 {
9849         struct drm_i915_private *dev_priv =
9850                 to_i915(plane_state->base.plane->dev);
9851         int width = plane_state->base.crtc_w;
9852         int height = plane_state->base.crtc_h;
9853
9854         if (!intel_cursor_size_ok(plane_state))
9855                 return false;
9856
9857         /* Cursor width is limited to a few power-of-two sizes */
9858         switch (width) {
9859         case 256:
9860         case 128:
9861         case 64:
9862                 break;
9863         default:
9864                 return false;
9865         }
9866
9867         /*
9868          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9869          * height from 8 lines up to the cursor width, when the
9870          * cursor is not rotated. Everything else requires square
9871          * cursors.
9872          */
9873         if (HAS_CUR_FBC(dev_priv) &&
9874             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9875                 if (height < 8 || height > width)
9876                         return false;
9877         } else {
9878                 if (height != width)
9879                         return false;
9880         }
9881
9882         return true;
9883 }
9884
9885 static int i9xx_check_cursor(struct intel_plane *plane,
9886                              struct intel_crtc_state *crtc_state,
9887                              struct intel_plane_state *plane_state)
9888 {
9889         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9890         const struct drm_framebuffer *fb = plane_state->base.fb;
9891         enum pipe pipe = plane->pipe;
9892         int ret;
9893
9894         ret = intel_check_cursor(crtc_state, plane_state);
9895         if (ret)
9896                 return ret;
9897
9898         /* if we want to turn off the cursor ignore width and height */
9899         if (!fb)
9900                 return 0;
9901
9902         /* Check for which cursor types we support */
9903         if (!i9xx_cursor_size_ok(plane_state)) {
9904                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9905                           plane_state->base.crtc_w,
9906                           plane_state->base.crtc_h);
9907                 return -EINVAL;
9908         }
9909
9910         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9911                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9912                               fb->pitches[0], plane_state->base.crtc_w);
9913                 return -EINVAL;
9914         }
9915
9916         /*
9917          * There's something wrong with the cursor on CHV pipe C.
9918          * If it straddles the left edge of the screen then
9919          * moving it away from the edge or disabling it often
9920          * results in a pipe underrun, and often that can lead to
9921          * dead pipe (constant underrun reported, and it scans
9922          * out just a solid color). To recover from that, the
9923          * display power well must be turned off and on again.
9924          * Refuse the put the cursor into that compromised position.
9925          */
9926         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9927             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9928                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9929                 return -EINVAL;
9930         }
9931
9932         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9933
9934         return 0;
9935 }
9936
9937 static void i9xx_update_cursor(struct intel_plane *plane,
9938                                const struct intel_crtc_state *crtc_state,
9939                                const struct intel_plane_state *plane_state)
9940 {
9941         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9942         enum pipe pipe = plane->pipe;
9943         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9944         unsigned long irqflags;
9945
9946         if (plane_state && plane_state->base.visible) {
9947                 cntl = plane_state->ctl;
9948
9949                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9950                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9951
9952                 base = intel_cursor_base(plane_state);
9953                 pos = intel_cursor_position(plane_state);
9954         }
9955
9956         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9957
9958         /*
9959          * On some platforms writing CURCNTR first will also
9960          * cause CURPOS to be armed by the CURBASE write.
9961          * Without the CURCNTR write the CURPOS write would
9962          * arm itself. Thus we always start the full update
9963          * with a CURCNTR write.
9964          *
9965          * On other platforms CURPOS always requires the
9966          * CURBASE write to arm the update. Additonally
9967          * a write to any of the cursor register will cancel
9968          * an already armed cursor update. Thus leaving out
9969          * the CURBASE write after CURPOS could lead to a
9970          * cursor that doesn't appear to move, or even change
9971          * shape. Thus we always write CURBASE.
9972          *
9973          * CURCNTR and CUR_FBC_CTL are always
9974          * armed by the CURBASE write only.
9975          */
9976         if (plane->cursor.base != base ||
9977             plane->cursor.size != fbc_ctl ||
9978             plane->cursor.cntl != cntl) {
9979                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9980                 if (HAS_CUR_FBC(dev_priv))
9981                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9982                 I915_WRITE_FW(CURPOS(pipe), pos);
9983                 I915_WRITE_FW(CURBASE(pipe), base);
9984
9985                 plane->cursor.base = base;
9986                 plane->cursor.size = fbc_ctl;
9987                 plane->cursor.cntl = cntl;
9988         } else {
9989                 I915_WRITE_FW(CURPOS(pipe), pos);
9990                 I915_WRITE_FW(CURBASE(pipe), base);
9991         }
9992
9993         POSTING_READ_FW(CURBASE(pipe));
9994
9995         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9996 }
9997
9998 static void i9xx_disable_cursor(struct intel_plane *plane,
9999                                 struct intel_crtc *crtc)
10000 {
10001         i9xx_update_cursor(plane, NULL, NULL);
10002 }
10003
10004 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10005                                      enum pipe *pipe)
10006 {
10007         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10008         enum intel_display_power_domain power_domain;
10009         bool ret;
10010         u32 val;
10011
10012         /*
10013          * Not 100% correct for planes that can move between pipes,
10014          * but that's only the case for gen2-3 which don't have any
10015          * display power wells.
10016          */
10017         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10018         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10019                 return false;
10020
10021         val = I915_READ(CURCNTR(plane->pipe));
10022
10023         ret = val & MCURSOR_MODE;
10024
10025         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10026                 *pipe = plane->pipe;
10027         else
10028                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10029                         MCURSOR_PIPE_SELECT_SHIFT;
10030
10031         intel_display_power_put(dev_priv, power_domain);
10032
10033         return ret;
10034 }
10035
10036 /* VESA 640x480x72Hz mode to set on the pipe */
10037 static const struct drm_display_mode load_detect_mode = {
10038         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10039                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10040 };
10041
10042 struct drm_framebuffer *
10043 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10044                          struct drm_mode_fb_cmd2 *mode_cmd)
10045 {
10046         struct intel_framebuffer *intel_fb;
10047         int ret;
10048
10049         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10050         if (!intel_fb)
10051                 return ERR_PTR(-ENOMEM);
10052
10053         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10054         if (ret)
10055                 goto err;
10056
10057         return &intel_fb->base;
10058
10059 err:
10060         kfree(intel_fb);
10061         return ERR_PTR(ret);
10062 }
10063
10064 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10065                                         struct drm_crtc *crtc)
10066 {
10067         struct drm_plane *plane;
10068         struct drm_plane_state *plane_state;
10069         int ret, i;
10070
10071         ret = drm_atomic_add_affected_planes(state, crtc);
10072         if (ret)
10073                 return ret;
10074
10075         for_each_new_plane_in_state(state, plane, plane_state, i) {
10076                 if (plane_state->crtc != crtc)
10077                         continue;
10078
10079                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10080                 if (ret)
10081                         return ret;
10082
10083                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10084         }
10085
10086         return 0;
10087 }
10088
10089 int intel_get_load_detect_pipe(struct drm_connector *connector,
10090                                const struct drm_display_mode *mode,
10091                                struct intel_load_detect_pipe *old,
10092                                struct drm_modeset_acquire_ctx *ctx)
10093 {
10094         struct intel_crtc *intel_crtc;
10095         struct intel_encoder *intel_encoder =
10096                 intel_attached_encoder(connector);
10097         struct drm_crtc *possible_crtc;
10098         struct drm_encoder *encoder = &intel_encoder->base;
10099         struct drm_crtc *crtc = NULL;
10100         struct drm_device *dev = encoder->dev;
10101         struct drm_i915_private *dev_priv = to_i915(dev);
10102         struct drm_mode_config *config = &dev->mode_config;
10103         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10104         struct drm_connector_state *connector_state;
10105         struct intel_crtc_state *crtc_state;
10106         int ret, i = -1;
10107
10108         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10109                       connector->base.id, connector->name,
10110                       encoder->base.id, encoder->name);
10111
10112         old->restore_state = NULL;
10113
10114         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10115
10116         /*
10117          * Algorithm gets a little messy:
10118          *
10119          *   - if the connector already has an assigned crtc, use it (but make
10120          *     sure it's on first)
10121          *
10122          *   - try to find the first unused crtc that can drive this connector,
10123          *     and use that if we find one
10124          */
10125
10126         /* See if we already have a CRTC for this connector */
10127         if (connector->state->crtc) {
10128                 crtc = connector->state->crtc;
10129
10130                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10131                 if (ret)
10132                         goto fail;
10133
10134                 /* Make sure the crtc and connector are running */
10135                 goto found;
10136         }
10137
10138         /* Find an unused one (if possible) */
10139         for_each_crtc(dev, possible_crtc) {
10140                 i++;
10141                 if (!(encoder->possible_crtcs & (1 << i)))
10142                         continue;
10143
10144                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10145                 if (ret)
10146                         goto fail;
10147
10148                 if (possible_crtc->state->enable) {
10149                         drm_modeset_unlock(&possible_crtc->mutex);
10150                         continue;
10151                 }
10152
10153                 crtc = possible_crtc;
10154                 break;
10155         }
10156
10157         /*
10158          * If we didn't find an unused CRTC, don't use any.
10159          */
10160         if (!crtc) {
10161                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10162                 ret = -ENODEV;
10163                 goto fail;
10164         }
10165
10166 found:
10167         intel_crtc = to_intel_crtc(crtc);
10168
10169         state = drm_atomic_state_alloc(dev);
10170         restore_state = drm_atomic_state_alloc(dev);
10171         if (!state || !restore_state) {
10172                 ret = -ENOMEM;
10173                 goto fail;
10174         }
10175
10176         state->acquire_ctx = ctx;
10177         restore_state->acquire_ctx = ctx;
10178
10179         connector_state = drm_atomic_get_connector_state(state, connector);
10180         if (IS_ERR(connector_state)) {
10181                 ret = PTR_ERR(connector_state);
10182                 goto fail;
10183         }
10184
10185         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10186         if (ret)
10187                 goto fail;
10188
10189         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10190         if (IS_ERR(crtc_state)) {
10191                 ret = PTR_ERR(crtc_state);
10192                 goto fail;
10193         }
10194
10195         crtc_state->base.active = crtc_state->base.enable = true;
10196
10197         if (!mode)
10198                 mode = &load_detect_mode;
10199
10200         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10201         if (ret)
10202                 goto fail;
10203
10204         ret = intel_modeset_disable_planes(state, crtc);
10205         if (ret)
10206                 goto fail;
10207
10208         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10209         if (!ret)
10210                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10211         if (!ret)
10212                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10213         if (ret) {
10214                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10215                 goto fail;
10216         }
10217
10218         ret = drm_atomic_commit(state);
10219         if (ret) {
10220                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10221                 goto fail;
10222         }
10223
10224         old->restore_state = restore_state;
10225         drm_atomic_state_put(state);
10226
10227         /* let the connector get through one full cycle before testing */
10228         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10229         return true;
10230
10231 fail:
10232         if (state) {
10233                 drm_atomic_state_put(state);
10234                 state = NULL;
10235         }
10236         if (restore_state) {
10237                 drm_atomic_state_put(restore_state);
10238                 restore_state = NULL;
10239         }
10240
10241         if (ret == -EDEADLK)
10242                 return ret;
10243
10244         return false;
10245 }
10246
10247 void intel_release_load_detect_pipe(struct drm_connector *connector,
10248                                     struct intel_load_detect_pipe *old,
10249                                     struct drm_modeset_acquire_ctx *ctx)
10250 {
10251         struct intel_encoder *intel_encoder =
10252                 intel_attached_encoder(connector);
10253         struct drm_encoder *encoder = &intel_encoder->base;
10254         struct drm_atomic_state *state = old->restore_state;
10255         int ret;
10256
10257         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10258                       connector->base.id, connector->name,
10259                       encoder->base.id, encoder->name);
10260
10261         if (!state)
10262                 return;
10263
10264         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10265         if (ret)
10266                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10267         drm_atomic_state_put(state);
10268 }
10269
10270 static int i9xx_pll_refclk(struct drm_device *dev,
10271                            const struct intel_crtc_state *pipe_config)
10272 {
10273         struct drm_i915_private *dev_priv = to_i915(dev);
10274         u32 dpll = pipe_config->dpll_hw_state.dpll;
10275
10276         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10277                 return dev_priv->vbt.lvds_ssc_freq;
10278         else if (HAS_PCH_SPLIT(dev_priv))
10279                 return 120000;
10280         else if (!IS_GEN2(dev_priv))
10281                 return 96000;
10282         else
10283                 return 48000;
10284 }
10285
10286 /* Returns the clock of the currently programmed mode of the given pipe. */
10287 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10288                                 struct intel_crtc_state *pipe_config)
10289 {
10290         struct drm_device *dev = crtc->base.dev;
10291         struct drm_i915_private *dev_priv = to_i915(dev);
10292         int pipe = pipe_config->cpu_transcoder;
10293         u32 dpll = pipe_config->dpll_hw_state.dpll;
10294         u32 fp;
10295         struct dpll clock;
10296         int port_clock;
10297         int refclk = i9xx_pll_refclk(dev, pipe_config);
10298
10299         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10300                 fp = pipe_config->dpll_hw_state.fp0;
10301         else
10302                 fp = pipe_config->dpll_hw_state.fp1;
10303
10304         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10305         if (IS_PINEVIEW(dev_priv)) {
10306                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10307                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10308         } else {
10309                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10310                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10311         }
10312
10313         if (!IS_GEN2(dev_priv)) {
10314                 if (IS_PINEVIEW(dev_priv))
10315                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10316                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10317                 else
10318                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10319                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10320
10321                 switch (dpll & DPLL_MODE_MASK) {
10322                 case DPLLB_MODE_DAC_SERIAL:
10323                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10324                                 5 : 10;
10325                         break;
10326                 case DPLLB_MODE_LVDS:
10327                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10328                                 7 : 14;
10329                         break;
10330                 default:
10331                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10332                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10333                         return;
10334                 }
10335
10336                 if (IS_PINEVIEW(dev_priv))
10337                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10338                 else
10339                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10340         } else {
10341                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10342                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10343
10344                 if (is_lvds) {
10345                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10346                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10347
10348                         if (lvds & LVDS_CLKB_POWER_UP)
10349                                 clock.p2 = 7;
10350                         else
10351                                 clock.p2 = 14;
10352                 } else {
10353                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10354                                 clock.p1 = 2;
10355                         else {
10356                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10357                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10358                         }
10359                         if (dpll & PLL_P2_DIVIDE_BY_4)
10360                                 clock.p2 = 4;
10361                         else
10362                                 clock.p2 = 2;
10363                 }
10364
10365                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10366         }
10367
10368         /*
10369          * This value includes pixel_multiplier. We will use
10370          * port_clock to compute adjusted_mode.crtc_clock in the
10371          * encoder's get_config() function.
10372          */
10373         pipe_config->port_clock = port_clock;
10374 }
10375
10376 int intel_dotclock_calculate(int link_freq,
10377                              const struct intel_link_m_n *m_n)
10378 {
10379         /*
10380          * The calculation for the data clock is:
10381          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10382          * But we want to avoid losing precison if possible, so:
10383          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10384          *
10385          * and the link clock is simpler:
10386          * link_clock = (m * link_clock) / n
10387          */
10388
10389         if (!m_n->link_n)
10390                 return 0;
10391
10392         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10393 }
10394
10395 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10396                                    struct intel_crtc_state *pipe_config)
10397 {
10398         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10399
10400         /* read out port_clock from the DPLL */
10401         i9xx_crtc_clock_get(crtc, pipe_config);
10402
10403         /*
10404          * In case there is an active pipe without active ports,
10405          * we may need some idea for the dotclock anyway.
10406          * Calculate one based on the FDI configuration.
10407          */
10408         pipe_config->base.adjusted_mode.crtc_clock =
10409                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10410                                          &pipe_config->fdi_m_n);
10411 }
10412
10413 /* Returns the currently programmed mode of the given encoder. */
10414 struct drm_display_mode *
10415 intel_encoder_current_mode(struct intel_encoder *encoder)
10416 {
10417         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10418         struct intel_crtc_state *crtc_state;
10419         struct drm_display_mode *mode;
10420         struct intel_crtc *crtc;
10421         enum pipe pipe;
10422
10423         if (!encoder->get_hw_state(encoder, &pipe))
10424                 return NULL;
10425
10426         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10427
10428         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10429         if (!mode)
10430                 return NULL;
10431
10432         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10433         if (!crtc_state) {
10434                 kfree(mode);
10435                 return NULL;
10436         }
10437
10438         crtc_state->base.crtc = &crtc->base;
10439
10440         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10441                 kfree(crtc_state);
10442                 kfree(mode);
10443                 return NULL;
10444         }
10445
10446         encoder->get_config(encoder, crtc_state);
10447
10448         intel_mode_from_pipe_config(mode, crtc_state);
10449
10450         kfree(crtc_state);
10451
10452         return mode;
10453 }
10454
10455 static void intel_crtc_destroy(struct drm_crtc *crtc)
10456 {
10457         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10458
10459         drm_crtc_cleanup(crtc);
10460         kfree(intel_crtc);
10461 }
10462
10463 /**
10464  * intel_wm_need_update - Check whether watermarks need updating
10465  * @plane: drm plane
10466  * @state: new plane state
10467  *
10468  * Check current plane state versus the new one to determine whether
10469  * watermarks need to be recalculated.
10470  *
10471  * Returns true or false.
10472  */
10473 static bool intel_wm_need_update(struct drm_plane *plane,
10474                                  struct drm_plane_state *state)
10475 {
10476         struct intel_plane_state *new = to_intel_plane_state(state);
10477         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10478
10479         /* Update watermarks on tiling or size changes. */
10480         if (new->base.visible != cur->base.visible)
10481                 return true;
10482
10483         if (!cur->base.fb || !new->base.fb)
10484                 return false;
10485
10486         if (cur->base.fb->modifier != new->base.fb->modifier ||
10487             cur->base.rotation != new->base.rotation ||
10488             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10489             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10490             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10491             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10492                 return true;
10493
10494         return false;
10495 }
10496
10497 static bool needs_scaling(const struct intel_plane_state *state)
10498 {
10499         int src_w = drm_rect_width(&state->base.src) >> 16;
10500         int src_h = drm_rect_height(&state->base.src) >> 16;
10501         int dst_w = drm_rect_width(&state->base.dst);
10502         int dst_h = drm_rect_height(&state->base.dst);
10503
10504         return (src_w != dst_w || src_h != dst_h);
10505 }
10506
10507 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10508                                     struct drm_crtc_state *crtc_state,
10509                                     const struct intel_plane_state *old_plane_state,
10510                                     struct drm_plane_state *plane_state)
10511 {
10512         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10513         struct drm_crtc *crtc = crtc_state->crtc;
10514         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10515         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10516         struct drm_device *dev = crtc->dev;
10517         struct drm_i915_private *dev_priv = to_i915(dev);
10518         bool mode_changed = needs_modeset(crtc_state);
10519         bool was_crtc_enabled = old_crtc_state->base.active;
10520         bool is_crtc_enabled = crtc_state->active;
10521         bool turn_off, turn_on, visible, was_visible;
10522         struct drm_framebuffer *fb = plane_state->fb;
10523         int ret;
10524
10525         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10526                 ret = skl_update_scaler_plane(
10527                         to_intel_crtc_state(crtc_state),
10528                         to_intel_plane_state(plane_state));
10529                 if (ret)
10530                         return ret;
10531         }
10532
10533         was_visible = old_plane_state->base.visible;
10534         visible = plane_state->visible;
10535
10536         if (!was_crtc_enabled && WARN_ON(was_visible))
10537                 was_visible = false;
10538
10539         /*
10540          * Visibility is calculated as if the crtc was on, but
10541          * after scaler setup everything depends on it being off
10542          * when the crtc isn't active.
10543          *
10544          * FIXME this is wrong for watermarks. Watermarks should also
10545          * be computed as if the pipe would be active. Perhaps move
10546          * per-plane wm computation to the .check_plane() hook, and
10547          * only combine the results from all planes in the current place?
10548          */
10549         if (!is_crtc_enabled) {
10550                 plane_state->visible = visible = false;
10551                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10552         }
10553
10554         if (!was_visible && !visible)
10555                 return 0;
10556
10557         if (fb != old_plane_state->base.fb)
10558                 pipe_config->fb_changed = true;
10559
10560         turn_off = was_visible && (!visible || mode_changed);
10561         turn_on = visible && (!was_visible || mode_changed);
10562
10563         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10564                          intel_crtc->base.base.id, intel_crtc->base.name,
10565                          plane->base.base.id, plane->base.name,
10566                          fb ? fb->base.id : -1);
10567
10568         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10569                          plane->base.base.id, plane->base.name,
10570                          was_visible, visible,
10571                          turn_off, turn_on, mode_changed);
10572
10573         if (turn_on) {
10574                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10575                         pipe_config->update_wm_pre = true;
10576
10577                 /* must disable cxsr around plane enable/disable */
10578                 if (plane->id != PLANE_CURSOR)
10579                         pipe_config->disable_cxsr = true;
10580         } else if (turn_off) {
10581                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10582                         pipe_config->update_wm_post = true;
10583
10584                 /* must disable cxsr around plane enable/disable */
10585                 if (plane->id != PLANE_CURSOR)
10586                         pipe_config->disable_cxsr = true;
10587         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10588                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10589                         /* FIXME bollocks */
10590                         pipe_config->update_wm_pre = true;
10591                         pipe_config->update_wm_post = true;
10592                 }
10593         }
10594
10595         if (visible || was_visible)
10596                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10597
10598         /*
10599          * WaCxSRDisabledForSpriteScaling:ivb
10600          *
10601          * cstate->update_wm was already set above, so this flag will
10602          * take effect when we commit and program watermarks.
10603          */
10604         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
10605             needs_scaling(to_intel_plane_state(plane_state)) &&
10606             !needs_scaling(old_plane_state))
10607                 pipe_config->disable_lp_wm = true;
10608
10609         return 0;
10610 }
10611
10612 static bool encoders_cloneable(const struct intel_encoder *a,
10613                                const struct intel_encoder *b)
10614 {
10615         /* masks could be asymmetric, so check both ways */
10616         return a == b || (a->cloneable & (1 << b->type) &&
10617                           b->cloneable & (1 << a->type));
10618 }
10619
10620 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10621                                          struct intel_crtc *crtc,
10622                                          struct intel_encoder *encoder)
10623 {
10624         struct intel_encoder *source_encoder;
10625         struct drm_connector *connector;
10626         struct drm_connector_state *connector_state;
10627         int i;
10628
10629         for_each_new_connector_in_state(state, connector, connector_state, i) {
10630                 if (connector_state->crtc != &crtc->base)
10631                         continue;
10632
10633                 source_encoder =
10634                         to_intel_encoder(connector_state->best_encoder);
10635                 if (!encoders_cloneable(encoder, source_encoder))
10636                         return false;
10637         }
10638
10639         return true;
10640 }
10641
10642 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10643                                    struct drm_crtc_state *crtc_state)
10644 {
10645         struct drm_device *dev = crtc->dev;
10646         struct drm_i915_private *dev_priv = to_i915(dev);
10647         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10648         struct intel_crtc_state *pipe_config =
10649                 to_intel_crtc_state(crtc_state);
10650         struct drm_atomic_state *state = crtc_state->state;
10651         int ret;
10652         bool mode_changed = needs_modeset(crtc_state);
10653
10654         if (mode_changed && !crtc_state->active)
10655                 pipe_config->update_wm_post = true;
10656
10657         if (mode_changed && crtc_state->enable &&
10658             dev_priv->display.crtc_compute_clock &&
10659             !WARN_ON(pipe_config->shared_dpll)) {
10660                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10661                                                            pipe_config);
10662                 if (ret)
10663                         return ret;
10664         }
10665
10666         if (crtc_state->color_mgmt_changed) {
10667                 ret = intel_color_check(crtc, crtc_state);
10668                 if (ret)
10669                         return ret;
10670
10671                 /*
10672                  * Changing color management on Intel hardware is
10673                  * handled as part of planes update.
10674                  */
10675                 crtc_state->planes_changed = true;
10676         }
10677
10678         ret = 0;
10679         if (dev_priv->display.compute_pipe_wm) {
10680                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10681                 if (ret) {
10682                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10683                         return ret;
10684                 }
10685         }
10686
10687         if (dev_priv->display.compute_intermediate_wm &&
10688             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10689                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10690                         return 0;
10691
10692                 /*
10693                  * Calculate 'intermediate' watermarks that satisfy both the
10694                  * old state and the new state.  We can program these
10695                  * immediately.
10696                  */
10697                 ret = dev_priv->display.compute_intermediate_wm(dev,
10698                                                                 intel_crtc,
10699                                                                 pipe_config);
10700                 if (ret) {
10701                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10702                         return ret;
10703                 }
10704         } else if (dev_priv->display.compute_intermediate_wm) {
10705                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10706                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10707         }
10708
10709         if (INTEL_GEN(dev_priv) >= 9) {
10710                 if (mode_changed)
10711                         ret = skl_update_scaler_crtc(pipe_config);
10712
10713                 if (!ret)
10714                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10715                                                             pipe_config);
10716                 if (!ret)
10717                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10718                                                          pipe_config);
10719         }
10720
10721         if (HAS_IPS(dev_priv))
10722                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10723
10724         return ret;
10725 }
10726
10727 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10728         .atomic_begin = intel_begin_crtc_commit,
10729         .atomic_flush = intel_finish_crtc_commit,
10730         .atomic_check = intel_crtc_atomic_check,
10731 };
10732
10733 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10734 {
10735         struct intel_connector *connector;
10736         struct drm_connector_list_iter conn_iter;
10737
10738         drm_connector_list_iter_begin(dev, &conn_iter);
10739         for_each_intel_connector_iter(connector, &conn_iter) {
10740                 if (connector->base.state->crtc)
10741                         drm_connector_put(&connector->base);
10742
10743                 if (connector->base.encoder) {
10744                         connector->base.state->best_encoder =
10745                                 connector->base.encoder;
10746                         connector->base.state->crtc =
10747                                 connector->base.encoder->crtc;
10748
10749                         drm_connector_get(&connector->base);
10750                 } else {
10751                         connector->base.state->best_encoder = NULL;
10752                         connector->base.state->crtc = NULL;
10753                 }
10754         }
10755         drm_connector_list_iter_end(&conn_iter);
10756 }
10757
10758 static void
10759 connected_sink_compute_bpp(struct intel_connector *connector,
10760                            struct intel_crtc_state *pipe_config)
10761 {
10762         const struct drm_display_info *info = &connector->base.display_info;
10763         int bpp = pipe_config->pipe_bpp;
10764
10765         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10766                       connector->base.base.id,
10767                       connector->base.name);
10768
10769         /* Don't use an invalid EDID bpc value */
10770         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10771                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10772                               bpp, info->bpc * 3);
10773                 pipe_config->pipe_bpp = info->bpc * 3;
10774         }
10775
10776         /* Clamp bpp to 8 on screens without EDID 1.4 */
10777         if (info->bpc == 0 && bpp > 24) {
10778                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10779                               bpp);
10780                 pipe_config->pipe_bpp = 24;
10781         }
10782 }
10783
10784 static int
10785 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10786                           struct intel_crtc_state *pipe_config)
10787 {
10788         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10789         struct drm_atomic_state *state;
10790         struct drm_connector *connector;
10791         struct drm_connector_state *connector_state;
10792         int bpp, i;
10793
10794         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10795             IS_CHERRYVIEW(dev_priv)))
10796                 bpp = 10*3;
10797         else if (INTEL_GEN(dev_priv) >= 5)
10798                 bpp = 12*3;
10799         else
10800                 bpp = 8*3;
10801
10802
10803         pipe_config->pipe_bpp = bpp;
10804
10805         state = pipe_config->base.state;
10806
10807         /* Clamp display bpp to EDID value */
10808         for_each_new_connector_in_state(state, connector, connector_state, i) {
10809                 if (connector_state->crtc != &crtc->base)
10810                         continue;
10811
10812                 connected_sink_compute_bpp(to_intel_connector(connector),
10813                                            pipe_config);
10814         }
10815
10816         return bpp;
10817 }
10818
10819 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10820 {
10821         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10822                         "type: 0x%x flags: 0x%x\n",
10823                 mode->crtc_clock,
10824                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10825                 mode->crtc_hsync_end, mode->crtc_htotal,
10826                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10827                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10828 }
10829
10830 static inline void
10831 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10832                       unsigned int lane_count, struct intel_link_m_n *m_n)
10833 {
10834         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10835                       id, lane_count,
10836                       m_n->gmch_m, m_n->gmch_n,
10837                       m_n->link_m, m_n->link_n, m_n->tu);
10838 }
10839
10840 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10841
10842 static const char * const output_type_str[] = {
10843         OUTPUT_TYPE(UNUSED),
10844         OUTPUT_TYPE(ANALOG),
10845         OUTPUT_TYPE(DVO),
10846         OUTPUT_TYPE(SDVO),
10847         OUTPUT_TYPE(LVDS),
10848         OUTPUT_TYPE(TVOUT),
10849         OUTPUT_TYPE(HDMI),
10850         OUTPUT_TYPE(DP),
10851         OUTPUT_TYPE(EDP),
10852         OUTPUT_TYPE(DSI),
10853         OUTPUT_TYPE(DDI),
10854         OUTPUT_TYPE(DP_MST),
10855 };
10856
10857 #undef OUTPUT_TYPE
10858
10859 static void snprintf_output_types(char *buf, size_t len,
10860                                   unsigned int output_types)
10861 {
10862         char *str = buf;
10863         int i;
10864
10865         str[0] = '\0';
10866
10867         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
10868                 int r;
10869
10870                 if ((output_types & BIT(i)) == 0)
10871                         continue;
10872
10873                 r = snprintf(str, len, "%s%s",
10874                              str != buf ? "," : "", output_type_str[i]);
10875                 if (r >= len)
10876                         break;
10877                 str += r;
10878                 len -= r;
10879
10880                 output_types &= ~BIT(i);
10881         }
10882
10883         WARN_ON_ONCE(output_types != 0);
10884 }
10885
10886 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10887                                    struct intel_crtc_state *pipe_config,
10888                                    const char *context)
10889 {
10890         struct drm_device *dev = crtc->base.dev;
10891         struct drm_i915_private *dev_priv = to_i915(dev);
10892         struct drm_plane *plane;
10893         struct intel_plane *intel_plane;
10894         struct intel_plane_state *state;
10895         struct drm_framebuffer *fb;
10896         char buf[64];
10897
10898         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10899                       crtc->base.base.id, crtc->base.name, context);
10900
10901         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
10902         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
10903                       buf, pipe_config->output_types);
10904
10905         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
10906                       transcoder_name(pipe_config->cpu_transcoder),
10907                       pipe_config->pipe_bpp, pipe_config->dither);
10908
10909         if (pipe_config->has_pch_encoder)
10910                 intel_dump_m_n_config(pipe_config, "fdi",
10911                                       pipe_config->fdi_lanes,
10912                                       &pipe_config->fdi_m_n);
10913
10914         if (pipe_config->ycbcr420)
10915                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
10916
10917         if (intel_crtc_has_dp_encoder(pipe_config)) {
10918                 intel_dump_m_n_config(pipe_config, "dp m_n",
10919                                 pipe_config->lane_count, &pipe_config->dp_m_n);
10920                 if (pipe_config->has_drrs)
10921                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
10922                                               pipe_config->lane_count,
10923                                               &pipe_config->dp_m2_n2);
10924         }
10925
10926         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10927                       pipe_config->has_audio, pipe_config->has_infoframe);
10928
10929         DRM_DEBUG_KMS("requested mode:\n");
10930         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10931         DRM_DEBUG_KMS("adjusted mode:\n");
10932         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10933         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10934         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
10935                       pipe_config->port_clock,
10936                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
10937                       pipe_config->pixel_rate);
10938
10939         if (INTEL_GEN(dev_priv) >= 9)
10940                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
10941                               crtc->num_scalers,
10942                               pipe_config->scaler_state.scaler_users,
10943                               pipe_config->scaler_state.scaler_id);
10944
10945         if (HAS_GMCH_DISPLAY(dev_priv))
10946                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10947                               pipe_config->gmch_pfit.control,
10948                               pipe_config->gmch_pfit.pgm_ratios,
10949                               pipe_config->gmch_pfit.lvds_border_bits);
10950         else
10951                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10952                               pipe_config->pch_pfit.pos,
10953                               pipe_config->pch_pfit.size,
10954                               enableddisabled(pipe_config->pch_pfit.enabled));
10955
10956         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
10957                       pipe_config->ips_enabled, pipe_config->double_wide);
10958
10959         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
10960
10961         DRM_DEBUG_KMS("planes on this crtc\n");
10962         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
10963                 struct drm_format_name_buf format_name;
10964                 intel_plane = to_intel_plane(plane);
10965                 if (intel_plane->pipe != crtc->pipe)
10966                         continue;
10967
10968                 state = to_intel_plane_state(plane->state);
10969                 fb = state->base.fb;
10970                 if (!fb) {
10971                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
10972                                       plane->base.id, plane->name, state->scaler_id);
10973                         continue;
10974                 }
10975
10976                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
10977                               plane->base.id, plane->name,
10978                               fb->base.id, fb->width, fb->height,
10979                               drm_get_format_name(fb->format->format, &format_name));
10980                 if (INTEL_GEN(dev_priv) >= 9)
10981                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
10982                                       state->scaler_id,
10983                                       state->base.src.x1 >> 16,
10984                                       state->base.src.y1 >> 16,
10985                                       drm_rect_width(&state->base.src) >> 16,
10986                                       drm_rect_height(&state->base.src) >> 16,
10987                                       state->base.dst.x1, state->base.dst.y1,
10988                                       drm_rect_width(&state->base.dst),
10989                                       drm_rect_height(&state->base.dst));
10990         }
10991 }
10992
10993 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
10994 {
10995         struct drm_device *dev = state->dev;
10996         struct drm_connector *connector;
10997         struct drm_connector_list_iter conn_iter;
10998         unsigned int used_ports = 0;
10999         unsigned int used_mst_ports = 0;
11000         bool ret = true;
11001
11002         /*
11003          * Walk the connector list instead of the encoder
11004          * list to detect the problem on ddi platforms
11005          * where there's just one encoder per digital port.
11006          */
11007         drm_connector_list_iter_begin(dev, &conn_iter);
11008         drm_for_each_connector_iter(connector, &conn_iter) {
11009                 struct drm_connector_state *connector_state;
11010                 struct intel_encoder *encoder;
11011
11012                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11013                 if (!connector_state)
11014                         connector_state = connector->state;
11015
11016                 if (!connector_state->best_encoder)
11017                         continue;
11018
11019                 encoder = to_intel_encoder(connector_state->best_encoder);
11020
11021                 WARN_ON(!connector_state->crtc);
11022
11023                 switch (encoder->type) {
11024                         unsigned int port_mask;
11025                 case INTEL_OUTPUT_DDI:
11026                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11027                                 break;
11028                         /* else: fall through */
11029                 case INTEL_OUTPUT_DP:
11030                 case INTEL_OUTPUT_HDMI:
11031                 case INTEL_OUTPUT_EDP:
11032                         port_mask = 1 << encoder->port;
11033
11034                         /* the same port mustn't appear more than once */
11035                         if (used_ports & port_mask)
11036                                 ret = false;
11037
11038                         used_ports |= port_mask;
11039                         break;
11040                 case INTEL_OUTPUT_DP_MST:
11041                         used_mst_ports |=
11042                                 1 << encoder->port;
11043                         break;
11044                 default:
11045                         break;
11046                 }
11047         }
11048         drm_connector_list_iter_end(&conn_iter);
11049
11050         /* can't mix MST and SST/HDMI on the same port */
11051         if (used_ports & used_mst_ports)
11052                 return false;
11053
11054         return ret;
11055 }
11056
11057 static void
11058 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11059 {
11060         struct drm_i915_private *dev_priv =
11061                 to_i915(crtc_state->base.crtc->dev);
11062         struct intel_crtc_scaler_state scaler_state;
11063         struct intel_dpll_hw_state dpll_hw_state;
11064         struct intel_shared_dpll *shared_dpll;
11065         struct intel_crtc_wm_state wm_state;
11066         bool force_thru, ips_force_disable;
11067
11068         /* FIXME: before the switch to atomic started, a new pipe_config was
11069          * kzalloc'd. Code that depends on any field being zero should be
11070          * fixed, so that the crtc_state can be safely duplicated. For now,
11071          * only fields that are know to not cause problems are preserved. */
11072
11073         scaler_state = crtc_state->scaler_state;
11074         shared_dpll = crtc_state->shared_dpll;
11075         dpll_hw_state = crtc_state->dpll_hw_state;
11076         force_thru = crtc_state->pch_pfit.force_thru;
11077         ips_force_disable = crtc_state->ips_force_disable;
11078         if (IS_G4X(dev_priv) ||
11079             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11080                 wm_state = crtc_state->wm;
11081
11082         /* Keep base drm_crtc_state intact, only clear our extended struct */
11083         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11084         memset(&crtc_state->base + 1, 0,
11085                sizeof(*crtc_state) - sizeof(crtc_state->base));
11086
11087         crtc_state->scaler_state = scaler_state;
11088         crtc_state->shared_dpll = shared_dpll;
11089         crtc_state->dpll_hw_state = dpll_hw_state;
11090         crtc_state->pch_pfit.force_thru = force_thru;
11091         crtc_state->ips_force_disable = ips_force_disable;
11092         if (IS_G4X(dev_priv) ||
11093             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11094                 crtc_state->wm = wm_state;
11095 }
11096
11097 static int
11098 intel_modeset_pipe_config(struct drm_crtc *crtc,
11099                           struct intel_crtc_state *pipe_config)
11100 {
11101         struct drm_atomic_state *state = pipe_config->base.state;
11102         struct intel_encoder *encoder;
11103         struct drm_connector *connector;
11104         struct drm_connector_state *connector_state;
11105         int base_bpp, ret = -EINVAL;
11106         int i;
11107         bool retry = true;
11108
11109         clear_intel_crtc_state(pipe_config);
11110
11111         pipe_config->cpu_transcoder =
11112                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11113
11114         /*
11115          * Sanitize sync polarity flags based on requested ones. If neither
11116          * positive or negative polarity is requested, treat this as meaning
11117          * negative polarity.
11118          */
11119         if (!(pipe_config->base.adjusted_mode.flags &
11120               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11121                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11122
11123         if (!(pipe_config->base.adjusted_mode.flags &
11124               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11125                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11126
11127         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11128                                              pipe_config);
11129         if (base_bpp < 0)
11130                 goto fail;
11131
11132         /*
11133          * Determine the real pipe dimensions. Note that stereo modes can
11134          * increase the actual pipe size due to the frame doubling and
11135          * insertion of additional space for blanks between the frame. This
11136          * is stored in the crtc timings. We use the requested mode to do this
11137          * computation to clearly distinguish it from the adjusted mode, which
11138          * can be changed by the connectors in the below retry loop.
11139          */
11140         drm_mode_get_hv_timing(&pipe_config->base.mode,
11141                                &pipe_config->pipe_src_w,
11142                                &pipe_config->pipe_src_h);
11143
11144         for_each_new_connector_in_state(state, connector, connector_state, i) {
11145                 if (connector_state->crtc != crtc)
11146                         continue;
11147
11148                 encoder = to_intel_encoder(connector_state->best_encoder);
11149
11150                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11151                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11152                         goto fail;
11153                 }
11154
11155                 /*
11156                  * Determine output_types before calling the .compute_config()
11157                  * hooks so that the hooks can use this information safely.
11158                  */
11159                 if (encoder->compute_output_type)
11160                         pipe_config->output_types |=
11161                                 BIT(encoder->compute_output_type(encoder, pipe_config,
11162                                                                  connector_state));
11163                 else
11164                         pipe_config->output_types |= BIT(encoder->type);
11165         }
11166
11167 encoder_retry:
11168         /* Ensure the port clock defaults are reset when retrying. */
11169         pipe_config->port_clock = 0;
11170         pipe_config->pixel_multiplier = 1;
11171
11172         /* Fill in default crtc timings, allow encoders to overwrite them. */
11173         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11174                               CRTC_STEREO_DOUBLE);
11175
11176         /* Pass our mode to the connectors and the CRTC to give them a chance to
11177          * adjust it according to limitations or connector properties, and also
11178          * a chance to reject the mode entirely.
11179          */
11180         for_each_new_connector_in_state(state, connector, connector_state, i) {
11181                 if (connector_state->crtc != crtc)
11182                         continue;
11183
11184                 encoder = to_intel_encoder(connector_state->best_encoder);
11185
11186                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
11187                         DRM_DEBUG_KMS("Encoder config failure\n");
11188                         goto fail;
11189                 }
11190         }
11191
11192         /* Set default port clock if not overwritten by the encoder. Needs to be
11193          * done afterwards in case the encoder adjusts the mode. */
11194         if (!pipe_config->port_clock)
11195                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11196                         * pipe_config->pixel_multiplier;
11197
11198         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11199         if (ret < 0) {
11200                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11201                 goto fail;
11202         }
11203
11204         if (ret == RETRY) {
11205                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11206                         ret = -EINVAL;
11207                         goto fail;
11208                 }
11209
11210                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11211                 retry = false;
11212                 goto encoder_retry;
11213         }
11214
11215         /* Dithering seems to not pass-through bits correctly when it should, so
11216          * only enable it on 6bpc panels and when its not a compliance
11217          * test requesting 6bpc video pattern.
11218          */
11219         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11220                 !pipe_config->dither_force_disable;
11221         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11222                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11223
11224 fail:
11225         return ret;
11226 }
11227
11228 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11229 {
11230         int diff;
11231
11232         if (clock1 == clock2)
11233                 return true;
11234
11235         if (!clock1 || !clock2)
11236                 return false;
11237
11238         diff = abs(clock1 - clock2);
11239
11240         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11241                 return true;
11242
11243         return false;
11244 }
11245
11246 static bool
11247 intel_compare_m_n(unsigned int m, unsigned int n,
11248                   unsigned int m2, unsigned int n2,
11249                   bool exact)
11250 {
11251         if (m == m2 && n == n2)
11252                 return true;
11253
11254         if (exact || !m || !n || !m2 || !n2)
11255                 return false;
11256
11257         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11258
11259         if (n > n2) {
11260                 while (n > n2) {
11261                         m2 <<= 1;
11262                         n2 <<= 1;
11263                 }
11264         } else if (n < n2) {
11265                 while (n < n2) {
11266                         m <<= 1;
11267                         n <<= 1;
11268                 }
11269         }
11270
11271         if (n != n2)
11272                 return false;
11273
11274         return intel_fuzzy_clock_check(m, m2);
11275 }
11276
11277 static bool
11278 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11279                        struct intel_link_m_n *m2_n2,
11280                        bool adjust)
11281 {
11282         if (m_n->tu == m2_n2->tu &&
11283             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11284                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11285             intel_compare_m_n(m_n->link_m, m_n->link_n,
11286                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11287                 if (adjust)
11288                         *m2_n2 = *m_n;
11289
11290                 return true;
11291         }
11292
11293         return false;
11294 }
11295
11296 static void __printf(3, 4)
11297 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11298 {
11299         struct va_format vaf;
11300         va_list args;
11301
11302         va_start(args, format);
11303         vaf.fmt = format;
11304         vaf.va = &args;
11305
11306         if (adjust)
11307                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11308         else
11309                 drm_err("mismatch in %s %pV", name, &vaf);
11310
11311         va_end(args);
11312 }
11313
11314 static bool
11315 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11316                           struct intel_crtc_state *current_config,
11317                           struct intel_crtc_state *pipe_config,
11318                           bool adjust)
11319 {
11320         bool ret = true;
11321         bool fixup_inherited = adjust &&
11322                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11323                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11324
11325 #define PIPE_CONF_CHECK_X(name) do { \
11326         if (current_config->name != pipe_config->name) { \
11327                 pipe_config_err(adjust, __stringify(name), \
11328                           "(expected 0x%08x, found 0x%08x)\n", \
11329                           current_config->name, \
11330                           pipe_config->name); \
11331                 ret = false; \
11332         } \
11333 } while (0)
11334
11335 #define PIPE_CONF_CHECK_I(name) do { \
11336         if (current_config->name != pipe_config->name) { \
11337                 pipe_config_err(adjust, __stringify(name), \
11338                           "(expected %i, found %i)\n", \
11339                           current_config->name, \
11340                           pipe_config->name); \
11341                 ret = false; \
11342         } \
11343 } while (0)
11344
11345 #define PIPE_CONF_CHECK_BOOL(name) do { \
11346         if (current_config->name != pipe_config->name) { \
11347                 pipe_config_err(adjust, __stringify(name), \
11348                           "(expected %s, found %s)\n", \
11349                           yesno(current_config->name), \
11350                           yesno(pipe_config->name)); \
11351                 ret = false; \
11352         } \
11353 } while (0)
11354
11355 /*
11356  * Checks state where we only read out the enabling, but not the entire
11357  * state itself (like full infoframes or ELD for audio). These states
11358  * require a full modeset on bootup to fix up.
11359  */
11360 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
11361         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11362                 PIPE_CONF_CHECK_BOOL(name); \
11363         } else { \
11364                 pipe_config_err(adjust, __stringify(name), \
11365                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11366                           yesno(current_config->name), \
11367                           yesno(pipe_config->name)); \
11368                 ret = false; \
11369         } \
11370 } while (0)
11371
11372 #define PIPE_CONF_CHECK_P(name) do { \
11373         if (current_config->name != pipe_config->name) { \
11374                 pipe_config_err(adjust, __stringify(name), \
11375                           "(expected %p, found %p)\n", \
11376                           current_config->name, \
11377                           pipe_config->name); \
11378                 ret = false; \
11379         } \
11380 } while (0)
11381
11382 #define PIPE_CONF_CHECK_M_N(name) do { \
11383         if (!intel_compare_link_m_n(&current_config->name, \
11384                                     &pipe_config->name,\
11385                                     adjust)) { \
11386                 pipe_config_err(adjust, __stringify(name), \
11387                           "(expected tu %i gmch %i/%i link %i/%i, " \
11388                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11389                           current_config->name.tu, \
11390                           current_config->name.gmch_m, \
11391                           current_config->name.gmch_n, \
11392                           current_config->name.link_m, \
11393                           current_config->name.link_n, \
11394                           pipe_config->name.tu, \
11395                           pipe_config->name.gmch_m, \
11396                           pipe_config->name.gmch_n, \
11397                           pipe_config->name.link_m, \
11398                           pipe_config->name.link_n); \
11399                 ret = false; \
11400         } \
11401 } while (0)
11402
11403 /* This is required for BDW+ where there is only one set of registers for
11404  * switching between high and low RR.
11405  * This macro can be used whenever a comparison has to be made between one
11406  * hw state and multiple sw state variables.
11407  */
11408 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
11409         if (!intel_compare_link_m_n(&current_config->name, \
11410                                     &pipe_config->name, adjust) && \
11411             !intel_compare_link_m_n(&current_config->alt_name, \
11412                                     &pipe_config->name, adjust)) { \
11413                 pipe_config_err(adjust, __stringify(name), \
11414                           "(expected tu %i gmch %i/%i link %i/%i, " \
11415                           "or tu %i gmch %i/%i link %i/%i, " \
11416                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11417                           current_config->name.tu, \
11418                           current_config->name.gmch_m, \
11419                           current_config->name.gmch_n, \
11420                           current_config->name.link_m, \
11421                           current_config->name.link_n, \
11422                           current_config->alt_name.tu, \
11423                           current_config->alt_name.gmch_m, \
11424                           current_config->alt_name.gmch_n, \
11425                           current_config->alt_name.link_m, \
11426                           current_config->alt_name.link_n, \
11427                           pipe_config->name.tu, \
11428                           pipe_config->name.gmch_m, \
11429                           pipe_config->name.gmch_n, \
11430                           pipe_config->name.link_m, \
11431                           pipe_config->name.link_n); \
11432                 ret = false; \
11433         } \
11434 } while (0)
11435
11436 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
11437         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11438                 pipe_config_err(adjust, __stringify(name), \
11439                           "(%x) (expected %i, found %i)\n", \
11440                           (mask), \
11441                           current_config->name & (mask), \
11442                           pipe_config->name & (mask)); \
11443                 ret = false; \
11444         } \
11445 } while (0)
11446
11447 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
11448         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11449                 pipe_config_err(adjust, __stringify(name), \
11450                           "(expected %i, found %i)\n", \
11451                           current_config->name, \
11452                           pipe_config->name); \
11453                 ret = false; \
11454         } \
11455 } while (0)
11456
11457 #define PIPE_CONF_QUIRK(quirk)  \
11458         ((current_config->quirks | pipe_config->quirks) & (quirk))
11459
11460         PIPE_CONF_CHECK_I(cpu_transcoder);
11461
11462         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11463         PIPE_CONF_CHECK_I(fdi_lanes);
11464         PIPE_CONF_CHECK_M_N(fdi_m_n);
11465
11466         PIPE_CONF_CHECK_I(lane_count);
11467         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11468
11469         if (INTEL_GEN(dev_priv) < 8) {
11470                 PIPE_CONF_CHECK_M_N(dp_m_n);
11471
11472                 if (current_config->has_drrs)
11473                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11474         } else
11475                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11476
11477         PIPE_CONF_CHECK_X(output_types);
11478
11479         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11480         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11481         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11482         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11483         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11484         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11485
11486         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11487         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11488         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11489         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11490         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11491         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11492
11493         PIPE_CONF_CHECK_I(pixel_multiplier);
11494         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11495         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11496             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11497                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11498
11499         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11500         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11501         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11502         PIPE_CONF_CHECK_BOOL(ycbcr420);
11503
11504         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11505
11506         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11507                               DRM_MODE_FLAG_INTERLACE);
11508
11509         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11510                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11511                                       DRM_MODE_FLAG_PHSYNC);
11512                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11513                                       DRM_MODE_FLAG_NHSYNC);
11514                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11515                                       DRM_MODE_FLAG_PVSYNC);
11516                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11517                                       DRM_MODE_FLAG_NVSYNC);
11518         }
11519
11520         PIPE_CONF_CHECK_X(gmch_pfit.control);
11521         /* pfit ratios are autocomputed by the hw on gen4+ */
11522         if (INTEL_GEN(dev_priv) < 4)
11523                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11524         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11525
11526         if (!adjust) {
11527                 PIPE_CONF_CHECK_I(pipe_src_w);
11528                 PIPE_CONF_CHECK_I(pipe_src_h);
11529
11530                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11531                 if (current_config->pch_pfit.enabled) {
11532                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11533                         PIPE_CONF_CHECK_X(pch_pfit.size);
11534                 }
11535
11536                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11537                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11538         }
11539
11540         PIPE_CONF_CHECK_BOOL(double_wide);
11541
11542         PIPE_CONF_CHECK_P(shared_dpll);
11543         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11544         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11545         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11546         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11547         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11548         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11549         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11550         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11551         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11552         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11553         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11554         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11555         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11556         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11557         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11558         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11559         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11560         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11561         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11562         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11563         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11564         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
11565         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
11566         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
11567         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
11568         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
11569         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
11570         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
11571         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
11572         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
11573         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
11574
11575         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11576         PIPE_CONF_CHECK_X(dsi_pll.div);
11577
11578         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11579                 PIPE_CONF_CHECK_I(pipe_bpp);
11580
11581         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11582         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11583
11584         PIPE_CONF_CHECK_I(min_voltage_level);
11585
11586 #undef PIPE_CONF_CHECK_X
11587 #undef PIPE_CONF_CHECK_I
11588 #undef PIPE_CONF_CHECK_BOOL
11589 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11590 #undef PIPE_CONF_CHECK_P
11591 #undef PIPE_CONF_CHECK_FLAGS
11592 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11593 #undef PIPE_CONF_QUIRK
11594
11595         return ret;
11596 }
11597
11598 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11599                                            const struct intel_crtc_state *pipe_config)
11600 {
11601         if (pipe_config->has_pch_encoder) {
11602                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11603                                                             &pipe_config->fdi_m_n);
11604                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11605
11606                 /*
11607                  * FDI already provided one idea for the dotclock.
11608                  * Yell if the encoder disagrees.
11609                  */
11610                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11611                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11612                      fdi_dotclock, dotclock);
11613         }
11614 }
11615
11616 static void verify_wm_state(struct drm_crtc *crtc,
11617                             struct drm_crtc_state *new_state)
11618 {
11619         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11620         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11621         struct skl_pipe_wm hw_wm, *sw_wm;
11622         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11623         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11624         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11625         const enum pipe pipe = intel_crtc->pipe;
11626         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11627
11628         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11629                 return;
11630
11631         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11632         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11633
11634         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11635         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11636
11637         if (INTEL_GEN(dev_priv) >= 11)
11638                 if (hw_ddb.enabled_slices != sw_ddb->enabled_slices)
11639                         DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
11640                                   sw_ddb->enabled_slices,
11641                                   hw_ddb.enabled_slices);
11642         /* planes */
11643         for_each_universal_plane(dev_priv, pipe, plane) {
11644                 hw_plane_wm = &hw_wm.planes[plane];
11645                 sw_plane_wm = &sw_wm->planes[plane];
11646
11647                 /* Watermarks */
11648                 for (level = 0; level <= max_level; level++) {
11649                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11650                                                 &sw_plane_wm->wm[level]))
11651                                 continue;
11652
11653                         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",
11654                                   pipe_name(pipe), plane + 1, level,
11655                                   sw_plane_wm->wm[level].plane_en,
11656                                   sw_plane_wm->wm[level].plane_res_b,
11657                                   sw_plane_wm->wm[level].plane_res_l,
11658                                   hw_plane_wm->wm[level].plane_en,
11659                                   hw_plane_wm->wm[level].plane_res_b,
11660                                   hw_plane_wm->wm[level].plane_res_l);
11661                 }
11662
11663                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11664                                          &sw_plane_wm->trans_wm)) {
11665                         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",
11666                                   pipe_name(pipe), plane + 1,
11667                                   sw_plane_wm->trans_wm.plane_en,
11668                                   sw_plane_wm->trans_wm.plane_res_b,
11669                                   sw_plane_wm->trans_wm.plane_res_l,
11670                                   hw_plane_wm->trans_wm.plane_en,
11671                                   hw_plane_wm->trans_wm.plane_res_b,
11672                                   hw_plane_wm->trans_wm.plane_res_l);
11673                 }
11674
11675                 /* DDB */
11676                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11677                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11678
11679                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11680                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11681                                   pipe_name(pipe), plane + 1,
11682                                   sw_ddb_entry->start, sw_ddb_entry->end,
11683                                   hw_ddb_entry->start, hw_ddb_entry->end);
11684                 }
11685         }
11686
11687         /*
11688          * cursor
11689          * If the cursor plane isn't active, we may not have updated it's ddb
11690          * allocation. In that case since the ddb allocation will be updated
11691          * once the plane becomes visible, we can skip this check
11692          */
11693         if (1) {
11694                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11695                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11696
11697                 /* Watermarks */
11698                 for (level = 0; level <= max_level; level++) {
11699                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11700                                                 &sw_plane_wm->wm[level]))
11701                                 continue;
11702
11703                         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",
11704                                   pipe_name(pipe), level,
11705                                   sw_plane_wm->wm[level].plane_en,
11706                                   sw_plane_wm->wm[level].plane_res_b,
11707                                   sw_plane_wm->wm[level].plane_res_l,
11708                                   hw_plane_wm->wm[level].plane_en,
11709                                   hw_plane_wm->wm[level].plane_res_b,
11710                                   hw_plane_wm->wm[level].plane_res_l);
11711                 }
11712
11713                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11714                                          &sw_plane_wm->trans_wm)) {
11715                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11716                                   pipe_name(pipe),
11717                                   sw_plane_wm->trans_wm.plane_en,
11718                                   sw_plane_wm->trans_wm.plane_res_b,
11719                                   sw_plane_wm->trans_wm.plane_res_l,
11720                                   hw_plane_wm->trans_wm.plane_en,
11721                                   hw_plane_wm->trans_wm.plane_res_b,
11722                                   hw_plane_wm->trans_wm.plane_res_l);
11723                 }
11724
11725                 /* DDB */
11726                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11727                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11728
11729                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11730                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11731                                   pipe_name(pipe),
11732                                   sw_ddb_entry->start, sw_ddb_entry->end,
11733                                   hw_ddb_entry->start, hw_ddb_entry->end);
11734                 }
11735         }
11736 }
11737
11738 static void
11739 verify_connector_state(struct drm_device *dev,
11740                        struct drm_atomic_state *state,
11741                        struct drm_crtc *crtc)
11742 {
11743         struct drm_connector *connector;
11744         struct drm_connector_state *new_conn_state;
11745         int i;
11746
11747         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11748                 struct drm_encoder *encoder = connector->encoder;
11749                 struct drm_crtc_state *crtc_state = NULL;
11750
11751                 if (new_conn_state->crtc != crtc)
11752                         continue;
11753
11754                 if (crtc)
11755                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11756
11757                 intel_connector_verify_state(crtc_state, new_conn_state);
11758
11759                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11760                      "connector's atomic encoder doesn't match legacy encoder\n");
11761         }
11762 }
11763
11764 static void
11765 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11766 {
11767         struct intel_encoder *encoder;
11768         struct drm_connector *connector;
11769         struct drm_connector_state *old_conn_state, *new_conn_state;
11770         int i;
11771
11772         for_each_intel_encoder(dev, encoder) {
11773                 bool enabled = false, found = false;
11774                 enum pipe pipe;
11775
11776                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11777                               encoder->base.base.id,
11778                               encoder->base.name);
11779
11780                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11781                                                    new_conn_state, i) {
11782                         if (old_conn_state->best_encoder == &encoder->base)
11783                                 found = true;
11784
11785                         if (new_conn_state->best_encoder != &encoder->base)
11786                                 continue;
11787                         found = enabled = true;
11788
11789                         I915_STATE_WARN(new_conn_state->crtc !=
11790                                         encoder->base.crtc,
11791                              "connector's crtc doesn't match encoder crtc\n");
11792                 }
11793
11794                 if (!found)
11795                         continue;
11796
11797                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11798                      "encoder's enabled state mismatch "
11799                      "(expected %i, found %i)\n",
11800                      !!encoder->base.crtc, enabled);
11801
11802                 if (!encoder->base.crtc) {
11803                         bool active;
11804
11805                         active = encoder->get_hw_state(encoder, &pipe);
11806                         I915_STATE_WARN(active,
11807                              "encoder detached but still enabled on pipe %c.\n",
11808                              pipe_name(pipe));
11809                 }
11810         }
11811 }
11812
11813 static void
11814 verify_crtc_state(struct drm_crtc *crtc,
11815                   struct drm_crtc_state *old_crtc_state,
11816                   struct drm_crtc_state *new_crtc_state)
11817 {
11818         struct drm_device *dev = crtc->dev;
11819         struct drm_i915_private *dev_priv = to_i915(dev);
11820         struct intel_encoder *encoder;
11821         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11822         struct intel_crtc_state *pipe_config, *sw_config;
11823         struct drm_atomic_state *old_state;
11824         bool active;
11825
11826         old_state = old_crtc_state->state;
11827         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11828         pipe_config = to_intel_crtc_state(old_crtc_state);
11829         memset(pipe_config, 0, sizeof(*pipe_config));
11830         pipe_config->base.crtc = crtc;
11831         pipe_config->base.state = old_state;
11832
11833         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11834
11835         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11836
11837         /* we keep both pipes enabled on 830 */
11838         if (IS_I830(dev_priv))
11839                 active = new_crtc_state->active;
11840
11841         I915_STATE_WARN(new_crtc_state->active != active,
11842              "crtc active state doesn't match with hw state "
11843              "(expected %i, found %i)\n", new_crtc_state->active, active);
11844
11845         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11846              "transitional active state does not match atomic hw state "
11847              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11848
11849         for_each_encoder_on_crtc(dev, crtc, encoder) {
11850                 enum pipe pipe;
11851
11852                 active = encoder->get_hw_state(encoder, &pipe);
11853                 I915_STATE_WARN(active != new_crtc_state->active,
11854                         "[ENCODER:%i] active %i with crtc active %i\n",
11855                         encoder->base.base.id, active, new_crtc_state->active);
11856
11857                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11858                                 "Encoder connected to wrong pipe %c\n",
11859                                 pipe_name(pipe));
11860
11861                 if (active)
11862                         encoder->get_config(encoder, pipe_config);
11863         }
11864
11865         intel_crtc_compute_pixel_rate(pipe_config);
11866
11867         if (!new_crtc_state->active)
11868                 return;
11869
11870         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11871
11872         sw_config = to_intel_crtc_state(new_crtc_state);
11873         if (!intel_pipe_config_compare(dev_priv, sw_config,
11874                                        pipe_config, false)) {
11875                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11876                 intel_dump_pipe_config(intel_crtc, pipe_config,
11877                                        "[hw state]");
11878                 intel_dump_pipe_config(intel_crtc, sw_config,
11879                                        "[sw state]");
11880         }
11881 }
11882
11883 static void
11884 intel_verify_planes(struct intel_atomic_state *state)
11885 {
11886         struct intel_plane *plane;
11887         const struct intel_plane_state *plane_state;
11888         int i;
11889
11890         for_each_new_intel_plane_in_state(state, plane,
11891                                           plane_state, i)
11892                 assert_plane(plane, plane_state->base.visible);
11893 }
11894
11895 static void
11896 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11897                          struct intel_shared_dpll *pll,
11898                          struct drm_crtc *crtc,
11899                          struct drm_crtc_state *new_state)
11900 {
11901         struct intel_dpll_hw_state dpll_hw_state;
11902         unsigned int crtc_mask;
11903         bool active;
11904
11905         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11906
11907         DRM_DEBUG_KMS("%s\n", pll->info->name);
11908
11909         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
11910
11911         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
11912                 I915_STATE_WARN(!pll->on && pll->active_mask,
11913                      "pll in active use but not on in sw tracking\n");
11914                 I915_STATE_WARN(pll->on && !pll->active_mask,
11915                      "pll is on but not used by any active crtc\n");
11916                 I915_STATE_WARN(pll->on != active,
11917                      "pll on state mismatch (expected %i, found %i)\n",
11918                      pll->on, active);
11919         }
11920
11921         if (!crtc) {
11922                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
11923                                 "more active pll users than references: %x vs %x\n",
11924                                 pll->active_mask, pll->state.crtc_mask);
11925
11926                 return;
11927         }
11928
11929         crtc_mask = drm_crtc_mask(crtc);
11930
11931         if (new_state->active)
11932                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
11933                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
11934                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11935         else
11936                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11937                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
11938                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11939
11940         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
11941                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
11942                         crtc_mask, pll->state.crtc_mask);
11943
11944         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
11945                                           &dpll_hw_state,
11946                                           sizeof(dpll_hw_state)),
11947                         "pll hw state mismatch\n");
11948 }
11949
11950 static void
11951 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
11952                          struct drm_crtc_state *old_crtc_state,
11953                          struct drm_crtc_state *new_crtc_state)
11954 {
11955         struct drm_i915_private *dev_priv = to_i915(dev);
11956         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
11957         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
11958
11959         if (new_state->shared_dpll)
11960                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
11961
11962         if (old_state->shared_dpll &&
11963             old_state->shared_dpll != new_state->shared_dpll) {
11964                 unsigned int crtc_mask = drm_crtc_mask(crtc);
11965                 struct intel_shared_dpll *pll = old_state->shared_dpll;
11966
11967                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11968                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
11969                                 pipe_name(drm_crtc_index(crtc)));
11970                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
11971                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
11972                                 pipe_name(drm_crtc_index(crtc)));
11973         }
11974 }
11975
11976 static void
11977 intel_modeset_verify_crtc(struct drm_crtc *crtc,
11978                           struct drm_atomic_state *state,
11979                           struct drm_crtc_state *old_state,
11980                           struct drm_crtc_state *new_state)
11981 {
11982         if (!needs_modeset(new_state) &&
11983             !to_intel_crtc_state(new_state)->update_pipe)
11984                 return;
11985
11986         verify_wm_state(crtc, new_state);
11987         verify_connector_state(crtc->dev, state, crtc);
11988         verify_crtc_state(crtc, old_state, new_state);
11989         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
11990 }
11991
11992 static void
11993 verify_disabled_dpll_state(struct drm_device *dev)
11994 {
11995         struct drm_i915_private *dev_priv = to_i915(dev);
11996         int i;
11997
11998         for (i = 0; i < dev_priv->num_shared_dpll; i++)
11999                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12000 }
12001
12002 static void
12003 intel_modeset_verify_disabled(struct drm_device *dev,
12004                               struct drm_atomic_state *state)
12005 {
12006         verify_encoder_state(dev, state);
12007         verify_connector_state(dev, state, NULL);
12008         verify_disabled_dpll_state(dev);
12009 }
12010
12011 static void update_scanline_offset(struct intel_crtc *crtc)
12012 {
12013         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12014
12015         /*
12016          * The scanline counter increments at the leading edge of hsync.
12017          *
12018          * On most platforms it starts counting from vtotal-1 on the
12019          * first active line. That means the scanline counter value is
12020          * always one less than what we would expect. Ie. just after
12021          * start of vblank, which also occurs at start of hsync (on the
12022          * last active line), the scanline counter will read vblank_start-1.
12023          *
12024          * On gen2 the scanline counter starts counting from 1 instead
12025          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12026          * to keep the value positive), instead of adding one.
12027          *
12028          * On HSW+ the behaviour of the scanline counter depends on the output
12029          * type. For DP ports it behaves like most other platforms, but on HDMI
12030          * there's an extra 1 line difference. So we need to add two instead of
12031          * one to the value.
12032          *
12033          * On VLV/CHV DSI the scanline counter would appear to increment
12034          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12035          * that means we can't tell whether we're in vblank or not while
12036          * we're on that particular line. We must still set scanline_offset
12037          * to 1 so that the vblank timestamps come out correct when we query
12038          * the scanline counter from within the vblank interrupt handler.
12039          * However if queried just before the start of vblank we'll get an
12040          * answer that's slightly in the future.
12041          */
12042         if (IS_GEN2(dev_priv)) {
12043                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
12044                 int vtotal;
12045
12046                 vtotal = adjusted_mode->crtc_vtotal;
12047                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12048                         vtotal /= 2;
12049
12050                 crtc->scanline_offset = vtotal - 1;
12051         } else if (HAS_DDI(dev_priv) &&
12052                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
12053                 crtc->scanline_offset = 2;
12054         } else
12055                 crtc->scanline_offset = 1;
12056 }
12057
12058 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12059 {
12060         struct drm_device *dev = state->dev;
12061         struct drm_i915_private *dev_priv = to_i915(dev);
12062         struct drm_crtc *crtc;
12063         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12064         int i;
12065
12066         if (!dev_priv->display.crtc_compute_clock)
12067                 return;
12068
12069         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12070                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12071                 struct intel_shared_dpll *old_dpll =
12072                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12073
12074                 if (!needs_modeset(new_crtc_state))
12075                         continue;
12076
12077                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12078
12079                 if (!old_dpll)
12080                         continue;
12081
12082                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12083         }
12084 }
12085
12086 /*
12087  * This implements the workaround described in the "notes" section of the mode
12088  * set sequence documentation. When going from no pipes or single pipe to
12089  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12090  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12091  */
12092 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12093 {
12094         struct drm_crtc_state *crtc_state;
12095         struct intel_crtc *intel_crtc;
12096         struct drm_crtc *crtc;
12097         struct intel_crtc_state *first_crtc_state = NULL;
12098         struct intel_crtc_state *other_crtc_state = NULL;
12099         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12100         int i;
12101
12102         /* look at all crtc's that are going to be enabled in during modeset */
12103         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12104                 intel_crtc = to_intel_crtc(crtc);
12105
12106                 if (!crtc_state->active || !needs_modeset(crtc_state))
12107                         continue;
12108
12109                 if (first_crtc_state) {
12110                         other_crtc_state = to_intel_crtc_state(crtc_state);
12111                         break;
12112                 } else {
12113                         first_crtc_state = to_intel_crtc_state(crtc_state);
12114                         first_pipe = intel_crtc->pipe;
12115                 }
12116         }
12117
12118         /* No workaround needed? */
12119         if (!first_crtc_state)
12120                 return 0;
12121
12122         /* w/a possibly needed, check how many crtc's are already enabled. */
12123         for_each_intel_crtc(state->dev, intel_crtc) {
12124                 struct intel_crtc_state *pipe_config;
12125
12126                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12127                 if (IS_ERR(pipe_config))
12128                         return PTR_ERR(pipe_config);
12129
12130                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12131
12132                 if (!pipe_config->base.active ||
12133                     needs_modeset(&pipe_config->base))
12134                         continue;
12135
12136                 /* 2 or more enabled crtcs means no need for w/a */
12137                 if (enabled_pipe != INVALID_PIPE)
12138                         return 0;
12139
12140                 enabled_pipe = intel_crtc->pipe;
12141         }
12142
12143         if (enabled_pipe != INVALID_PIPE)
12144                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12145         else if (other_crtc_state)
12146                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12147
12148         return 0;
12149 }
12150
12151 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12152 {
12153         struct drm_crtc *crtc;
12154
12155         /* Add all pipes to the state */
12156         for_each_crtc(state->dev, crtc) {
12157                 struct drm_crtc_state *crtc_state;
12158
12159                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12160                 if (IS_ERR(crtc_state))
12161                         return PTR_ERR(crtc_state);
12162         }
12163
12164         return 0;
12165 }
12166
12167 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12168 {
12169         struct drm_crtc *crtc;
12170
12171         /*
12172          * Add all pipes to the state, and force
12173          * a modeset on all the active ones.
12174          */
12175         for_each_crtc(state->dev, crtc) {
12176                 struct drm_crtc_state *crtc_state;
12177                 int ret;
12178
12179                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12180                 if (IS_ERR(crtc_state))
12181                         return PTR_ERR(crtc_state);
12182
12183                 if (!crtc_state->active || needs_modeset(crtc_state))
12184                         continue;
12185
12186                 crtc_state->mode_changed = true;
12187
12188                 ret = drm_atomic_add_affected_connectors(state, crtc);
12189                 if (ret)
12190                         return ret;
12191
12192                 ret = drm_atomic_add_affected_planes(state, crtc);
12193                 if (ret)
12194                         return ret;
12195         }
12196
12197         return 0;
12198 }
12199
12200 static int intel_modeset_checks(struct drm_atomic_state *state)
12201 {
12202         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12203         struct drm_i915_private *dev_priv = to_i915(state->dev);
12204         struct drm_crtc *crtc;
12205         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12206         int ret = 0, i;
12207
12208         if (!check_digital_port_conflicts(state)) {
12209                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12210                 return -EINVAL;
12211         }
12212
12213         intel_state->modeset = true;
12214         intel_state->active_crtcs = dev_priv->active_crtcs;
12215         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12216         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12217
12218         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12219                 if (new_crtc_state->active)
12220                         intel_state->active_crtcs |= 1 << i;
12221                 else
12222                         intel_state->active_crtcs &= ~(1 << i);
12223
12224                 if (old_crtc_state->active != new_crtc_state->active)
12225                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12226         }
12227
12228         /*
12229          * See if the config requires any additional preparation, e.g.
12230          * to adjust global state with pipes off.  We need to do this
12231          * here so we can get the modeset_pipe updated config for the new
12232          * mode set on this crtc.  For other crtcs we need to use the
12233          * adjusted_mode bits in the crtc directly.
12234          */
12235         if (dev_priv->display.modeset_calc_cdclk) {
12236                 ret = dev_priv->display.modeset_calc_cdclk(state);
12237                 if (ret < 0)
12238                         return ret;
12239
12240                 /*
12241                  * Writes to dev_priv->cdclk.logical must protected by
12242                  * holding all the crtc locks, even if we don't end up
12243                  * touching the hardware
12244                  */
12245                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12246                                         &intel_state->cdclk.logical)) {
12247                         ret = intel_lock_all_pipes(state);
12248                         if (ret < 0)
12249                                 return ret;
12250                 }
12251
12252                 /* All pipes must be switched off while we change the cdclk. */
12253                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12254                                               &intel_state->cdclk.actual)) {
12255                         ret = intel_modeset_all_pipes(state);
12256                         if (ret < 0)
12257                                 return ret;
12258                 }
12259
12260                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12261                               intel_state->cdclk.logical.cdclk,
12262                               intel_state->cdclk.actual.cdclk);
12263                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12264                               intel_state->cdclk.logical.voltage_level,
12265                               intel_state->cdclk.actual.voltage_level);
12266         } else {
12267                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12268         }
12269
12270         intel_modeset_clear_plls(state);
12271
12272         if (IS_HASWELL(dev_priv))
12273                 return haswell_mode_set_planes_workaround(state);
12274
12275         return 0;
12276 }
12277
12278 /*
12279  * Handle calculation of various watermark data at the end of the atomic check
12280  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12281  * handlers to ensure that all derived state has been updated.
12282  */
12283 static int calc_watermark_data(struct drm_atomic_state *state)
12284 {
12285         struct drm_device *dev = state->dev;
12286         struct drm_i915_private *dev_priv = to_i915(dev);
12287
12288         /* Is there platform-specific watermark information to calculate? */
12289         if (dev_priv->display.compute_global_watermarks)
12290                 return dev_priv->display.compute_global_watermarks(state);
12291
12292         return 0;
12293 }
12294
12295 /**
12296  * intel_atomic_check - validate state object
12297  * @dev: drm device
12298  * @state: state to validate
12299  */
12300 static int intel_atomic_check(struct drm_device *dev,
12301                               struct drm_atomic_state *state)
12302 {
12303         struct drm_i915_private *dev_priv = to_i915(dev);
12304         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12305         struct drm_crtc *crtc;
12306         struct drm_crtc_state *old_crtc_state, *crtc_state;
12307         int ret, i;
12308         bool any_ms = false;
12309
12310         /* Catch I915_MODE_FLAG_INHERITED */
12311         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12312                                       crtc_state, i) {
12313                 if (crtc_state->mode.private_flags !=
12314                     old_crtc_state->mode.private_flags)
12315                         crtc_state->mode_changed = true;
12316         }
12317
12318         ret = drm_atomic_helper_check_modeset(dev, state);
12319         if (ret)
12320                 return ret;
12321
12322         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12323                 struct intel_crtc_state *pipe_config =
12324                         to_intel_crtc_state(crtc_state);
12325
12326                 if (!needs_modeset(crtc_state))
12327                         continue;
12328
12329                 if (!crtc_state->enable) {
12330                         any_ms = true;
12331                         continue;
12332                 }
12333
12334                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12335                 if (ret) {
12336                         intel_dump_pipe_config(to_intel_crtc(crtc),
12337                                                pipe_config, "[failed]");
12338                         return ret;
12339                 }
12340
12341                 if (i915_modparams.fastboot &&
12342                     intel_pipe_config_compare(dev_priv,
12343                                         to_intel_crtc_state(old_crtc_state),
12344                                         pipe_config, true)) {
12345                         crtc_state->mode_changed = false;
12346                         pipe_config->update_pipe = true;
12347                 }
12348
12349                 if (needs_modeset(crtc_state))
12350                         any_ms = true;
12351
12352                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12353                                        needs_modeset(crtc_state) ?
12354                                        "[modeset]" : "[fastset]");
12355         }
12356
12357         if (any_ms) {
12358                 ret = intel_modeset_checks(state);
12359
12360                 if (ret)
12361                         return ret;
12362         } else {
12363                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12364         }
12365
12366         ret = drm_atomic_helper_check_planes(dev, state);
12367         if (ret)
12368                 return ret;
12369
12370         intel_fbc_choose_crtc(dev_priv, intel_state);
12371         return calc_watermark_data(state);
12372 }
12373
12374 static int intel_atomic_prepare_commit(struct drm_device *dev,
12375                                        struct drm_atomic_state *state)
12376 {
12377         return drm_atomic_helper_prepare_planes(dev, state);
12378 }
12379
12380 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12381 {
12382         struct drm_device *dev = crtc->base.dev;
12383
12384         if (!dev->max_vblank_count)
12385                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12386
12387         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12388 }
12389
12390 static void intel_update_crtc(struct drm_crtc *crtc,
12391                               struct drm_atomic_state *state,
12392                               struct drm_crtc_state *old_crtc_state,
12393                               struct drm_crtc_state *new_crtc_state)
12394 {
12395         struct drm_device *dev = crtc->dev;
12396         struct drm_i915_private *dev_priv = to_i915(dev);
12397         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12398         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12399         bool modeset = needs_modeset(new_crtc_state);
12400         struct intel_plane_state *new_plane_state =
12401                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
12402                                                  to_intel_plane(crtc->primary));
12403
12404         if (modeset) {
12405                 update_scanline_offset(intel_crtc);
12406                 dev_priv->display.crtc_enable(pipe_config, state);
12407
12408                 /* vblanks work again, re-enable pipe CRC. */
12409                 intel_crtc_enable_pipe_crc(intel_crtc);
12410         } else {
12411                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12412                                        pipe_config);
12413         }
12414
12415         if (new_plane_state)
12416                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
12417
12418         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12419 }
12420
12421 static void intel_update_crtcs(struct drm_atomic_state *state)
12422 {
12423         struct drm_crtc *crtc;
12424         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12425         int i;
12426
12427         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12428                 if (!new_crtc_state->active)
12429                         continue;
12430
12431                 intel_update_crtc(crtc, state, old_crtc_state,
12432                                   new_crtc_state);
12433         }
12434 }
12435
12436 static void skl_update_crtcs(struct drm_atomic_state *state)
12437 {
12438         struct drm_i915_private *dev_priv = to_i915(state->dev);
12439         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12440         struct drm_crtc *crtc;
12441         struct intel_crtc *intel_crtc;
12442         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12443         struct intel_crtc_state *cstate;
12444         unsigned int updated = 0;
12445         bool progress;
12446         enum pipe pipe;
12447         int i;
12448         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
12449         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
12450
12451         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12452
12453         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12454                 /* ignore allocations for crtc's that have been turned off. */
12455                 if (new_crtc_state->active)
12456                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12457
12458         /* If 2nd DBuf slice required, enable it here */
12459         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
12460                 icl_dbuf_slices_update(dev_priv, required_slices);
12461
12462         /*
12463          * Whenever the number of active pipes changes, we need to make sure we
12464          * update the pipes in the right order so that their ddb allocations
12465          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12466          * cause pipe underruns and other bad stuff.
12467          */
12468         do {
12469                 progress = false;
12470
12471                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12472                         bool vbl_wait = false;
12473                         unsigned int cmask = drm_crtc_mask(crtc);
12474
12475                         intel_crtc = to_intel_crtc(crtc);
12476                         cstate = to_intel_crtc_state(new_crtc_state);
12477                         pipe = intel_crtc->pipe;
12478
12479                         if (updated & cmask || !cstate->base.active)
12480                                 continue;
12481
12482                         if (skl_ddb_allocation_overlaps(dev_priv,
12483                                                         entries,
12484                                                         &cstate->wm.skl.ddb,
12485                                                         i))
12486                                 continue;
12487
12488                         updated |= cmask;
12489                         entries[i] = &cstate->wm.skl.ddb;
12490
12491                         /*
12492                          * If this is an already active pipe, it's DDB changed,
12493                          * and this isn't the last pipe that needs updating
12494                          * then we need to wait for a vblank to pass for the
12495                          * new ddb allocation to take effect.
12496                          */
12497                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12498                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12499                             !new_crtc_state->active_changed &&
12500                             intel_state->wm_results.dirty_pipes != updated)
12501                                 vbl_wait = true;
12502
12503                         intel_update_crtc(crtc, state, old_crtc_state,
12504                                           new_crtc_state);
12505
12506                         if (vbl_wait)
12507                                 intel_wait_for_vblank(dev_priv, pipe);
12508
12509                         progress = true;
12510                 }
12511         } while (progress);
12512
12513         /* If 2nd DBuf slice is no more required disable it */
12514         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
12515                 icl_dbuf_slices_update(dev_priv, required_slices);
12516 }
12517
12518 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12519 {
12520         struct intel_atomic_state *state, *next;
12521         struct llist_node *freed;
12522
12523         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12524         llist_for_each_entry_safe(state, next, freed, freed)
12525                 drm_atomic_state_put(&state->base);
12526 }
12527
12528 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12529 {
12530         struct drm_i915_private *dev_priv =
12531                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12532
12533         intel_atomic_helper_free_state(dev_priv);
12534 }
12535
12536 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12537 {
12538         struct wait_queue_entry wait_fence, wait_reset;
12539         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12540
12541         init_wait_entry(&wait_fence, 0);
12542         init_wait_entry(&wait_reset, 0);
12543         for (;;) {
12544                 prepare_to_wait(&intel_state->commit_ready.wait,
12545                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12546                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12547                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12548
12549
12550                 if (i915_sw_fence_done(&intel_state->commit_ready)
12551                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12552                         break;
12553
12554                 schedule();
12555         }
12556         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12557         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12558 }
12559
12560 static void intel_atomic_cleanup_work(struct work_struct *work)
12561 {
12562         struct drm_atomic_state *state =
12563                 container_of(work, struct drm_atomic_state, commit_work);
12564         struct drm_i915_private *i915 = to_i915(state->dev);
12565
12566         drm_atomic_helper_cleanup_planes(&i915->drm, state);
12567         drm_atomic_helper_commit_cleanup_done(state);
12568         drm_atomic_state_put(state);
12569
12570         intel_atomic_helper_free_state(i915);
12571 }
12572
12573 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12574 {
12575         struct drm_device *dev = state->dev;
12576         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12577         struct drm_i915_private *dev_priv = to_i915(dev);
12578         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12579         struct drm_crtc *crtc;
12580         struct intel_crtc_state *intel_cstate;
12581         u64 put_domains[I915_MAX_PIPES] = {};
12582         int i;
12583
12584         intel_atomic_commit_fence_wait(intel_state);
12585
12586         drm_atomic_helper_wait_for_dependencies(state);
12587
12588         if (intel_state->modeset)
12589                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12590
12591         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12592                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12593
12594                 if (needs_modeset(new_crtc_state) ||
12595                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12596
12597                         put_domains[to_intel_crtc(crtc)->pipe] =
12598                                 modeset_get_crtc_power_domains(crtc,
12599                                         to_intel_crtc_state(new_crtc_state));
12600                 }
12601
12602                 if (!needs_modeset(new_crtc_state))
12603                         continue;
12604
12605                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12606                                        to_intel_crtc_state(new_crtc_state));
12607
12608                 if (old_crtc_state->active) {
12609                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
12610
12611                         /*
12612                          * We need to disable pipe CRC before disabling the pipe,
12613                          * or we race against vblank off.
12614                          */
12615                         intel_crtc_disable_pipe_crc(intel_crtc);
12616
12617                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
12618                         intel_crtc->active = false;
12619                         intel_fbc_disable(intel_crtc);
12620                         intel_disable_shared_dpll(intel_crtc);
12621
12622                         /*
12623                          * Underruns don't always raise
12624                          * interrupts, so check manually.
12625                          */
12626                         intel_check_cpu_fifo_underruns(dev_priv);
12627                         intel_check_pch_fifo_underruns(dev_priv);
12628
12629                         if (!new_crtc_state->active) {
12630                                 /*
12631                                  * Make sure we don't call initial_watermarks
12632                                  * for ILK-style watermark updates.
12633                                  *
12634                                  * No clue what this is supposed to achieve.
12635                                  */
12636                                 if (INTEL_GEN(dev_priv) >= 9)
12637                                         dev_priv->display.initial_watermarks(intel_state,
12638                                                                              to_intel_crtc_state(new_crtc_state));
12639                         }
12640                 }
12641         }
12642
12643         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12644         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12645                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12646
12647         if (intel_state->modeset) {
12648                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12649
12650                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12651
12652                 /*
12653                  * SKL workaround: bspec recommends we disable the SAGV when we
12654                  * have more then one pipe enabled
12655                  */
12656                 if (!intel_can_enable_sagv(state))
12657                         intel_disable_sagv(dev_priv);
12658
12659                 intel_modeset_verify_disabled(dev, state);
12660         }
12661
12662         /* Complete the events for pipes that have now been disabled */
12663         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12664                 bool modeset = needs_modeset(new_crtc_state);
12665
12666                 /* Complete events for now disable pipes here. */
12667                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12668                         spin_lock_irq(&dev->event_lock);
12669                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12670                         spin_unlock_irq(&dev->event_lock);
12671
12672                         new_crtc_state->event = NULL;
12673                 }
12674         }
12675
12676         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12677         dev_priv->display.update_crtcs(state);
12678
12679         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12680          * already, but still need the state for the delayed optimization. To
12681          * fix this:
12682          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12683          * - schedule that vblank worker _before_ calling hw_done
12684          * - at the start of commit_tail, cancel it _synchrously
12685          * - switch over to the vblank wait helper in the core after that since
12686          *   we don't need out special handling any more.
12687          */
12688         drm_atomic_helper_wait_for_flip_done(dev, state);
12689
12690         /*
12691          * Now that the vblank has passed, we can go ahead and program the
12692          * optimal watermarks on platforms that need two-step watermark
12693          * programming.
12694          *
12695          * TODO: Move this (and other cleanup) to an async worker eventually.
12696          */
12697         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12698                 intel_cstate = to_intel_crtc_state(new_crtc_state);
12699
12700                 if (dev_priv->display.optimize_watermarks)
12701                         dev_priv->display.optimize_watermarks(intel_state,
12702                                                               intel_cstate);
12703         }
12704
12705         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12706                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12707
12708                 if (put_domains[i])
12709                         modeset_put_power_domains(dev_priv, put_domains[i]);
12710
12711                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12712         }
12713
12714         if (intel_state->modeset)
12715                 intel_verify_planes(intel_state);
12716
12717         if (intel_state->modeset && intel_can_enable_sagv(state))
12718                 intel_enable_sagv(dev_priv);
12719
12720         drm_atomic_helper_commit_hw_done(state);
12721
12722         if (intel_state->modeset) {
12723                 /* As one of the primary mmio accessors, KMS has a high
12724                  * likelihood of triggering bugs in unclaimed access. After we
12725                  * finish modesetting, see if an error has been flagged, and if
12726                  * so enable debugging for the next modeset - and hope we catch
12727                  * the culprit.
12728                  */
12729                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12730                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12731         }
12732
12733         /*
12734          * Defer the cleanup of the old state to a separate worker to not
12735          * impede the current task (userspace for blocking modesets) that
12736          * are executed inline. For out-of-line asynchronous modesets/flips,
12737          * deferring to a new worker seems overkill, but we would place a
12738          * schedule point (cond_resched()) here anyway to keep latencies
12739          * down.
12740          */
12741         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
12742         schedule_work(&state->commit_work);
12743 }
12744
12745 static void intel_atomic_commit_work(struct work_struct *work)
12746 {
12747         struct drm_atomic_state *state =
12748                 container_of(work, struct drm_atomic_state, commit_work);
12749
12750         intel_atomic_commit_tail(state);
12751 }
12752
12753 static int __i915_sw_fence_call
12754 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12755                           enum i915_sw_fence_notify notify)
12756 {
12757         struct intel_atomic_state *state =
12758                 container_of(fence, struct intel_atomic_state, commit_ready);
12759
12760         switch (notify) {
12761         case FENCE_COMPLETE:
12762                 /* we do blocking waits in the worker, nothing to do here */
12763                 break;
12764         case FENCE_FREE:
12765                 {
12766                         struct intel_atomic_helper *helper =
12767                                 &to_i915(state->base.dev)->atomic_helper;
12768
12769                         if (llist_add(&state->freed, &helper->free_list))
12770                                 schedule_work(&helper->free_work);
12771                         break;
12772                 }
12773         }
12774
12775         return NOTIFY_DONE;
12776 }
12777
12778 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12779 {
12780         struct drm_plane_state *old_plane_state, *new_plane_state;
12781         struct drm_plane *plane;
12782         int i;
12783
12784         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12785                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12786                                   intel_fb_obj(new_plane_state->fb),
12787                                   to_intel_plane(plane)->frontbuffer_bit);
12788 }
12789
12790 /**
12791  * intel_atomic_commit - commit validated state object
12792  * @dev: DRM device
12793  * @state: the top-level driver state object
12794  * @nonblock: nonblocking commit
12795  *
12796  * This function commits a top-level state object that has been validated
12797  * with drm_atomic_helper_check().
12798  *
12799  * RETURNS
12800  * Zero for success or -errno.
12801  */
12802 static int intel_atomic_commit(struct drm_device *dev,
12803                                struct drm_atomic_state *state,
12804                                bool nonblock)
12805 {
12806         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12807         struct drm_i915_private *dev_priv = to_i915(dev);
12808         int ret = 0;
12809
12810         drm_atomic_state_get(state);
12811         i915_sw_fence_init(&intel_state->commit_ready,
12812                            intel_atomic_commit_ready);
12813
12814         /*
12815          * The intel_legacy_cursor_update() fast path takes care
12816          * of avoiding the vblank waits for simple cursor
12817          * movement and flips. For cursor on/off and size changes,
12818          * we want to perform the vblank waits so that watermark
12819          * updates happen during the correct frames. Gen9+ have
12820          * double buffered watermarks and so shouldn't need this.
12821          *
12822          * Unset state->legacy_cursor_update before the call to
12823          * drm_atomic_helper_setup_commit() because otherwise
12824          * drm_atomic_helper_wait_for_flip_done() is a noop and
12825          * we get FIFO underruns because we didn't wait
12826          * for vblank.
12827          *
12828          * FIXME doing watermarks and fb cleanup from a vblank worker
12829          * (assuming we had any) would solve these problems.
12830          */
12831         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12832                 struct intel_crtc_state *new_crtc_state;
12833                 struct intel_crtc *crtc;
12834                 int i;
12835
12836                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12837                         if (new_crtc_state->wm.need_postvbl_update ||
12838                             new_crtc_state->update_wm_post)
12839                                 state->legacy_cursor_update = false;
12840         }
12841
12842         ret = intel_atomic_prepare_commit(dev, state);
12843         if (ret) {
12844                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12845                 i915_sw_fence_commit(&intel_state->commit_ready);
12846                 return ret;
12847         }
12848
12849         ret = drm_atomic_helper_setup_commit(state, nonblock);
12850         if (!ret)
12851                 ret = drm_atomic_helper_swap_state(state, true);
12852
12853         if (ret) {
12854                 i915_sw_fence_commit(&intel_state->commit_ready);
12855
12856                 drm_atomic_helper_cleanup_planes(dev, state);
12857                 return ret;
12858         }
12859         dev_priv->wm.distrust_bios_wm = false;
12860         intel_shared_dpll_swap_state(state);
12861         intel_atomic_track_fbs(state);
12862
12863         if (intel_state->modeset) {
12864                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12865                        sizeof(intel_state->min_cdclk));
12866                 memcpy(dev_priv->min_voltage_level,
12867                        intel_state->min_voltage_level,
12868                        sizeof(intel_state->min_voltage_level));
12869                 dev_priv->active_crtcs = intel_state->active_crtcs;
12870                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12871                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12872         }
12873
12874         drm_atomic_state_get(state);
12875         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12876
12877         i915_sw_fence_commit(&intel_state->commit_ready);
12878         if (nonblock && intel_state->modeset) {
12879                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12880         } else if (nonblock) {
12881                 queue_work(system_unbound_wq, &state->commit_work);
12882         } else {
12883                 if (intel_state->modeset)
12884                         flush_workqueue(dev_priv->modeset_wq);
12885                 intel_atomic_commit_tail(state);
12886         }
12887
12888         return 0;
12889 }
12890
12891 static const struct drm_crtc_funcs intel_crtc_funcs = {
12892         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12893         .set_config = drm_atomic_helper_set_config,
12894         .destroy = intel_crtc_destroy,
12895         .page_flip = drm_atomic_helper_page_flip,
12896         .atomic_duplicate_state = intel_crtc_duplicate_state,
12897         .atomic_destroy_state = intel_crtc_destroy_state,
12898         .set_crc_source = intel_crtc_set_crc_source,
12899         .verify_crc_source = intel_crtc_verify_crc_source,
12900         .get_crc_sources = intel_crtc_get_crc_sources,
12901 };
12902
12903 struct wait_rps_boost {
12904         struct wait_queue_entry wait;
12905
12906         struct drm_crtc *crtc;
12907         struct i915_request *request;
12908 };
12909
12910 static int do_rps_boost(struct wait_queue_entry *_wait,
12911                         unsigned mode, int sync, void *key)
12912 {
12913         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
12914         struct i915_request *rq = wait->request;
12915
12916         /*
12917          * If we missed the vblank, but the request is already running it
12918          * is reasonable to assume that it will complete before the next
12919          * vblank without our intervention, so leave RPS alone.
12920          */
12921         if (!i915_request_started(rq))
12922                 gen6_rps_boost(rq, NULL);
12923         i915_request_put(rq);
12924
12925         drm_crtc_vblank_put(wait->crtc);
12926
12927         list_del(&wait->wait.entry);
12928         kfree(wait);
12929         return 1;
12930 }
12931
12932 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
12933                                        struct dma_fence *fence)
12934 {
12935         struct wait_rps_boost *wait;
12936
12937         if (!dma_fence_is_i915(fence))
12938                 return;
12939
12940         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
12941                 return;
12942
12943         if (drm_crtc_vblank_get(crtc))
12944                 return;
12945
12946         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
12947         if (!wait) {
12948                 drm_crtc_vblank_put(crtc);
12949                 return;
12950         }
12951
12952         wait->request = to_request(dma_fence_get(fence));
12953         wait->crtc = crtc;
12954
12955         wait->wait.func = do_rps_boost;
12956         wait->wait.flags = 0;
12957
12958         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
12959 }
12960
12961 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
12962 {
12963         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
12964         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12965         struct drm_framebuffer *fb = plane_state->base.fb;
12966         struct i915_vma *vma;
12967
12968         if (plane->id == PLANE_CURSOR &&
12969             INTEL_INFO(dev_priv)->cursor_needs_physical) {
12970                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12971                 const int align = intel_cursor_alignment(dev_priv);
12972
12973                 return i915_gem_object_attach_phys(obj, align);
12974         }
12975
12976         vma = intel_pin_and_fence_fb_obj(fb,
12977                                          plane_state->base.rotation,
12978                                          intel_plane_uses_fence(plane_state),
12979                                          &plane_state->flags);
12980         if (IS_ERR(vma))
12981                 return PTR_ERR(vma);
12982
12983         plane_state->vma = vma;
12984
12985         return 0;
12986 }
12987
12988 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
12989 {
12990         struct i915_vma *vma;
12991
12992         vma = fetch_and_zero(&old_plane_state->vma);
12993         if (vma)
12994                 intel_unpin_fb_vma(vma, old_plane_state->flags);
12995 }
12996
12997 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
12998 {
12999         struct i915_sched_attr attr = {
13000                 .priority = I915_PRIORITY_DISPLAY,
13001         };
13002
13003         i915_gem_object_wait_priority(obj, 0, &attr);
13004 }
13005
13006 /**
13007  * intel_prepare_plane_fb - Prepare fb for usage on plane
13008  * @plane: drm plane to prepare for
13009  * @new_state: the plane state being prepared
13010  *
13011  * Prepares a framebuffer for usage on a display plane.  Generally this
13012  * involves pinning the underlying object and updating the frontbuffer tracking
13013  * bits.  Some older platforms need special physical address handling for
13014  * cursor planes.
13015  *
13016  * Must be called with struct_mutex held.
13017  *
13018  * Returns 0 on success, negative error code on failure.
13019  */
13020 int
13021 intel_prepare_plane_fb(struct drm_plane *plane,
13022                        struct drm_plane_state *new_state)
13023 {
13024         struct intel_atomic_state *intel_state =
13025                 to_intel_atomic_state(new_state->state);
13026         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13027         struct drm_framebuffer *fb = new_state->fb;
13028         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13029         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13030         int ret;
13031
13032         if (old_obj) {
13033                 struct drm_crtc_state *crtc_state =
13034                         drm_atomic_get_new_crtc_state(new_state->state,
13035                                                       plane->state->crtc);
13036
13037                 /* Big Hammer, we also need to ensure that any pending
13038                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13039                  * current scanout is retired before unpinning the old
13040                  * framebuffer. Note that we rely on userspace rendering
13041                  * into the buffer attached to the pipe they are waiting
13042                  * on. If not, userspace generates a GPU hang with IPEHR
13043                  * point to the MI_WAIT_FOR_EVENT.
13044                  *
13045                  * This should only fail upon a hung GPU, in which case we
13046                  * can safely continue.
13047                  */
13048                 if (needs_modeset(crtc_state)) {
13049                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13050                                                               old_obj->resv, NULL,
13051                                                               false, 0,
13052                                                               GFP_KERNEL);
13053                         if (ret < 0)
13054                                 return ret;
13055                 }
13056         }
13057
13058         if (new_state->fence) { /* explicit fencing */
13059                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13060                                                     new_state->fence,
13061                                                     I915_FENCE_TIMEOUT,
13062                                                     GFP_KERNEL);
13063                 if (ret < 0)
13064                         return ret;
13065         }
13066
13067         if (!obj)
13068                 return 0;
13069
13070         ret = i915_gem_object_pin_pages(obj);
13071         if (ret)
13072                 return ret;
13073
13074         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13075         if (ret) {
13076                 i915_gem_object_unpin_pages(obj);
13077                 return ret;
13078         }
13079
13080         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
13081
13082         fb_obj_bump_render_priority(obj);
13083
13084         mutex_unlock(&dev_priv->drm.struct_mutex);
13085         i915_gem_object_unpin_pages(obj);
13086         if (ret)
13087                 return ret;
13088
13089         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13090
13091         if (!new_state->fence) { /* implicit fencing */
13092                 struct dma_fence *fence;
13093
13094                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13095                                                       obj->resv, NULL,
13096                                                       false, I915_FENCE_TIMEOUT,
13097                                                       GFP_KERNEL);
13098                 if (ret < 0)
13099                         return ret;
13100
13101                 fence = reservation_object_get_excl_rcu(obj->resv);
13102                 if (fence) {
13103                         add_rps_boost_after_vblank(new_state->crtc, fence);
13104                         dma_fence_put(fence);
13105                 }
13106         } else {
13107                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
13108         }
13109
13110         /*
13111          * We declare pageflips to be interactive and so merit a small bias
13112          * towards upclocking to deliver the frame on time. By only changing
13113          * the RPS thresholds to sample more regularly and aim for higher
13114          * clocks we can hopefully deliver low power workloads (like kodi)
13115          * that are not quite steady state without resorting to forcing
13116          * maximum clocks following a vblank miss (see do_rps_boost()).
13117          */
13118         if (!intel_state->rps_interactive) {
13119                 intel_rps_mark_interactive(dev_priv, true);
13120                 intel_state->rps_interactive = true;
13121         }
13122
13123         return 0;
13124 }
13125
13126 /**
13127  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13128  * @plane: drm plane to clean up for
13129  * @old_state: the state from the previous modeset
13130  *
13131  * Cleans up a framebuffer that has just been removed from a plane.
13132  *
13133  * Must be called with struct_mutex held.
13134  */
13135 void
13136 intel_cleanup_plane_fb(struct drm_plane *plane,
13137                        struct drm_plane_state *old_state)
13138 {
13139         struct intel_atomic_state *intel_state =
13140                 to_intel_atomic_state(old_state->state);
13141         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13142
13143         if (intel_state->rps_interactive) {
13144                 intel_rps_mark_interactive(dev_priv, false);
13145                 intel_state->rps_interactive = false;
13146         }
13147
13148         /* Should only be called after a successful intel_prepare_plane_fb()! */
13149         mutex_lock(&dev_priv->drm.struct_mutex);
13150         intel_plane_unpin_fb(to_intel_plane_state(old_state));
13151         mutex_unlock(&dev_priv->drm.struct_mutex);
13152 }
13153
13154 int
13155 skl_max_scale(struct intel_crtc *intel_crtc,
13156               struct intel_crtc_state *crtc_state,
13157               uint32_t pixel_format)
13158 {
13159         struct drm_i915_private *dev_priv;
13160         int max_scale, mult;
13161         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
13162
13163         if (!intel_crtc || !crtc_state->base.enable)
13164                 return DRM_PLANE_HELPER_NO_SCALING;
13165
13166         dev_priv = to_i915(intel_crtc->base.dev);
13167
13168         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13169         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13170
13171         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
13172                 max_dotclk *= 2;
13173
13174         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13175                 return DRM_PLANE_HELPER_NO_SCALING;
13176
13177         /*
13178          * skl max scale is lower of:
13179          *    close to 3 but not 3, -1 is for that purpose
13180          *            or
13181          *    cdclk/crtc_clock
13182          */
13183         mult = pixel_format == DRM_FORMAT_NV12 ? 2 : 3;
13184         tmpclk1 = (1 << 16) * mult - 1;
13185         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
13186         max_scale = min(tmpclk1, tmpclk2);
13187
13188         return max_scale;
13189 }
13190
13191 static int
13192 intel_check_primary_plane(struct intel_plane *plane,
13193                           struct intel_crtc_state *crtc_state,
13194                           struct intel_plane_state *state)
13195 {
13196         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13197         struct drm_crtc *crtc = state->base.crtc;
13198         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
13199         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
13200         bool can_position = false;
13201         int ret;
13202         uint32_t pixel_format = 0;
13203
13204         if (INTEL_GEN(dev_priv) >= 9) {
13205                 /* use scaler when colorkey is not required */
13206                 if (!state->ckey.flags) {
13207                         min_scale = 1;
13208                         if (state->base.fb)
13209                                 pixel_format = state->base.fb->format->format;
13210                         max_scale = skl_max_scale(to_intel_crtc(crtc),
13211                                                   crtc_state, pixel_format);
13212                 }
13213                 can_position = true;
13214         }
13215
13216         ret = drm_atomic_helper_check_plane_state(&state->base,
13217                                                   &crtc_state->base,
13218                                                   min_scale, max_scale,
13219                                                   can_position, true);
13220         if (ret)
13221                 return ret;
13222
13223         if (!state->base.fb)
13224                 return 0;
13225
13226         if (INTEL_GEN(dev_priv) >= 9) {
13227                 ret = skl_check_plane_surface(crtc_state, state);
13228                 if (ret)
13229                         return ret;
13230
13231                 state->ctl = skl_plane_ctl(crtc_state, state);
13232         } else {
13233                 ret = i9xx_check_plane_surface(state);
13234                 if (ret)
13235                         return ret;
13236
13237                 state->ctl = i9xx_plane_ctl(crtc_state, state);
13238         }
13239
13240         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
13241                 state->color_ctl = glk_plane_color_ctl(crtc_state, state);
13242
13243         return 0;
13244 }
13245
13246 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13247                                     struct drm_crtc_state *old_crtc_state)
13248 {
13249         struct drm_device *dev = crtc->dev;
13250         struct drm_i915_private *dev_priv = to_i915(dev);
13251         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13252         struct intel_crtc_state *old_intel_cstate =
13253                 to_intel_crtc_state(old_crtc_state);
13254         struct intel_atomic_state *old_intel_state =
13255                 to_intel_atomic_state(old_crtc_state->state);
13256         struct intel_crtc_state *intel_cstate =
13257                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13258         bool modeset = needs_modeset(&intel_cstate->base);
13259
13260         if (!modeset &&
13261             (intel_cstate->base.color_mgmt_changed ||
13262              intel_cstate->update_pipe)) {
13263                 intel_color_set_csc(&intel_cstate->base);
13264                 intel_color_load_luts(&intel_cstate->base);
13265         }
13266
13267         /* Perform vblank evasion around commit operation */
13268         intel_pipe_update_start(intel_cstate);
13269
13270         if (modeset)
13271                 goto out;
13272
13273         if (intel_cstate->update_pipe)
13274                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
13275         else if (INTEL_GEN(dev_priv) >= 9)
13276                 skl_detach_scalers(intel_crtc);
13277
13278 out:
13279         if (dev_priv->display.atomic_update_watermarks)
13280                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13281                                                            intel_cstate);
13282 }
13283
13284 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
13285                                   struct intel_crtc_state *crtc_state)
13286 {
13287         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13288
13289         if (!IS_GEN2(dev_priv))
13290                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
13291
13292         if (crtc_state->has_pch_encoder) {
13293                 enum pipe pch_transcoder =
13294                         intel_crtc_pch_transcoder(crtc);
13295
13296                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13297         }
13298 }
13299
13300 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13301                                      struct drm_crtc_state *old_crtc_state)
13302 {
13303         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13304         struct intel_atomic_state *old_intel_state =
13305                 to_intel_atomic_state(old_crtc_state->state);
13306         struct intel_crtc_state *new_crtc_state =
13307                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13308
13309         intel_pipe_update_end(new_crtc_state);
13310
13311         if (new_crtc_state->update_pipe &&
13312             !needs_modeset(&new_crtc_state->base) &&
13313             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED)
13314                 intel_crtc_arm_fifo_underrun(intel_crtc, new_crtc_state);
13315 }
13316
13317 /**
13318  * intel_plane_destroy - destroy a plane
13319  * @plane: plane to destroy
13320  *
13321  * Common destruction function for all types of planes (primary, cursor,
13322  * sprite).
13323  */
13324 void intel_plane_destroy(struct drm_plane *plane)
13325 {
13326         drm_plane_cleanup(plane);
13327         kfree(to_intel_plane(plane));
13328 }
13329
13330 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
13331                                             u32 format, u64 modifier)
13332 {
13333         switch (modifier) {
13334         case DRM_FORMAT_MOD_LINEAR:
13335         case I915_FORMAT_MOD_X_TILED:
13336                 break;
13337         default:
13338                 return false;
13339         }
13340
13341         switch (format) {
13342         case DRM_FORMAT_C8:
13343         case DRM_FORMAT_RGB565:
13344         case DRM_FORMAT_XRGB1555:
13345         case DRM_FORMAT_XRGB8888:
13346                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13347                         modifier == I915_FORMAT_MOD_X_TILED;
13348         default:
13349                 return false;
13350         }
13351 }
13352
13353 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
13354                                             u32 format, u64 modifier)
13355 {
13356         switch (modifier) {
13357         case DRM_FORMAT_MOD_LINEAR:
13358         case I915_FORMAT_MOD_X_TILED:
13359                 break;
13360         default:
13361                 return false;
13362         }
13363
13364         switch (format) {
13365         case DRM_FORMAT_C8:
13366         case DRM_FORMAT_RGB565:
13367         case DRM_FORMAT_XRGB8888:
13368         case DRM_FORMAT_XBGR8888:
13369         case DRM_FORMAT_XRGB2101010:
13370         case DRM_FORMAT_XBGR2101010:
13371                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13372                         modifier == I915_FORMAT_MOD_X_TILED;
13373         default:
13374                 return false;
13375         }
13376 }
13377
13378 static bool skl_plane_format_mod_supported(struct drm_plane *_plane,
13379                                            u32 format, u64 modifier)
13380 {
13381         struct intel_plane *plane = to_intel_plane(_plane);
13382
13383         switch (modifier) {
13384         case DRM_FORMAT_MOD_LINEAR:
13385         case I915_FORMAT_MOD_X_TILED:
13386         case I915_FORMAT_MOD_Y_TILED:
13387         case I915_FORMAT_MOD_Yf_TILED:
13388                 break;
13389         case I915_FORMAT_MOD_Y_TILED_CCS:
13390         case I915_FORMAT_MOD_Yf_TILED_CCS:
13391                 if (!plane->has_ccs)
13392                         return false;
13393                 break;
13394         default:
13395                 return false;
13396         }
13397
13398         switch (format) {
13399         case DRM_FORMAT_XRGB8888:
13400         case DRM_FORMAT_XBGR8888:
13401         case DRM_FORMAT_ARGB8888:
13402         case DRM_FORMAT_ABGR8888:
13403                 if (modifier == I915_FORMAT_MOD_Yf_TILED_CCS ||
13404                     modifier == I915_FORMAT_MOD_Y_TILED_CCS)
13405                         return true;
13406                 /* fall through */
13407         case DRM_FORMAT_RGB565:
13408         case DRM_FORMAT_XRGB2101010:
13409         case DRM_FORMAT_XBGR2101010:
13410         case DRM_FORMAT_YUYV:
13411         case DRM_FORMAT_YVYU:
13412         case DRM_FORMAT_UYVY:
13413         case DRM_FORMAT_VYUY:
13414         case DRM_FORMAT_NV12:
13415                 if (modifier == I915_FORMAT_MOD_Yf_TILED)
13416                         return true;
13417                 /* fall through */
13418         case DRM_FORMAT_C8:
13419                 if (modifier == DRM_FORMAT_MOD_LINEAR ||
13420                     modifier == I915_FORMAT_MOD_X_TILED ||
13421                     modifier == I915_FORMAT_MOD_Y_TILED)
13422                         return true;
13423                 /* fall through */
13424         default:
13425                 return false;
13426         }
13427 }
13428
13429 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
13430                                               u32 format, u64 modifier)
13431 {
13432         return modifier == DRM_FORMAT_MOD_LINEAR &&
13433                 format == DRM_FORMAT_ARGB8888;
13434 }
13435
13436 static struct drm_plane_funcs skl_plane_funcs = {
13437         .update_plane = drm_atomic_helper_update_plane,
13438         .disable_plane = drm_atomic_helper_disable_plane,
13439         .destroy = intel_plane_destroy,
13440         .atomic_get_property = intel_plane_atomic_get_property,
13441         .atomic_set_property = intel_plane_atomic_set_property,
13442         .atomic_duplicate_state = intel_plane_duplicate_state,
13443         .atomic_destroy_state = intel_plane_destroy_state,
13444         .format_mod_supported = skl_plane_format_mod_supported,
13445 };
13446
13447 static struct drm_plane_funcs i965_plane_funcs = {
13448         .update_plane = drm_atomic_helper_update_plane,
13449         .disable_plane = drm_atomic_helper_disable_plane,
13450         .destroy = intel_plane_destroy,
13451         .atomic_get_property = intel_plane_atomic_get_property,
13452         .atomic_set_property = intel_plane_atomic_set_property,
13453         .atomic_duplicate_state = intel_plane_duplicate_state,
13454         .atomic_destroy_state = intel_plane_destroy_state,
13455         .format_mod_supported = i965_plane_format_mod_supported,
13456 };
13457
13458 static struct drm_plane_funcs i8xx_plane_funcs = {
13459         .update_plane = drm_atomic_helper_update_plane,
13460         .disable_plane = drm_atomic_helper_disable_plane,
13461         .destroy = intel_plane_destroy,
13462         .atomic_get_property = intel_plane_atomic_get_property,
13463         .atomic_set_property = intel_plane_atomic_set_property,
13464         .atomic_duplicate_state = intel_plane_duplicate_state,
13465         .atomic_destroy_state = intel_plane_destroy_state,
13466         .format_mod_supported = i8xx_plane_format_mod_supported,
13467 };
13468
13469 static int
13470 intel_legacy_cursor_update(struct drm_plane *plane,
13471                            struct drm_crtc *crtc,
13472                            struct drm_framebuffer *fb,
13473                            int crtc_x, int crtc_y,
13474                            unsigned int crtc_w, unsigned int crtc_h,
13475                            uint32_t src_x, uint32_t src_y,
13476                            uint32_t src_w, uint32_t src_h,
13477                            struct drm_modeset_acquire_ctx *ctx)
13478 {
13479         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13480         int ret;
13481         struct drm_plane_state *old_plane_state, *new_plane_state;
13482         struct intel_plane *intel_plane = to_intel_plane(plane);
13483         struct drm_framebuffer *old_fb;
13484         struct drm_crtc_state *crtc_state = crtc->state;
13485
13486         /*
13487          * When crtc is inactive or there is a modeset pending,
13488          * wait for it to complete in the slowpath
13489          */
13490         if (!crtc_state->active || needs_modeset(crtc_state) ||
13491             to_intel_crtc_state(crtc_state)->update_pipe)
13492                 goto slow;
13493
13494         old_plane_state = plane->state;
13495         /*
13496          * Don't do an async update if there is an outstanding commit modifying
13497          * the plane.  This prevents our async update's changes from getting
13498          * overridden by a previous synchronous update's state.
13499          */
13500         if (old_plane_state->commit &&
13501             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13502                 goto slow;
13503
13504         /*
13505          * If any parameters change that may affect watermarks,
13506          * take the slowpath. Only changing fb or position should be
13507          * in the fastpath.
13508          */
13509         if (old_plane_state->crtc != crtc ||
13510             old_plane_state->src_w != src_w ||
13511             old_plane_state->src_h != src_h ||
13512             old_plane_state->crtc_w != crtc_w ||
13513             old_plane_state->crtc_h != crtc_h ||
13514             !old_plane_state->fb != !fb)
13515                 goto slow;
13516
13517         new_plane_state = intel_plane_duplicate_state(plane);
13518         if (!new_plane_state)
13519                 return -ENOMEM;
13520
13521         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13522
13523         new_plane_state->src_x = src_x;
13524         new_plane_state->src_y = src_y;
13525         new_plane_state->src_w = src_w;
13526         new_plane_state->src_h = src_h;
13527         new_plane_state->crtc_x = crtc_x;
13528         new_plane_state->crtc_y = crtc_y;
13529         new_plane_state->crtc_w = crtc_w;
13530         new_plane_state->crtc_h = crtc_h;
13531
13532         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13533                                                   to_intel_crtc_state(crtc->state), /* FIXME need a new crtc state? */
13534                                                   to_intel_plane_state(plane->state),
13535                                                   to_intel_plane_state(new_plane_state));
13536         if (ret)
13537                 goto out_free;
13538
13539         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13540         if (ret)
13541                 goto out_free;
13542
13543         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13544         if (ret)
13545                 goto out_unlock;
13546
13547         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13548
13549         old_fb = old_plane_state->fb;
13550         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13551                           intel_plane->frontbuffer_bit);
13552
13553         /* Swap plane state */
13554         plane->state = new_plane_state;
13555
13556         if (plane->state->visible) {
13557                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13558                 intel_plane->update_plane(intel_plane,
13559                                           to_intel_crtc_state(crtc->state),
13560                                           to_intel_plane_state(plane->state));
13561         } else {
13562                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13563                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13564         }
13565
13566         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13567
13568 out_unlock:
13569         mutex_unlock(&dev_priv->drm.struct_mutex);
13570 out_free:
13571         if (ret)
13572                 intel_plane_destroy_state(plane, new_plane_state);
13573         else
13574                 intel_plane_destroy_state(plane, old_plane_state);
13575         return ret;
13576
13577 slow:
13578         return drm_atomic_helper_update_plane(plane, crtc, fb,
13579                                               crtc_x, crtc_y, crtc_w, crtc_h,
13580                                               src_x, src_y, src_w, src_h, ctx);
13581 }
13582
13583 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13584         .update_plane = intel_legacy_cursor_update,
13585         .disable_plane = drm_atomic_helper_disable_plane,
13586         .destroy = intel_plane_destroy,
13587         .atomic_get_property = intel_plane_atomic_get_property,
13588         .atomic_set_property = intel_plane_atomic_set_property,
13589         .atomic_duplicate_state = intel_plane_duplicate_state,
13590         .atomic_destroy_state = intel_plane_destroy_state,
13591         .format_mod_supported = intel_cursor_format_mod_supported,
13592 };
13593
13594 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13595                                enum i9xx_plane_id i9xx_plane)
13596 {
13597         if (!HAS_FBC(dev_priv))
13598                 return false;
13599
13600         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13601                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13602         else if (IS_IVYBRIDGE(dev_priv))
13603                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13604                         i9xx_plane == PLANE_C;
13605         else if (INTEL_GEN(dev_priv) >= 4)
13606                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13607         else
13608                 return i9xx_plane == PLANE_A;
13609 }
13610
13611 static bool skl_plane_has_fbc(struct drm_i915_private *dev_priv,
13612                               enum pipe pipe, enum plane_id plane_id)
13613 {
13614         if (!HAS_FBC(dev_priv))
13615                 return false;
13616
13617         return pipe == PIPE_A && plane_id == PLANE_PRIMARY;
13618 }
13619
13620 bool skl_plane_has_planar(struct drm_i915_private *dev_priv,
13621                           enum pipe pipe, enum plane_id plane_id)
13622 {
13623         if (plane_id == PLANE_PRIMARY) {
13624                 if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
13625                         return false;
13626                 else if ((INTEL_GEN(dev_priv) == 9 && pipe == PIPE_C) &&
13627                          !IS_GEMINILAKE(dev_priv))
13628                         return false;
13629         } else if (plane_id >= PLANE_SPRITE0) {
13630                 if (plane_id == PLANE_CURSOR)
13631                         return false;
13632                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) == 10) {
13633                         if (plane_id != PLANE_SPRITE0)
13634                                 return false;
13635                 } else {
13636                         if (plane_id != PLANE_SPRITE0 || pipe == PIPE_C ||
13637                             IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
13638                                 return false;
13639                 }
13640         }
13641         return true;
13642 }
13643
13644 static struct intel_plane *
13645 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13646 {
13647         struct intel_plane *primary = NULL;
13648         struct intel_plane_state *state = NULL;
13649         const struct drm_plane_funcs *plane_funcs;
13650         const uint32_t *intel_primary_formats;
13651         unsigned int supported_rotations;
13652         unsigned int num_formats;
13653         const uint64_t *modifiers;
13654         int ret;
13655
13656         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13657         if (!primary) {
13658                 ret = -ENOMEM;
13659                 goto fail;
13660         }
13661
13662         state = intel_create_plane_state(&primary->base);
13663         if (!state) {
13664                 ret = -ENOMEM;
13665                 goto fail;
13666         }
13667
13668         primary->base.state = &state->base;
13669
13670         primary->can_scale = false;
13671         primary->max_downscale = 1;
13672         if (INTEL_GEN(dev_priv) >= 9) {
13673                 primary->can_scale = true;
13674                 state->scaler_id = -1;
13675         }
13676         primary->pipe = pipe;
13677         /*
13678          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13679          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13680          */
13681         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13682                 primary->i9xx_plane = (enum i9xx_plane_id) !pipe;
13683         else
13684                 primary->i9xx_plane = (enum i9xx_plane_id) pipe;
13685         primary->id = PLANE_PRIMARY;
13686         primary->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, primary->id);
13687
13688         if (INTEL_GEN(dev_priv) >= 9)
13689                 primary->has_fbc = skl_plane_has_fbc(dev_priv,
13690                                                      primary->pipe,
13691                                                      primary->id);
13692         else
13693                 primary->has_fbc = i9xx_plane_has_fbc(dev_priv,
13694                                                       primary->i9xx_plane);
13695
13696         if (primary->has_fbc) {
13697                 struct intel_fbc *fbc = &dev_priv->fbc;
13698
13699                 fbc->possible_framebuffer_bits |= primary->frontbuffer_bit;
13700         }
13701
13702         primary->check_plane = intel_check_primary_plane;
13703
13704         if (INTEL_GEN(dev_priv) >= 9) {
13705                 primary->has_ccs = skl_plane_has_ccs(dev_priv, pipe,
13706                                                      PLANE_PRIMARY);
13707
13708                 if (skl_plane_has_planar(dev_priv, pipe, PLANE_PRIMARY)) {
13709                         intel_primary_formats = skl_pri_planar_formats;
13710                         num_formats = ARRAY_SIZE(skl_pri_planar_formats);
13711                 } else {
13712                         intel_primary_formats = skl_primary_formats;
13713                         num_formats = ARRAY_SIZE(skl_primary_formats);
13714                 }
13715
13716                 if (primary->has_ccs)
13717                         modifiers = skl_format_modifiers_ccs;
13718                 else
13719                         modifiers = skl_format_modifiers_noccs;
13720
13721                 primary->update_plane = skl_update_plane;
13722                 primary->disable_plane = skl_disable_plane;
13723                 primary->get_hw_state = skl_plane_get_hw_state;
13724
13725                 plane_funcs = &skl_plane_funcs;
13726         } else if (INTEL_GEN(dev_priv) >= 4) {
13727                 intel_primary_formats = i965_primary_formats;
13728                 num_formats = ARRAY_SIZE(i965_primary_formats);
13729                 modifiers = i9xx_format_modifiers;
13730
13731                 primary->update_plane = i9xx_update_plane;
13732                 primary->disable_plane = i9xx_disable_plane;
13733                 primary->get_hw_state = i9xx_plane_get_hw_state;
13734
13735                 plane_funcs = &i965_plane_funcs;
13736         } else {
13737                 intel_primary_formats = i8xx_primary_formats;
13738                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13739                 modifiers = i9xx_format_modifiers;
13740
13741                 primary->update_plane = i9xx_update_plane;
13742                 primary->disable_plane = i9xx_disable_plane;
13743                 primary->get_hw_state = i9xx_plane_get_hw_state;
13744
13745                 plane_funcs = &i8xx_plane_funcs;
13746         }
13747
13748         if (INTEL_GEN(dev_priv) >= 9)
13749                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13750                                                0, plane_funcs,
13751                                                intel_primary_formats, num_formats,
13752                                                modifiers,
13753                                                DRM_PLANE_TYPE_PRIMARY,
13754                                                "plane 1%c", pipe_name(pipe));
13755         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13756                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13757                                                0, plane_funcs,
13758                                                intel_primary_formats, num_formats,
13759                                                modifiers,
13760                                                DRM_PLANE_TYPE_PRIMARY,
13761                                                "primary %c", pipe_name(pipe));
13762         else
13763                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13764                                                0, plane_funcs,
13765                                                intel_primary_formats, num_formats,
13766                                                modifiers,
13767                                                DRM_PLANE_TYPE_PRIMARY,
13768                                                "plane %c",
13769                                                plane_name(primary->i9xx_plane));
13770         if (ret)
13771                 goto fail;
13772
13773         if (INTEL_GEN(dev_priv) >= 10) {
13774                 supported_rotations =
13775                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13776                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270 |
13777                         DRM_MODE_REFLECT_X;
13778         } else if (INTEL_GEN(dev_priv) >= 9) {
13779                 supported_rotations =
13780                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13781                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13782         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13783                 supported_rotations =
13784                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13785                         DRM_MODE_REFLECT_X;
13786         } else if (INTEL_GEN(dev_priv) >= 4) {
13787                 supported_rotations =
13788                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13789         } else {
13790                 supported_rotations = DRM_MODE_ROTATE_0;
13791         }
13792
13793         if (INTEL_GEN(dev_priv) >= 4)
13794                 drm_plane_create_rotation_property(&primary->base,
13795                                                    DRM_MODE_ROTATE_0,
13796                                                    supported_rotations);
13797
13798         if (INTEL_GEN(dev_priv) >= 9)
13799                 drm_plane_create_color_properties(&primary->base,
13800                                                   BIT(DRM_COLOR_YCBCR_BT601) |
13801                                                   BIT(DRM_COLOR_YCBCR_BT709),
13802                                                   BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
13803                                                   BIT(DRM_COLOR_YCBCR_FULL_RANGE),
13804                                                   DRM_COLOR_YCBCR_BT709,
13805                                                   DRM_COLOR_YCBCR_LIMITED_RANGE);
13806
13807         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13808
13809         return primary;
13810
13811 fail:
13812         kfree(state);
13813         kfree(primary);
13814
13815         return ERR_PTR(ret);
13816 }
13817
13818 static struct intel_plane *
13819 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13820                           enum pipe pipe)
13821 {
13822         struct intel_plane *cursor = NULL;
13823         struct intel_plane_state *state = NULL;
13824         int ret;
13825
13826         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13827         if (!cursor) {
13828                 ret = -ENOMEM;
13829                 goto fail;
13830         }
13831
13832         state = intel_create_plane_state(&cursor->base);
13833         if (!state) {
13834                 ret = -ENOMEM;
13835                 goto fail;
13836         }
13837
13838         cursor->base.state = &state->base;
13839
13840         cursor->can_scale = false;
13841         cursor->max_downscale = 1;
13842         cursor->pipe = pipe;
13843         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13844         cursor->id = PLANE_CURSOR;
13845         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13846
13847         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13848                 cursor->update_plane = i845_update_cursor;
13849                 cursor->disable_plane = i845_disable_cursor;
13850                 cursor->get_hw_state = i845_cursor_get_hw_state;
13851                 cursor->check_plane = i845_check_cursor;
13852         } else {
13853                 cursor->update_plane = i9xx_update_cursor;
13854                 cursor->disable_plane = i9xx_disable_cursor;
13855                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13856                 cursor->check_plane = i9xx_check_cursor;
13857         }
13858
13859         cursor->cursor.base = ~0;
13860         cursor->cursor.cntl = ~0;
13861
13862         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13863                 cursor->cursor.size = ~0;
13864
13865         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13866                                        0, &intel_cursor_plane_funcs,
13867                                        intel_cursor_formats,
13868                                        ARRAY_SIZE(intel_cursor_formats),
13869                                        cursor_format_modifiers,
13870                                        DRM_PLANE_TYPE_CURSOR,
13871                                        "cursor %c", pipe_name(pipe));
13872         if (ret)
13873                 goto fail;
13874
13875         if (INTEL_GEN(dev_priv) >= 4)
13876                 drm_plane_create_rotation_property(&cursor->base,
13877                                                    DRM_MODE_ROTATE_0,
13878                                                    DRM_MODE_ROTATE_0 |
13879                                                    DRM_MODE_ROTATE_180);
13880
13881         if (INTEL_GEN(dev_priv) >= 9)
13882                 state->scaler_id = -1;
13883
13884         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13885
13886         return cursor;
13887
13888 fail:
13889         kfree(state);
13890         kfree(cursor);
13891
13892         return ERR_PTR(ret);
13893 }
13894
13895 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13896                                     struct intel_crtc_state *crtc_state)
13897 {
13898         struct intel_crtc_scaler_state *scaler_state =
13899                 &crtc_state->scaler_state;
13900         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13901         int i;
13902
13903         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13904         if (!crtc->num_scalers)
13905                 return;
13906
13907         for (i = 0; i < crtc->num_scalers; i++) {
13908                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13909
13910                 scaler->in_use = 0;
13911                 scaler->mode = PS_SCALER_MODE_DYN;
13912         }
13913
13914         scaler_state->scaler_id = -1;
13915 }
13916
13917 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13918 {
13919         struct intel_crtc *intel_crtc;
13920         struct intel_crtc_state *crtc_state = NULL;
13921         struct intel_plane *primary = NULL;
13922         struct intel_plane *cursor = NULL;
13923         int sprite, ret;
13924
13925         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13926         if (!intel_crtc)
13927                 return -ENOMEM;
13928
13929         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13930         if (!crtc_state) {
13931                 ret = -ENOMEM;
13932                 goto fail;
13933         }
13934         intel_crtc->config = crtc_state;
13935         intel_crtc->base.state = &crtc_state->base;
13936         crtc_state->base.crtc = &intel_crtc->base;
13937
13938         primary = intel_primary_plane_create(dev_priv, pipe);
13939         if (IS_ERR(primary)) {
13940                 ret = PTR_ERR(primary);
13941                 goto fail;
13942         }
13943         intel_crtc->plane_ids_mask |= BIT(primary->id);
13944
13945         for_each_sprite(dev_priv, pipe, sprite) {
13946                 struct intel_plane *plane;
13947
13948                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13949                 if (IS_ERR(plane)) {
13950                         ret = PTR_ERR(plane);
13951                         goto fail;
13952                 }
13953                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13954         }
13955
13956         cursor = intel_cursor_plane_create(dev_priv, pipe);
13957         if (IS_ERR(cursor)) {
13958                 ret = PTR_ERR(cursor);
13959                 goto fail;
13960         }
13961         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13962
13963         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13964                                         &primary->base, &cursor->base,
13965                                         &intel_crtc_funcs,
13966                                         "pipe %c", pipe_name(pipe));
13967         if (ret)
13968                 goto fail;
13969
13970         intel_crtc->pipe = pipe;
13971
13972         /* initialize shared scalers */
13973         intel_crtc_init_scalers(intel_crtc, crtc_state);
13974
13975         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
13976                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
13977         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
13978
13979         if (INTEL_GEN(dev_priv) < 9) {
13980                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
13981
13982                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13983                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
13984                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
13985         }
13986
13987         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13988
13989         intel_color_init(&intel_crtc->base);
13990
13991         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13992
13993         return 0;
13994
13995 fail:
13996         /*
13997          * drm_mode_config_cleanup() will free up any
13998          * crtcs/planes already initialized.
13999          */
14000         kfree(crtc_state);
14001         kfree(intel_crtc);
14002
14003         return ret;
14004 }
14005
14006 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14007 {
14008         struct drm_device *dev = connector->base.dev;
14009
14010         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14011
14012         if (!connector->base.state->crtc)
14013                 return INVALID_PIPE;
14014
14015         return to_intel_crtc(connector->base.state->crtc)->pipe;
14016 }
14017
14018 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
14019                                       struct drm_file *file)
14020 {
14021         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14022         struct drm_crtc *drmmode_crtc;
14023         struct intel_crtc *crtc;
14024
14025         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
14026         if (!drmmode_crtc)
14027                 return -ENOENT;
14028
14029         crtc = to_intel_crtc(drmmode_crtc);
14030         pipe_from_crtc_id->pipe = crtc->pipe;
14031
14032         return 0;
14033 }
14034
14035 static int intel_encoder_clones(struct intel_encoder *encoder)
14036 {
14037         struct drm_device *dev = encoder->base.dev;
14038         struct intel_encoder *source_encoder;
14039         int index_mask = 0;
14040         int entry = 0;
14041
14042         for_each_intel_encoder(dev, source_encoder) {
14043                 if (encoders_cloneable(encoder, source_encoder))
14044                         index_mask |= (1 << entry);
14045
14046                 entry++;
14047         }
14048
14049         return index_mask;
14050 }
14051
14052 static bool has_edp_a(struct drm_i915_private *dev_priv)
14053 {
14054         if (!IS_MOBILE(dev_priv))
14055                 return false;
14056
14057         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14058                 return false;
14059
14060         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14061                 return false;
14062
14063         return true;
14064 }
14065
14066 static bool intel_crt_present(struct drm_i915_private *dev_priv)
14067 {
14068         if (INTEL_GEN(dev_priv) >= 9)
14069                 return false;
14070
14071         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14072                 return false;
14073
14074         if (IS_CHERRYVIEW(dev_priv))
14075                 return false;
14076
14077         if (HAS_PCH_LPT_H(dev_priv) &&
14078             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14079                 return false;
14080
14081         /* DDI E can't be used if DDI A requires 4 lanes */
14082         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14083                 return false;
14084
14085         if (!dev_priv->vbt.int_crt_support)
14086                 return false;
14087
14088         return true;
14089 }
14090
14091 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14092 {
14093         int pps_num;
14094         int pps_idx;
14095
14096         if (HAS_DDI(dev_priv))
14097                 return;
14098         /*
14099          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14100          * everywhere where registers can be write protected.
14101          */
14102         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14103                 pps_num = 2;
14104         else
14105                 pps_num = 1;
14106
14107         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14108                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14109
14110                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14111                 I915_WRITE(PP_CONTROL(pps_idx), val);
14112         }
14113 }
14114
14115 static void intel_pps_init(struct drm_i915_private *dev_priv)
14116 {
14117         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14118                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14119         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14120                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14121         else
14122                 dev_priv->pps_mmio_base = PPS_BASE;
14123
14124         intel_pps_unlock_regs_wa(dev_priv);
14125 }
14126
14127 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14128 {
14129         struct intel_encoder *encoder;
14130         bool dpd_is_edp = false;
14131
14132         intel_pps_init(dev_priv);
14133
14134         /*
14135          * intel_edp_init_connector() depends on this completing first, to
14136          * prevent the registeration of both eDP and LVDS and the incorrect
14137          * sharing of the PPS.
14138          */
14139         intel_lvds_init(dev_priv);
14140
14141         if (intel_crt_present(dev_priv))
14142                 intel_crt_init(dev_priv);
14143
14144         if (IS_ICELAKE(dev_priv)) {
14145                 intel_ddi_init(dev_priv, PORT_A);
14146                 intel_ddi_init(dev_priv, PORT_B);
14147                 intel_ddi_init(dev_priv, PORT_C);
14148                 intel_ddi_init(dev_priv, PORT_D);
14149                 intel_ddi_init(dev_priv, PORT_E);
14150                 intel_ddi_init(dev_priv, PORT_F);
14151         } else if (IS_GEN9_LP(dev_priv)) {
14152                 /*
14153                  * FIXME: Broxton doesn't support port detection via the
14154                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14155                  * detect the ports.
14156                  */
14157                 intel_ddi_init(dev_priv, PORT_A);
14158                 intel_ddi_init(dev_priv, PORT_B);
14159                 intel_ddi_init(dev_priv, PORT_C);
14160
14161                 vlv_dsi_init(dev_priv);
14162         } else if (HAS_DDI(dev_priv)) {
14163                 int found;
14164
14165                 /*
14166                  * Haswell uses DDI functions to detect digital outputs.
14167                  * On SKL pre-D0 the strap isn't connected, so we assume
14168                  * it's there.
14169                  */
14170                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14171                 /* WaIgnoreDDIAStrap: skl */
14172                 if (found || IS_GEN9_BC(dev_priv))
14173                         intel_ddi_init(dev_priv, PORT_A);
14174
14175                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
14176                  * register */
14177                 found = I915_READ(SFUSE_STRAP);
14178
14179                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14180                         intel_ddi_init(dev_priv, PORT_B);
14181                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14182                         intel_ddi_init(dev_priv, PORT_C);
14183                 if (found & SFUSE_STRAP_DDID_DETECTED)
14184                         intel_ddi_init(dev_priv, PORT_D);
14185                 if (found & SFUSE_STRAP_DDIF_DETECTED)
14186                         intel_ddi_init(dev_priv, PORT_F);
14187                 /*
14188                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14189                  */
14190                 if (IS_GEN9_BC(dev_priv) &&
14191                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14192                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14193                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14194                         intel_ddi_init(dev_priv, PORT_E);
14195
14196         } else if (HAS_PCH_SPLIT(dev_priv)) {
14197                 int found;
14198                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14199
14200                 if (has_edp_a(dev_priv))
14201                         intel_dp_init(dev_priv, DP_A, PORT_A);
14202
14203                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14204                         /* PCH SDVOB multiplex with HDMIB */
14205                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14206                         if (!found)
14207                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14208                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14209                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14210                 }
14211
14212                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14213                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14214
14215                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14216                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14217
14218                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14219                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14220
14221                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14222                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14223         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14224                 bool has_edp, has_port;
14225
14226                 /*
14227                  * The DP_DETECTED bit is the latched state of the DDC
14228                  * SDA pin at boot. However since eDP doesn't require DDC
14229                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14230                  * eDP ports may have been muxed to an alternate function.
14231                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14232                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14233                  * detect eDP ports.
14234                  *
14235                  * Sadly the straps seem to be missing sometimes even for HDMI
14236                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14237                  * and VBT for the presence of the port. Additionally we can't
14238                  * trust the port type the VBT declares as we've seen at least
14239                  * HDMI ports that the VBT claim are DP or eDP.
14240                  */
14241                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14242                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14243                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14244                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14245                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14246                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14247
14248                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14249                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14250                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14251                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14252                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14253                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14254
14255                 if (IS_CHERRYVIEW(dev_priv)) {
14256                         /*
14257                          * eDP not supported on port D,
14258                          * so no need to worry about it
14259                          */
14260                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14261                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14262                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14263                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14264                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14265                 }
14266
14267                 vlv_dsi_init(dev_priv);
14268         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
14269                 bool found = false;
14270
14271                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14272                         DRM_DEBUG_KMS("probing SDVOB\n");
14273                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14274                         if (!found && IS_G4X(dev_priv)) {
14275                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14276                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14277                         }
14278
14279                         if (!found && IS_G4X(dev_priv))
14280                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14281                 }
14282
14283                 /* Before G4X SDVOC doesn't have its own detect register */
14284
14285                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14286                         DRM_DEBUG_KMS("probing SDVOC\n");
14287                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14288                 }
14289
14290                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14291
14292                         if (IS_G4X(dev_priv)) {
14293                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14294                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14295                         }
14296                         if (IS_G4X(dev_priv))
14297                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14298                 }
14299
14300                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14301                         intel_dp_init(dev_priv, DP_D, PORT_D);
14302         } else if (IS_GEN2(dev_priv))
14303                 intel_dvo_init(dev_priv);
14304
14305         if (SUPPORTS_TV(dev_priv))
14306                 intel_tv_init(dev_priv);
14307
14308         intel_psr_init(dev_priv);
14309
14310         for_each_intel_encoder(&dev_priv->drm, encoder) {
14311                 encoder->base.possible_crtcs = encoder->crtc_mask;
14312                 encoder->base.possible_clones =
14313                         intel_encoder_clones(encoder);
14314         }
14315
14316         intel_init_pch_refclk(dev_priv);
14317
14318         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14319 }
14320
14321 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14322 {
14323         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14324         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14325
14326         drm_framebuffer_cleanup(fb);
14327
14328         i915_gem_object_lock(obj);
14329         WARN_ON(!obj->framebuffer_references--);
14330         i915_gem_object_unlock(obj);
14331
14332         i915_gem_object_put(obj);
14333
14334         kfree(intel_fb);
14335 }
14336
14337 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14338                                                 struct drm_file *file,
14339                                                 unsigned int *handle)
14340 {
14341         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14342
14343         if (obj->userptr.mm) {
14344                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14345                 return -EINVAL;
14346         }
14347
14348         return drm_gem_handle_create(file, &obj->base, handle);
14349 }
14350
14351 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14352                                         struct drm_file *file,
14353                                         unsigned flags, unsigned color,
14354                                         struct drm_clip_rect *clips,
14355                                         unsigned num_clips)
14356 {
14357         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14358
14359         i915_gem_object_flush_if_display(obj);
14360         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14361
14362         return 0;
14363 }
14364
14365 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14366         .destroy = intel_user_framebuffer_destroy,
14367         .create_handle = intel_user_framebuffer_create_handle,
14368         .dirty = intel_user_framebuffer_dirty,
14369 };
14370
14371 static
14372 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14373                          uint64_t fb_modifier, uint32_t pixel_format)
14374 {
14375         u32 gen = INTEL_GEN(dev_priv);
14376
14377         if (gen >= 9) {
14378                 int cpp = drm_format_plane_cpp(pixel_format, 0);
14379
14380                 /* "The stride in bytes must not exceed the of the size of 8K
14381                  *  pixels and 32K bytes."
14382                  */
14383                 return min(8192 * cpp, 32768);
14384         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
14385                 return 32*1024;
14386         } else if (gen >= 4) {
14387                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14388                         return 16*1024;
14389                 else
14390                         return 32*1024;
14391         } else if (gen >= 3) {
14392                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
14393                         return 8*1024;
14394                 else
14395                         return 16*1024;
14396         } else {
14397                 /* XXX DSPC is limited to 4k tiled */
14398                 return 8*1024;
14399         }
14400 }
14401
14402 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14403                                   struct drm_i915_gem_object *obj,
14404                                   struct drm_mode_fb_cmd2 *mode_cmd)
14405 {
14406         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14407         struct drm_framebuffer *fb = &intel_fb->base;
14408         struct drm_format_name_buf format_name;
14409         u32 pitch_limit;
14410         unsigned int tiling, stride;
14411         int ret = -EINVAL;
14412         int i;
14413
14414         i915_gem_object_lock(obj);
14415         obj->framebuffer_references++;
14416         tiling = i915_gem_object_get_tiling(obj);
14417         stride = i915_gem_object_get_stride(obj);
14418         i915_gem_object_unlock(obj);
14419
14420         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14421                 /*
14422                  * If there's a fence, enforce that
14423                  * the fb modifier and tiling mode match.
14424                  */
14425                 if (tiling != I915_TILING_NONE &&
14426                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14427                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14428                         goto err;
14429                 }
14430         } else {
14431                 if (tiling == I915_TILING_X) {
14432                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14433                 } else if (tiling == I915_TILING_Y) {
14434                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14435                         goto err;
14436                 }
14437         }
14438
14439         /* Passed in modifier sanity checking. */
14440         switch (mode_cmd->modifier[0]) {
14441         case I915_FORMAT_MOD_Y_TILED_CCS:
14442         case I915_FORMAT_MOD_Yf_TILED_CCS:
14443                 switch (mode_cmd->pixel_format) {
14444                 case DRM_FORMAT_XBGR8888:
14445                 case DRM_FORMAT_ABGR8888:
14446                 case DRM_FORMAT_XRGB8888:
14447                 case DRM_FORMAT_ARGB8888:
14448                         break;
14449                 default:
14450                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
14451                         goto err;
14452                 }
14453                 /* fall through */
14454         case I915_FORMAT_MOD_Y_TILED:
14455         case I915_FORMAT_MOD_Yf_TILED:
14456                 if (INTEL_GEN(dev_priv) < 9) {
14457                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14458                                       mode_cmd->modifier[0]);
14459                         goto err;
14460                 }
14461         case DRM_FORMAT_MOD_LINEAR:
14462         case I915_FORMAT_MOD_X_TILED:
14463                 break;
14464         default:
14465                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14466                               mode_cmd->modifier[0]);
14467                 goto err;
14468         }
14469
14470         /*
14471          * gen2/3 display engine uses the fence if present,
14472          * so the tiling mode must match the fb modifier exactly.
14473          */
14474         if (INTEL_GEN(dev_priv) < 4 &&
14475             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14476                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14477                 goto err;
14478         }
14479
14480         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14481                                            mode_cmd->pixel_format);
14482         if (mode_cmd->pitches[0] > pitch_limit) {
14483                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14484                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14485                               "tiled" : "linear",
14486                               mode_cmd->pitches[0], pitch_limit);
14487                 goto err;
14488         }
14489
14490         /*
14491          * If there's a fence, enforce that
14492          * the fb pitch and fence stride match.
14493          */
14494         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14495                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14496                               mode_cmd->pitches[0], stride);
14497                 goto err;
14498         }
14499
14500         /* Reject formats not supported by any plane early. */
14501         switch (mode_cmd->pixel_format) {
14502         case DRM_FORMAT_C8:
14503         case DRM_FORMAT_RGB565:
14504         case DRM_FORMAT_XRGB8888:
14505         case DRM_FORMAT_ARGB8888:
14506                 break;
14507         case DRM_FORMAT_XRGB1555:
14508                 if (INTEL_GEN(dev_priv) > 3) {
14509                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14510                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14511                         goto err;
14512                 }
14513                 break;
14514         case DRM_FORMAT_ABGR8888:
14515                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14516                     INTEL_GEN(dev_priv) < 9) {
14517                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14518                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14519                         goto err;
14520                 }
14521                 break;
14522         case DRM_FORMAT_XBGR8888:
14523         case DRM_FORMAT_XRGB2101010:
14524         case DRM_FORMAT_XBGR2101010:
14525                 if (INTEL_GEN(dev_priv) < 4) {
14526                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14527                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14528                         goto err;
14529                 }
14530                 break;
14531         case DRM_FORMAT_ABGR2101010:
14532                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14533                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14534                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14535                         goto err;
14536                 }
14537                 break;
14538         case DRM_FORMAT_YUYV:
14539         case DRM_FORMAT_UYVY:
14540         case DRM_FORMAT_YVYU:
14541         case DRM_FORMAT_VYUY:
14542                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14543                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14544                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14545                         goto err;
14546                 }
14547                 break;
14548         case DRM_FORMAT_NV12:
14549                 if (INTEL_GEN(dev_priv) < 9 || IS_SKYLAKE(dev_priv) ||
14550                     IS_BROXTON(dev_priv)) {
14551                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14552                                       drm_get_format_name(mode_cmd->pixel_format,
14553                                                           &format_name));
14554                         goto err;
14555                 }
14556                 break;
14557         default:
14558                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14559                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14560                 goto err;
14561         }
14562
14563         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14564         if (mode_cmd->offsets[0] != 0)
14565                 goto err;
14566
14567         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14568
14569         if (fb->format->format == DRM_FORMAT_NV12 &&
14570             (fb->width < SKL_MIN_YUV_420_SRC_W ||
14571              fb->height < SKL_MIN_YUV_420_SRC_H ||
14572              (fb->width % 4) != 0 || (fb->height % 4) != 0)) {
14573                 DRM_DEBUG_KMS("src dimensions not correct for NV12\n");
14574                 return -EINVAL;
14575         }
14576
14577         for (i = 0; i < fb->format->num_planes; i++) {
14578                 u32 stride_alignment;
14579
14580                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14581                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14582                         goto err;
14583                 }
14584
14585                 stride_alignment = intel_fb_stride_alignment(fb, i);
14586
14587                 /*
14588                  * Display WA #0531: skl,bxt,kbl,glk
14589                  *
14590                  * Render decompression and plane width > 3840
14591                  * combined with horizontal panning requires the
14592                  * plane stride to be a multiple of 4. We'll just
14593                  * require the entire fb to accommodate that to avoid
14594                  * potential runtime errors at plane configuration time.
14595                  */
14596                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14597                     (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
14598                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS))
14599                         stride_alignment *= 4;
14600
14601                 if (fb->pitches[i] & (stride_alignment - 1)) {
14602                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14603                                       i, fb->pitches[i], stride_alignment);
14604                         goto err;
14605                 }
14606
14607                 fb->obj[i] = &obj->base;
14608         }
14609
14610         ret = intel_fill_fb_info(dev_priv, fb);
14611         if (ret)
14612                 goto err;
14613
14614         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14615         if (ret) {
14616                 DRM_ERROR("framebuffer init failed %d\n", ret);
14617                 goto err;
14618         }
14619
14620         return 0;
14621
14622 err:
14623         i915_gem_object_lock(obj);
14624         obj->framebuffer_references--;
14625         i915_gem_object_unlock(obj);
14626         return ret;
14627 }
14628
14629 static struct drm_framebuffer *
14630 intel_user_framebuffer_create(struct drm_device *dev,
14631                               struct drm_file *filp,
14632                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14633 {
14634         struct drm_framebuffer *fb;
14635         struct drm_i915_gem_object *obj;
14636         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14637
14638         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14639         if (!obj)
14640                 return ERR_PTR(-ENOENT);
14641
14642         fb = intel_framebuffer_create(obj, &mode_cmd);
14643         if (IS_ERR(fb))
14644                 i915_gem_object_put(obj);
14645
14646         return fb;
14647 }
14648
14649 static void intel_atomic_state_free(struct drm_atomic_state *state)
14650 {
14651         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14652
14653         drm_atomic_state_default_release(state);
14654
14655         i915_sw_fence_fini(&intel_state->commit_ready);
14656
14657         kfree(state);
14658 }
14659
14660 static enum drm_mode_status
14661 intel_mode_valid(struct drm_device *dev,
14662                  const struct drm_display_mode *mode)
14663 {
14664         struct drm_i915_private *dev_priv = to_i915(dev);
14665         int hdisplay_max, htotal_max;
14666         int vdisplay_max, vtotal_max;
14667
14668         /*
14669          * Can't reject DBLSCAN here because Xorg ddxen can add piles
14670          * of DBLSCAN modes to the output's mode list when they detect
14671          * the scaling mode property on the connector. And they don't
14672          * ask the kernel to validate those modes in any way until
14673          * modeset time at which point the client gets a protocol error.
14674          * So in order to not upset those clients we silently ignore the
14675          * DBLSCAN flag on such connectors. For other connectors we will
14676          * reject modes with the DBLSCAN flag in encoder->compute_config().
14677          * And we always reject DBLSCAN modes in connector->mode_valid()
14678          * as we never want such modes on the connector's mode list.
14679          */
14680
14681         if (mode->vscan > 1)
14682                 return MODE_NO_VSCAN;
14683
14684         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14685                 return MODE_H_ILLEGAL;
14686
14687         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14688                            DRM_MODE_FLAG_NCSYNC |
14689                            DRM_MODE_FLAG_PCSYNC))
14690                 return MODE_HSYNC;
14691
14692         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14693                            DRM_MODE_FLAG_PIXMUX |
14694                            DRM_MODE_FLAG_CLKDIV2))
14695                 return MODE_BAD;
14696
14697         if (INTEL_GEN(dev_priv) >= 9 ||
14698             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
14699                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
14700                 vdisplay_max = 4096;
14701                 htotal_max = 8192;
14702                 vtotal_max = 8192;
14703         } else if (INTEL_GEN(dev_priv) >= 3) {
14704                 hdisplay_max = 4096;
14705                 vdisplay_max = 4096;
14706                 htotal_max = 8192;
14707                 vtotal_max = 8192;
14708         } else {
14709                 hdisplay_max = 2048;
14710                 vdisplay_max = 2048;
14711                 htotal_max = 4096;
14712                 vtotal_max = 4096;
14713         }
14714
14715         if (mode->hdisplay > hdisplay_max ||
14716             mode->hsync_start > htotal_max ||
14717             mode->hsync_end > htotal_max ||
14718             mode->htotal > htotal_max)
14719                 return MODE_H_ILLEGAL;
14720
14721         if (mode->vdisplay > vdisplay_max ||
14722             mode->vsync_start > vtotal_max ||
14723             mode->vsync_end > vtotal_max ||
14724             mode->vtotal > vtotal_max)
14725                 return MODE_V_ILLEGAL;
14726
14727         return MODE_OK;
14728 }
14729
14730 static const struct drm_mode_config_funcs intel_mode_funcs = {
14731         .fb_create = intel_user_framebuffer_create,
14732         .get_format_info = intel_get_format_info,
14733         .output_poll_changed = intel_fbdev_output_poll_changed,
14734         .mode_valid = intel_mode_valid,
14735         .atomic_check = intel_atomic_check,
14736         .atomic_commit = intel_atomic_commit,
14737         .atomic_state_alloc = intel_atomic_state_alloc,
14738         .atomic_state_clear = intel_atomic_state_clear,
14739         .atomic_state_free = intel_atomic_state_free,
14740 };
14741
14742 /**
14743  * intel_init_display_hooks - initialize the display modesetting hooks
14744  * @dev_priv: device private
14745  */
14746 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14747 {
14748         intel_init_cdclk_hooks(dev_priv);
14749
14750         if (INTEL_GEN(dev_priv) >= 9) {
14751                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14752                 dev_priv->display.get_initial_plane_config =
14753                         skylake_get_initial_plane_config;
14754                 dev_priv->display.crtc_compute_clock =
14755                         haswell_crtc_compute_clock;
14756                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14757                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14758         } else if (HAS_DDI(dev_priv)) {
14759                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14760                 dev_priv->display.get_initial_plane_config =
14761                         i9xx_get_initial_plane_config;
14762                 dev_priv->display.crtc_compute_clock =
14763                         haswell_crtc_compute_clock;
14764                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14765                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14766         } else if (HAS_PCH_SPLIT(dev_priv)) {
14767                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14768                 dev_priv->display.get_initial_plane_config =
14769                         i9xx_get_initial_plane_config;
14770                 dev_priv->display.crtc_compute_clock =
14771                         ironlake_crtc_compute_clock;
14772                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14773                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14774         } else if (IS_CHERRYVIEW(dev_priv)) {
14775                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14776                 dev_priv->display.get_initial_plane_config =
14777                         i9xx_get_initial_plane_config;
14778                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14779                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14780                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14781         } else if (IS_VALLEYVIEW(dev_priv)) {
14782                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14783                 dev_priv->display.get_initial_plane_config =
14784                         i9xx_get_initial_plane_config;
14785                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14786                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14787                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14788         } else if (IS_G4X(dev_priv)) {
14789                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14790                 dev_priv->display.get_initial_plane_config =
14791                         i9xx_get_initial_plane_config;
14792                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14793                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14794                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14795         } else if (IS_PINEVIEW(dev_priv)) {
14796                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14797                 dev_priv->display.get_initial_plane_config =
14798                         i9xx_get_initial_plane_config;
14799                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14800                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14801                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14802         } else if (!IS_GEN2(dev_priv)) {
14803                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14804                 dev_priv->display.get_initial_plane_config =
14805                         i9xx_get_initial_plane_config;
14806                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14807                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14808                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14809         } else {
14810                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14811                 dev_priv->display.get_initial_plane_config =
14812                         i9xx_get_initial_plane_config;
14813                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14814                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14815                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14816         }
14817
14818         if (IS_GEN5(dev_priv)) {
14819                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14820         } else if (IS_GEN6(dev_priv)) {
14821                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14822         } else if (IS_IVYBRIDGE(dev_priv)) {
14823                 /* FIXME: detect B0+ stepping and use auto training */
14824                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14825         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14826                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14827         }
14828
14829         if (INTEL_GEN(dev_priv) >= 9)
14830                 dev_priv->display.update_crtcs = skl_update_crtcs;
14831         else
14832                 dev_priv->display.update_crtcs = intel_update_crtcs;
14833 }
14834
14835 /*
14836  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14837  */
14838 static void quirk_ssc_force_disable(struct drm_device *dev)
14839 {
14840         struct drm_i915_private *dev_priv = to_i915(dev);
14841         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14842         DRM_INFO("applying lvds SSC disable quirk\n");
14843 }
14844
14845 /*
14846  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14847  * brightness value
14848  */
14849 static void quirk_invert_brightness(struct drm_device *dev)
14850 {
14851         struct drm_i915_private *dev_priv = to_i915(dev);
14852         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14853         DRM_INFO("applying inverted panel brightness quirk\n");
14854 }
14855
14856 /* Some VBT's incorrectly indicate no backlight is present */
14857 static void quirk_backlight_present(struct drm_device *dev)
14858 {
14859         struct drm_i915_private *dev_priv = to_i915(dev);
14860         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14861         DRM_INFO("applying backlight present quirk\n");
14862 }
14863
14864 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14865  * which is 300 ms greater than eDP spec T12 min.
14866  */
14867 static void quirk_increase_t12_delay(struct drm_device *dev)
14868 {
14869         struct drm_i915_private *dev_priv = to_i915(dev);
14870
14871         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14872         DRM_INFO("Applying T12 delay quirk\n");
14873 }
14874
14875 /*
14876  * GeminiLake NUC HDMI outputs require additional off time
14877  * this allows the onboard retimer to correctly sync to signal
14878  */
14879 static void quirk_increase_ddi_disabled_time(struct drm_device *dev)
14880 {
14881         struct drm_i915_private *dev_priv = to_i915(dev);
14882
14883         dev_priv->quirks |= QUIRK_INCREASE_DDI_DISABLED_TIME;
14884         DRM_INFO("Applying Increase DDI Disabled quirk\n");
14885 }
14886
14887 struct intel_quirk {
14888         int device;
14889         int subsystem_vendor;
14890         int subsystem_device;
14891         void (*hook)(struct drm_device *dev);
14892 };
14893
14894 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14895 struct intel_dmi_quirk {
14896         void (*hook)(struct drm_device *dev);
14897         const struct dmi_system_id (*dmi_id_list)[];
14898 };
14899
14900 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14901 {
14902         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14903         return 1;
14904 }
14905
14906 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14907         {
14908                 .dmi_id_list = &(const struct dmi_system_id[]) {
14909                         {
14910                                 .callback = intel_dmi_reverse_brightness,
14911                                 .ident = "NCR Corporation",
14912                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14913                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14914                                 },
14915                         },
14916                         { }  /* terminating entry */
14917                 },
14918                 .hook = quirk_invert_brightness,
14919         },
14920 };
14921
14922 static struct intel_quirk intel_quirks[] = {
14923         /* Lenovo U160 cannot use SSC on LVDS */
14924         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14925
14926         /* Sony Vaio Y cannot use SSC on LVDS */
14927         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14928
14929         /* Acer Aspire 5734Z must invert backlight brightness */
14930         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14931
14932         /* Acer/eMachines G725 */
14933         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14934
14935         /* Acer/eMachines e725 */
14936         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14937
14938         /* Acer/Packard Bell NCL20 */
14939         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14940
14941         /* Acer Aspire 4736Z */
14942         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14943
14944         /* Acer Aspire 5336 */
14945         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14946
14947         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14948         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14949
14950         /* Acer C720 Chromebook (Core i3 4005U) */
14951         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14952
14953         /* Apple Macbook 2,1 (Core 2 T7400) */
14954         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14955
14956         /* Apple Macbook 4,1 */
14957         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14958
14959         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14960         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14961
14962         /* HP Chromebook 14 (Celeron 2955U) */
14963         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14964
14965         /* Dell Chromebook 11 */
14966         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14967
14968         /* Dell Chromebook 11 (2015 version) */
14969         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14970
14971         /* Toshiba Satellite P50-C-18C */
14972         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14973
14974         /* GeminiLake NUC */
14975         { 0x3185, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14976         { 0x3184, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
14977         /* ASRock ITX*/
14978         { 0x3185, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14979         { 0x3184, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
14980 };
14981
14982 static void intel_init_quirks(struct drm_device *dev)
14983 {
14984         struct pci_dev *d = dev->pdev;
14985         int i;
14986
14987         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14988                 struct intel_quirk *q = &intel_quirks[i];
14989
14990                 if (d->device == q->device &&
14991                     (d->subsystem_vendor == q->subsystem_vendor ||
14992                      q->subsystem_vendor == PCI_ANY_ID) &&
14993                     (d->subsystem_device == q->subsystem_device ||
14994                      q->subsystem_device == PCI_ANY_ID))
14995                         q->hook(dev);
14996         }
14997         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14998                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14999                         intel_dmi_quirks[i].hook(dev);
15000         }
15001 }
15002
15003 /* Disable the VGA plane that we never use */
15004 static void i915_disable_vga(struct drm_i915_private *dev_priv)
15005 {
15006         struct pci_dev *pdev = dev_priv->drm.pdev;
15007         u8 sr1;
15008         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15009
15010         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15011         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
15012         outb(SR01, VGA_SR_INDEX);
15013         sr1 = inb(VGA_SR_DATA);
15014         outb(sr1 | 1<<5, VGA_SR_DATA);
15015         vga_put(pdev, VGA_RSRC_LEGACY_IO);
15016         udelay(300);
15017
15018         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15019         POSTING_READ(vga_reg);
15020 }
15021
15022 void intel_modeset_init_hw(struct drm_device *dev)
15023 {
15024         struct drm_i915_private *dev_priv = to_i915(dev);
15025
15026         intel_update_cdclk(dev_priv);
15027         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
15028         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
15029 }
15030
15031 /*
15032  * Calculate what we think the watermarks should be for the state we've read
15033  * out of the hardware and then immediately program those watermarks so that
15034  * we ensure the hardware settings match our internal state.
15035  *
15036  * We can calculate what we think WM's should be by creating a duplicate of the
15037  * current state (which was constructed during hardware readout) and running it
15038  * through the atomic check code to calculate new watermark values in the
15039  * state object.
15040  */
15041 static void sanitize_watermarks(struct drm_device *dev)
15042 {
15043         struct drm_i915_private *dev_priv = to_i915(dev);
15044         struct drm_atomic_state *state;
15045         struct intel_atomic_state *intel_state;
15046         struct drm_crtc *crtc;
15047         struct drm_crtc_state *cstate;
15048         struct drm_modeset_acquire_ctx ctx;
15049         int ret;
15050         int i;
15051
15052         /* Only supported on platforms that use atomic watermark design */
15053         if (!dev_priv->display.optimize_watermarks)
15054                 return;
15055
15056         /*
15057          * We need to hold connection_mutex before calling duplicate_state so
15058          * that the connector loop is protected.
15059          */
15060         drm_modeset_acquire_init(&ctx, 0);
15061 retry:
15062         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15063         if (ret == -EDEADLK) {
15064                 drm_modeset_backoff(&ctx);
15065                 goto retry;
15066         } else if (WARN_ON(ret)) {
15067                 goto fail;
15068         }
15069
15070         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15071         if (WARN_ON(IS_ERR(state)))
15072                 goto fail;
15073
15074         intel_state = to_intel_atomic_state(state);
15075
15076         /*
15077          * Hardware readout is the only time we don't want to calculate
15078          * intermediate watermarks (since we don't trust the current
15079          * watermarks).
15080          */
15081         if (!HAS_GMCH_DISPLAY(dev_priv))
15082                 intel_state->skip_intermediate_wm = true;
15083
15084         ret = intel_atomic_check(dev, state);
15085         if (ret) {
15086                 /*
15087                  * If we fail here, it means that the hardware appears to be
15088                  * programmed in a way that shouldn't be possible, given our
15089                  * understanding of watermark requirements.  This might mean a
15090                  * mistake in the hardware readout code or a mistake in the
15091                  * watermark calculations for a given platform.  Raise a WARN
15092                  * so that this is noticeable.
15093                  *
15094                  * If this actually happens, we'll have to just leave the
15095                  * BIOS-programmed watermarks untouched and hope for the best.
15096                  */
15097                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15098                 goto put_state;
15099         }
15100
15101         /* Write calculated watermark values back */
15102         for_each_new_crtc_in_state(state, crtc, cstate, i) {
15103                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15104
15105                 cs->wm.need_postvbl_update = true;
15106                 dev_priv->display.optimize_watermarks(intel_state, cs);
15107
15108                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
15109         }
15110
15111 put_state:
15112         drm_atomic_state_put(state);
15113 fail:
15114         drm_modeset_drop_locks(&ctx);
15115         drm_modeset_acquire_fini(&ctx);
15116 }
15117
15118 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
15119 {
15120         if (IS_GEN5(dev_priv)) {
15121                 u32 fdi_pll_clk =
15122                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
15123
15124                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
15125         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
15126                 dev_priv->fdi_pll_freq = 270000;
15127         } else {
15128                 return;
15129         }
15130
15131         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
15132 }
15133
15134 int intel_modeset_init(struct drm_device *dev)
15135 {
15136         struct drm_i915_private *dev_priv = to_i915(dev);
15137         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15138         enum pipe pipe;
15139         struct intel_crtc *crtc;
15140
15141         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15142
15143         drm_mode_config_init(dev);
15144
15145         dev->mode_config.min_width = 0;
15146         dev->mode_config.min_height = 0;
15147
15148         dev->mode_config.preferred_depth = 24;
15149         dev->mode_config.prefer_shadow = 1;
15150
15151         dev->mode_config.allow_fb_modifiers = true;
15152
15153         dev->mode_config.funcs = &intel_mode_funcs;
15154
15155         init_llist_head(&dev_priv->atomic_helper.free_list);
15156         INIT_WORK(&dev_priv->atomic_helper.free_work,
15157                   intel_atomic_helper_free_state_worker);
15158
15159         intel_init_quirks(dev);
15160
15161         intel_init_pm(dev_priv);
15162
15163         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15164                 return 0;
15165
15166         /*
15167          * There may be no VBT; and if the BIOS enabled SSC we can
15168          * just keep using it to avoid unnecessary flicker.  Whereas if the
15169          * BIOS isn't using it, don't assume it will work even if the VBT
15170          * indicates as much.
15171          */
15172         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15173                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15174                                             DREF_SSC1_ENABLE);
15175
15176                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15177                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15178                                      bios_lvds_use_ssc ? "en" : "dis",
15179                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15180                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15181                 }
15182         }
15183
15184         /* maximum framebuffer dimensions */
15185         if (IS_GEN2(dev_priv)) {
15186                 dev->mode_config.max_width = 2048;
15187                 dev->mode_config.max_height = 2048;
15188         } else if (IS_GEN3(dev_priv)) {
15189                 dev->mode_config.max_width = 4096;
15190                 dev->mode_config.max_height = 4096;
15191         } else {
15192                 dev->mode_config.max_width = 8192;
15193                 dev->mode_config.max_height = 8192;
15194         }
15195
15196         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15197                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15198                 dev->mode_config.cursor_height = 1023;
15199         } else if (IS_GEN2(dev_priv)) {
15200                 dev->mode_config.cursor_width = 64;
15201                 dev->mode_config.cursor_height = 64;
15202         } else {
15203                 dev->mode_config.cursor_width = 256;
15204                 dev->mode_config.cursor_height = 256;
15205         }
15206
15207         dev->mode_config.fb_base = ggtt->gmadr.start;
15208
15209         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15210                       INTEL_INFO(dev_priv)->num_pipes,
15211                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15212
15213         for_each_pipe(dev_priv, pipe) {
15214                 int ret;
15215
15216                 ret = intel_crtc_init(dev_priv, pipe);
15217                 if (ret) {
15218                         drm_mode_config_cleanup(dev);
15219                         return ret;
15220                 }
15221         }
15222
15223         intel_shared_dpll_init(dev);
15224         intel_update_fdi_pll_freq(dev_priv);
15225
15226         intel_update_czclk(dev_priv);
15227         intel_modeset_init_hw(dev);
15228
15229         if (dev_priv->max_cdclk_freq == 0)
15230                 intel_update_max_cdclk(dev_priv);
15231
15232         /* Just disable it once at startup */
15233         i915_disable_vga(dev_priv);
15234         intel_setup_outputs(dev_priv);
15235
15236         drm_modeset_lock_all(dev);
15237         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15238         drm_modeset_unlock_all(dev);
15239
15240         for_each_intel_crtc(dev, crtc) {
15241                 struct intel_initial_plane_config plane_config = {};
15242
15243                 if (!crtc->active)
15244                         continue;
15245
15246                 /*
15247                  * Note that reserving the BIOS fb up front prevents us
15248                  * from stuffing other stolen allocations like the ring
15249                  * on top.  This prevents some ugliness at boot time, and
15250                  * can even allow for smooth boot transitions if the BIOS
15251                  * fb is large enough for the active pipe configuration.
15252                  */
15253                 dev_priv->display.get_initial_plane_config(crtc,
15254                                                            &plane_config);
15255
15256                 /*
15257                  * If the fb is shared between multiple heads, we'll
15258                  * just get the first one.
15259                  */
15260                 intel_find_initial_plane_obj(crtc, &plane_config);
15261         }
15262
15263         /*
15264          * Make sure hardware watermarks really match the state we read out.
15265          * Note that we need to do this after reconstructing the BIOS fb's
15266          * since the watermark calculation done here will use pstate->fb.
15267          */
15268         if (!HAS_GMCH_DISPLAY(dev_priv))
15269                 sanitize_watermarks(dev);
15270
15271         return 0;
15272 }
15273
15274 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15275 {
15276         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15277         /* 640x480@60Hz, ~25175 kHz */
15278         struct dpll clock = {
15279                 .m1 = 18,
15280                 .m2 = 7,
15281                 .p1 = 13,
15282                 .p2 = 4,
15283                 .n = 2,
15284         };
15285         u32 dpll, fp;
15286         int i;
15287
15288         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15289
15290         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15291                       pipe_name(pipe), clock.vco, clock.dot);
15292
15293         fp = i9xx_dpll_compute_fp(&clock);
15294         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
15295                 DPLL_VGA_MODE_DIS |
15296                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15297                 PLL_P2_DIVIDE_BY_4 |
15298                 PLL_REF_INPUT_DREFCLK |
15299                 DPLL_VCO_ENABLE;
15300
15301         I915_WRITE(FP0(pipe), fp);
15302         I915_WRITE(FP1(pipe), fp);
15303
15304         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15305         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15306         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15307         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15308         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15309         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15310         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15311
15312         /*
15313          * Apparently we need to have VGA mode enabled prior to changing
15314          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15315          * dividers, even though the register value does change.
15316          */
15317         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15318         I915_WRITE(DPLL(pipe), dpll);
15319
15320         /* Wait for the clocks to stabilize. */
15321         POSTING_READ(DPLL(pipe));
15322         udelay(150);
15323
15324         /* The pixel multiplier can only be updated once the
15325          * DPLL is enabled and the clocks are stable.
15326          *
15327          * So write it again.
15328          */
15329         I915_WRITE(DPLL(pipe), dpll);
15330
15331         /* We do this three times for luck */
15332         for (i = 0; i < 3 ; i++) {
15333                 I915_WRITE(DPLL(pipe), dpll);
15334                 POSTING_READ(DPLL(pipe));
15335                 udelay(150); /* wait for warmup */
15336         }
15337
15338         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15339         POSTING_READ(PIPECONF(pipe));
15340
15341         intel_wait_for_pipe_scanline_moving(crtc);
15342 }
15343
15344 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15345 {
15346         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15347
15348         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15349                       pipe_name(pipe));
15350
15351         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15352         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15353         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15354         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15355         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
15356
15357         I915_WRITE(PIPECONF(pipe), 0);
15358         POSTING_READ(PIPECONF(pipe));
15359
15360         intel_wait_for_pipe_scanline_stopped(crtc);
15361
15362         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15363         POSTING_READ(DPLL(pipe));
15364 }
15365
15366 static bool intel_plane_mapping_ok(struct intel_crtc *crtc,
15367                                    struct intel_plane *plane)
15368 {
15369         enum pipe pipe;
15370
15371         if (!plane->get_hw_state(plane, &pipe))
15372                 return true;
15373
15374         return pipe == crtc->pipe;
15375 }
15376
15377 static void
15378 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15379 {
15380         struct intel_crtc *crtc;
15381
15382         if (INTEL_GEN(dev_priv) >= 4)
15383                 return;
15384
15385         for_each_intel_crtc(&dev_priv->drm, crtc) {
15386                 struct intel_plane *plane =
15387                         to_intel_plane(crtc->base.primary);
15388
15389                 if (intel_plane_mapping_ok(crtc, plane))
15390                         continue;
15391
15392                 DRM_DEBUG_KMS("%s attached to the wrong pipe, disabling plane\n",
15393                               plane->base.name);
15394                 intel_plane_disable_noatomic(crtc, plane);
15395         }
15396 }
15397
15398 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15399 {
15400         struct drm_device *dev = crtc->base.dev;
15401         struct intel_encoder *encoder;
15402
15403         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15404                 return true;
15405
15406         return false;
15407 }
15408
15409 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15410 {
15411         struct drm_device *dev = encoder->base.dev;
15412         struct intel_connector *connector;
15413
15414         for_each_connector_on_encoder(dev, &encoder->base, connector)
15415                 return connector;
15416
15417         return NULL;
15418 }
15419
15420 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15421                               enum pipe pch_transcoder)
15422 {
15423         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15424                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15425 }
15426
15427 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15428                                 struct drm_modeset_acquire_ctx *ctx)
15429 {
15430         struct drm_device *dev = crtc->base.dev;
15431         struct drm_i915_private *dev_priv = to_i915(dev);
15432         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15433
15434         /* Clear any frame start delays used for debugging left by the BIOS */
15435         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15436                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15437
15438                 I915_WRITE(reg,
15439                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15440         }
15441
15442         /* restore vblank interrupts to correct state */
15443         drm_crtc_vblank_reset(&crtc->base);
15444         if (crtc->active) {
15445                 struct intel_plane *plane;
15446
15447                 drm_crtc_vblank_on(&crtc->base);
15448
15449                 /* Disable everything but the primary plane */
15450                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15451                         const struct intel_plane_state *plane_state =
15452                                 to_intel_plane_state(plane->base.state);
15453
15454                         if (plane_state->base.visible &&
15455                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15456                                 intel_plane_disable_noatomic(crtc, plane);
15457                 }
15458         }
15459
15460         /* Adjust the state of the output pipe according to whether we
15461          * have active connectors/encoders. */
15462         if (crtc->active && !intel_crtc_has_encoders(crtc))
15463                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15464
15465         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15466                 /*
15467                  * We start out with underrun reporting disabled to avoid races.
15468                  * For correct bookkeeping mark this on active crtcs.
15469                  *
15470                  * Also on gmch platforms we dont have any hardware bits to
15471                  * disable the underrun reporting. Which means we need to start
15472                  * out with underrun reporting disabled also on inactive pipes,
15473                  * since otherwise we'll complain about the garbage we read when
15474                  * e.g. coming up after runtime pm.
15475                  *
15476                  * No protection against concurrent access is required - at
15477                  * worst a fifo underrun happens which also sets this to false.
15478                  */
15479                 crtc->cpu_fifo_underrun_disabled = true;
15480                 /*
15481                  * We track the PCH trancoder underrun reporting state
15482                  * within the crtc. With crtc for pipe A housing the underrun
15483                  * reporting state for PCH transcoder A, crtc for pipe B housing
15484                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15485                  * and marking underrun reporting as disabled for the non-existing
15486                  * PCH transcoders B and C would prevent enabling the south
15487                  * error interrupt (see cpt_can_enable_serr_int()).
15488                  */
15489                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15490                         crtc->pch_fifo_underrun_disabled = true;
15491         }
15492 }
15493
15494 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15495 {
15496         struct intel_connector *connector;
15497
15498         /* We need to check both for a crtc link (meaning that the
15499          * encoder is active and trying to read from a pipe) and the
15500          * pipe itself being active. */
15501         bool has_active_crtc = encoder->base.crtc &&
15502                 to_intel_crtc(encoder->base.crtc)->active;
15503
15504         connector = intel_encoder_find_connector(encoder);
15505         if (connector && !has_active_crtc) {
15506                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15507                               encoder->base.base.id,
15508                               encoder->base.name);
15509
15510                 /* Connector is active, but has no active pipe. This is
15511                  * fallout from our resume register restoring. Disable
15512                  * the encoder manually again. */
15513                 if (encoder->base.crtc) {
15514                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15515
15516                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15517                                       encoder->base.base.id,
15518                                       encoder->base.name);
15519                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15520                         if (encoder->post_disable)
15521                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15522                 }
15523                 encoder->base.crtc = NULL;
15524
15525                 /* Inconsistent output/port/pipe state happens presumably due to
15526                  * a bug in one of the get_hw_state functions. Or someplace else
15527                  * in our code, like the register restore mess on resume. Clamp
15528                  * things to off as a safer default. */
15529
15530                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15531                 connector->base.encoder = NULL;
15532         }
15533
15534         /* notify opregion of the sanitized encoder state */
15535         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
15536 }
15537
15538 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15539 {
15540         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15541
15542         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15543                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15544                 i915_disable_vga(dev_priv);
15545         }
15546 }
15547
15548 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15549 {
15550         /* This function can be called both from intel_modeset_setup_hw_state or
15551          * at a very early point in our resume sequence, where the power well
15552          * structures are not yet restored. Since this function is at a very
15553          * paranoid "someone might have enabled VGA while we were not looking"
15554          * level, just check if the power well is enabled instead of trying to
15555          * follow the "don't touch the power well if we don't need it" policy
15556          * the rest of the driver uses. */
15557         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15558                 return;
15559
15560         i915_redisable_vga_power_on(dev_priv);
15561
15562         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15563 }
15564
15565 /* FIXME read out full plane state for all planes */
15566 static void readout_plane_state(struct intel_crtc *crtc)
15567 {
15568         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15569         struct intel_crtc_state *crtc_state =
15570                 to_intel_crtc_state(crtc->base.state);
15571         struct intel_plane *plane;
15572
15573         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
15574                 struct intel_plane_state *plane_state =
15575                         to_intel_plane_state(plane->base.state);
15576                 enum pipe pipe;
15577                 bool visible;
15578
15579                 visible = plane->get_hw_state(plane, &pipe);
15580
15581                 intel_set_plane_visible(crtc_state, plane_state, visible);
15582         }
15583 }
15584
15585 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15586 {
15587         struct drm_i915_private *dev_priv = to_i915(dev);
15588         enum pipe pipe;
15589         struct intel_crtc *crtc;
15590         struct intel_encoder *encoder;
15591         struct intel_connector *connector;
15592         struct drm_connector_list_iter conn_iter;
15593         int i;
15594
15595         dev_priv->active_crtcs = 0;
15596
15597         for_each_intel_crtc(dev, crtc) {
15598                 struct intel_crtc_state *crtc_state =
15599                         to_intel_crtc_state(crtc->base.state);
15600
15601                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15602                 memset(crtc_state, 0, sizeof(*crtc_state));
15603                 crtc_state->base.crtc = &crtc->base;
15604
15605                 crtc_state->base.active = crtc_state->base.enable =
15606                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15607
15608                 crtc->base.enabled = crtc_state->base.enable;
15609                 crtc->active = crtc_state->base.active;
15610
15611                 if (crtc_state->base.active)
15612                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15613
15614                 readout_plane_state(crtc);
15615
15616                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15617                               crtc->base.base.id, crtc->base.name,
15618                               enableddisabled(crtc_state->base.active));
15619         }
15620
15621         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15622                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15623
15624                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15625                                                         &pll->state.hw_state);
15626                 pll->state.crtc_mask = 0;
15627                 for_each_intel_crtc(dev, crtc) {
15628                         struct intel_crtc_state *crtc_state =
15629                                 to_intel_crtc_state(crtc->base.state);
15630
15631                         if (crtc_state->base.active &&
15632                             crtc_state->shared_dpll == pll)
15633                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15634                 }
15635                 pll->active_mask = pll->state.crtc_mask;
15636
15637                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15638                               pll->info->name, pll->state.crtc_mask, pll->on);
15639         }
15640
15641         for_each_intel_encoder(dev, encoder) {
15642                 pipe = 0;
15643
15644                 if (encoder->get_hw_state(encoder, &pipe)) {
15645                         struct intel_crtc_state *crtc_state;
15646
15647                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15648                         crtc_state = to_intel_crtc_state(crtc->base.state);
15649
15650                         encoder->base.crtc = &crtc->base;
15651                         encoder->get_config(encoder, crtc_state);
15652                 } else {
15653                         encoder->base.crtc = NULL;
15654                 }
15655
15656                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15657                               encoder->base.base.id, encoder->base.name,
15658                               enableddisabled(encoder->base.crtc),
15659                               pipe_name(pipe));
15660         }
15661
15662         drm_connector_list_iter_begin(dev, &conn_iter);
15663         for_each_intel_connector_iter(connector, &conn_iter) {
15664                 if (connector->get_hw_state(connector)) {
15665                         connector->base.dpms = DRM_MODE_DPMS_ON;
15666
15667                         encoder = connector->encoder;
15668                         connector->base.encoder = &encoder->base;
15669
15670                         if (encoder->base.crtc &&
15671                             encoder->base.crtc->state->active) {
15672                                 /*
15673                                  * This has to be done during hardware readout
15674                                  * because anything calling .crtc_disable may
15675                                  * rely on the connector_mask being accurate.
15676                                  */
15677                                 encoder->base.crtc->state->connector_mask |=
15678                                         drm_connector_mask(&connector->base);
15679                                 encoder->base.crtc->state->encoder_mask |=
15680                                         drm_encoder_mask(&encoder->base);
15681                         }
15682
15683                 } else {
15684                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15685                         connector->base.encoder = NULL;
15686                 }
15687                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15688                               connector->base.base.id, connector->base.name,
15689                               enableddisabled(connector->base.encoder));
15690         }
15691         drm_connector_list_iter_end(&conn_iter);
15692
15693         for_each_intel_crtc(dev, crtc) {
15694                 struct intel_crtc_state *crtc_state =
15695                         to_intel_crtc_state(crtc->base.state);
15696                 int min_cdclk = 0;
15697
15698                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15699                 if (crtc_state->base.active) {
15700                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15701                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
15702                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
15703                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15704                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15705
15706                         /*
15707                          * The initial mode needs to be set in order to keep
15708                          * the atomic core happy. It wants a valid mode if the
15709                          * crtc's enabled, so we do the above call.
15710                          *
15711                          * But we don't set all the derived state fully, hence
15712                          * set a flag to indicate that a full recalculation is
15713                          * needed on the next commit.
15714                          */
15715                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15716
15717                         intel_crtc_compute_pixel_rate(crtc_state);
15718
15719                         if (dev_priv->display.modeset_calc_cdclk) {
15720                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15721                                 if (WARN_ON(min_cdclk < 0))
15722                                         min_cdclk = 0;
15723                         }
15724
15725                         drm_calc_timestamping_constants(&crtc->base,
15726                                                         &crtc_state->base.adjusted_mode);
15727                         update_scanline_offset(crtc);
15728                 }
15729
15730                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15731                 dev_priv->min_voltage_level[crtc->pipe] =
15732                         crtc_state->min_voltage_level;
15733
15734                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15735         }
15736 }
15737
15738 static void
15739 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15740 {
15741         struct intel_encoder *encoder;
15742
15743         for_each_intel_encoder(&dev_priv->drm, encoder) {
15744                 u64 get_domains;
15745                 enum intel_display_power_domain domain;
15746                 struct intel_crtc_state *crtc_state;
15747
15748                 if (!encoder->get_power_domains)
15749                         continue;
15750
15751                 /*
15752                  * MST-primary and inactive encoders don't have a crtc state
15753                  * and neither of these require any power domain references.
15754                  */
15755                 if (!encoder->base.crtc)
15756                         continue;
15757
15758                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
15759                 get_domains = encoder->get_power_domains(encoder, crtc_state);
15760                 for_each_power_domain(domain, get_domains)
15761                         intel_display_power_get(dev_priv, domain);
15762         }
15763 }
15764
15765 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15766 {
15767         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15768         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15769                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15770                            DARBF_GATING_DIS);
15771
15772         if (IS_HASWELL(dev_priv)) {
15773                 /*
15774                  * WaRsPkgCStateDisplayPMReq:hsw
15775                  * System hang if this isn't done before disabling all planes!
15776                  */
15777                 I915_WRITE(CHICKEN_PAR1_1,
15778                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15779         }
15780 }
15781
15782 /* Scan out the current hw modeset state,
15783  * and sanitizes it to the current state
15784  */
15785 static void
15786 intel_modeset_setup_hw_state(struct drm_device *dev,
15787                              struct drm_modeset_acquire_ctx *ctx)
15788 {
15789         struct drm_i915_private *dev_priv = to_i915(dev);
15790         enum pipe pipe;
15791         struct intel_crtc *crtc;
15792         struct intel_encoder *encoder;
15793         int i;
15794
15795         intel_early_display_was(dev_priv);
15796         intel_modeset_readout_hw_state(dev);
15797
15798         /* HW state is read out, now we need to sanitize this mess. */
15799         get_encoder_power_domains(dev_priv);
15800
15801         intel_sanitize_plane_mapping(dev_priv);
15802
15803         for_each_intel_encoder(dev, encoder) {
15804                 intel_sanitize_encoder(encoder);
15805         }
15806
15807         for_each_pipe(dev_priv, pipe) {
15808                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15809
15810                 intel_sanitize_crtc(crtc, ctx);
15811                 intel_dump_pipe_config(crtc, crtc->config,
15812                                        "[setup_hw_state]");
15813         }
15814
15815         intel_modeset_update_connector_atomic_state(dev);
15816
15817         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15818                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15819
15820                 if (!pll->on || pll->active_mask)
15821                         continue;
15822
15823                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
15824                               pll->info->name);
15825
15826                 pll->info->funcs->disable(dev_priv, pll);
15827                 pll->on = false;
15828         }
15829
15830         if (IS_G4X(dev_priv)) {
15831                 g4x_wm_get_hw_state(dev);
15832                 g4x_wm_sanitize(dev_priv);
15833         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15834                 vlv_wm_get_hw_state(dev);
15835                 vlv_wm_sanitize(dev_priv);
15836         } else if (INTEL_GEN(dev_priv) >= 9) {
15837                 skl_wm_get_hw_state(dev);
15838         } else if (HAS_PCH_SPLIT(dev_priv)) {
15839                 ilk_wm_get_hw_state(dev);
15840         }
15841
15842         for_each_intel_crtc(dev, crtc) {
15843                 u64 put_domains;
15844
15845                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15846                 if (WARN_ON(put_domains))
15847                         modeset_put_power_domains(dev_priv, put_domains);
15848         }
15849         intel_display_set_init_power(dev_priv, false);
15850
15851         intel_power_domains_verify_state(dev_priv);
15852
15853         intel_fbc_init_pipe_state(dev_priv);
15854 }
15855
15856 void intel_display_resume(struct drm_device *dev)
15857 {
15858         struct drm_i915_private *dev_priv = to_i915(dev);
15859         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15860         struct drm_modeset_acquire_ctx ctx;
15861         int ret;
15862
15863         dev_priv->modeset_restore_state = NULL;
15864         if (state)
15865                 state->acquire_ctx = &ctx;
15866
15867         drm_modeset_acquire_init(&ctx, 0);
15868
15869         while (1) {
15870                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15871                 if (ret != -EDEADLK)
15872                         break;
15873
15874                 drm_modeset_backoff(&ctx);
15875         }
15876
15877         if (!ret)
15878                 ret = __intel_display_resume(dev, state, &ctx);
15879
15880         intel_enable_ipc(dev_priv);
15881         drm_modeset_drop_locks(&ctx);
15882         drm_modeset_acquire_fini(&ctx);
15883
15884         if (ret)
15885                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15886         if (state)
15887                 drm_atomic_state_put(state);
15888 }
15889
15890 int intel_connector_register(struct drm_connector *connector)
15891 {
15892         struct intel_connector *intel_connector = to_intel_connector(connector);
15893         int ret;
15894
15895         ret = intel_backlight_device_register(intel_connector);
15896         if (ret)
15897                 goto err;
15898
15899         return 0;
15900
15901 err:
15902         return ret;
15903 }
15904
15905 void intel_connector_unregister(struct drm_connector *connector)
15906 {
15907         struct intel_connector *intel_connector = to_intel_connector(connector);
15908
15909         intel_backlight_device_unregister(intel_connector);
15910         intel_panel_destroy_backlight(connector);
15911 }
15912
15913 static void intel_hpd_poll_fini(struct drm_device *dev)
15914 {
15915         struct intel_connector *connector;
15916         struct drm_connector_list_iter conn_iter;
15917
15918         /* Kill all the work that may have been queued by hpd. */
15919         drm_connector_list_iter_begin(dev, &conn_iter);
15920         for_each_intel_connector_iter(connector, &conn_iter) {
15921                 if (connector->modeset_retry_work.func)
15922                         cancel_work_sync(&connector->modeset_retry_work);
15923                 if (connector->hdcp_shim) {
15924                         cancel_delayed_work_sync(&connector->hdcp_check_work);
15925                         cancel_work_sync(&connector->hdcp_prop_work);
15926                 }
15927         }
15928         drm_connector_list_iter_end(&conn_iter);
15929 }
15930
15931 void intel_modeset_cleanup(struct drm_device *dev)
15932 {
15933         struct drm_i915_private *dev_priv = to_i915(dev);
15934
15935         flush_workqueue(dev_priv->modeset_wq);
15936
15937         flush_work(&dev_priv->atomic_helper.free_work);
15938         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15939
15940         intel_disable_gt_powersave(dev_priv);
15941
15942         /*
15943          * Interrupts and polling as the first thing to avoid creating havoc.
15944          * Too much stuff here (turning of connectors, ...) would
15945          * experience fancy races otherwise.
15946          */
15947         intel_irq_uninstall(dev_priv);
15948
15949         /*
15950          * Due to the hpd irq storm handling the hotplug work can re-arm the
15951          * poll handlers. Hence disable polling after hpd handling is shut down.
15952          */
15953         intel_hpd_poll_fini(dev);
15954
15955         /* poll work can call into fbdev, hence clean that up afterwards */
15956         intel_fbdev_fini(dev_priv);
15957
15958         intel_unregister_dsm_handler();
15959
15960         intel_fbc_global_disable(dev_priv);
15961
15962         /* flush any delayed tasks or pending work */
15963         flush_scheduled_work();
15964
15965         drm_mode_config_cleanup(dev);
15966
15967         intel_cleanup_overlay(dev_priv);
15968
15969         intel_cleanup_gt_powersave(dev_priv);
15970
15971         intel_teardown_gmbus(dev_priv);
15972
15973         destroy_workqueue(dev_priv->modeset_wq);
15974 }
15975
15976 void intel_connector_attach_encoder(struct intel_connector *connector,
15977                                     struct intel_encoder *encoder)
15978 {
15979         connector->encoder = encoder;
15980         drm_connector_attach_encoder(&connector->base, &encoder->base);
15981 }
15982
15983 /*
15984  * set vga decode state - true == enable VGA decode
15985  */
15986 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15987 {
15988         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15989         u16 gmch_ctrl;
15990
15991         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15992                 DRM_ERROR("failed to read control word\n");
15993                 return -EIO;
15994         }
15995
15996         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15997                 return 0;
15998
15999         if (state)
16000                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16001         else
16002                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16003
16004         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16005                 DRM_ERROR("failed to write control word\n");
16006                 return -EIO;
16007         }
16008
16009         return 0;
16010 }
16011
16012 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
16013
16014 struct intel_display_error_state {
16015
16016         u32 power_well_driver;
16017
16018         int num_transcoders;
16019
16020         struct intel_cursor_error_state {
16021                 u32 control;
16022                 u32 position;
16023                 u32 base;
16024                 u32 size;
16025         } cursor[I915_MAX_PIPES];
16026
16027         struct intel_pipe_error_state {
16028                 bool power_domain_on;
16029                 u32 source;
16030                 u32 stat;
16031         } pipe[I915_MAX_PIPES];
16032
16033         struct intel_plane_error_state {
16034                 u32 control;
16035                 u32 stride;
16036                 u32 size;
16037                 u32 pos;
16038                 u32 addr;
16039                 u32 surface;
16040                 u32 tile_offset;
16041         } plane[I915_MAX_PIPES];
16042
16043         struct intel_transcoder_error_state {
16044                 bool power_domain_on;
16045                 enum transcoder cpu_transcoder;
16046
16047                 u32 conf;
16048
16049                 u32 htotal;
16050                 u32 hblank;
16051                 u32 hsync;
16052                 u32 vtotal;
16053                 u32 vblank;
16054                 u32 vsync;
16055         } transcoder[4];
16056 };
16057
16058 struct intel_display_error_state *
16059 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16060 {
16061         struct intel_display_error_state *error;
16062         int transcoders[] = {
16063                 TRANSCODER_A,
16064                 TRANSCODER_B,
16065                 TRANSCODER_C,
16066                 TRANSCODER_EDP,
16067         };
16068         int i;
16069
16070         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16071                 return NULL;
16072
16073         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16074         if (error == NULL)
16075                 return NULL;
16076
16077         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16078                 error->power_well_driver =
16079                         I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL));
16080
16081         for_each_pipe(dev_priv, i) {
16082                 error->pipe[i].power_domain_on =
16083                         __intel_display_power_is_enabled(dev_priv,
16084                                                          POWER_DOMAIN_PIPE(i));
16085                 if (!error->pipe[i].power_domain_on)
16086                         continue;
16087
16088                 error->cursor[i].control = I915_READ(CURCNTR(i));
16089                 error->cursor[i].position = I915_READ(CURPOS(i));
16090                 error->cursor[i].base = I915_READ(CURBASE(i));
16091
16092                 error->plane[i].control = I915_READ(DSPCNTR(i));
16093                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16094                 if (INTEL_GEN(dev_priv) <= 3) {
16095                         error->plane[i].size = I915_READ(DSPSIZE(i));
16096                         error->plane[i].pos = I915_READ(DSPPOS(i));
16097                 }
16098                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16099                         error->plane[i].addr = I915_READ(DSPADDR(i));
16100                 if (INTEL_GEN(dev_priv) >= 4) {
16101                         error->plane[i].surface = I915_READ(DSPSURF(i));
16102                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16103                 }
16104
16105                 error->pipe[i].source = I915_READ(PIPESRC(i));
16106
16107                 if (HAS_GMCH_DISPLAY(dev_priv))
16108                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16109         }
16110
16111         /* Note: this does not include DSI transcoders. */
16112         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16113         if (HAS_DDI(dev_priv))
16114                 error->num_transcoders++; /* Account for eDP. */
16115
16116         for (i = 0; i < error->num_transcoders; i++) {
16117                 enum transcoder cpu_transcoder = transcoders[i];
16118
16119                 error->transcoder[i].power_domain_on =
16120                         __intel_display_power_is_enabled(dev_priv,
16121                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16122                 if (!error->transcoder[i].power_domain_on)
16123                         continue;
16124
16125                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16126
16127                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16128                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16129                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16130                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16131                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16132                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16133                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16134         }
16135
16136         return error;
16137 }
16138
16139 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16140
16141 void
16142 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16143                                 struct intel_display_error_state *error)
16144 {
16145         struct drm_i915_private *dev_priv = m->i915;
16146         int i;
16147
16148         if (!error)
16149                 return;
16150
16151         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16152         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16153                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16154                            error->power_well_driver);
16155         for_each_pipe(dev_priv, i) {
16156                 err_printf(m, "Pipe [%d]:\n", i);
16157                 err_printf(m, "  Power: %s\n",
16158                            onoff(error->pipe[i].power_domain_on));
16159                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16160                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16161
16162                 err_printf(m, "Plane [%d]:\n", i);
16163                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16164                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16165                 if (INTEL_GEN(dev_priv) <= 3) {
16166                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16167                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16168                 }
16169                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16170                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16171                 if (INTEL_GEN(dev_priv) >= 4) {
16172                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16173                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16174                 }
16175
16176                 err_printf(m, "Cursor [%d]:\n", i);
16177                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16178                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16179                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16180         }
16181
16182         for (i = 0; i < error->num_transcoders; i++) {
16183                 err_printf(m, "CPU transcoder: %s\n",
16184                            transcoder_name(error->transcoder[i].cpu_transcoder));
16185                 err_printf(m, "  Power: %s\n",
16186                            onoff(error->transcoder[i].power_domain_on));
16187                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16188                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16189                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16190                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16191                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16192                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16193                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16194         }
16195 }
16196
16197 #endif