Merge tag 'armsoc-drivers' of git://git.kernel.org/pub/scm/linux/kernel/git/arm/arm-soc
[sfrench/cifs-2.6.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "i915_gem_clflush.h"
41 #include "intel_dsi.h"
42 #include "i915_trace.h"
43 #include <drm/drm_atomic.h>
44 #include <drm/drm_atomic_helper.h>
45 #include <drm/drm_dp_helper.h>
46 #include <drm/drm_crtc_helper.h>
47 #include <drm/drm_plane_helper.h>
48 #include <drm/drm_rect.h>
49 #include <drm/drm_atomic_uapi.h>
50 #include <linux/dma_remapping.h>
51 #include <linux/reservation.h>
52
53 /* Primary plane formats for gen <= 3 */
54 static const uint32_t i8xx_primary_formats[] = {
55         DRM_FORMAT_C8,
56         DRM_FORMAT_RGB565,
57         DRM_FORMAT_XRGB1555,
58         DRM_FORMAT_XRGB8888,
59 };
60
61 /* Primary plane formats for gen >= 4 */
62 static const uint32_t i965_primary_formats[] = {
63         DRM_FORMAT_C8,
64         DRM_FORMAT_RGB565,
65         DRM_FORMAT_XRGB8888,
66         DRM_FORMAT_XBGR8888,
67         DRM_FORMAT_XRGB2101010,
68         DRM_FORMAT_XBGR2101010,
69 };
70
71 static const uint64_t i9xx_format_modifiers[] = {
72         I915_FORMAT_MOD_X_TILED,
73         DRM_FORMAT_MOD_LINEAR,
74         DRM_FORMAT_MOD_INVALID
75 };
76
77 static const uint32_t skl_primary_formats[] = {
78         DRM_FORMAT_C8,
79         DRM_FORMAT_RGB565,
80         DRM_FORMAT_XRGB8888,
81         DRM_FORMAT_XBGR8888,
82         DRM_FORMAT_ARGB8888,
83         DRM_FORMAT_ABGR8888,
84         DRM_FORMAT_XRGB2101010,
85         DRM_FORMAT_XBGR2101010,
86         DRM_FORMAT_YUYV,
87         DRM_FORMAT_YVYU,
88         DRM_FORMAT_UYVY,
89         DRM_FORMAT_VYUY,
90 };
91
92 static const uint32_t skl_pri_planar_formats[] = {
93         DRM_FORMAT_C8,
94         DRM_FORMAT_RGB565,
95         DRM_FORMAT_XRGB8888,
96         DRM_FORMAT_XBGR8888,
97         DRM_FORMAT_ARGB8888,
98         DRM_FORMAT_ABGR8888,
99         DRM_FORMAT_XRGB2101010,
100         DRM_FORMAT_XBGR2101010,
101         DRM_FORMAT_YUYV,
102         DRM_FORMAT_YVYU,
103         DRM_FORMAT_UYVY,
104         DRM_FORMAT_VYUY,
105         DRM_FORMAT_NV12,
106 };
107
108 static const uint64_t skl_format_modifiers_noccs[] = {
109         I915_FORMAT_MOD_Yf_TILED,
110         I915_FORMAT_MOD_Y_TILED,
111         I915_FORMAT_MOD_X_TILED,
112         DRM_FORMAT_MOD_LINEAR,
113         DRM_FORMAT_MOD_INVALID
114 };
115
116 static const uint64_t skl_format_modifiers_ccs[] = {
117         I915_FORMAT_MOD_Yf_TILED_CCS,
118         I915_FORMAT_MOD_Y_TILED_CCS,
119         I915_FORMAT_MOD_Yf_TILED,
120         I915_FORMAT_MOD_Y_TILED,
121         I915_FORMAT_MOD_X_TILED,
122         DRM_FORMAT_MOD_LINEAR,
123         DRM_FORMAT_MOD_INVALID
124 };
125
126 /* Cursor formats */
127 static const uint32_t intel_cursor_formats[] = {
128         DRM_FORMAT_ARGB8888,
129 };
130
131 static const uint64_t cursor_format_modifiers[] = {
132         DRM_FORMAT_MOD_LINEAR,
133         DRM_FORMAT_MOD_INVALID
134 };
135
136 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
137                                 struct intel_crtc_state *pipe_config);
138 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
139                                    struct intel_crtc_state *pipe_config);
140
141 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
142                                   struct drm_i915_gem_object *obj,
143                                   struct drm_mode_fb_cmd2 *mode_cmd);
144 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
145 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
146 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
147 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
148                                          struct intel_link_m_n *m_n,
149                                          struct intel_link_m_n *m2_n2);
150 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
151 static void haswell_set_pipeconf(struct drm_crtc *crtc);
152 static void haswell_set_pipemisc(struct drm_crtc *crtc);
153 static void vlv_prepare_pll(struct intel_crtc *crtc,
154                             const struct intel_crtc_state *pipe_config);
155 static void chv_prepare_pll(struct intel_crtc *crtc,
156                             const struct intel_crtc_state *pipe_config);
157 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
158 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
159 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
160                                     struct intel_crtc_state *crtc_state);
161 static void skylake_pfit_enable(struct intel_crtc *crtc);
162 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
163 static void ironlake_pfit_enable(struct intel_crtc *crtc);
164 static void intel_modeset_setup_hw_state(struct drm_device *dev,
165                                          struct drm_modeset_acquire_ctx *ctx);
166 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
167
168 struct intel_limit {
169         struct {
170                 int min, max;
171         } dot, vco, n, m, m1, m2, p, p1;
172
173         struct {
174                 int dot_limit;
175                 int p2_slow, p2_fast;
176         } p2;
177 };
178
179 /* returns HPLL frequency in kHz */
180 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
181 {
182         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
183
184         /* Obtain SKU information */
185         mutex_lock(&dev_priv->sb_lock);
186         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
187                 CCK_FUSE_HPLL_FREQ_MASK;
188         mutex_unlock(&dev_priv->sb_lock);
189
190         return vco_freq[hpll_freq] * 1000;
191 }
192
193 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
194                       const char *name, u32 reg, int ref_freq)
195 {
196         u32 val;
197         int divider;
198
199         mutex_lock(&dev_priv->sb_lock);
200         val = vlv_cck_read(dev_priv, reg);
201         mutex_unlock(&dev_priv->sb_lock);
202
203         divider = val & CCK_FREQUENCY_VALUES;
204
205         WARN((val & CCK_FREQUENCY_STATUS) !=
206              (divider << CCK_FREQUENCY_STATUS_SHIFT),
207              "%s change in progress\n", name);
208
209         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
210 }
211
212 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
213                            const char *name, u32 reg)
214 {
215         if (dev_priv->hpll_freq == 0)
216                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
217
218         return vlv_get_cck_clock(dev_priv, name, reg,
219                                  dev_priv->hpll_freq);
220 }
221
222 static void intel_update_czclk(struct drm_i915_private *dev_priv)
223 {
224         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
225                 return;
226
227         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
228                                                       CCK_CZ_CLOCK_CONTROL);
229
230         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
231 }
232
233 static inline u32 /* units of 100MHz */
234 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
235                     const struct intel_crtc_state *pipe_config)
236 {
237         if (HAS_DDI(dev_priv))
238                 return pipe_config->port_clock; /* SPLL */
239         else
240                 return dev_priv->fdi_pll_freq;
241 }
242
243 static const struct intel_limit intel_limits_i8xx_dac = {
244         .dot = { .min = 25000, .max = 350000 },
245         .vco = { .min = 908000, .max = 1512000 },
246         .n = { .min = 2, .max = 16 },
247         .m = { .min = 96, .max = 140 },
248         .m1 = { .min = 18, .max = 26 },
249         .m2 = { .min = 6, .max = 16 },
250         .p = { .min = 4, .max = 128 },
251         .p1 = { .min = 2, .max = 33 },
252         .p2 = { .dot_limit = 165000,
253                 .p2_slow = 4, .p2_fast = 2 },
254 };
255
256 static const struct intel_limit intel_limits_i8xx_dvo = {
257         .dot = { .min = 25000, .max = 350000 },
258         .vco = { .min = 908000, .max = 1512000 },
259         .n = { .min = 2, .max = 16 },
260         .m = { .min = 96, .max = 140 },
261         .m1 = { .min = 18, .max = 26 },
262         .m2 = { .min = 6, .max = 16 },
263         .p = { .min = 4, .max = 128 },
264         .p1 = { .min = 2, .max = 33 },
265         .p2 = { .dot_limit = 165000,
266                 .p2_slow = 4, .p2_fast = 4 },
267 };
268
269 static const struct intel_limit intel_limits_i8xx_lvds = {
270         .dot = { .min = 25000, .max = 350000 },
271         .vco = { .min = 908000, .max = 1512000 },
272         .n = { .min = 2, .max = 16 },
273         .m = { .min = 96, .max = 140 },
274         .m1 = { .min = 18, .max = 26 },
275         .m2 = { .min = 6, .max = 16 },
276         .p = { .min = 4, .max = 128 },
277         .p1 = { .min = 1, .max = 6 },
278         .p2 = { .dot_limit = 165000,
279                 .p2_slow = 14, .p2_fast = 7 },
280 };
281
282 static const struct intel_limit intel_limits_i9xx_sdvo = {
283         .dot = { .min = 20000, .max = 400000 },
284         .vco = { .min = 1400000, .max = 2800000 },
285         .n = { .min = 1, .max = 6 },
286         .m = { .min = 70, .max = 120 },
287         .m1 = { .min = 8, .max = 18 },
288         .m2 = { .min = 3, .max = 7 },
289         .p = { .min = 5, .max = 80 },
290         .p1 = { .min = 1, .max = 8 },
291         .p2 = { .dot_limit = 200000,
292                 .p2_slow = 10, .p2_fast = 5 },
293 };
294
295 static const struct intel_limit intel_limits_i9xx_lvds = {
296         .dot = { .min = 20000, .max = 400000 },
297         .vco = { .min = 1400000, .max = 2800000 },
298         .n = { .min = 1, .max = 6 },
299         .m = { .min = 70, .max = 120 },
300         .m1 = { .min = 8, .max = 18 },
301         .m2 = { .min = 3, .max = 7 },
302         .p = { .min = 7, .max = 98 },
303         .p1 = { .min = 1, .max = 8 },
304         .p2 = { .dot_limit = 112000,
305                 .p2_slow = 14, .p2_fast = 7 },
306 };
307
308
309 static const struct intel_limit intel_limits_g4x_sdvo = {
310         .dot = { .min = 25000, .max = 270000 },
311         .vco = { .min = 1750000, .max = 3500000},
312         .n = { .min = 1, .max = 4 },
313         .m = { .min = 104, .max = 138 },
314         .m1 = { .min = 17, .max = 23 },
315         .m2 = { .min = 5, .max = 11 },
316         .p = { .min = 10, .max = 30 },
317         .p1 = { .min = 1, .max = 3},
318         .p2 = { .dot_limit = 270000,
319                 .p2_slow = 10,
320                 .p2_fast = 10
321         },
322 };
323
324 static const struct intel_limit intel_limits_g4x_hdmi = {
325         .dot = { .min = 22000, .max = 400000 },
326         .vco = { .min = 1750000, .max = 3500000},
327         .n = { .min = 1, .max = 4 },
328         .m = { .min = 104, .max = 138 },
329         .m1 = { .min = 16, .max = 23 },
330         .m2 = { .min = 5, .max = 11 },
331         .p = { .min = 5, .max = 80 },
332         .p1 = { .min = 1, .max = 8},
333         .p2 = { .dot_limit = 165000,
334                 .p2_slow = 10, .p2_fast = 5 },
335 };
336
337 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
338         .dot = { .min = 20000, .max = 115000 },
339         .vco = { .min = 1750000, .max = 3500000 },
340         .n = { .min = 1, .max = 3 },
341         .m = { .min = 104, .max = 138 },
342         .m1 = { .min = 17, .max = 23 },
343         .m2 = { .min = 5, .max = 11 },
344         .p = { .min = 28, .max = 112 },
345         .p1 = { .min = 2, .max = 8 },
346         .p2 = { .dot_limit = 0,
347                 .p2_slow = 14, .p2_fast = 14
348         },
349 };
350
351 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
352         .dot = { .min = 80000, .max = 224000 },
353         .vco = { .min = 1750000, .max = 3500000 },
354         .n = { .min = 1, .max = 3 },
355         .m = { .min = 104, .max = 138 },
356         .m1 = { .min = 17, .max = 23 },
357         .m2 = { .min = 5, .max = 11 },
358         .p = { .min = 14, .max = 42 },
359         .p1 = { .min = 2, .max = 6 },
360         .p2 = { .dot_limit = 0,
361                 .p2_slow = 7, .p2_fast = 7
362         },
363 };
364
365 static const struct intel_limit intel_limits_pineview_sdvo = {
366         .dot = { .min = 20000, .max = 400000},
367         .vco = { .min = 1700000, .max = 3500000 },
368         /* Pineview's Ncounter is a ring counter */
369         .n = { .min = 3, .max = 6 },
370         .m = { .min = 2, .max = 256 },
371         /* Pineview only has one combined m divider, which we treat as m2. */
372         .m1 = { .min = 0, .max = 0 },
373         .m2 = { .min = 0, .max = 254 },
374         .p = { .min = 5, .max = 80 },
375         .p1 = { .min = 1, .max = 8 },
376         .p2 = { .dot_limit = 200000,
377                 .p2_slow = 10, .p2_fast = 5 },
378 };
379
380 static const struct intel_limit intel_limits_pineview_lvds = {
381         .dot = { .min = 20000, .max = 400000 },
382         .vco = { .min = 1700000, .max = 3500000 },
383         .n = { .min = 3, .max = 6 },
384         .m = { .min = 2, .max = 256 },
385         .m1 = { .min = 0, .max = 0 },
386         .m2 = { .min = 0, .max = 254 },
387         .p = { .min = 7, .max = 112 },
388         .p1 = { .min = 1, .max = 8 },
389         .p2 = { .dot_limit = 112000,
390                 .p2_slow = 14, .p2_fast = 14 },
391 };
392
393 /* Ironlake / Sandybridge
394  *
395  * We calculate clock using (register_value + 2) for N/M1/M2, so here
396  * the range value for them is (actual_value - 2).
397  */
398 static const struct intel_limit intel_limits_ironlake_dac = {
399         .dot = { .min = 25000, .max = 350000 },
400         .vco = { .min = 1760000, .max = 3510000 },
401         .n = { .min = 1, .max = 5 },
402         .m = { .min = 79, .max = 127 },
403         .m1 = { .min = 12, .max = 22 },
404         .m2 = { .min = 5, .max = 9 },
405         .p = { .min = 5, .max = 80 },
406         .p1 = { .min = 1, .max = 8 },
407         .p2 = { .dot_limit = 225000,
408                 .p2_slow = 10, .p2_fast = 5 },
409 };
410
411 static const struct intel_limit intel_limits_ironlake_single_lvds = {
412         .dot = { .min = 25000, .max = 350000 },
413         .vco = { .min = 1760000, .max = 3510000 },
414         .n = { .min = 1, .max = 3 },
415         .m = { .min = 79, .max = 118 },
416         .m1 = { .min = 12, .max = 22 },
417         .m2 = { .min = 5, .max = 9 },
418         .p = { .min = 28, .max = 112 },
419         .p1 = { .min = 2, .max = 8 },
420         .p2 = { .dot_limit = 225000,
421                 .p2_slow = 14, .p2_fast = 14 },
422 };
423
424 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
425         .dot = { .min = 25000, .max = 350000 },
426         .vco = { .min = 1760000, .max = 3510000 },
427         .n = { .min = 1, .max = 3 },
428         .m = { .min = 79, .max = 127 },
429         .m1 = { .min = 12, .max = 22 },
430         .m2 = { .min = 5, .max = 9 },
431         .p = { .min = 14, .max = 56 },
432         .p1 = { .min = 2, .max = 8 },
433         .p2 = { .dot_limit = 225000,
434                 .p2_slow = 7, .p2_fast = 7 },
435 };
436
437 /* LVDS 100mhz refclk limits. */
438 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
439         .dot = { .min = 25000, .max = 350000 },
440         .vco = { .min = 1760000, .max = 3510000 },
441         .n = { .min = 1, .max = 2 },
442         .m = { .min = 79, .max = 126 },
443         .m1 = { .min = 12, .max = 22 },
444         .m2 = { .min = 5, .max = 9 },
445         .p = { .min = 28, .max = 112 },
446         .p1 = { .min = 2, .max = 8 },
447         .p2 = { .dot_limit = 225000,
448                 .p2_slow = 14, .p2_fast = 14 },
449 };
450
451 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
452         .dot = { .min = 25000, .max = 350000 },
453         .vco = { .min = 1760000, .max = 3510000 },
454         .n = { .min = 1, .max = 3 },
455         .m = { .min = 79, .max = 126 },
456         .m1 = { .min = 12, .max = 22 },
457         .m2 = { .min = 5, .max = 9 },
458         .p = { .min = 14, .max = 42 },
459         .p1 = { .min = 2, .max = 6 },
460         .p2 = { .dot_limit = 225000,
461                 .p2_slow = 7, .p2_fast = 7 },
462 };
463
464 static const struct intel_limit intel_limits_vlv = {
465          /*
466           * These are the data rate limits (measured in fast clocks)
467           * since those are the strictest limits we have. The fast
468           * clock and actual rate limits are more relaxed, so checking
469           * them would make no difference.
470           */
471         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
472         .vco = { .min = 4000000, .max = 6000000 },
473         .n = { .min = 1, .max = 7 },
474         .m1 = { .min = 2, .max = 3 },
475         .m2 = { .min = 11, .max = 156 },
476         .p1 = { .min = 2, .max = 3 },
477         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
478 };
479
480 static const struct intel_limit intel_limits_chv = {
481         /*
482          * These are the data rate limits (measured in fast clocks)
483          * since those are the strictest limits we have.  The fast
484          * clock and actual rate limits are more relaxed, so checking
485          * them would make no difference.
486          */
487         .dot = { .min = 25000 * 5, .max = 540000 * 5},
488         .vco = { .min = 4800000, .max = 6480000 },
489         .n = { .min = 1, .max = 1 },
490         .m1 = { .min = 2, .max = 2 },
491         .m2 = { .min = 24 << 22, .max = 175 << 22 },
492         .p1 = { .min = 2, .max = 4 },
493         .p2 = { .p2_slow = 1, .p2_fast = 14 },
494 };
495
496 static const struct intel_limit intel_limits_bxt = {
497         /* FIXME: find real dot limits */
498         .dot = { .min = 0, .max = INT_MAX },
499         .vco = { .min = 4800000, .max = 6700000 },
500         .n = { .min = 1, .max = 1 },
501         .m1 = { .min = 2, .max = 2 },
502         /* FIXME: find real m2 limits */
503         .m2 = { .min = 2 << 22, .max = 255 << 22 },
504         .p1 = { .min = 2, .max = 4 },
505         .p2 = { .p2_slow = 1, .p2_fast = 20 },
506 };
507
508 static void
509 skl_wa_528(struct drm_i915_private *dev_priv, int pipe, bool enable)
510 {
511         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
512                 return;
513
514         if (enable)
515                 I915_WRITE(CHICKEN_PIPESL_1(pipe), HSW_FBCQ_DIS);
516         else
517                 I915_WRITE(CHICKEN_PIPESL_1(pipe), 0);
518 }
519
520 static void
521 skl_wa_clkgate(struct drm_i915_private *dev_priv, int pipe, bool enable)
522 {
523         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
524                 return;
525
526         if (enable)
527                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
528                            DUPS1_GATING_DIS | DUPS2_GATING_DIS);
529         else
530                 I915_WRITE(CLKGATE_DIS_PSL(pipe),
531                            I915_READ(CLKGATE_DIS_PSL(pipe)) &
532                            ~(DUPS1_GATING_DIS | DUPS2_GATING_DIS));
533 }
534
535 static bool
536 needs_modeset(const struct drm_crtc_state *state)
537 {
538         return drm_atomic_crtc_needs_modeset(state);
539 }
540
541 /*
542  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
543  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
544  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
545  * The helpers' return value is the rate of the clock that is fed to the
546  * display engine's pipe which can be the above fast dot clock rate or a
547  * divided-down version of it.
548  */
549 /* m1 is reserved as 0 in Pineview, n is a ring counter */
550 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
551 {
552         clock->m = clock->m2 + 2;
553         clock->p = clock->p1 * clock->p2;
554         if (WARN_ON(clock->n == 0 || clock->p == 0))
555                 return 0;
556         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
557         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
558
559         return clock->dot;
560 }
561
562 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
563 {
564         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
565 }
566
567 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
568 {
569         clock->m = i9xx_dpll_compute_m(clock);
570         clock->p = clock->p1 * clock->p2;
571         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
572                 return 0;
573         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
574         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
575
576         return clock->dot;
577 }
578
579 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
580 {
581         clock->m = clock->m1 * clock->m2;
582         clock->p = clock->p1 * clock->p2;
583         if (WARN_ON(clock->n == 0 || clock->p == 0))
584                 return 0;
585         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
586         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
587
588         return clock->dot / 5;
589 }
590
591 int chv_calc_dpll_params(int refclk, struct dpll *clock)
592 {
593         clock->m = clock->m1 * clock->m2;
594         clock->p = clock->p1 * clock->p2;
595         if (WARN_ON(clock->n == 0 || clock->p == 0))
596                 return 0;
597         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
598                         clock->n << 22);
599         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
600
601         return clock->dot / 5;
602 }
603
604 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
605
606 /*
607  * Returns whether the given set of divisors are valid for a given refclk with
608  * the given connectors.
609  */
610 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
611                                const struct intel_limit *limit,
612                                const struct dpll *clock)
613 {
614         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
615                 INTELPllInvalid("n out of range\n");
616         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
617                 INTELPllInvalid("p1 out of range\n");
618         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
619                 INTELPllInvalid("m2 out of range\n");
620         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
621                 INTELPllInvalid("m1 out of range\n");
622
623         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
624             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
625                 if (clock->m1 <= clock->m2)
626                         INTELPllInvalid("m1 <= m2\n");
627
628         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
629             !IS_GEN9_LP(dev_priv)) {
630                 if (clock->p < limit->p.min || limit->p.max < clock->p)
631                         INTELPllInvalid("p out of range\n");
632                 if (clock->m < limit->m.min || limit->m.max < clock->m)
633                         INTELPllInvalid("m out of range\n");
634         }
635
636         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
637                 INTELPllInvalid("vco out of range\n");
638         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
639          * connector, etc., rather than just a single range.
640          */
641         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
642                 INTELPllInvalid("dot out of range\n");
643
644         return true;
645 }
646
647 static int
648 i9xx_select_p2_div(const struct intel_limit *limit,
649                    const struct intel_crtc_state *crtc_state,
650                    int target)
651 {
652         struct drm_device *dev = crtc_state->base.crtc->dev;
653
654         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
655                 /*
656                  * For LVDS just rely on its current settings for dual-channel.
657                  * We haven't figured out how to reliably set up different
658                  * single/dual channel state, if we even can.
659                  */
660                 if (intel_is_dual_link_lvds(dev))
661                         return limit->p2.p2_fast;
662                 else
663                         return limit->p2.p2_slow;
664         } else {
665                 if (target < limit->p2.dot_limit)
666                         return limit->p2.p2_slow;
667                 else
668                         return limit->p2.p2_fast;
669         }
670 }
671
672 /*
673  * Returns a set of divisors for the desired target clock with the given
674  * refclk, or FALSE.  The returned values represent the clock equation:
675  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
676  *
677  * Target and reference clocks are specified in kHz.
678  *
679  * If match_clock is provided, then best_clock P divider must match the P
680  * divider from @match_clock used for LVDS downclocking.
681  */
682 static bool
683 i9xx_find_best_dpll(const struct intel_limit *limit,
684                     struct intel_crtc_state *crtc_state,
685                     int target, int refclk, struct dpll *match_clock,
686                     struct dpll *best_clock)
687 {
688         struct drm_device *dev = crtc_state->base.crtc->dev;
689         struct dpll clock;
690         int err = target;
691
692         memset(best_clock, 0, sizeof(*best_clock));
693
694         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
695
696         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
697              clock.m1++) {
698                 for (clock.m2 = limit->m2.min;
699                      clock.m2 <= limit->m2.max; clock.m2++) {
700                         if (clock.m2 >= clock.m1)
701                                 break;
702                         for (clock.n = limit->n.min;
703                              clock.n <= limit->n.max; clock.n++) {
704                                 for (clock.p1 = limit->p1.min;
705                                         clock.p1 <= limit->p1.max; clock.p1++) {
706                                         int this_err;
707
708                                         i9xx_calc_dpll_params(refclk, &clock);
709                                         if (!intel_PLL_is_valid(to_i915(dev),
710                                                                 limit,
711                                                                 &clock))
712                                                 continue;
713                                         if (match_clock &&
714                                             clock.p != match_clock->p)
715                                                 continue;
716
717                                         this_err = abs(clock.dot - target);
718                                         if (this_err < err) {
719                                                 *best_clock = clock;
720                                                 err = this_err;
721                                         }
722                                 }
723                         }
724                 }
725         }
726
727         return (err != target);
728 }
729
730 /*
731  * Returns a set of divisors for the desired target clock with the given
732  * refclk, or FALSE.  The returned values represent the clock equation:
733  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
734  *
735  * Target and reference clocks are specified in kHz.
736  *
737  * If match_clock is provided, then best_clock P divider must match the P
738  * divider from @match_clock used for LVDS downclocking.
739  */
740 static bool
741 pnv_find_best_dpll(const struct intel_limit *limit,
742                    struct intel_crtc_state *crtc_state,
743                    int target, int refclk, struct dpll *match_clock,
744                    struct dpll *best_clock)
745 {
746         struct drm_device *dev = crtc_state->base.crtc->dev;
747         struct dpll clock;
748         int err = target;
749
750         memset(best_clock, 0, sizeof(*best_clock));
751
752         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
753
754         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
755              clock.m1++) {
756                 for (clock.m2 = limit->m2.min;
757                      clock.m2 <= limit->m2.max; clock.m2++) {
758                         for (clock.n = limit->n.min;
759                              clock.n <= limit->n.max; clock.n++) {
760                                 for (clock.p1 = limit->p1.min;
761                                         clock.p1 <= limit->p1.max; clock.p1++) {
762                                         int this_err;
763
764                                         pnv_calc_dpll_params(refclk, &clock);
765                                         if (!intel_PLL_is_valid(to_i915(dev),
766                                                                 limit,
767                                                                 &clock))
768                                                 continue;
769                                         if (match_clock &&
770                                             clock.p != match_clock->p)
771                                                 continue;
772
773                                         this_err = abs(clock.dot - target);
774                                         if (this_err < err) {
775                                                 *best_clock = clock;
776                                                 err = this_err;
777                                         }
778                                 }
779                         }
780                 }
781         }
782
783         return (err != target);
784 }
785
786 /*
787  * Returns a set of divisors for the desired target clock with the given
788  * refclk, or FALSE.  The returned values represent the clock equation:
789  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
790  *
791  * Target and reference clocks are specified in kHz.
792  *
793  * If match_clock is provided, then best_clock P divider must match the P
794  * divider from @match_clock used for LVDS downclocking.
795  */
796 static bool
797 g4x_find_best_dpll(const struct intel_limit *limit,
798                    struct intel_crtc_state *crtc_state,
799                    int target, int refclk, struct dpll *match_clock,
800                    struct dpll *best_clock)
801 {
802         struct drm_device *dev = crtc_state->base.crtc->dev;
803         struct dpll clock;
804         int max_n;
805         bool found = false;
806         /* approximately equals target * 0.00585 */
807         int err_most = (target >> 8) + (target >> 9);
808
809         memset(best_clock, 0, sizeof(*best_clock));
810
811         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
812
813         max_n = limit->n.max;
814         /* based on hardware requirement, prefer smaller n to precision */
815         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
816                 /* based on hardware requirement, prefere larger m1,m2 */
817                 for (clock.m1 = limit->m1.max;
818                      clock.m1 >= limit->m1.min; clock.m1--) {
819                         for (clock.m2 = limit->m2.max;
820                              clock.m2 >= limit->m2.min; clock.m2--) {
821                                 for (clock.p1 = limit->p1.max;
822                                      clock.p1 >= limit->p1.min; clock.p1--) {
823                                         int this_err;
824
825                                         i9xx_calc_dpll_params(refclk, &clock);
826                                         if (!intel_PLL_is_valid(to_i915(dev),
827                                                                 limit,
828                                                                 &clock))
829                                                 continue;
830
831                                         this_err = abs(clock.dot - target);
832                                         if (this_err < err_most) {
833                                                 *best_clock = clock;
834                                                 err_most = this_err;
835                                                 max_n = clock.n;
836                                                 found = true;
837                                         }
838                                 }
839                         }
840                 }
841         }
842         return found;
843 }
844
845 /*
846  * Check if the calculated PLL configuration is more optimal compared to the
847  * best configuration and error found so far. Return the calculated error.
848  */
849 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
850                                const struct dpll *calculated_clock,
851                                const struct dpll *best_clock,
852                                unsigned int best_error_ppm,
853                                unsigned int *error_ppm)
854 {
855         /*
856          * For CHV ignore the error and consider only the P value.
857          * Prefer a bigger P value based on HW requirements.
858          */
859         if (IS_CHERRYVIEW(to_i915(dev))) {
860                 *error_ppm = 0;
861
862                 return calculated_clock->p > best_clock->p;
863         }
864
865         if (WARN_ON_ONCE(!target_freq))
866                 return false;
867
868         *error_ppm = div_u64(1000000ULL *
869                                 abs(target_freq - calculated_clock->dot),
870                              target_freq);
871         /*
872          * Prefer a better P value over a better (smaller) error if the error
873          * is small. Ensure this preference for future configurations too by
874          * setting the error to 0.
875          */
876         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
877                 *error_ppm = 0;
878
879                 return true;
880         }
881
882         return *error_ppm + 10 < best_error_ppm;
883 }
884
885 /*
886  * Returns a set of divisors for the desired target clock with the given
887  * refclk, or FALSE.  The returned values represent the clock equation:
888  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
889  */
890 static bool
891 vlv_find_best_dpll(const struct intel_limit *limit,
892                    struct intel_crtc_state *crtc_state,
893                    int target, int refclk, struct dpll *match_clock,
894                    struct dpll *best_clock)
895 {
896         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
897         struct drm_device *dev = crtc->base.dev;
898         struct dpll clock;
899         unsigned int bestppm = 1000000;
900         /* min update 19.2 MHz */
901         int max_n = min(limit->n.max, refclk / 19200);
902         bool found = false;
903
904         target *= 5; /* fast clock */
905
906         memset(best_clock, 0, sizeof(*best_clock));
907
908         /* based on hardware requirement, prefer smaller n to precision */
909         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
910                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
911                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
912                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
913                                 clock.p = clock.p1 * clock.p2;
914                                 /* based on hardware requirement, prefer bigger m1,m2 values */
915                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
916                                         unsigned int ppm;
917
918                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
919                                                                      refclk * clock.m1);
920
921                                         vlv_calc_dpll_params(refclk, &clock);
922
923                                         if (!intel_PLL_is_valid(to_i915(dev),
924                                                                 limit,
925                                                                 &clock))
926                                                 continue;
927
928                                         if (!vlv_PLL_is_optimal(dev, target,
929                                                                 &clock,
930                                                                 best_clock,
931                                                                 bestppm, &ppm))
932                                                 continue;
933
934                                         *best_clock = clock;
935                                         bestppm = ppm;
936                                         found = true;
937                                 }
938                         }
939                 }
940         }
941
942         return found;
943 }
944
945 /*
946  * Returns a set of divisors for the desired target clock with the given
947  * refclk, or FALSE.  The returned values represent the clock equation:
948  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
949  */
950 static bool
951 chv_find_best_dpll(const struct intel_limit *limit,
952                    struct intel_crtc_state *crtc_state,
953                    int target, int refclk, struct dpll *match_clock,
954                    struct dpll *best_clock)
955 {
956         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
957         struct drm_device *dev = crtc->base.dev;
958         unsigned int best_error_ppm;
959         struct dpll clock;
960         uint64_t m2;
961         int found = false;
962
963         memset(best_clock, 0, sizeof(*best_clock));
964         best_error_ppm = 1000000;
965
966         /*
967          * Based on hardware doc, the n always set to 1, and m1 always
968          * set to 2.  If requires to support 200Mhz refclk, we need to
969          * revisit this because n may not 1 anymore.
970          */
971         clock.n = 1, clock.m1 = 2;
972         target *= 5;    /* fast clock */
973
974         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
975                 for (clock.p2 = limit->p2.p2_fast;
976                                 clock.p2 >= limit->p2.p2_slow;
977                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
978                         unsigned int error_ppm;
979
980                         clock.p = clock.p1 * clock.p2;
981
982                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
983                                         clock.n) << 22, refclk * clock.m1);
984
985                         if (m2 > INT_MAX/clock.m1)
986                                 continue;
987
988                         clock.m2 = m2;
989
990                         chv_calc_dpll_params(refclk, &clock);
991
992                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
993                                 continue;
994
995                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
996                                                 best_error_ppm, &error_ppm))
997                                 continue;
998
999                         *best_clock = clock;
1000                         best_error_ppm = error_ppm;
1001                         found = true;
1002                 }
1003         }
1004
1005         return found;
1006 }
1007
1008 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
1009                         struct dpll *best_clock)
1010 {
1011         int refclk = 100000;
1012         const struct intel_limit *limit = &intel_limits_bxt;
1013
1014         return chv_find_best_dpll(limit, crtc_state,
1015                                   target_clock, refclk, NULL, best_clock);
1016 }
1017
1018 bool intel_crtc_active(struct intel_crtc *crtc)
1019 {
1020         /* Be paranoid as we can arrive here with only partial
1021          * state retrieved from the hardware during setup.
1022          *
1023          * We can ditch the adjusted_mode.crtc_clock check as soon
1024          * as Haswell has gained clock readout/fastboot support.
1025          *
1026          * We can ditch the crtc->primary->state->fb check as soon as we can
1027          * properly reconstruct framebuffers.
1028          *
1029          * FIXME: The intel_crtc->active here should be switched to
1030          * crtc->state->active once we have proper CRTC states wired up
1031          * for atomic.
1032          */
1033         return crtc->active && crtc->base.primary->state->fb &&
1034                 crtc->config->base.adjusted_mode.crtc_clock;
1035 }
1036
1037 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
1038                                              enum pipe pipe)
1039 {
1040         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
1041
1042         return crtc->config->cpu_transcoder;
1043 }
1044
1045 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
1046                                     enum pipe pipe)
1047 {
1048         i915_reg_t reg = PIPEDSL(pipe);
1049         u32 line1, line2;
1050         u32 line_mask;
1051
1052         if (IS_GEN2(dev_priv))
1053                 line_mask = DSL_LINEMASK_GEN2;
1054         else
1055                 line_mask = DSL_LINEMASK_GEN3;
1056
1057         line1 = I915_READ(reg) & line_mask;
1058         msleep(5);
1059         line2 = I915_READ(reg) & line_mask;
1060
1061         return line1 != line2;
1062 }
1063
1064 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1065 {
1066         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1067         enum pipe pipe = crtc->pipe;
1068
1069         /* Wait for the display line to settle/start moving */
1070         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1071                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1072                           pipe_name(pipe), onoff(state));
1073 }
1074
1075 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1076 {
1077         wait_for_pipe_scanline_moving(crtc, false);
1078 }
1079
1080 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1081 {
1082         wait_for_pipe_scanline_moving(crtc, true);
1083 }
1084
1085 static void
1086 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1087 {
1088         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1089         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1090
1091         if (INTEL_GEN(dev_priv) >= 4) {
1092                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1093                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1094
1095                 /* Wait for the Pipe State to go off */
1096                 if (intel_wait_for_register(dev_priv,
1097                                             reg, I965_PIPECONF_ACTIVE, 0,
1098                                             100))
1099                         WARN(1, "pipe_off wait timed out\n");
1100         } else {
1101                 intel_wait_for_pipe_scanline_stopped(crtc);
1102         }
1103 }
1104
1105 /* Only for pre-ILK configs */
1106 void assert_pll(struct drm_i915_private *dev_priv,
1107                 enum pipe pipe, bool state)
1108 {
1109         u32 val;
1110         bool cur_state;
1111
1112         val = I915_READ(DPLL(pipe));
1113         cur_state = !!(val & DPLL_VCO_ENABLE);
1114         I915_STATE_WARN(cur_state != state,
1115              "PLL state assertion failure (expected %s, current %s)\n",
1116                         onoff(state), onoff(cur_state));
1117 }
1118
1119 /* XXX: the dsi pll is shared between MIPI DSI ports */
1120 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1121 {
1122         u32 val;
1123         bool cur_state;
1124
1125         mutex_lock(&dev_priv->sb_lock);
1126         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1127         mutex_unlock(&dev_priv->sb_lock);
1128
1129         cur_state = val & DSI_PLL_VCO_EN;
1130         I915_STATE_WARN(cur_state != state,
1131              "DSI PLL state assertion failure (expected %s, current %s)\n",
1132                         onoff(state), onoff(cur_state));
1133 }
1134
1135 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1136                           enum pipe pipe, bool state)
1137 {
1138         bool cur_state;
1139         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1140                                                                       pipe);
1141
1142         if (HAS_DDI(dev_priv)) {
1143                 /* DDI does not have a specific FDI_TX register */
1144                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1145                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1146         } else {
1147                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1148                 cur_state = !!(val & FDI_TX_ENABLE);
1149         }
1150         I915_STATE_WARN(cur_state != state,
1151              "FDI TX state assertion failure (expected %s, current %s)\n",
1152                         onoff(state), onoff(cur_state));
1153 }
1154 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1155 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1156
1157 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1158                           enum pipe pipe, bool state)
1159 {
1160         u32 val;
1161         bool cur_state;
1162
1163         val = I915_READ(FDI_RX_CTL(pipe));
1164         cur_state = !!(val & FDI_RX_ENABLE);
1165         I915_STATE_WARN(cur_state != state,
1166              "FDI RX state assertion failure (expected %s, current %s)\n",
1167                         onoff(state), onoff(cur_state));
1168 }
1169 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1170 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1171
1172 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1173                                       enum pipe pipe)
1174 {
1175         u32 val;
1176
1177         /* ILK FDI PLL is always enabled */
1178         if (IS_GEN5(dev_priv))
1179                 return;
1180
1181         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1182         if (HAS_DDI(dev_priv))
1183                 return;
1184
1185         val = I915_READ(FDI_TX_CTL(pipe));
1186         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1187 }
1188
1189 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1190                        enum pipe pipe, bool state)
1191 {
1192         u32 val;
1193         bool cur_state;
1194
1195         val = I915_READ(FDI_RX_CTL(pipe));
1196         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1197         I915_STATE_WARN(cur_state != state,
1198              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1199                         onoff(state), onoff(cur_state));
1200 }
1201
1202 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1203 {
1204         i915_reg_t pp_reg;
1205         u32 val;
1206         enum pipe panel_pipe = INVALID_PIPE;
1207         bool locked = true;
1208
1209         if (WARN_ON(HAS_DDI(dev_priv)))
1210                 return;
1211
1212         if (HAS_PCH_SPLIT(dev_priv)) {
1213                 u32 port_sel;
1214
1215                 pp_reg = PP_CONTROL(0);
1216                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1217
1218                 switch (port_sel) {
1219                 case PANEL_PORT_SELECT_LVDS:
1220                         intel_lvds_port_enabled(dev_priv, PCH_LVDS, &panel_pipe);
1221                         break;
1222                 case PANEL_PORT_SELECT_DPA:
1223                         intel_dp_port_enabled(dev_priv, DP_A, PORT_A, &panel_pipe);
1224                         break;
1225                 case PANEL_PORT_SELECT_DPC:
1226                         intel_dp_port_enabled(dev_priv, PCH_DP_C, PORT_C, &panel_pipe);
1227                         break;
1228                 case PANEL_PORT_SELECT_DPD:
1229                         intel_dp_port_enabled(dev_priv, PCH_DP_D, PORT_D, &panel_pipe);
1230                         break;
1231                 default:
1232                         MISSING_CASE(port_sel);
1233                         break;
1234                 }
1235         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1236                 /* presumably write lock depends on pipe, not port select */
1237                 pp_reg = PP_CONTROL(pipe);
1238                 panel_pipe = pipe;
1239         } else {
1240                 u32 port_sel;
1241
1242                 pp_reg = PP_CONTROL(0);
1243                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1244
1245                 WARN_ON(port_sel != PANEL_PORT_SELECT_LVDS);
1246                 intel_lvds_port_enabled(dev_priv, LVDS, &panel_pipe);
1247         }
1248
1249         val = I915_READ(pp_reg);
1250         if (!(val & PANEL_POWER_ON) ||
1251             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1252                 locked = false;
1253
1254         I915_STATE_WARN(panel_pipe == pipe && locked,
1255              "panel assertion failure, pipe %c regs locked\n",
1256              pipe_name(pipe));
1257 }
1258
1259 void assert_pipe(struct drm_i915_private *dev_priv,
1260                  enum pipe pipe, bool state)
1261 {
1262         bool cur_state;
1263         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1264                                                                       pipe);
1265         enum intel_display_power_domain power_domain;
1266
1267         /* we keep both pipes enabled on 830 */
1268         if (IS_I830(dev_priv))
1269                 state = true;
1270
1271         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1272         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1273                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1274                 cur_state = !!(val & PIPECONF_ENABLE);
1275
1276                 intel_display_power_put(dev_priv, power_domain);
1277         } else {
1278                 cur_state = false;
1279         }
1280
1281         I915_STATE_WARN(cur_state != state,
1282              "pipe %c assertion failure (expected %s, current %s)\n",
1283                         pipe_name(pipe), onoff(state), onoff(cur_state));
1284 }
1285
1286 static void assert_plane(struct intel_plane *plane, bool state)
1287 {
1288         enum pipe pipe;
1289         bool cur_state;
1290
1291         cur_state = plane->get_hw_state(plane, &pipe);
1292
1293         I915_STATE_WARN(cur_state != state,
1294                         "%s assertion failure (expected %s, current %s)\n",
1295                         plane->base.name, onoff(state), onoff(cur_state));
1296 }
1297
1298 #define assert_plane_enabled(p) assert_plane(p, true)
1299 #define assert_plane_disabled(p) assert_plane(p, false)
1300
1301 static void assert_planes_disabled(struct intel_crtc *crtc)
1302 {
1303         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1304         struct intel_plane *plane;
1305
1306         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1307                 assert_plane_disabled(plane);
1308 }
1309
1310 static void assert_vblank_disabled(struct drm_crtc *crtc)
1311 {
1312         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1313                 drm_crtc_vblank_put(crtc);
1314 }
1315
1316 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1317                                     enum pipe pipe)
1318 {
1319         u32 val;
1320         bool enabled;
1321
1322         val = I915_READ(PCH_TRANSCONF(pipe));
1323         enabled = !!(val & TRANS_ENABLE);
1324         I915_STATE_WARN(enabled,
1325              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1326              pipe_name(pipe));
1327 }
1328
1329 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1330                                    enum pipe pipe, enum port port,
1331                                    i915_reg_t dp_reg)
1332 {
1333         enum pipe port_pipe;
1334         bool state;
1335
1336         state = intel_dp_port_enabled(dev_priv, dp_reg, port, &port_pipe);
1337
1338         I915_STATE_WARN(state && port_pipe == pipe,
1339                         "PCH DP %c enabled on transcoder %c, should be disabled\n",
1340                         port_name(port), pipe_name(pipe));
1341
1342         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1343                         "IBX PCH DP %c still using transcoder B\n",
1344                         port_name(port));
1345 }
1346
1347 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1348                                      enum pipe pipe, enum port port,
1349                                      i915_reg_t hdmi_reg)
1350 {
1351         enum pipe port_pipe;
1352         bool state;
1353
1354         state = intel_sdvo_port_enabled(dev_priv, hdmi_reg, &port_pipe);
1355
1356         I915_STATE_WARN(state && port_pipe == pipe,
1357                         "PCH HDMI %c enabled on transcoder %c, should be disabled\n",
1358                         port_name(port), pipe_name(pipe));
1359
1360         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && !state && port_pipe == PIPE_B,
1361                         "IBX PCH HDMI %c still using transcoder B\n",
1362                         port_name(port));
1363 }
1364
1365 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1366                                       enum pipe pipe)
1367 {
1368         enum pipe port_pipe;
1369
1370         assert_pch_dp_disabled(dev_priv, pipe, PORT_B, PCH_DP_B);
1371         assert_pch_dp_disabled(dev_priv, pipe, PORT_C, PCH_DP_C);
1372         assert_pch_dp_disabled(dev_priv, pipe, PORT_D, PCH_DP_D);
1373
1374         I915_STATE_WARN(intel_crt_port_enabled(dev_priv, PCH_ADPA, &port_pipe) &&
1375                         port_pipe == pipe,
1376                         "PCH VGA enabled on transcoder %c, should be disabled\n",
1377                         pipe_name(pipe));
1378
1379         I915_STATE_WARN(intel_lvds_port_enabled(dev_priv, PCH_LVDS, &port_pipe) &&
1380                         port_pipe == pipe,
1381                         "PCH LVDS enabled on transcoder %c, should be disabled\n",
1382                         pipe_name(pipe));
1383
1384         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_B, PCH_HDMIB);
1385         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_C, PCH_HDMIC);
1386         assert_pch_hdmi_disabled(dev_priv, pipe, PORT_D, PCH_HDMID);
1387 }
1388
1389 static void _vlv_enable_pll(struct intel_crtc *crtc,
1390                             const struct intel_crtc_state *pipe_config)
1391 {
1392         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1393         enum pipe pipe = crtc->pipe;
1394
1395         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1396         POSTING_READ(DPLL(pipe));
1397         udelay(150);
1398
1399         if (intel_wait_for_register(dev_priv,
1400                                     DPLL(pipe),
1401                                     DPLL_LOCK_VLV,
1402                                     DPLL_LOCK_VLV,
1403                                     1))
1404                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1405 }
1406
1407 static void vlv_enable_pll(struct intel_crtc *crtc,
1408                            const struct intel_crtc_state *pipe_config)
1409 {
1410         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1411         enum pipe pipe = crtc->pipe;
1412
1413         assert_pipe_disabled(dev_priv, pipe);
1414
1415         /* PLL is protected by panel, make sure we can write it */
1416         assert_panel_unlocked(dev_priv, pipe);
1417
1418         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1419                 _vlv_enable_pll(crtc, pipe_config);
1420
1421         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1422         POSTING_READ(DPLL_MD(pipe));
1423 }
1424
1425
1426 static void _chv_enable_pll(struct intel_crtc *crtc,
1427                             const struct intel_crtc_state *pipe_config)
1428 {
1429         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1430         enum pipe pipe = crtc->pipe;
1431         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1432         u32 tmp;
1433
1434         mutex_lock(&dev_priv->sb_lock);
1435
1436         /* Enable back the 10bit clock to display controller */
1437         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1438         tmp |= DPIO_DCLKP_EN;
1439         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1440
1441         mutex_unlock(&dev_priv->sb_lock);
1442
1443         /*
1444          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1445          */
1446         udelay(1);
1447
1448         /* Enable PLL */
1449         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1450
1451         /* Check PLL is locked */
1452         if (intel_wait_for_register(dev_priv,
1453                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1454                                     1))
1455                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1456 }
1457
1458 static void chv_enable_pll(struct intel_crtc *crtc,
1459                            const struct intel_crtc_state *pipe_config)
1460 {
1461         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1462         enum pipe pipe = crtc->pipe;
1463
1464         assert_pipe_disabled(dev_priv, pipe);
1465
1466         /* PLL is protected by panel, make sure we can write it */
1467         assert_panel_unlocked(dev_priv, pipe);
1468
1469         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1470                 _chv_enable_pll(crtc, pipe_config);
1471
1472         if (pipe != PIPE_A) {
1473                 /*
1474                  * WaPixelRepeatModeFixForC0:chv
1475                  *
1476                  * DPLLCMD is AWOL. Use chicken bits to propagate
1477                  * the value from DPLLBMD to either pipe B or C.
1478                  */
1479                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1480                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1481                 I915_WRITE(CBR4_VLV, 0);
1482                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1483
1484                 /*
1485                  * DPLLB VGA mode also seems to cause problems.
1486                  * We should always have it disabled.
1487                  */
1488                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1489         } else {
1490                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1491                 POSTING_READ(DPLL_MD(pipe));
1492         }
1493 }
1494
1495 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1496 {
1497         struct intel_crtc *crtc;
1498         int count = 0;
1499
1500         for_each_intel_crtc(&dev_priv->drm, crtc) {
1501                 count += crtc->base.state->active &&
1502                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1503         }
1504
1505         return count;
1506 }
1507
1508 static void i9xx_enable_pll(struct intel_crtc *crtc,
1509                             const struct intel_crtc_state *crtc_state)
1510 {
1511         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1512         i915_reg_t reg = DPLL(crtc->pipe);
1513         u32 dpll = crtc_state->dpll_hw_state.dpll;
1514         int i;
1515
1516         assert_pipe_disabled(dev_priv, crtc->pipe);
1517
1518         /* PLL is protected by panel, make sure we can write it */
1519         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1520                 assert_panel_unlocked(dev_priv, crtc->pipe);
1521
1522         /* Enable DVO 2x clock on both PLLs if necessary */
1523         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1524                 /*
1525                  * It appears to be important that we don't enable this
1526                  * for the current pipe before otherwise configuring the
1527                  * PLL. No idea how this should be handled if multiple
1528                  * DVO outputs are enabled simultaneosly.
1529                  */
1530                 dpll |= DPLL_DVO_2X_MODE;
1531                 I915_WRITE(DPLL(!crtc->pipe),
1532                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1533         }
1534
1535         /*
1536          * Apparently we need to have VGA mode enabled prior to changing
1537          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1538          * dividers, even though the register value does change.
1539          */
1540         I915_WRITE(reg, 0);
1541
1542         I915_WRITE(reg, dpll);
1543
1544         /* Wait for the clocks to stabilize. */
1545         POSTING_READ(reg);
1546         udelay(150);
1547
1548         if (INTEL_GEN(dev_priv) >= 4) {
1549                 I915_WRITE(DPLL_MD(crtc->pipe),
1550                            crtc_state->dpll_hw_state.dpll_md);
1551         } else {
1552                 /* The pixel multiplier can only be updated once the
1553                  * DPLL is enabled and the clocks are stable.
1554                  *
1555                  * So write it again.
1556                  */
1557                 I915_WRITE(reg, dpll);
1558         }
1559
1560         /* We do this three times for luck */
1561         for (i = 0; i < 3; i++) {
1562                 I915_WRITE(reg, dpll);
1563                 POSTING_READ(reg);
1564                 udelay(150); /* wait for warmup */
1565         }
1566 }
1567
1568 static void i9xx_disable_pll(struct intel_crtc *crtc)
1569 {
1570         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1571         enum pipe pipe = crtc->pipe;
1572
1573         /* Disable DVO 2x clock on both PLLs if necessary */
1574         if (IS_I830(dev_priv) &&
1575             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1576             !intel_num_dvo_pipes(dev_priv)) {
1577                 I915_WRITE(DPLL(PIPE_B),
1578                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1579                 I915_WRITE(DPLL(PIPE_A),
1580                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1581         }
1582
1583         /* Don't disable pipe or pipe PLLs if needed */
1584         if (IS_I830(dev_priv))
1585                 return;
1586
1587         /* Make sure the pipe isn't still relying on us */
1588         assert_pipe_disabled(dev_priv, pipe);
1589
1590         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1591         POSTING_READ(DPLL(pipe));
1592 }
1593
1594 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1595 {
1596         u32 val;
1597
1598         /* Make sure the pipe isn't still relying on us */
1599         assert_pipe_disabled(dev_priv, pipe);
1600
1601         val = DPLL_INTEGRATED_REF_CLK_VLV |
1602                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1603         if (pipe != PIPE_A)
1604                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1605
1606         I915_WRITE(DPLL(pipe), val);
1607         POSTING_READ(DPLL(pipe));
1608 }
1609
1610 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1611 {
1612         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1613         u32 val;
1614
1615         /* Make sure the pipe isn't still relying on us */
1616         assert_pipe_disabled(dev_priv, pipe);
1617
1618         val = DPLL_SSC_REF_CLK_CHV |
1619                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1620         if (pipe != PIPE_A)
1621                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1622
1623         I915_WRITE(DPLL(pipe), val);
1624         POSTING_READ(DPLL(pipe));
1625
1626         mutex_lock(&dev_priv->sb_lock);
1627
1628         /* Disable 10bit clock to display controller */
1629         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1630         val &= ~DPIO_DCLKP_EN;
1631         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1632
1633         mutex_unlock(&dev_priv->sb_lock);
1634 }
1635
1636 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1637                          struct intel_digital_port *dport,
1638                          unsigned int expected_mask)
1639 {
1640         u32 port_mask;
1641         i915_reg_t dpll_reg;
1642
1643         switch (dport->base.port) {
1644         case PORT_B:
1645                 port_mask = DPLL_PORTB_READY_MASK;
1646                 dpll_reg = DPLL(0);
1647                 break;
1648         case PORT_C:
1649                 port_mask = DPLL_PORTC_READY_MASK;
1650                 dpll_reg = DPLL(0);
1651                 expected_mask <<= 4;
1652                 break;
1653         case PORT_D:
1654                 port_mask = DPLL_PORTD_READY_MASK;
1655                 dpll_reg = DPIO_PHY_STATUS;
1656                 break;
1657         default:
1658                 BUG();
1659         }
1660
1661         if (intel_wait_for_register(dev_priv,
1662                                     dpll_reg, port_mask, expected_mask,
1663                                     1000))
1664                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1665                      port_name(dport->base.port),
1666                      I915_READ(dpll_reg) & port_mask, expected_mask);
1667 }
1668
1669 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1670                                            enum pipe pipe)
1671 {
1672         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1673                                                                 pipe);
1674         i915_reg_t reg;
1675         uint32_t val, pipeconf_val;
1676
1677         /* Make sure PCH DPLL is enabled */
1678         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1679
1680         /* FDI must be feeding us bits for PCH ports */
1681         assert_fdi_tx_enabled(dev_priv, pipe);
1682         assert_fdi_rx_enabled(dev_priv, pipe);
1683
1684         if (HAS_PCH_CPT(dev_priv)) {
1685                 /* Workaround: Set the timing override bit before enabling the
1686                  * pch transcoder. */
1687                 reg = TRANS_CHICKEN2(pipe);
1688                 val = I915_READ(reg);
1689                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1690                 I915_WRITE(reg, val);
1691         }
1692
1693         reg = PCH_TRANSCONF(pipe);
1694         val = I915_READ(reg);
1695         pipeconf_val = I915_READ(PIPECONF(pipe));
1696
1697         if (HAS_PCH_IBX(dev_priv)) {
1698                 /*
1699                  * Make the BPC in transcoder be consistent with
1700                  * that in pipeconf reg. For HDMI we must use 8bpc
1701                  * here for both 8bpc and 12bpc.
1702                  */
1703                 val &= ~PIPECONF_BPC_MASK;
1704                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1705                         val |= PIPECONF_8BPC;
1706                 else
1707                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1708         }
1709
1710         val &= ~TRANS_INTERLACE_MASK;
1711         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1712                 if (HAS_PCH_IBX(dev_priv) &&
1713                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1714                         val |= TRANS_LEGACY_INTERLACED_ILK;
1715                 else
1716                         val |= TRANS_INTERLACED;
1717         else
1718                 val |= TRANS_PROGRESSIVE;
1719
1720         I915_WRITE(reg, val | TRANS_ENABLE);
1721         if (intel_wait_for_register(dev_priv,
1722                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1723                                     100))
1724                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1725 }
1726
1727 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1728                                       enum transcoder cpu_transcoder)
1729 {
1730         u32 val, pipeconf_val;
1731
1732         /* FDI must be feeding us bits for PCH ports */
1733         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1734         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1735
1736         /* Workaround: set timing override bit. */
1737         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1738         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1739         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1740
1741         val = TRANS_ENABLE;
1742         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1743
1744         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1745             PIPECONF_INTERLACED_ILK)
1746                 val |= TRANS_INTERLACED;
1747         else
1748                 val |= TRANS_PROGRESSIVE;
1749
1750         I915_WRITE(LPT_TRANSCONF, val);
1751         if (intel_wait_for_register(dev_priv,
1752                                     LPT_TRANSCONF,
1753                                     TRANS_STATE_ENABLE,
1754                                     TRANS_STATE_ENABLE,
1755                                     100))
1756                 DRM_ERROR("Failed to enable PCH transcoder\n");
1757 }
1758
1759 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1760                                             enum pipe pipe)
1761 {
1762         i915_reg_t reg;
1763         uint32_t val;
1764
1765         /* FDI relies on the transcoder */
1766         assert_fdi_tx_disabled(dev_priv, pipe);
1767         assert_fdi_rx_disabled(dev_priv, pipe);
1768
1769         /* Ports must be off as well */
1770         assert_pch_ports_disabled(dev_priv, pipe);
1771
1772         reg = PCH_TRANSCONF(pipe);
1773         val = I915_READ(reg);
1774         val &= ~TRANS_ENABLE;
1775         I915_WRITE(reg, val);
1776         /* wait for PCH transcoder off, transcoder state */
1777         if (intel_wait_for_register(dev_priv,
1778                                     reg, TRANS_STATE_ENABLE, 0,
1779                                     50))
1780                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1781
1782         if (HAS_PCH_CPT(dev_priv)) {
1783                 /* Workaround: Clear the timing override chicken bit again. */
1784                 reg = TRANS_CHICKEN2(pipe);
1785                 val = I915_READ(reg);
1786                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1787                 I915_WRITE(reg, val);
1788         }
1789 }
1790
1791 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1792 {
1793         u32 val;
1794
1795         val = I915_READ(LPT_TRANSCONF);
1796         val &= ~TRANS_ENABLE;
1797         I915_WRITE(LPT_TRANSCONF, val);
1798         /* wait for PCH transcoder off, transcoder state */
1799         if (intel_wait_for_register(dev_priv,
1800                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1801                                     50))
1802                 DRM_ERROR("Failed to disable PCH transcoder\n");
1803
1804         /* Workaround: clear timing override bit. */
1805         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1806         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1807         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1808 }
1809
1810 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1811 {
1812         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1813
1814         if (HAS_PCH_LPT(dev_priv))
1815                 return PIPE_A;
1816         else
1817                 return crtc->pipe;
1818 }
1819
1820 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1821 {
1822         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1823         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1824         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1825         enum pipe pipe = crtc->pipe;
1826         i915_reg_t reg;
1827         u32 val;
1828
1829         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1830
1831         assert_planes_disabled(crtc);
1832
1833         /*
1834          * A pipe without a PLL won't actually be able to drive bits from
1835          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1836          * need the check.
1837          */
1838         if (HAS_GMCH_DISPLAY(dev_priv)) {
1839                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1840                         assert_dsi_pll_enabled(dev_priv);
1841                 else
1842                         assert_pll_enabled(dev_priv, pipe);
1843         } else {
1844                 if (new_crtc_state->has_pch_encoder) {
1845                         /* if driving the PCH, we need FDI enabled */
1846                         assert_fdi_rx_pll_enabled(dev_priv,
1847                                                   intel_crtc_pch_transcoder(crtc));
1848                         assert_fdi_tx_pll_enabled(dev_priv,
1849                                                   (enum pipe) cpu_transcoder);
1850                 }
1851                 /* FIXME: assert CPU port conditions for SNB+ */
1852         }
1853
1854         reg = PIPECONF(cpu_transcoder);
1855         val = I915_READ(reg);
1856         if (val & PIPECONF_ENABLE) {
1857                 /* we keep both pipes enabled on 830 */
1858                 WARN_ON(!IS_I830(dev_priv));
1859                 return;
1860         }
1861
1862         I915_WRITE(reg, val | PIPECONF_ENABLE);
1863         POSTING_READ(reg);
1864
1865         /*
1866          * Until the pipe starts PIPEDSL reads will return a stale value,
1867          * which causes an apparent vblank timestamp jump when PIPEDSL
1868          * resets to its proper value. That also messes up the frame count
1869          * when it's derived from the timestamps. So let's wait for the
1870          * pipe to start properly before we call drm_crtc_vblank_on()
1871          */
1872         if (dev_priv->drm.max_vblank_count == 0)
1873                 intel_wait_for_pipe_scanline_moving(crtc);
1874 }
1875
1876 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1877 {
1878         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1879         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1880         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1881         enum pipe pipe = crtc->pipe;
1882         i915_reg_t reg;
1883         u32 val;
1884
1885         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1886
1887         /*
1888          * Make sure planes won't keep trying to pump pixels to us,
1889          * or we might hang the display.
1890          */
1891         assert_planes_disabled(crtc);
1892
1893         reg = PIPECONF(cpu_transcoder);
1894         val = I915_READ(reg);
1895         if ((val & PIPECONF_ENABLE) == 0)
1896                 return;
1897
1898         /*
1899          * Double wide has implications for planes
1900          * so best keep it disabled when not needed.
1901          */
1902         if (old_crtc_state->double_wide)
1903                 val &= ~PIPECONF_DOUBLE_WIDE;
1904
1905         /* Don't disable pipe or pipe PLLs if needed */
1906         if (!IS_I830(dev_priv))
1907                 val &= ~PIPECONF_ENABLE;
1908
1909         I915_WRITE(reg, val);
1910         if ((val & PIPECONF_ENABLE) == 0)
1911                 intel_wait_for_pipe_off(old_crtc_state);
1912 }
1913
1914 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1915 {
1916         return IS_GEN2(dev_priv) ? 2048 : 4096;
1917 }
1918
1919 static unsigned int
1920 intel_tile_width_bytes(const struct drm_framebuffer *fb, int color_plane)
1921 {
1922         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1923         unsigned int cpp = fb->format->cpp[color_plane];
1924
1925         switch (fb->modifier) {
1926         case DRM_FORMAT_MOD_LINEAR:
1927                 return cpp;
1928         case I915_FORMAT_MOD_X_TILED:
1929                 if (IS_GEN2(dev_priv))
1930                         return 128;
1931                 else
1932                         return 512;
1933         case I915_FORMAT_MOD_Y_TILED_CCS:
1934                 if (color_plane == 1)
1935                         return 128;
1936                 /* fall through */
1937         case I915_FORMAT_MOD_Y_TILED:
1938                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
1939                         return 128;
1940                 else
1941                         return 512;
1942         case I915_FORMAT_MOD_Yf_TILED_CCS:
1943                 if (color_plane == 1)
1944                         return 128;
1945                 /* fall through */
1946         case I915_FORMAT_MOD_Yf_TILED:
1947                 switch (cpp) {
1948                 case 1:
1949                         return 64;
1950                 case 2:
1951                 case 4:
1952                         return 128;
1953                 case 8:
1954                 case 16:
1955                         return 256;
1956                 default:
1957                         MISSING_CASE(cpp);
1958                         return cpp;
1959                 }
1960                 break;
1961         default:
1962                 MISSING_CASE(fb->modifier);
1963                 return cpp;
1964         }
1965 }
1966
1967 static unsigned int
1968 intel_tile_height(const struct drm_framebuffer *fb, int color_plane)
1969 {
1970         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
1971                 return 1;
1972         else
1973                 return intel_tile_size(to_i915(fb->dev)) /
1974                         intel_tile_width_bytes(fb, color_plane);
1975 }
1976
1977 /* Return the tile dimensions in pixel units */
1978 static void intel_tile_dims(const struct drm_framebuffer *fb, int color_plane,
1979                             unsigned int *tile_width,
1980                             unsigned int *tile_height)
1981 {
1982         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, color_plane);
1983         unsigned int cpp = fb->format->cpp[color_plane];
1984
1985         *tile_width = tile_width_bytes / cpp;
1986         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1987 }
1988
1989 unsigned int
1990 intel_fb_align_height(const struct drm_framebuffer *fb,
1991                       int color_plane, unsigned int height)
1992 {
1993         unsigned int tile_height = intel_tile_height(fb, color_plane);
1994
1995         return ALIGN(height, tile_height);
1996 }
1997
1998 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
1999 {
2000         unsigned int size = 0;
2001         int i;
2002
2003         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2004                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2005
2006         return size;
2007 }
2008
2009 static void
2010 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2011                         const struct drm_framebuffer *fb,
2012                         unsigned int rotation)
2013 {
2014         view->type = I915_GGTT_VIEW_NORMAL;
2015         if (drm_rotation_90_or_270(rotation)) {
2016                 view->type = I915_GGTT_VIEW_ROTATED;
2017                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2018         }
2019 }
2020
2021 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2022 {
2023         if (IS_I830(dev_priv))
2024                 return 16 * 1024;
2025         else if (IS_I85X(dev_priv))
2026                 return 256;
2027         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2028                 return 32;
2029         else
2030                 return 4 * 1024;
2031 }
2032
2033 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2034 {
2035         if (INTEL_GEN(dev_priv) >= 9)
2036                 return 256 * 1024;
2037         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2038                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2039                 return 128 * 1024;
2040         else if (INTEL_GEN(dev_priv) >= 4)
2041                 return 4 * 1024;
2042         else
2043                 return 0;
2044 }
2045
2046 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2047                                          int color_plane)
2048 {
2049         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2050
2051         /* AUX_DIST needs only 4K alignment */
2052         if (color_plane == 1)
2053                 return 4096;
2054
2055         switch (fb->modifier) {
2056         case DRM_FORMAT_MOD_LINEAR:
2057                 return intel_linear_alignment(dev_priv);
2058         case I915_FORMAT_MOD_X_TILED:
2059                 if (INTEL_GEN(dev_priv) >= 9)
2060                         return 256 * 1024;
2061                 return 0;
2062         case I915_FORMAT_MOD_Y_TILED_CCS:
2063         case I915_FORMAT_MOD_Yf_TILED_CCS:
2064         case I915_FORMAT_MOD_Y_TILED:
2065         case I915_FORMAT_MOD_Yf_TILED:
2066                 return 1 * 1024 * 1024;
2067         default:
2068                 MISSING_CASE(fb->modifier);
2069                 return 0;
2070         }
2071 }
2072
2073 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2074 {
2075         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2076         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2077
2078         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2079 }
2080
2081 struct i915_vma *
2082 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2083                            const struct i915_ggtt_view *view,
2084                            bool uses_fence,
2085                            unsigned long *out_flags)
2086 {
2087         struct drm_device *dev = fb->dev;
2088         struct drm_i915_private *dev_priv = to_i915(dev);
2089         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2090         struct i915_vma *vma;
2091         unsigned int pinctl;
2092         u32 alignment;
2093
2094         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2095
2096         alignment = intel_surf_alignment(fb, 0);
2097
2098         /* Note that the w/a also requires 64 PTE of padding following the
2099          * bo. We currently fill all unused PTE with the shadow page and so
2100          * we should always have valid PTE following the scanout preventing
2101          * the VT-d warning.
2102          */
2103         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2104                 alignment = 256 * 1024;
2105
2106         /*
2107          * Global gtt pte registers are special registers which actually forward
2108          * writes to a chunk of system memory. Which means that there is no risk
2109          * that the register values disappear as soon as we call
2110          * intel_runtime_pm_put(), so it is correct to wrap only the
2111          * pin/unpin/fence and not more.
2112          */
2113         intel_runtime_pm_get(dev_priv);
2114
2115         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2116
2117         pinctl = 0;
2118
2119         /* Valleyview is definitely limited to scanning out the first
2120          * 512MiB. Lets presume this behaviour was inherited from the
2121          * g4x display engine and that all earlier gen are similarly
2122          * limited. Testing suggests that it is a little more
2123          * complicated than this. For example, Cherryview appears quite
2124          * happy to scanout from anywhere within its global aperture.
2125          */
2126         if (HAS_GMCH_DISPLAY(dev_priv))
2127                 pinctl |= PIN_MAPPABLE;
2128
2129         vma = i915_gem_object_pin_to_display_plane(obj,
2130                                                    alignment, view, pinctl);
2131         if (IS_ERR(vma))
2132                 goto err;
2133
2134         if (uses_fence && i915_vma_is_map_and_fenceable(vma)) {
2135                 int ret;
2136
2137                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2138                  * fence, whereas 965+ only requires a fence if using
2139                  * framebuffer compression.  For simplicity, we always, when
2140                  * possible, install a fence as the cost is not that onerous.
2141                  *
2142                  * If we fail to fence the tiled scanout, then either the
2143                  * modeset will reject the change (which is highly unlikely as
2144                  * the affected systems, all but one, do not have unmappable
2145                  * space) or we will not be able to enable full powersaving
2146                  * techniques (also likely not to apply due to various limits
2147                  * FBC and the like impose on the size of the buffer, which
2148                  * presumably we violated anyway with this unmappable buffer).
2149                  * Anyway, it is presumably better to stumble onwards with
2150                  * something and try to run the system in a "less than optimal"
2151                  * mode that matches the user configuration.
2152                  */
2153                 ret = i915_vma_pin_fence(vma);
2154                 if (ret != 0 && INTEL_GEN(dev_priv) < 4) {
2155                         i915_gem_object_unpin_from_display_plane(vma);
2156                         vma = ERR_PTR(ret);
2157                         goto err;
2158                 }
2159
2160                 if (ret == 0 && vma->fence)
2161                         *out_flags |= PLANE_HAS_FENCE;
2162         }
2163
2164         i915_vma_get(vma);
2165 err:
2166         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2167
2168         intel_runtime_pm_put(dev_priv);
2169         return vma;
2170 }
2171
2172 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2173 {
2174         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2175
2176         if (flags & PLANE_HAS_FENCE)
2177                 i915_vma_unpin_fence(vma);
2178         i915_gem_object_unpin_from_display_plane(vma);
2179         i915_vma_put(vma);
2180 }
2181
2182 static int intel_fb_pitch(const struct drm_framebuffer *fb, int color_plane,
2183                           unsigned int rotation)
2184 {
2185         if (drm_rotation_90_or_270(rotation))
2186                 return to_intel_framebuffer(fb)->rotated[color_plane].pitch;
2187         else
2188                 return fb->pitches[color_plane];
2189 }
2190
2191 /*
2192  * Convert the x/y offsets into a linear offset.
2193  * Only valid with 0/180 degree rotation, which is fine since linear
2194  * offset is only used with linear buffers on pre-hsw and tiled buffers
2195  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2196  */
2197 u32 intel_fb_xy_to_linear(int x, int y,
2198                           const struct intel_plane_state *state,
2199                           int color_plane)
2200 {
2201         const struct drm_framebuffer *fb = state->base.fb;
2202         unsigned int cpp = fb->format->cpp[color_plane];
2203         unsigned int pitch = state->color_plane[color_plane].stride;
2204
2205         return y * pitch + x * cpp;
2206 }
2207
2208 /*
2209  * Add the x/y offsets derived from fb->offsets[] to the user
2210  * specified plane src x/y offsets. The resulting x/y offsets
2211  * specify the start of scanout from the beginning of the gtt mapping.
2212  */
2213 void intel_add_fb_offsets(int *x, int *y,
2214                           const struct intel_plane_state *state,
2215                           int color_plane)
2216
2217 {
2218         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2219         unsigned int rotation = state->base.rotation;
2220
2221         if (drm_rotation_90_or_270(rotation)) {
2222                 *x += intel_fb->rotated[color_plane].x;
2223                 *y += intel_fb->rotated[color_plane].y;
2224         } else {
2225                 *x += intel_fb->normal[color_plane].x;
2226                 *y += intel_fb->normal[color_plane].y;
2227         }
2228 }
2229
2230 static u32 intel_adjust_tile_offset(int *x, int *y,
2231                                     unsigned int tile_width,
2232                                     unsigned int tile_height,
2233                                     unsigned int tile_size,
2234                                     unsigned int pitch_tiles,
2235                                     u32 old_offset,
2236                                     u32 new_offset)
2237 {
2238         unsigned int pitch_pixels = pitch_tiles * tile_width;
2239         unsigned int tiles;
2240
2241         WARN_ON(old_offset & (tile_size - 1));
2242         WARN_ON(new_offset & (tile_size - 1));
2243         WARN_ON(new_offset > old_offset);
2244
2245         tiles = (old_offset - new_offset) / tile_size;
2246
2247         *y += tiles / pitch_tiles * tile_height;
2248         *x += tiles % pitch_tiles * tile_width;
2249
2250         /* minimize x in case it got needlessly big */
2251         *y += *x / pitch_pixels * tile_height;
2252         *x %= pitch_pixels;
2253
2254         return new_offset;
2255 }
2256
2257 static u32 intel_adjust_aligned_offset(int *x, int *y,
2258                                        const struct drm_framebuffer *fb,
2259                                        int color_plane,
2260                                        unsigned int rotation,
2261                                        unsigned int pitch,
2262                                        u32 old_offset, u32 new_offset)
2263 {
2264         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2265         unsigned int cpp = fb->format->cpp[color_plane];
2266
2267         WARN_ON(new_offset > old_offset);
2268
2269         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2270                 unsigned int tile_size, tile_width, tile_height;
2271                 unsigned int pitch_tiles;
2272
2273                 tile_size = intel_tile_size(dev_priv);
2274                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2275
2276                 if (drm_rotation_90_or_270(rotation)) {
2277                         pitch_tiles = pitch / tile_height;
2278                         swap(tile_width, tile_height);
2279                 } else {
2280                         pitch_tiles = pitch / (tile_width * cpp);
2281                 }
2282
2283                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2284                                          tile_size, pitch_tiles,
2285                                          old_offset, new_offset);
2286         } else {
2287                 old_offset += *y * pitch + *x * cpp;
2288
2289                 *y = (old_offset - new_offset) / pitch;
2290                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2291         }
2292
2293         return new_offset;
2294 }
2295
2296 /*
2297  * Adjust the tile offset by moving the difference into
2298  * the x/y offsets.
2299  */
2300 static u32 intel_plane_adjust_aligned_offset(int *x, int *y,
2301                                              const struct intel_plane_state *state,
2302                                              int color_plane,
2303                                              u32 old_offset, u32 new_offset)
2304 {
2305         return intel_adjust_aligned_offset(x, y, state->base.fb, color_plane,
2306                                            state->base.rotation,
2307                                            state->color_plane[color_plane].stride,
2308                                            old_offset, new_offset);
2309 }
2310
2311 /*
2312  * Computes the aligned offset to the base tile and adjusts
2313  * x, y. bytes per pixel is assumed to be a power-of-two.
2314  *
2315  * In the 90/270 rotated case, x and y are assumed
2316  * to be already rotated to match the rotated GTT view, and
2317  * pitch is the tile_height aligned framebuffer height.
2318  *
2319  * This function is used when computing the derived information
2320  * under intel_framebuffer, so using any of that information
2321  * here is not allowed. Anything under drm_framebuffer can be
2322  * used. This is why the user has to pass in the pitch since it
2323  * is specified in the rotated orientation.
2324  */
2325 static u32 intel_compute_aligned_offset(struct drm_i915_private *dev_priv,
2326                                         int *x, int *y,
2327                                         const struct drm_framebuffer *fb,
2328                                         int color_plane,
2329                                         unsigned int pitch,
2330                                         unsigned int rotation,
2331                                         u32 alignment)
2332 {
2333         uint64_t fb_modifier = fb->modifier;
2334         unsigned int cpp = fb->format->cpp[color_plane];
2335         u32 offset, offset_aligned;
2336
2337         if (alignment)
2338                 alignment--;
2339
2340         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2341                 unsigned int tile_size, tile_width, tile_height;
2342                 unsigned int tile_rows, tiles, pitch_tiles;
2343
2344                 tile_size = intel_tile_size(dev_priv);
2345                 intel_tile_dims(fb, color_plane, &tile_width, &tile_height);
2346
2347                 if (drm_rotation_90_or_270(rotation)) {
2348                         pitch_tiles = pitch / tile_height;
2349                         swap(tile_width, tile_height);
2350                 } else {
2351                         pitch_tiles = pitch / (tile_width * cpp);
2352                 }
2353
2354                 tile_rows = *y / tile_height;
2355                 *y %= tile_height;
2356
2357                 tiles = *x / tile_width;
2358                 *x %= tile_width;
2359
2360                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2361                 offset_aligned = offset & ~alignment;
2362
2363                 intel_adjust_tile_offset(x, y, tile_width, tile_height,
2364                                          tile_size, pitch_tiles,
2365                                          offset, offset_aligned);
2366         } else {
2367                 offset = *y * pitch + *x * cpp;
2368                 offset_aligned = offset & ~alignment;
2369
2370                 *y = (offset & alignment) / pitch;
2371                 *x = ((offset & alignment) - *y * pitch) / cpp;
2372         }
2373
2374         return offset_aligned;
2375 }
2376
2377 static u32 intel_plane_compute_aligned_offset(int *x, int *y,
2378                                               const struct intel_plane_state *state,
2379                                               int color_plane)
2380 {
2381         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2382         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2383         const struct drm_framebuffer *fb = state->base.fb;
2384         unsigned int rotation = state->base.rotation;
2385         int pitch = state->color_plane[color_plane].stride;
2386         u32 alignment;
2387
2388         if (intel_plane->id == PLANE_CURSOR)
2389                 alignment = intel_cursor_alignment(dev_priv);
2390         else
2391                 alignment = intel_surf_alignment(fb, color_plane);
2392
2393         return intel_compute_aligned_offset(dev_priv, x, y, fb, color_plane,
2394                                             pitch, rotation, alignment);
2395 }
2396
2397 /* Convert the fb->offset[] into x/y offsets */
2398 static int intel_fb_offset_to_xy(int *x, int *y,
2399                                  const struct drm_framebuffer *fb,
2400                                  int color_plane)
2401 {
2402         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2403
2404         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2405             fb->offsets[color_plane] % intel_tile_size(dev_priv))
2406                 return -EINVAL;
2407
2408         *x = 0;
2409         *y = 0;
2410
2411         intel_adjust_aligned_offset(x, y,
2412                                     fb, color_plane, DRM_MODE_ROTATE_0,
2413                                     fb->pitches[color_plane],
2414                                     fb->offsets[color_plane], 0);
2415
2416         return 0;
2417 }
2418
2419 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2420 {
2421         switch (fb_modifier) {
2422         case I915_FORMAT_MOD_X_TILED:
2423                 return I915_TILING_X;
2424         case I915_FORMAT_MOD_Y_TILED:
2425         case I915_FORMAT_MOD_Y_TILED_CCS:
2426                 return I915_TILING_Y;
2427         default:
2428                 return I915_TILING_NONE;
2429         }
2430 }
2431
2432 /*
2433  * From the Sky Lake PRM:
2434  * "The Color Control Surface (CCS) contains the compression status of
2435  *  the cache-line pairs. The compression state of the cache-line pair
2436  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2437  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2438  *  cache-line-pairs. CCS is always Y tiled."
2439  *
2440  * Since cache line pairs refers to horizontally adjacent cache lines,
2441  * each cache line in the CCS corresponds to an area of 32x16 cache
2442  * lines on the main surface. Since each pixel is 4 bytes, this gives
2443  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2444  * main surface.
2445  */
2446 static const struct drm_format_info ccs_formats[] = {
2447         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2448         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2449         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2450         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2451 };
2452
2453 static const struct drm_format_info *
2454 lookup_format_info(const struct drm_format_info formats[],
2455                    int num_formats, u32 format)
2456 {
2457         int i;
2458
2459         for (i = 0; i < num_formats; i++) {
2460                 if (formats[i].format == format)
2461                         return &formats[i];
2462         }
2463
2464         return NULL;
2465 }
2466
2467 static const struct drm_format_info *
2468 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2469 {
2470         switch (cmd->modifier[0]) {
2471         case I915_FORMAT_MOD_Y_TILED_CCS:
2472         case I915_FORMAT_MOD_Yf_TILED_CCS:
2473                 return lookup_format_info(ccs_formats,
2474                                           ARRAY_SIZE(ccs_formats),
2475                                           cmd->pixel_format);
2476         default:
2477                 return NULL;
2478         }
2479 }
2480
2481 bool is_ccs_modifier(u64 modifier)
2482 {
2483         return modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2484                modifier == I915_FORMAT_MOD_Yf_TILED_CCS;
2485 }
2486
2487 static int
2488 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2489                    struct drm_framebuffer *fb)
2490 {
2491         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2492         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2493         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2494         u32 gtt_offset_rotated = 0;
2495         unsigned int max_size = 0;
2496         int i, num_planes = fb->format->num_planes;
2497         unsigned int tile_size = intel_tile_size(dev_priv);
2498
2499         for (i = 0; i < num_planes; i++) {
2500                 unsigned int width, height;
2501                 unsigned int cpp, size;
2502                 u32 offset;
2503                 int x, y;
2504                 int ret;
2505
2506                 cpp = fb->format->cpp[i];
2507                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2508                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2509
2510                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2511                 if (ret) {
2512                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2513                                       i, fb->offsets[i]);
2514                         return ret;
2515                 }
2516
2517                 if (is_ccs_modifier(fb->modifier) && i == 1) {
2518                         int hsub = fb->format->hsub;
2519                         int vsub = fb->format->vsub;
2520                         int tile_width, tile_height;
2521                         int main_x, main_y;
2522                         int ccs_x, ccs_y;
2523
2524                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2525                         tile_width *= hsub;
2526                         tile_height *= vsub;
2527
2528                         ccs_x = (x * hsub) % tile_width;
2529                         ccs_y = (y * vsub) % tile_height;
2530                         main_x = intel_fb->normal[0].x % tile_width;
2531                         main_y = intel_fb->normal[0].y % tile_height;
2532
2533                         /*
2534                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2535                          * x/y offsets must match between CCS and the main surface.
2536                          */
2537                         if (main_x != ccs_x || main_y != ccs_y) {
2538                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2539                                               main_x, main_y,
2540                                               ccs_x, ccs_y,
2541                                               intel_fb->normal[0].x,
2542                                               intel_fb->normal[0].y,
2543                                               x, y);
2544                                 return -EINVAL;
2545                         }
2546                 }
2547
2548                 /*
2549                  * The fence (if used) is aligned to the start of the object
2550                  * so having the framebuffer wrap around across the edge of the
2551                  * fenced region doesn't really work. We have no API to configure
2552                  * the fence start offset within the object (nor could we probably
2553                  * on gen2/3). So it's just easier if we just require that the
2554                  * fb layout agrees with the fence layout. We already check that the
2555                  * fb stride matches the fence stride elsewhere.
2556                  */
2557                 if (i == 0 && i915_gem_object_is_tiled(obj) &&
2558                     (x + width) * cpp > fb->pitches[i]) {
2559                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2560                                       i, fb->offsets[i]);
2561                         return -EINVAL;
2562                 }
2563
2564                 /*
2565                  * First pixel of the framebuffer from
2566                  * the start of the normal gtt mapping.
2567                  */
2568                 intel_fb->normal[i].x = x;
2569                 intel_fb->normal[i].y = y;
2570
2571                 offset = intel_compute_aligned_offset(dev_priv, &x, &y, fb, i,
2572                                                       fb->pitches[i],
2573                                                       DRM_MODE_ROTATE_0,
2574                                                       tile_size);
2575                 offset /= tile_size;
2576
2577                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2578                         unsigned int tile_width, tile_height;
2579                         unsigned int pitch_tiles;
2580                         struct drm_rect r;
2581
2582                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2583
2584                         rot_info->plane[i].offset = offset;
2585                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2586                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2587                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2588
2589                         intel_fb->rotated[i].pitch =
2590                                 rot_info->plane[i].height * tile_height;
2591
2592                         /* how many tiles does this plane need */
2593                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2594                         /*
2595                          * If the plane isn't horizontally tile aligned,
2596                          * we need one more tile.
2597                          */
2598                         if (x != 0)
2599                                 size++;
2600
2601                         /* rotate the x/y offsets to match the GTT view */
2602                         r.x1 = x;
2603                         r.y1 = y;
2604                         r.x2 = x + width;
2605                         r.y2 = y + height;
2606                         drm_rect_rotate(&r,
2607                                         rot_info->plane[i].width * tile_width,
2608                                         rot_info->plane[i].height * tile_height,
2609                                         DRM_MODE_ROTATE_270);
2610                         x = r.x1;
2611                         y = r.y1;
2612
2613                         /* rotate the tile dimensions to match the GTT view */
2614                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2615                         swap(tile_width, tile_height);
2616
2617                         /*
2618                          * We only keep the x/y offsets, so push all of the
2619                          * gtt offset into the x/y offsets.
2620                          */
2621                         intel_adjust_tile_offset(&x, &y,
2622                                                  tile_width, tile_height,
2623                                                  tile_size, pitch_tiles,
2624                                                  gtt_offset_rotated * tile_size, 0);
2625
2626                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2627
2628                         /*
2629                          * First pixel of the framebuffer from
2630                          * the start of the rotated gtt mapping.
2631                          */
2632                         intel_fb->rotated[i].x = x;
2633                         intel_fb->rotated[i].y = y;
2634                 } else {
2635                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2636                                             x * cpp, tile_size);
2637                 }
2638
2639                 /* how many tiles in total needed in the bo */
2640                 max_size = max(max_size, offset + size);
2641         }
2642
2643         if (mul_u32_u32(max_size, tile_size) > obj->base.size) {
2644                 DRM_DEBUG_KMS("fb too big for bo (need %llu bytes, have %zu bytes)\n",
2645                               mul_u32_u32(max_size, tile_size), obj->base.size);
2646                 return -EINVAL;
2647         }
2648
2649         return 0;
2650 }
2651
2652 static int i9xx_format_to_fourcc(int format)
2653 {
2654         switch (format) {
2655         case DISPPLANE_8BPP:
2656                 return DRM_FORMAT_C8;
2657         case DISPPLANE_BGRX555:
2658                 return DRM_FORMAT_XRGB1555;
2659         case DISPPLANE_BGRX565:
2660                 return DRM_FORMAT_RGB565;
2661         default:
2662         case DISPPLANE_BGRX888:
2663                 return DRM_FORMAT_XRGB8888;
2664         case DISPPLANE_RGBX888:
2665                 return DRM_FORMAT_XBGR8888;
2666         case DISPPLANE_BGRX101010:
2667                 return DRM_FORMAT_XRGB2101010;
2668         case DISPPLANE_RGBX101010:
2669                 return DRM_FORMAT_XBGR2101010;
2670         }
2671 }
2672
2673 int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2674 {
2675         switch (format) {
2676         case PLANE_CTL_FORMAT_RGB_565:
2677                 return DRM_FORMAT_RGB565;
2678         case PLANE_CTL_FORMAT_NV12:
2679                 return DRM_FORMAT_NV12;
2680         default:
2681         case PLANE_CTL_FORMAT_XRGB_8888:
2682                 if (rgb_order) {
2683                         if (alpha)
2684                                 return DRM_FORMAT_ABGR8888;
2685                         else
2686                                 return DRM_FORMAT_XBGR8888;
2687                 } else {
2688                         if (alpha)
2689                                 return DRM_FORMAT_ARGB8888;
2690                         else
2691                                 return DRM_FORMAT_XRGB8888;
2692                 }
2693         case PLANE_CTL_FORMAT_XRGB_2101010:
2694                 if (rgb_order)
2695                         return DRM_FORMAT_XBGR2101010;
2696                 else
2697                         return DRM_FORMAT_XRGB2101010;
2698         }
2699 }
2700
2701 static bool
2702 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2703                               struct intel_initial_plane_config *plane_config)
2704 {
2705         struct drm_device *dev = crtc->base.dev;
2706         struct drm_i915_private *dev_priv = to_i915(dev);
2707         struct drm_i915_gem_object *obj = NULL;
2708         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2709         struct drm_framebuffer *fb = &plane_config->fb->base;
2710         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2711         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2712                                     PAGE_SIZE);
2713
2714         size_aligned -= base_aligned;
2715
2716         if (plane_config->size == 0)
2717                 return false;
2718
2719         /* If the FB is too big, just don't use it since fbdev is not very
2720          * important and we should probably use that space with FBC or other
2721          * features. */
2722         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2723                 return false;
2724
2725         switch (fb->modifier) {
2726         case DRM_FORMAT_MOD_LINEAR:
2727         case I915_FORMAT_MOD_X_TILED:
2728         case I915_FORMAT_MOD_Y_TILED:
2729                 break;
2730         default:
2731                 DRM_DEBUG_DRIVER("Unsupported modifier for initial FB: 0x%llx\n",
2732                                  fb->modifier);
2733                 return false;
2734         }
2735
2736         mutex_lock(&dev->struct_mutex);
2737         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2738                                                              base_aligned,
2739                                                              base_aligned,
2740                                                              size_aligned);
2741         mutex_unlock(&dev->struct_mutex);
2742         if (!obj)
2743                 return false;
2744
2745         switch (plane_config->tiling) {
2746         case I915_TILING_NONE:
2747                 break;
2748         case I915_TILING_X:
2749         case I915_TILING_Y:
2750                 obj->tiling_and_stride = fb->pitches[0] | plane_config->tiling;
2751                 break;
2752         default:
2753                 MISSING_CASE(plane_config->tiling);
2754                 return false;
2755         }
2756
2757         mode_cmd.pixel_format = fb->format->format;
2758         mode_cmd.width = fb->width;
2759         mode_cmd.height = fb->height;
2760         mode_cmd.pitches[0] = fb->pitches[0];
2761         mode_cmd.modifier[0] = fb->modifier;
2762         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2763
2764         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2765                 DRM_DEBUG_KMS("intel fb init failed\n");
2766                 goto out_unref_obj;
2767         }
2768
2769
2770         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2771         return true;
2772
2773 out_unref_obj:
2774         i915_gem_object_put(obj);
2775         return false;
2776 }
2777
2778 static void
2779 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2780                         struct intel_plane_state *plane_state,
2781                         bool visible)
2782 {
2783         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2784
2785         plane_state->base.visible = visible;
2786
2787         if (visible)
2788                 crtc_state->base.plane_mask |= drm_plane_mask(&plane->base);
2789         else
2790                 crtc_state->base.plane_mask &= ~drm_plane_mask(&plane->base);
2791
2792         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2793                       crtc_state->base.crtc->name,
2794                       crtc_state->active_planes);
2795 }
2796
2797 static void fixup_active_planes(struct intel_crtc_state *crtc_state)
2798 {
2799         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
2800         struct drm_plane *plane;
2801
2802         /*
2803          * Active_planes aliases if multiple "primary" or cursor planes
2804          * have been used on the same (or wrong) pipe. plane_mask uses
2805          * unique ids, hence we can use that to reconstruct active_planes.
2806          */
2807         crtc_state->active_planes = 0;
2808
2809         drm_for_each_plane_mask(plane, &dev_priv->drm,
2810                                 crtc_state->base.plane_mask)
2811                 crtc_state->active_planes |= BIT(to_intel_plane(plane)->id);
2812 }
2813
2814 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2815                                          struct intel_plane *plane)
2816 {
2817         struct intel_crtc_state *crtc_state =
2818                 to_intel_crtc_state(crtc->base.state);
2819         struct intel_plane_state *plane_state =
2820                 to_intel_plane_state(plane->base.state);
2821
2822         intel_set_plane_visible(crtc_state, plane_state, false);
2823         fixup_active_planes(crtc_state);
2824
2825         if (plane->id == PLANE_PRIMARY)
2826                 intel_pre_disable_primary_noatomic(&crtc->base);
2827
2828         trace_intel_disable_plane(&plane->base, crtc);
2829         plane->disable_plane(plane, crtc);
2830 }
2831
2832 static void
2833 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2834                              struct intel_initial_plane_config *plane_config)
2835 {
2836         struct drm_device *dev = intel_crtc->base.dev;
2837         struct drm_i915_private *dev_priv = to_i915(dev);
2838         struct drm_crtc *c;
2839         struct drm_i915_gem_object *obj;
2840         struct drm_plane *primary = intel_crtc->base.primary;
2841         struct drm_plane_state *plane_state = primary->state;
2842         struct intel_plane *intel_plane = to_intel_plane(primary);
2843         struct intel_plane_state *intel_state =
2844                 to_intel_plane_state(plane_state);
2845         struct drm_framebuffer *fb;
2846
2847         if (!plane_config->fb)
2848                 return;
2849
2850         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2851                 fb = &plane_config->fb->base;
2852                 goto valid_fb;
2853         }
2854
2855         kfree(plane_config->fb);
2856
2857         /*
2858          * Failed to alloc the obj, check to see if we should share
2859          * an fb with another CRTC instead
2860          */
2861         for_each_crtc(dev, c) {
2862                 struct intel_plane_state *state;
2863
2864                 if (c == &intel_crtc->base)
2865                         continue;
2866
2867                 if (!to_intel_crtc(c)->active)
2868                         continue;
2869
2870                 state = to_intel_plane_state(c->primary->state);
2871                 if (!state->vma)
2872                         continue;
2873
2874                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2875                         fb = state->base.fb;
2876                         drm_framebuffer_get(fb);
2877                         goto valid_fb;
2878                 }
2879         }
2880
2881         /*
2882          * We've failed to reconstruct the BIOS FB.  Current display state
2883          * indicates that the primary plane is visible, but has a NULL FB,
2884          * which will lead to problems later if we don't fix it up.  The
2885          * simplest solution is to just disable the primary plane now and
2886          * pretend the BIOS never had it enabled.
2887          */
2888         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2889
2890         return;
2891
2892 valid_fb:
2893         intel_fill_fb_ggtt_view(&intel_state->view, fb,
2894                                 intel_state->base.rotation);
2895         intel_state->color_plane[0].stride =
2896                 intel_fb_pitch(fb, 0, intel_state->base.rotation);
2897
2898         mutex_lock(&dev->struct_mutex);
2899         intel_state->vma =
2900                 intel_pin_and_fence_fb_obj(fb,
2901                                            &intel_state->view,
2902                                            intel_plane_uses_fence(intel_state),
2903                                            &intel_state->flags);
2904         mutex_unlock(&dev->struct_mutex);
2905         if (IS_ERR(intel_state->vma)) {
2906                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2907                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2908
2909                 intel_state->vma = NULL;
2910                 drm_framebuffer_put(fb);
2911                 return;
2912         }
2913
2914         obj = intel_fb_obj(fb);
2915         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
2916
2917         plane_state->src_x = 0;
2918         plane_state->src_y = 0;
2919         plane_state->src_w = fb->width << 16;
2920         plane_state->src_h = fb->height << 16;
2921
2922         plane_state->crtc_x = 0;
2923         plane_state->crtc_y = 0;
2924         plane_state->crtc_w = fb->width;
2925         plane_state->crtc_h = fb->height;
2926
2927         intel_state->base.src = drm_plane_state_src(plane_state);
2928         intel_state->base.dst = drm_plane_state_dest(plane_state);
2929
2930         if (i915_gem_object_is_tiled(obj))
2931                 dev_priv->preserve_bios_swizzle = true;
2932
2933         plane_state->fb = fb;
2934         plane_state->crtc = &intel_crtc->base;
2935
2936         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2937                   &obj->frontbuffer_bits);
2938 }
2939
2940 static int skl_max_plane_width(const struct drm_framebuffer *fb,
2941                                int color_plane,
2942                                unsigned int rotation)
2943 {
2944         int cpp = fb->format->cpp[color_plane];
2945
2946         switch (fb->modifier) {
2947         case DRM_FORMAT_MOD_LINEAR:
2948         case I915_FORMAT_MOD_X_TILED:
2949                 switch (cpp) {
2950                 case 8:
2951                         return 4096;
2952                 case 4:
2953                 case 2:
2954                 case 1:
2955                         return 8192;
2956                 default:
2957                         MISSING_CASE(cpp);
2958                         break;
2959                 }
2960                 break;
2961         case I915_FORMAT_MOD_Y_TILED_CCS:
2962         case I915_FORMAT_MOD_Yf_TILED_CCS:
2963                 /* FIXME AUX plane? */
2964         case I915_FORMAT_MOD_Y_TILED:
2965         case I915_FORMAT_MOD_Yf_TILED:
2966                 switch (cpp) {
2967                 case 8:
2968                         return 2048;
2969                 case 4:
2970                         return 4096;
2971                 case 2:
2972                 case 1:
2973                         return 8192;
2974                 default:
2975                         MISSING_CASE(cpp);
2976                         break;
2977                 }
2978                 break;
2979         default:
2980                 MISSING_CASE(fb->modifier);
2981         }
2982
2983         return 2048;
2984 }
2985
2986 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2987                                            int main_x, int main_y, u32 main_offset)
2988 {
2989         const struct drm_framebuffer *fb = plane_state->base.fb;
2990         int hsub = fb->format->hsub;
2991         int vsub = fb->format->vsub;
2992         int aux_x = plane_state->color_plane[1].x;
2993         int aux_y = plane_state->color_plane[1].y;
2994         u32 aux_offset = plane_state->color_plane[1].offset;
2995         u32 alignment = intel_surf_alignment(fb, 1);
2996
2997         while (aux_offset >= main_offset && aux_y <= main_y) {
2998                 int x, y;
2999
3000                 if (aux_x == main_x && aux_y == main_y)
3001                         break;
3002
3003                 if (aux_offset == 0)
3004                         break;
3005
3006                 x = aux_x / hsub;
3007                 y = aux_y / vsub;
3008                 aux_offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 1,
3009                                                                aux_offset, aux_offset - alignment);
3010                 aux_x = x * hsub + aux_x % hsub;
3011                 aux_y = y * vsub + aux_y % vsub;
3012         }
3013
3014         if (aux_x != main_x || aux_y != main_y)
3015                 return false;
3016
3017         plane_state->color_plane[1].offset = aux_offset;
3018         plane_state->color_plane[1].x = aux_x;
3019         plane_state->color_plane[1].y = aux_y;
3020
3021         return true;
3022 }
3023
3024 static int skl_check_main_surface(struct intel_plane_state *plane_state)
3025 {
3026         const struct drm_framebuffer *fb = plane_state->base.fb;
3027         unsigned int rotation = plane_state->base.rotation;
3028         int x = plane_state->base.src.x1 >> 16;
3029         int y = plane_state->base.src.y1 >> 16;
3030         int w = drm_rect_width(&plane_state->base.src) >> 16;
3031         int h = drm_rect_height(&plane_state->base.src) >> 16;
3032         int max_width = skl_max_plane_width(fb, 0, rotation);
3033         int max_height = 4096;
3034         u32 alignment, offset, aux_offset = plane_state->color_plane[1].offset;
3035
3036         if (w > max_width || h > max_height) {
3037                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
3038                               w, h, max_width, max_height);
3039                 return -EINVAL;
3040         }
3041
3042         intel_add_fb_offsets(&x, &y, plane_state, 0);
3043         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 0);
3044         alignment = intel_surf_alignment(fb, 0);
3045
3046         /*
3047          * AUX surface offset is specified as the distance from the
3048          * main surface offset, and it must be non-negative. Make
3049          * sure that is what we will get.
3050          */
3051         if (offset > aux_offset)
3052                 offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3053                                                            offset, aux_offset & ~(alignment - 1));
3054
3055         /*
3056          * When using an X-tiled surface, the plane blows up
3057          * if the x offset + width exceed the stride.
3058          *
3059          * TODO: linear and Y-tiled seem fine, Yf untested,
3060          */
3061         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3062                 int cpp = fb->format->cpp[0];
3063
3064                 while ((x + w) * cpp > plane_state->color_plane[0].stride) {
3065                         if (offset == 0) {
3066                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3067                                 return -EINVAL;
3068                         }
3069
3070                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3071                                                                    offset, offset - alignment);
3072                 }
3073         }
3074
3075         /*
3076          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3077          * they match with the main surface x/y offsets.
3078          */
3079         if (is_ccs_modifier(fb->modifier)) {
3080                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3081                         if (offset == 0)
3082                                 break;
3083
3084                         offset = intel_plane_adjust_aligned_offset(&x, &y, plane_state, 0,
3085                                                                    offset, offset - alignment);
3086                 }
3087
3088                 if (x != plane_state->color_plane[1].x || y != plane_state->color_plane[1].y) {
3089                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3090                         return -EINVAL;
3091                 }
3092         }
3093
3094         plane_state->color_plane[0].offset = offset;
3095         plane_state->color_plane[0].x = x;
3096         plane_state->color_plane[0].y = y;
3097
3098         return 0;
3099 }
3100
3101 static int
3102 skl_check_nv12_surface(struct intel_plane_state *plane_state)
3103 {
3104         /* Display WA #1106 */
3105         if (plane_state->base.rotation !=
3106             (DRM_MODE_REFLECT_X | DRM_MODE_ROTATE_90) &&
3107             plane_state->base.rotation != DRM_MODE_ROTATE_270)
3108                 return 0;
3109
3110         /*
3111          * src coordinates are rotated here.
3112          * We check height but report it as width
3113          */
3114         if (((drm_rect_height(&plane_state->base.src) >> 16) % 4) != 0) {
3115                 DRM_DEBUG_KMS("src width must be multiple "
3116                               "of 4 for rotated NV12\n");
3117                 return -EINVAL;
3118         }
3119
3120         return 0;
3121 }
3122
3123 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3124 {
3125         const struct drm_framebuffer *fb = plane_state->base.fb;
3126         unsigned int rotation = plane_state->base.rotation;
3127         int max_width = skl_max_plane_width(fb, 1, rotation);
3128         int max_height = 4096;
3129         int x = plane_state->base.src.x1 >> 17;
3130         int y = plane_state->base.src.y1 >> 17;
3131         int w = drm_rect_width(&plane_state->base.src) >> 17;
3132         int h = drm_rect_height(&plane_state->base.src) >> 17;
3133         u32 offset;
3134
3135         intel_add_fb_offsets(&x, &y, plane_state, 1);
3136         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3137
3138         /* FIXME not quite sure how/if these apply to the chroma plane */
3139         if (w > max_width || h > max_height) {
3140                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3141                               w, h, max_width, max_height);
3142                 return -EINVAL;
3143         }
3144
3145         plane_state->color_plane[1].offset = offset;
3146         plane_state->color_plane[1].x = x;
3147         plane_state->color_plane[1].y = y;
3148
3149         return 0;
3150 }
3151
3152 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3153 {
3154         const struct drm_framebuffer *fb = plane_state->base.fb;
3155         int src_x = plane_state->base.src.x1 >> 16;
3156         int src_y = plane_state->base.src.y1 >> 16;
3157         int hsub = fb->format->hsub;
3158         int vsub = fb->format->vsub;
3159         int x = src_x / hsub;
3160         int y = src_y / vsub;
3161         u32 offset;
3162
3163         intel_add_fb_offsets(&x, &y, plane_state, 1);
3164         offset = intel_plane_compute_aligned_offset(&x, &y, plane_state, 1);
3165
3166         plane_state->color_plane[1].offset = offset;
3167         plane_state->color_plane[1].x = x * hsub + src_x % hsub;
3168         plane_state->color_plane[1].y = y * vsub + src_y % vsub;
3169
3170         return 0;
3171 }
3172
3173 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3174 {
3175         const struct drm_framebuffer *fb = plane_state->base.fb;
3176         unsigned int rotation = plane_state->base.rotation;
3177         int ret;
3178
3179         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3180         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3181         plane_state->color_plane[1].stride = intel_fb_pitch(fb, 1, rotation);
3182
3183         ret = intel_plane_check_stride(plane_state);
3184         if (ret)
3185                 return ret;
3186
3187         if (!plane_state->base.visible)
3188                 return 0;
3189
3190         /* Rotate src coordinates to match rotated GTT view */
3191         if (drm_rotation_90_or_270(rotation))
3192                 drm_rect_rotate(&plane_state->base.src,
3193                                 fb->width << 16, fb->height << 16,
3194                                 DRM_MODE_ROTATE_270);
3195
3196         /*
3197          * Handle the AUX surface first since
3198          * the main surface setup depends on it.
3199          */
3200         if (fb->format->format == DRM_FORMAT_NV12) {
3201                 ret = skl_check_nv12_surface(plane_state);
3202                 if (ret)
3203                         return ret;
3204                 ret = skl_check_nv12_aux_surface(plane_state);
3205                 if (ret)
3206                         return ret;
3207         } else if (is_ccs_modifier(fb->modifier)) {
3208                 ret = skl_check_ccs_aux_surface(plane_state);
3209                 if (ret)
3210                         return ret;
3211         } else {
3212                 plane_state->color_plane[1].offset = ~0xfff;
3213                 plane_state->color_plane[1].x = 0;
3214                 plane_state->color_plane[1].y = 0;
3215         }
3216
3217         ret = skl_check_main_surface(plane_state);
3218         if (ret)
3219                 return ret;
3220
3221         return 0;
3222 }
3223
3224 unsigned int
3225 i9xx_plane_max_stride(struct intel_plane *plane,
3226                       u32 pixel_format, u64 modifier,
3227                       unsigned int rotation)
3228 {
3229         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3230
3231         if (!HAS_GMCH_DISPLAY(dev_priv)) {
3232                 return 32*1024;
3233         } else if (INTEL_GEN(dev_priv) >= 4) {
3234                 if (modifier == I915_FORMAT_MOD_X_TILED)
3235                         return 16*1024;
3236                 else
3237                         return 32*1024;
3238         } else if (INTEL_GEN(dev_priv) >= 3) {
3239                 if (modifier == I915_FORMAT_MOD_X_TILED)
3240                         return 8*1024;
3241                 else
3242                         return 16*1024;
3243         } else {
3244                 if (plane->i9xx_plane == PLANE_C)
3245                         return 4*1024;
3246                 else
3247                         return 8*1024;
3248         }
3249 }
3250
3251 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3252                           const struct intel_plane_state *plane_state)
3253 {
3254         struct drm_i915_private *dev_priv =
3255                 to_i915(plane_state->base.plane->dev);
3256         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3257         const struct drm_framebuffer *fb = plane_state->base.fb;
3258         unsigned int rotation = plane_state->base.rotation;
3259         u32 dspcntr;
3260
3261         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3262
3263         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3264             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3265                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3266
3267         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3268                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3269
3270         if (INTEL_GEN(dev_priv) < 5)
3271                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3272
3273         switch (fb->format->format) {
3274         case DRM_FORMAT_C8:
3275                 dspcntr |= DISPPLANE_8BPP;
3276                 break;
3277         case DRM_FORMAT_XRGB1555:
3278                 dspcntr |= DISPPLANE_BGRX555;
3279                 break;
3280         case DRM_FORMAT_RGB565:
3281                 dspcntr |= DISPPLANE_BGRX565;
3282                 break;
3283         case DRM_FORMAT_XRGB8888:
3284                 dspcntr |= DISPPLANE_BGRX888;
3285                 break;
3286         case DRM_FORMAT_XBGR8888:
3287                 dspcntr |= DISPPLANE_RGBX888;
3288                 break;
3289         case DRM_FORMAT_XRGB2101010:
3290                 dspcntr |= DISPPLANE_BGRX101010;
3291                 break;
3292         case DRM_FORMAT_XBGR2101010:
3293                 dspcntr |= DISPPLANE_RGBX101010;
3294                 break;
3295         default:
3296                 MISSING_CASE(fb->format->format);
3297                 return 0;
3298         }
3299
3300         if (INTEL_GEN(dev_priv) >= 4 &&
3301             fb->modifier == I915_FORMAT_MOD_X_TILED)
3302                 dspcntr |= DISPPLANE_TILED;
3303
3304         if (rotation & DRM_MODE_ROTATE_180)
3305                 dspcntr |= DISPPLANE_ROTATE_180;
3306
3307         if (rotation & DRM_MODE_REFLECT_X)
3308                 dspcntr |= DISPPLANE_MIRROR;
3309
3310         return dspcntr;
3311 }
3312
3313 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3314 {
3315         struct drm_i915_private *dev_priv =
3316                 to_i915(plane_state->base.plane->dev);
3317         const struct drm_framebuffer *fb = plane_state->base.fb;
3318         unsigned int rotation = plane_state->base.rotation;
3319         int src_x = plane_state->base.src.x1 >> 16;
3320         int src_y = plane_state->base.src.y1 >> 16;
3321         u32 offset;
3322         int ret;
3323
3324         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
3325         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
3326
3327         ret = intel_plane_check_stride(plane_state);
3328         if (ret)
3329                 return ret;
3330
3331         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3332
3333         if (INTEL_GEN(dev_priv) >= 4)
3334                 offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
3335                                                             plane_state, 0);
3336         else
3337                 offset = 0;
3338
3339         /* HSW/BDW do this automagically in hardware */
3340         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3341                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3342                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3343
3344                 if (rotation & DRM_MODE_ROTATE_180) {
3345                         src_x += src_w - 1;
3346                         src_y += src_h - 1;
3347                 } else if (rotation & DRM_MODE_REFLECT_X) {
3348                         src_x += src_w - 1;
3349                 }
3350         }
3351
3352         plane_state->color_plane[0].offset = offset;
3353         plane_state->color_plane[0].x = src_x;
3354         plane_state->color_plane[0].y = src_y;
3355
3356         return 0;
3357 }
3358
3359 static int
3360 i9xx_plane_check(struct intel_crtc_state *crtc_state,
3361                  struct intel_plane_state *plane_state)
3362 {
3363         int ret;
3364
3365         ret = chv_plane_check_rotation(plane_state);
3366         if (ret)
3367                 return ret;
3368
3369         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
3370                                                   &crtc_state->base,
3371                                                   DRM_PLANE_HELPER_NO_SCALING,
3372                                                   DRM_PLANE_HELPER_NO_SCALING,
3373                                                   false, true);
3374         if (ret)
3375                 return ret;
3376
3377         if (!plane_state->base.visible)
3378                 return 0;
3379
3380         ret = intel_plane_check_src_coordinates(plane_state);
3381         if (ret)
3382                 return ret;
3383
3384         ret = i9xx_check_plane_surface(plane_state);
3385         if (ret)
3386                 return ret;
3387
3388         plane_state->ctl = i9xx_plane_ctl(crtc_state, plane_state);
3389
3390         return 0;
3391 }
3392
3393 static void i9xx_update_plane(struct intel_plane *plane,
3394                               const struct intel_crtc_state *crtc_state,
3395                               const struct intel_plane_state *plane_state)
3396 {
3397         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3398         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3399         u32 linear_offset;
3400         u32 dspcntr = plane_state->ctl;
3401         i915_reg_t reg = DSPCNTR(i9xx_plane);
3402         int x = plane_state->color_plane[0].x;
3403         int y = plane_state->color_plane[0].y;
3404         unsigned long irqflags;
3405         u32 dspaddr_offset;
3406
3407         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3408
3409         if (INTEL_GEN(dev_priv) >= 4)
3410                 dspaddr_offset = plane_state->color_plane[0].offset;
3411         else
3412                 dspaddr_offset = linear_offset;
3413
3414         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3415
3416         if (INTEL_GEN(dev_priv) < 4) {
3417                 /* pipesrc and dspsize control the size that is scaled from,
3418                  * which should always be the user's requested size.
3419                  */
3420                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3421                               ((crtc_state->pipe_src_h - 1) << 16) |
3422                               (crtc_state->pipe_src_w - 1));
3423                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3424         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3425                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3426                               ((crtc_state->pipe_src_h - 1) << 16) |
3427                               (crtc_state->pipe_src_w - 1));
3428                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3429                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3430         }
3431
3432         I915_WRITE_FW(reg, dspcntr);
3433
3434         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), plane_state->color_plane[0].stride);
3435         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3436                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3437                               intel_plane_ggtt_offset(plane_state) +
3438                               dspaddr_offset);
3439                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3440         } else if (INTEL_GEN(dev_priv) >= 4) {
3441                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3442                               intel_plane_ggtt_offset(plane_state) +
3443                               dspaddr_offset);
3444                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3445                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3446         } else {
3447                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3448                               intel_plane_ggtt_offset(plane_state) +
3449                               dspaddr_offset);
3450         }
3451         POSTING_READ_FW(reg);
3452
3453         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3454 }
3455
3456 static void i9xx_disable_plane(struct intel_plane *plane,
3457                                struct intel_crtc *crtc)
3458 {
3459         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3460         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3461         unsigned long irqflags;
3462
3463         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3464
3465         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3466         if (INTEL_GEN(dev_priv) >= 4)
3467                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3468         else
3469                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3470         POSTING_READ_FW(DSPCNTR(i9xx_plane));
3471
3472         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3473 }
3474
3475 static bool i9xx_plane_get_hw_state(struct intel_plane *plane,
3476                                     enum pipe *pipe)
3477 {
3478         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3479         enum intel_display_power_domain power_domain;
3480         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3481         bool ret;
3482         u32 val;
3483
3484         /*
3485          * Not 100% correct for planes that can move between pipes,
3486          * but that's only the case for gen2-4 which don't have any
3487          * display power wells.
3488          */
3489         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
3490         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3491                 return false;
3492
3493         val = I915_READ(DSPCNTR(i9xx_plane));
3494
3495         ret = val & DISPLAY_PLANE_ENABLE;
3496
3497         if (INTEL_GEN(dev_priv) >= 5)
3498                 *pipe = plane->pipe;
3499         else
3500                 *pipe = (val & DISPPLANE_SEL_PIPE_MASK) >>
3501                         DISPPLANE_SEL_PIPE_SHIFT;
3502
3503         intel_display_power_put(dev_priv, power_domain);
3504
3505         return ret;
3506 }
3507
3508 static u32
3509 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int color_plane)
3510 {
3511         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3512                 return 64;
3513         else
3514                 return intel_tile_width_bytes(fb, color_plane);
3515 }
3516
3517 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3518 {
3519         struct drm_device *dev = intel_crtc->base.dev;
3520         struct drm_i915_private *dev_priv = to_i915(dev);
3521
3522         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3523         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3524         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3525 }
3526
3527 /*
3528  * This function detaches (aka. unbinds) unused scalers in hardware
3529  */
3530 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3531 {
3532         struct intel_crtc_scaler_state *scaler_state;
3533         int i;
3534
3535         scaler_state = &intel_crtc->config->scaler_state;
3536
3537         /* loop through and disable scalers that aren't in use */
3538         for (i = 0; i < intel_crtc->num_scalers; i++) {
3539                 if (!scaler_state->scalers[i].in_use)
3540                         skl_detach_scaler(intel_crtc, i);
3541         }
3542 }
3543
3544 u32 skl_plane_stride(const struct intel_plane_state *plane_state,
3545                      int color_plane)
3546 {
3547         const struct drm_framebuffer *fb = plane_state->base.fb;
3548         unsigned int rotation = plane_state->base.rotation;
3549         u32 stride = plane_state->color_plane[color_plane].stride;
3550
3551         if (color_plane >= fb->format->num_planes)
3552                 return 0;
3553
3554         /*
3555          * The stride is either expressed as a multiple of 64 bytes chunks for
3556          * linear buffers or in number of tiles for tiled buffers.
3557          */
3558         if (drm_rotation_90_or_270(rotation))
3559                 stride /= intel_tile_height(fb, color_plane);
3560         else
3561                 stride /= intel_fb_stride_alignment(fb, color_plane);
3562
3563         return stride;
3564 }
3565
3566 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3567 {
3568         switch (pixel_format) {
3569         case DRM_FORMAT_C8:
3570                 return PLANE_CTL_FORMAT_INDEXED;
3571         case DRM_FORMAT_RGB565:
3572                 return PLANE_CTL_FORMAT_RGB_565;
3573         case DRM_FORMAT_XBGR8888:
3574         case DRM_FORMAT_ABGR8888:
3575                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3576         case DRM_FORMAT_XRGB8888:
3577         case DRM_FORMAT_ARGB8888:
3578                 return PLANE_CTL_FORMAT_XRGB_8888;
3579         case DRM_FORMAT_XRGB2101010:
3580                 return PLANE_CTL_FORMAT_XRGB_2101010;
3581         case DRM_FORMAT_XBGR2101010:
3582                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3583         case DRM_FORMAT_YUYV:
3584                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3585         case DRM_FORMAT_YVYU:
3586                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3587         case DRM_FORMAT_UYVY:
3588                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3589         case DRM_FORMAT_VYUY:
3590                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3591         case DRM_FORMAT_NV12:
3592                 return PLANE_CTL_FORMAT_NV12;
3593         default:
3594                 MISSING_CASE(pixel_format);
3595         }
3596
3597         return 0;
3598 }
3599
3600 /*
3601  * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3602  * to be already pre-multiplied. We need to add a knob (or a different
3603  * DRM_FORMAT) for user-space to configure that.
3604  */
3605 static u32 skl_plane_ctl_alpha(uint32_t pixel_format)
3606 {
3607         switch (pixel_format) {
3608         case DRM_FORMAT_ABGR8888:
3609         case DRM_FORMAT_ARGB8888:
3610                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3611         default:
3612                 return PLANE_CTL_ALPHA_DISABLE;
3613         }
3614 }
3615
3616 static u32 glk_plane_color_ctl_alpha(uint32_t pixel_format)
3617 {
3618         switch (pixel_format) {
3619         case DRM_FORMAT_ABGR8888:
3620         case DRM_FORMAT_ARGB8888:
3621                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3622         default:
3623                 return PLANE_COLOR_ALPHA_DISABLE;
3624         }
3625 }
3626
3627 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3628 {
3629         switch (fb_modifier) {
3630         case DRM_FORMAT_MOD_LINEAR:
3631                 break;
3632         case I915_FORMAT_MOD_X_TILED:
3633                 return PLANE_CTL_TILED_X;
3634         case I915_FORMAT_MOD_Y_TILED:
3635                 return PLANE_CTL_TILED_Y;
3636         case I915_FORMAT_MOD_Y_TILED_CCS:
3637                 return PLANE_CTL_TILED_Y | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3638         case I915_FORMAT_MOD_Yf_TILED:
3639                 return PLANE_CTL_TILED_YF;
3640         case I915_FORMAT_MOD_Yf_TILED_CCS:
3641                 return PLANE_CTL_TILED_YF | PLANE_CTL_RENDER_DECOMPRESSION_ENABLE;
3642         default:
3643                 MISSING_CASE(fb_modifier);
3644         }
3645
3646         return 0;
3647 }
3648
3649 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3650 {
3651         switch (rotate) {
3652         case DRM_MODE_ROTATE_0:
3653                 break;
3654         /*
3655          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3656          * while i915 HW rotation is clockwise, thats why this swapping.
3657          */
3658         case DRM_MODE_ROTATE_90:
3659                 return PLANE_CTL_ROTATE_270;
3660         case DRM_MODE_ROTATE_180:
3661                 return PLANE_CTL_ROTATE_180;
3662         case DRM_MODE_ROTATE_270:
3663                 return PLANE_CTL_ROTATE_90;
3664         default:
3665                 MISSING_CASE(rotate);
3666         }
3667
3668         return 0;
3669 }
3670
3671 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3672 {
3673         switch (reflect) {
3674         case 0:
3675                 break;
3676         case DRM_MODE_REFLECT_X:
3677                 return PLANE_CTL_FLIP_HORIZONTAL;
3678         case DRM_MODE_REFLECT_Y:
3679         default:
3680                 MISSING_CASE(reflect);
3681         }
3682
3683         return 0;
3684 }
3685
3686 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3687                   const struct intel_plane_state *plane_state)
3688 {
3689         struct drm_i915_private *dev_priv =
3690                 to_i915(plane_state->base.plane->dev);
3691         const struct drm_framebuffer *fb = plane_state->base.fb;
3692         unsigned int rotation = plane_state->base.rotation;
3693         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3694         u32 plane_ctl;
3695
3696         plane_ctl = PLANE_CTL_ENABLE;
3697
3698         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3699                 plane_ctl |= skl_plane_ctl_alpha(fb->format->format);
3700                 plane_ctl |=
3701                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3702                         PLANE_CTL_PIPE_CSC_ENABLE |
3703                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3704
3705                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3706                         plane_ctl |= PLANE_CTL_YUV_TO_RGB_CSC_FORMAT_BT709;
3707
3708                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3709                         plane_ctl |= PLANE_CTL_YUV_RANGE_CORRECTION_DISABLE;
3710         }
3711
3712         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3713         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3714         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3715
3716         if (INTEL_GEN(dev_priv) >= 10)
3717                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3718                                                 DRM_MODE_REFLECT_MASK);
3719
3720         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3721                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3722         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3723                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3724
3725         return plane_ctl;
3726 }
3727
3728 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3729                         const struct intel_plane_state *plane_state)
3730 {
3731         struct drm_i915_private *dev_priv =
3732                 to_i915(plane_state->base.plane->dev);
3733         const struct drm_framebuffer *fb = plane_state->base.fb;
3734         u32 plane_color_ctl = 0;
3735
3736         if (INTEL_GEN(dev_priv) < 11) {
3737                 plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3738                 plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3739         }
3740         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3741         plane_color_ctl |= glk_plane_color_ctl_alpha(fb->format->format);
3742
3743         if (fb->format->is_yuv) {
3744                 if (plane_state->base.color_encoding == DRM_COLOR_YCBCR_BT709)
3745                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV709_TO_RGB709;
3746                 else
3747                         plane_color_ctl |= PLANE_COLOR_CSC_MODE_YUV601_TO_RGB709;
3748
3749                 if (plane_state->base.color_range == DRM_COLOR_YCBCR_FULL_RANGE)
3750                         plane_color_ctl |= PLANE_COLOR_YUV_RANGE_CORRECTION_DISABLE;
3751         }
3752
3753         return plane_color_ctl;
3754 }
3755
3756 static int
3757 __intel_display_resume(struct drm_device *dev,
3758                        struct drm_atomic_state *state,
3759                        struct drm_modeset_acquire_ctx *ctx)
3760 {
3761         struct drm_crtc_state *crtc_state;
3762         struct drm_crtc *crtc;
3763         int i, ret;
3764
3765         intel_modeset_setup_hw_state(dev, ctx);
3766         i915_redisable_vga(to_i915(dev));
3767
3768         if (!state)
3769                 return 0;
3770
3771         /*
3772          * We've duplicated the state, pointers to the old state are invalid.
3773          *
3774          * Don't attempt to use the old state until we commit the duplicated state.
3775          */
3776         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3777                 /*
3778                  * Force recalculation even if we restore
3779                  * current state. With fast modeset this may not result
3780                  * in a modeset when the state is compatible.
3781                  */
3782                 crtc_state->mode_changed = true;
3783         }
3784
3785         /* ignore any reset values/BIOS leftovers in the WM registers */
3786         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3787                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3788
3789         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3790
3791         WARN_ON(ret == -EDEADLK);
3792         return ret;
3793 }
3794
3795 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3796 {
3797         return intel_has_gpu_reset(dev_priv) &&
3798                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3799 }
3800
3801 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3802 {
3803         struct drm_device *dev = &dev_priv->drm;
3804         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3805         struct drm_atomic_state *state;
3806         int ret;
3807
3808         /* reset doesn't touch the display */
3809         if (!i915_modparams.force_reset_modeset_test &&
3810             !gpu_reset_clobbers_display(dev_priv))
3811                 return;
3812
3813         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3814         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3815         wake_up_all(&dev_priv->gpu_error.wait_queue);
3816
3817         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3818                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3819                 i915_gem_set_wedged(dev_priv);
3820         }
3821
3822         /*
3823          * Need mode_config.mutex so that we don't
3824          * trample ongoing ->detect() and whatnot.
3825          */
3826         mutex_lock(&dev->mode_config.mutex);
3827         drm_modeset_acquire_init(ctx, 0);
3828         while (1) {
3829                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3830                 if (ret != -EDEADLK)
3831                         break;
3832
3833                 drm_modeset_backoff(ctx);
3834         }
3835         /*
3836          * Disabling the crtcs gracefully seems nicer. Also the
3837          * g33 docs say we should at least disable all the planes.
3838          */
3839         state = drm_atomic_helper_duplicate_state(dev, ctx);
3840         if (IS_ERR(state)) {
3841                 ret = PTR_ERR(state);
3842                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3843                 return;
3844         }
3845
3846         ret = drm_atomic_helper_disable_all(dev, ctx);
3847         if (ret) {
3848                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3849                 drm_atomic_state_put(state);
3850                 return;
3851         }
3852
3853         dev_priv->modeset_restore_state = state;
3854         state->acquire_ctx = ctx;
3855 }
3856
3857 void intel_finish_reset(struct drm_i915_private *dev_priv)
3858 {
3859         struct drm_device *dev = &dev_priv->drm;
3860         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3861         struct drm_atomic_state *state;
3862         int ret;
3863
3864         /* reset doesn't touch the display */
3865         if (!test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
3866                 return;
3867
3868         state = fetch_and_zero(&dev_priv->modeset_restore_state);
3869         if (!state)
3870                 goto unlock;
3871
3872         /* reset doesn't touch the display */
3873         if (!gpu_reset_clobbers_display(dev_priv)) {
3874                 /* for testing only restore the display */
3875                 ret = __intel_display_resume(dev, state, ctx);
3876                 if (ret)
3877                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3878         } else {
3879                 /*
3880                  * The display has been reset as well,
3881                  * so need a full re-initialization.
3882                  */
3883                 intel_runtime_pm_disable_interrupts(dev_priv);
3884                 intel_runtime_pm_enable_interrupts(dev_priv);
3885
3886                 intel_pps_unlock_regs_wa(dev_priv);
3887                 intel_modeset_init_hw(dev);
3888                 intel_init_clock_gating(dev_priv);
3889
3890                 spin_lock_irq(&dev_priv->irq_lock);
3891                 if (dev_priv->display.hpd_irq_setup)
3892                         dev_priv->display.hpd_irq_setup(dev_priv);
3893                 spin_unlock_irq(&dev_priv->irq_lock);
3894
3895                 ret = __intel_display_resume(dev, state, ctx);
3896                 if (ret)
3897                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3898
3899                 intel_hpd_init(dev_priv);
3900         }
3901
3902         drm_atomic_state_put(state);
3903 unlock:
3904         drm_modeset_drop_locks(ctx);
3905         drm_modeset_acquire_fini(ctx);
3906         mutex_unlock(&dev->mode_config.mutex);
3907
3908         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3909 }
3910
3911 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3912                                      const struct intel_crtc_state *new_crtc_state)
3913 {
3914         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3915         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3916
3917         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3918         crtc->base.mode = new_crtc_state->base.mode;
3919
3920         /*
3921          * Update pipe size and adjust fitter if needed: the reason for this is
3922          * that in compute_mode_changes we check the native mode (not the pfit
3923          * mode) to see if we can flip rather than do a full mode set. In the
3924          * fastboot case, we'll flip, but if we don't update the pipesrc and
3925          * pfit state, we'll end up with a big fb scanned out into the wrong
3926          * sized surface.
3927          */
3928
3929         I915_WRITE(PIPESRC(crtc->pipe),
3930                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3931                    (new_crtc_state->pipe_src_h - 1));
3932
3933         /* on skylake this is done by detaching scalers */
3934         if (INTEL_GEN(dev_priv) >= 9) {
3935                 skl_detach_scalers(crtc);
3936
3937                 if (new_crtc_state->pch_pfit.enabled)
3938                         skylake_pfit_enable(crtc);
3939         } else if (HAS_PCH_SPLIT(dev_priv)) {
3940                 if (new_crtc_state->pch_pfit.enabled)
3941                         ironlake_pfit_enable(crtc);
3942                 else if (old_crtc_state->pch_pfit.enabled)
3943                         ironlake_pfit_disable(crtc, true);
3944         }
3945 }
3946
3947 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3948 {
3949         struct drm_device *dev = crtc->base.dev;
3950         struct drm_i915_private *dev_priv = to_i915(dev);
3951         int pipe = crtc->pipe;
3952         i915_reg_t reg;
3953         u32 temp;
3954
3955         /* enable normal train */
3956         reg = FDI_TX_CTL(pipe);
3957         temp = I915_READ(reg);
3958         if (IS_IVYBRIDGE(dev_priv)) {
3959                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3960                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3961         } else {
3962                 temp &= ~FDI_LINK_TRAIN_NONE;
3963                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3964         }
3965         I915_WRITE(reg, temp);
3966
3967         reg = FDI_RX_CTL(pipe);
3968         temp = I915_READ(reg);
3969         if (HAS_PCH_CPT(dev_priv)) {
3970                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3971                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3972         } else {
3973                 temp &= ~FDI_LINK_TRAIN_NONE;
3974                 temp |= FDI_LINK_TRAIN_NONE;
3975         }
3976         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3977
3978         /* wait one idle pattern time */
3979         POSTING_READ(reg);
3980         udelay(1000);
3981
3982         /* IVB wants error correction enabled */
3983         if (IS_IVYBRIDGE(dev_priv))
3984                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3985                            FDI_FE_ERRC_ENABLE);
3986 }
3987
3988 /* The FDI link training functions for ILK/Ibexpeak. */
3989 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3990                                     const struct intel_crtc_state *crtc_state)
3991 {
3992         struct drm_device *dev = crtc->base.dev;
3993         struct drm_i915_private *dev_priv = to_i915(dev);
3994         int pipe = crtc->pipe;
3995         i915_reg_t reg;
3996         u32 temp, tries;
3997
3998         /* FDI needs bits from pipe first */
3999         assert_pipe_enabled(dev_priv, pipe);
4000
4001         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4002            for train result */
4003         reg = FDI_RX_IMR(pipe);
4004         temp = I915_READ(reg);
4005         temp &= ~FDI_RX_SYMBOL_LOCK;
4006         temp &= ~FDI_RX_BIT_LOCK;
4007         I915_WRITE(reg, temp);
4008         I915_READ(reg);
4009         udelay(150);
4010
4011         /* enable CPU FDI TX and PCH FDI RX */
4012         reg = FDI_TX_CTL(pipe);
4013         temp = I915_READ(reg);
4014         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4015         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4016         temp &= ~FDI_LINK_TRAIN_NONE;
4017         temp |= FDI_LINK_TRAIN_PATTERN_1;
4018         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4019
4020         reg = FDI_RX_CTL(pipe);
4021         temp = I915_READ(reg);
4022         temp &= ~FDI_LINK_TRAIN_NONE;
4023         temp |= FDI_LINK_TRAIN_PATTERN_1;
4024         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4025
4026         POSTING_READ(reg);
4027         udelay(150);
4028
4029         /* Ironlake workaround, enable clock pointer after FDI enable*/
4030         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4031         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
4032                    FDI_RX_PHASE_SYNC_POINTER_EN);
4033
4034         reg = FDI_RX_IIR(pipe);
4035         for (tries = 0; tries < 5; tries++) {
4036                 temp = I915_READ(reg);
4037                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4038
4039                 if ((temp & FDI_RX_BIT_LOCK)) {
4040                         DRM_DEBUG_KMS("FDI train 1 done.\n");
4041                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4042                         break;
4043                 }
4044         }
4045         if (tries == 5)
4046                 DRM_ERROR("FDI train 1 fail!\n");
4047
4048         /* Train 2 */
4049         reg = FDI_TX_CTL(pipe);
4050         temp = I915_READ(reg);
4051         temp &= ~FDI_LINK_TRAIN_NONE;
4052         temp |= FDI_LINK_TRAIN_PATTERN_2;
4053         I915_WRITE(reg, temp);
4054
4055         reg = FDI_RX_CTL(pipe);
4056         temp = I915_READ(reg);
4057         temp &= ~FDI_LINK_TRAIN_NONE;
4058         temp |= FDI_LINK_TRAIN_PATTERN_2;
4059         I915_WRITE(reg, temp);
4060
4061         POSTING_READ(reg);
4062         udelay(150);
4063
4064         reg = FDI_RX_IIR(pipe);
4065         for (tries = 0; tries < 5; tries++) {
4066                 temp = I915_READ(reg);
4067                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4068
4069                 if (temp & FDI_RX_SYMBOL_LOCK) {
4070                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4071                         DRM_DEBUG_KMS("FDI train 2 done.\n");
4072                         break;
4073                 }
4074         }
4075         if (tries == 5)
4076                 DRM_ERROR("FDI train 2 fail!\n");
4077
4078         DRM_DEBUG_KMS("FDI train done\n");
4079
4080 }
4081
4082 static const int snb_b_fdi_train_param[] = {
4083         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
4084         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
4085         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
4086         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
4087 };
4088
4089 /* The FDI link training functions for SNB/Cougarpoint. */
4090 static void gen6_fdi_link_train(struct intel_crtc *crtc,
4091                                 const struct intel_crtc_state *crtc_state)
4092 {
4093         struct drm_device *dev = crtc->base.dev;
4094         struct drm_i915_private *dev_priv = to_i915(dev);
4095         int pipe = crtc->pipe;
4096         i915_reg_t reg;
4097         u32 temp, i, retry;
4098
4099         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4100            for train result */
4101         reg = FDI_RX_IMR(pipe);
4102         temp = I915_READ(reg);
4103         temp &= ~FDI_RX_SYMBOL_LOCK;
4104         temp &= ~FDI_RX_BIT_LOCK;
4105         I915_WRITE(reg, temp);
4106
4107         POSTING_READ(reg);
4108         udelay(150);
4109
4110         /* enable CPU FDI TX and PCH FDI RX */
4111         reg = FDI_TX_CTL(pipe);
4112         temp = I915_READ(reg);
4113         temp &= ~FDI_DP_PORT_WIDTH_MASK;
4114         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4115         temp &= ~FDI_LINK_TRAIN_NONE;
4116         temp |= FDI_LINK_TRAIN_PATTERN_1;
4117         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4118         /* SNB-B */
4119         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4120         I915_WRITE(reg, temp | FDI_TX_ENABLE);
4121
4122         I915_WRITE(FDI_RX_MISC(pipe),
4123                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4124
4125         reg = FDI_RX_CTL(pipe);
4126         temp = I915_READ(reg);
4127         if (HAS_PCH_CPT(dev_priv)) {
4128                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4129                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4130         } else {
4131                 temp &= ~FDI_LINK_TRAIN_NONE;
4132                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4133         }
4134         I915_WRITE(reg, temp | FDI_RX_ENABLE);
4135
4136         POSTING_READ(reg);
4137         udelay(150);
4138
4139         for (i = 0; i < 4; i++) {
4140                 reg = FDI_TX_CTL(pipe);
4141                 temp = I915_READ(reg);
4142                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4143                 temp |= snb_b_fdi_train_param[i];
4144                 I915_WRITE(reg, temp);
4145
4146                 POSTING_READ(reg);
4147                 udelay(500);
4148
4149                 for (retry = 0; retry < 5; retry++) {
4150                         reg = FDI_RX_IIR(pipe);
4151                         temp = I915_READ(reg);
4152                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4153                         if (temp & FDI_RX_BIT_LOCK) {
4154                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4155                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4156                                 break;
4157                         }
4158                         udelay(50);
4159                 }
4160                 if (retry < 5)
4161                         break;
4162         }
4163         if (i == 4)
4164                 DRM_ERROR("FDI train 1 fail!\n");
4165
4166         /* Train 2 */
4167         reg = FDI_TX_CTL(pipe);
4168         temp = I915_READ(reg);
4169         temp &= ~FDI_LINK_TRAIN_NONE;
4170         temp |= FDI_LINK_TRAIN_PATTERN_2;
4171         if (IS_GEN6(dev_priv)) {
4172                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4173                 /* SNB-B */
4174                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4175         }
4176         I915_WRITE(reg, temp);
4177
4178         reg = FDI_RX_CTL(pipe);
4179         temp = I915_READ(reg);
4180         if (HAS_PCH_CPT(dev_priv)) {
4181                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4182                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4183         } else {
4184                 temp &= ~FDI_LINK_TRAIN_NONE;
4185                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4186         }
4187         I915_WRITE(reg, temp);
4188
4189         POSTING_READ(reg);
4190         udelay(150);
4191
4192         for (i = 0; i < 4; i++) {
4193                 reg = FDI_TX_CTL(pipe);
4194                 temp = I915_READ(reg);
4195                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4196                 temp |= snb_b_fdi_train_param[i];
4197                 I915_WRITE(reg, temp);
4198
4199                 POSTING_READ(reg);
4200                 udelay(500);
4201
4202                 for (retry = 0; retry < 5; retry++) {
4203                         reg = FDI_RX_IIR(pipe);
4204                         temp = I915_READ(reg);
4205                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4206                         if (temp & FDI_RX_SYMBOL_LOCK) {
4207                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4208                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4209                                 break;
4210                         }
4211                         udelay(50);
4212                 }
4213                 if (retry < 5)
4214                         break;
4215         }
4216         if (i == 4)
4217                 DRM_ERROR("FDI train 2 fail!\n");
4218
4219         DRM_DEBUG_KMS("FDI train done.\n");
4220 }
4221
4222 /* Manual link training for Ivy Bridge A0 parts */
4223 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4224                                       const struct intel_crtc_state *crtc_state)
4225 {
4226         struct drm_device *dev = crtc->base.dev;
4227         struct drm_i915_private *dev_priv = to_i915(dev);
4228         int pipe = crtc->pipe;
4229         i915_reg_t reg;
4230         u32 temp, i, j;
4231
4232         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4233            for train result */
4234         reg = FDI_RX_IMR(pipe);
4235         temp = I915_READ(reg);
4236         temp &= ~FDI_RX_SYMBOL_LOCK;
4237         temp &= ~FDI_RX_BIT_LOCK;
4238         I915_WRITE(reg, temp);
4239
4240         POSTING_READ(reg);
4241         udelay(150);
4242
4243         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4244                       I915_READ(FDI_RX_IIR(pipe)));
4245
4246         /* Try each vswing and preemphasis setting twice before moving on */
4247         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4248                 /* disable first in case we need to retry */
4249                 reg = FDI_TX_CTL(pipe);
4250                 temp = I915_READ(reg);
4251                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4252                 temp &= ~FDI_TX_ENABLE;
4253                 I915_WRITE(reg, temp);
4254
4255                 reg = FDI_RX_CTL(pipe);
4256                 temp = I915_READ(reg);
4257                 temp &= ~FDI_LINK_TRAIN_AUTO;
4258                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4259                 temp &= ~FDI_RX_ENABLE;
4260                 I915_WRITE(reg, temp);
4261
4262                 /* enable CPU FDI TX and PCH FDI RX */
4263                 reg = FDI_TX_CTL(pipe);
4264                 temp = I915_READ(reg);
4265                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4266                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4267                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4268                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4269                 temp |= snb_b_fdi_train_param[j/2];
4270                 temp |= FDI_COMPOSITE_SYNC;
4271                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4272
4273                 I915_WRITE(FDI_RX_MISC(pipe),
4274                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4275
4276                 reg = FDI_RX_CTL(pipe);
4277                 temp = I915_READ(reg);
4278                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4279                 temp |= FDI_COMPOSITE_SYNC;
4280                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4281
4282                 POSTING_READ(reg);
4283                 udelay(1); /* should be 0.5us */
4284
4285                 for (i = 0; i < 4; i++) {
4286                         reg = FDI_RX_IIR(pipe);
4287                         temp = I915_READ(reg);
4288                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4289
4290                         if (temp & FDI_RX_BIT_LOCK ||
4291                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4292                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4293                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4294                                               i);
4295                                 break;
4296                         }
4297                         udelay(1); /* should be 0.5us */
4298                 }
4299                 if (i == 4) {
4300                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4301                         continue;
4302                 }
4303
4304                 /* Train 2 */
4305                 reg = FDI_TX_CTL(pipe);
4306                 temp = I915_READ(reg);
4307                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4308                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4309                 I915_WRITE(reg, temp);
4310
4311                 reg = FDI_RX_CTL(pipe);
4312                 temp = I915_READ(reg);
4313                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4314                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4315                 I915_WRITE(reg, temp);
4316
4317                 POSTING_READ(reg);
4318                 udelay(2); /* should be 1.5us */
4319
4320                 for (i = 0; i < 4; i++) {
4321                         reg = FDI_RX_IIR(pipe);
4322                         temp = I915_READ(reg);
4323                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4324
4325                         if (temp & FDI_RX_SYMBOL_LOCK ||
4326                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4327                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4328                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4329                                               i);
4330                                 goto train_done;
4331                         }
4332                         udelay(2); /* should be 1.5us */
4333                 }
4334                 if (i == 4)
4335                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4336         }
4337
4338 train_done:
4339         DRM_DEBUG_KMS("FDI train done.\n");
4340 }
4341
4342 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4343 {
4344         struct drm_device *dev = intel_crtc->base.dev;
4345         struct drm_i915_private *dev_priv = to_i915(dev);
4346         int pipe = intel_crtc->pipe;
4347         i915_reg_t reg;
4348         u32 temp;
4349
4350         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4351         reg = FDI_RX_CTL(pipe);
4352         temp = I915_READ(reg);
4353         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4354         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4355         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4356         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4357
4358         POSTING_READ(reg);
4359         udelay(200);
4360
4361         /* Switch from Rawclk to PCDclk */
4362         temp = I915_READ(reg);
4363         I915_WRITE(reg, temp | FDI_PCDCLK);
4364
4365         POSTING_READ(reg);
4366         udelay(200);
4367
4368         /* Enable CPU FDI TX PLL, always on for Ironlake */
4369         reg = FDI_TX_CTL(pipe);
4370         temp = I915_READ(reg);
4371         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4372                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4373
4374                 POSTING_READ(reg);
4375                 udelay(100);
4376         }
4377 }
4378
4379 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4380 {
4381         struct drm_device *dev = intel_crtc->base.dev;
4382         struct drm_i915_private *dev_priv = to_i915(dev);
4383         int pipe = intel_crtc->pipe;
4384         i915_reg_t reg;
4385         u32 temp;
4386
4387         /* Switch from PCDclk to Rawclk */
4388         reg = FDI_RX_CTL(pipe);
4389         temp = I915_READ(reg);
4390         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4391
4392         /* Disable CPU FDI TX PLL */
4393         reg = FDI_TX_CTL(pipe);
4394         temp = I915_READ(reg);
4395         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4396
4397         POSTING_READ(reg);
4398         udelay(100);
4399
4400         reg = FDI_RX_CTL(pipe);
4401         temp = I915_READ(reg);
4402         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4403
4404         /* Wait for the clocks to turn off. */
4405         POSTING_READ(reg);
4406         udelay(100);
4407 }
4408
4409 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4410 {
4411         struct drm_device *dev = crtc->dev;
4412         struct drm_i915_private *dev_priv = to_i915(dev);
4413         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4414         int pipe = intel_crtc->pipe;
4415         i915_reg_t reg;
4416         u32 temp;
4417
4418         /* disable CPU FDI tx and PCH FDI rx */
4419         reg = FDI_TX_CTL(pipe);
4420         temp = I915_READ(reg);
4421         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4422         POSTING_READ(reg);
4423
4424         reg = FDI_RX_CTL(pipe);
4425         temp = I915_READ(reg);
4426         temp &= ~(0x7 << 16);
4427         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4428         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4429
4430         POSTING_READ(reg);
4431         udelay(100);
4432
4433         /* Ironlake workaround, disable clock pointer after downing FDI */
4434         if (HAS_PCH_IBX(dev_priv))
4435                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4436
4437         /* still set train pattern 1 */
4438         reg = FDI_TX_CTL(pipe);
4439         temp = I915_READ(reg);
4440         temp &= ~FDI_LINK_TRAIN_NONE;
4441         temp |= FDI_LINK_TRAIN_PATTERN_1;
4442         I915_WRITE(reg, temp);
4443
4444         reg = FDI_RX_CTL(pipe);
4445         temp = I915_READ(reg);
4446         if (HAS_PCH_CPT(dev_priv)) {
4447                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4448                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4449         } else {
4450                 temp &= ~FDI_LINK_TRAIN_NONE;
4451                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4452         }
4453         /* BPC in FDI rx is consistent with that in PIPECONF */
4454         temp &= ~(0x07 << 16);
4455         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4456         I915_WRITE(reg, temp);
4457
4458         POSTING_READ(reg);
4459         udelay(100);
4460 }
4461
4462 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4463 {
4464         struct drm_crtc *crtc;
4465         bool cleanup_done;
4466
4467         drm_for_each_crtc(crtc, &dev_priv->drm) {
4468                 struct drm_crtc_commit *commit;
4469                 spin_lock(&crtc->commit_lock);
4470                 commit = list_first_entry_or_null(&crtc->commit_list,
4471                                                   struct drm_crtc_commit, commit_entry);
4472                 cleanup_done = commit ?
4473                         try_wait_for_completion(&commit->cleanup_done) : true;
4474                 spin_unlock(&crtc->commit_lock);
4475
4476                 if (cleanup_done)
4477                         continue;
4478
4479                 drm_crtc_wait_one_vblank(crtc);
4480
4481                 return true;
4482         }
4483
4484         return false;
4485 }
4486
4487 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4488 {
4489         u32 temp;
4490
4491         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4492
4493         mutex_lock(&dev_priv->sb_lock);
4494
4495         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4496         temp |= SBI_SSCCTL_DISABLE;
4497         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4498
4499         mutex_unlock(&dev_priv->sb_lock);
4500 }
4501
4502 /* Program iCLKIP clock to the desired frequency */
4503 static void lpt_program_iclkip(struct intel_crtc *crtc)
4504 {
4505         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4506         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4507         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4508         u32 temp;
4509
4510         lpt_disable_iclkip(dev_priv);
4511
4512         /* The iCLK virtual clock root frequency is in MHz,
4513          * but the adjusted_mode->crtc_clock in in KHz. To get the
4514          * divisors, it is necessary to divide one by another, so we
4515          * convert the virtual clock precision to KHz here for higher
4516          * precision.
4517          */
4518         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4519                 u32 iclk_virtual_root_freq = 172800 * 1000;
4520                 u32 iclk_pi_range = 64;
4521                 u32 desired_divisor;
4522
4523                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4524                                                     clock << auxdiv);
4525                 divsel = (desired_divisor / iclk_pi_range) - 2;
4526                 phaseinc = desired_divisor % iclk_pi_range;
4527
4528                 /*
4529                  * Near 20MHz is a corner case which is
4530                  * out of range for the 7-bit divisor
4531                  */
4532                 if (divsel <= 0x7f)
4533                         break;
4534         }
4535
4536         /* This should not happen with any sane values */
4537         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4538                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4539         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4540                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4541
4542         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4543                         clock,
4544                         auxdiv,
4545                         divsel,
4546                         phasedir,
4547                         phaseinc);
4548
4549         mutex_lock(&dev_priv->sb_lock);
4550
4551         /* Program SSCDIVINTPHASE6 */
4552         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4553         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4554         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4555         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4556         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4557         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4558         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4559         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4560
4561         /* Program SSCAUXDIV */
4562         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4563         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4564         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4565         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4566
4567         /* Enable modulator and associated divider */
4568         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4569         temp &= ~SBI_SSCCTL_DISABLE;
4570         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4571
4572         mutex_unlock(&dev_priv->sb_lock);
4573
4574         /* Wait for initialization time */
4575         udelay(24);
4576
4577         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4578 }
4579
4580 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4581 {
4582         u32 divsel, phaseinc, auxdiv;
4583         u32 iclk_virtual_root_freq = 172800 * 1000;
4584         u32 iclk_pi_range = 64;
4585         u32 desired_divisor;
4586         u32 temp;
4587
4588         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4589                 return 0;
4590
4591         mutex_lock(&dev_priv->sb_lock);
4592
4593         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4594         if (temp & SBI_SSCCTL_DISABLE) {
4595                 mutex_unlock(&dev_priv->sb_lock);
4596                 return 0;
4597         }
4598
4599         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4600         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4601                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4602         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4603                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4604
4605         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4606         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4607                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4608
4609         mutex_unlock(&dev_priv->sb_lock);
4610
4611         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4612
4613         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4614                                  desired_divisor << auxdiv);
4615 }
4616
4617 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4618                                                 enum pipe pch_transcoder)
4619 {
4620         struct drm_device *dev = crtc->base.dev;
4621         struct drm_i915_private *dev_priv = to_i915(dev);
4622         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4623
4624         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4625                    I915_READ(HTOTAL(cpu_transcoder)));
4626         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4627                    I915_READ(HBLANK(cpu_transcoder)));
4628         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4629                    I915_READ(HSYNC(cpu_transcoder)));
4630
4631         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4632                    I915_READ(VTOTAL(cpu_transcoder)));
4633         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4634                    I915_READ(VBLANK(cpu_transcoder)));
4635         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4636                    I915_READ(VSYNC(cpu_transcoder)));
4637         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4638                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4639 }
4640
4641 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4642 {
4643         struct drm_i915_private *dev_priv = to_i915(dev);
4644         uint32_t temp;
4645
4646         temp = I915_READ(SOUTH_CHICKEN1);
4647         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4648                 return;
4649
4650         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4651         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4652
4653         temp &= ~FDI_BC_BIFURCATION_SELECT;
4654         if (enable)
4655                 temp |= FDI_BC_BIFURCATION_SELECT;
4656
4657         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4658         I915_WRITE(SOUTH_CHICKEN1, temp);
4659         POSTING_READ(SOUTH_CHICKEN1);
4660 }
4661
4662 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4663 {
4664         struct drm_device *dev = intel_crtc->base.dev;
4665
4666         switch (intel_crtc->pipe) {
4667         case PIPE_A:
4668                 break;
4669         case PIPE_B:
4670                 if (intel_crtc->config->fdi_lanes > 2)
4671                         cpt_set_fdi_bc_bifurcation(dev, false);
4672                 else
4673                         cpt_set_fdi_bc_bifurcation(dev, true);
4674
4675                 break;
4676         case PIPE_C:
4677                 cpt_set_fdi_bc_bifurcation(dev, true);
4678
4679                 break;
4680         default:
4681                 BUG();
4682         }
4683 }
4684
4685 /*
4686  * Finds the encoder associated with the given CRTC. This can only be
4687  * used when we know that the CRTC isn't feeding multiple encoders!
4688  */
4689 static struct intel_encoder *
4690 intel_get_crtc_new_encoder(const struct intel_atomic_state *state,
4691                            const struct intel_crtc_state *crtc_state)
4692 {
4693         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4694         const struct drm_connector_state *connector_state;
4695         const struct drm_connector *connector;
4696         struct intel_encoder *encoder = NULL;
4697         int num_encoders = 0;
4698         int i;
4699
4700         for_each_new_connector_in_state(&state->base, connector, connector_state, i) {
4701                 if (connector_state->crtc != &crtc->base)
4702                         continue;
4703
4704                 encoder = to_intel_encoder(connector_state->best_encoder);
4705                 num_encoders++;
4706         }
4707
4708         WARN(num_encoders != 1, "%d encoders for pipe %c\n",
4709              num_encoders, pipe_name(crtc->pipe));
4710
4711         return encoder;
4712 }
4713
4714 /*
4715  * Enable PCH resources required for PCH ports:
4716  *   - PCH PLLs
4717  *   - FDI training & RX/TX
4718  *   - update transcoder timings
4719  *   - DP transcoding bits
4720  *   - transcoder
4721  */
4722 static void ironlake_pch_enable(const struct intel_atomic_state *state,
4723                                 const struct intel_crtc_state *crtc_state)
4724 {
4725         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4726         struct drm_device *dev = crtc->base.dev;
4727         struct drm_i915_private *dev_priv = to_i915(dev);
4728         int pipe = crtc->pipe;
4729         u32 temp;
4730
4731         assert_pch_transcoder_disabled(dev_priv, pipe);
4732
4733         if (IS_IVYBRIDGE(dev_priv))
4734                 ivybridge_update_fdi_bc_bifurcation(crtc);
4735
4736         /* Write the TU size bits before fdi link training, so that error
4737          * detection works. */
4738         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4739                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4740
4741         /* For PCH output, training FDI link */
4742         dev_priv->display.fdi_link_train(crtc, crtc_state);
4743
4744         /* We need to program the right clock selection before writing the pixel
4745          * mutliplier into the DPLL. */
4746         if (HAS_PCH_CPT(dev_priv)) {
4747                 u32 sel;
4748
4749                 temp = I915_READ(PCH_DPLL_SEL);
4750                 temp |= TRANS_DPLL_ENABLE(pipe);
4751                 sel = TRANS_DPLLB_SEL(pipe);
4752                 if (crtc_state->shared_dpll ==
4753                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4754                         temp |= sel;
4755                 else
4756                         temp &= ~sel;
4757                 I915_WRITE(PCH_DPLL_SEL, temp);
4758         }
4759
4760         /* XXX: pch pll's can be enabled any time before we enable the PCH
4761          * transcoder, and we actually should do this to not upset any PCH
4762          * transcoder that already use the clock when we share it.
4763          *
4764          * Note that enable_shared_dpll tries to do the right thing, but
4765          * get_shared_dpll unconditionally resets the pll - we need that to have
4766          * the right LVDS enable sequence. */
4767         intel_enable_shared_dpll(crtc);
4768
4769         /* set transcoder timing, panel must allow it */
4770         assert_panel_unlocked(dev_priv, pipe);
4771         ironlake_pch_transcoder_set_timings(crtc, pipe);
4772
4773         intel_fdi_normal_train(crtc);
4774
4775         /* For PCH DP, enable TRANS_DP_CTL */
4776         if (HAS_PCH_CPT(dev_priv) &&
4777             intel_crtc_has_dp_encoder(crtc_state)) {
4778                 const struct drm_display_mode *adjusted_mode =
4779                         &crtc_state->base.adjusted_mode;
4780                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4781                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4782                 enum port port;
4783
4784                 temp = I915_READ(reg);
4785                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4786                           TRANS_DP_SYNC_MASK |
4787                           TRANS_DP_BPC_MASK);
4788                 temp |= TRANS_DP_OUTPUT_ENABLE;
4789                 temp |= bpc << 9; /* same format but at 11:9 */
4790
4791                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4792                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4793                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4794                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4795
4796                 port = intel_get_crtc_new_encoder(state, crtc_state)->port;
4797                 WARN_ON(port < PORT_B || port > PORT_D);
4798                 temp |= TRANS_DP_PORT_SEL(port);
4799
4800                 I915_WRITE(reg, temp);
4801         }
4802
4803         ironlake_enable_pch_transcoder(dev_priv, pipe);
4804 }
4805
4806 static void lpt_pch_enable(const struct intel_atomic_state *state,
4807                            const struct intel_crtc_state *crtc_state)
4808 {
4809         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4810         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4811         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4812
4813         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4814
4815         lpt_program_iclkip(crtc);
4816
4817         /* Set transcoder timing. */
4818         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4819
4820         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4821 }
4822
4823 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4824 {
4825         struct drm_i915_private *dev_priv = to_i915(dev);
4826         i915_reg_t dslreg = PIPEDSL(pipe);
4827         u32 temp;
4828
4829         temp = I915_READ(dslreg);
4830         udelay(500);
4831         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4832                 if (wait_for(I915_READ(dslreg) != temp, 5))
4833                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4834         }
4835 }
4836
4837 /*
4838  * The hardware phase 0.0 refers to the center of the pixel.
4839  * We want to start from the top/left edge which is phase
4840  * -0.5. That matches how the hardware calculates the scaling
4841  * factors (from top-left of the first pixel to bottom-right
4842  * of the last pixel, as opposed to the pixel centers).
4843  *
4844  * For 4:2:0 subsampled chroma planes we obviously have to
4845  * adjust that so that the chroma sample position lands in
4846  * the right spot.
4847  *
4848  * Note that for packed YCbCr 4:2:2 formats there is no way to
4849  * control chroma siting. The hardware simply replicates the
4850  * chroma samples for both of the luma samples, and thus we don't
4851  * actually get the expected MPEG2 chroma siting convention :(
4852  * The same behaviour is observed on pre-SKL platforms as well.
4853  */
4854 u16 skl_scaler_calc_phase(int sub, bool chroma_cosited)
4855 {
4856         int phase = -0x8000;
4857         u16 trip = 0;
4858
4859         if (chroma_cosited)
4860                 phase += (sub - 1) * 0x8000 / sub;
4861
4862         if (phase < 0)
4863                 phase = 0x10000 + phase;
4864         else
4865                 trip = PS_PHASE_TRIP;
4866
4867         return ((phase >> 2) & PS_PHASE_MASK) | trip;
4868 }
4869
4870 static int
4871 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4872                   unsigned int scaler_user, int *scaler_id,
4873                   int src_w, int src_h, int dst_w, int dst_h,
4874                   bool plane_scaler_check,
4875                   uint32_t pixel_format)
4876 {
4877         struct intel_crtc_scaler_state *scaler_state =
4878                 &crtc_state->scaler_state;
4879         struct intel_crtc *intel_crtc =
4880                 to_intel_crtc(crtc_state->base.crtc);
4881         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4882         const struct drm_display_mode *adjusted_mode =
4883                 &crtc_state->base.adjusted_mode;
4884         int need_scaling;
4885
4886         /*
4887          * Src coordinates are already rotated by 270 degrees for
4888          * the 90/270 degree plane rotation cases (to match the
4889          * GTT mapping), hence no need to account for rotation here.
4890          */
4891         need_scaling = src_w != dst_w || src_h != dst_h;
4892
4893         if (plane_scaler_check)
4894                 if (pixel_format == DRM_FORMAT_NV12)
4895                         need_scaling = true;
4896
4897         if (crtc_state->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4898                 need_scaling = true;
4899
4900         /*
4901          * Scaling/fitting not supported in IF-ID mode in GEN9+
4902          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4903          * Once NV12 is enabled, handle it here while allocating scaler
4904          * for NV12.
4905          */
4906         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4907             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4908                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4909                 return -EINVAL;
4910         }
4911
4912         /*
4913          * if plane is being disabled or scaler is no more required or force detach
4914          *  - free scaler binded to this plane/crtc
4915          *  - in order to do this, update crtc->scaler_usage
4916          *
4917          * Here scaler state in crtc_state is set free so that
4918          * scaler can be assigned to other user. Actual register
4919          * update to free the scaler is done in plane/panel-fit programming.
4920          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4921          */
4922         if (force_detach || !need_scaling) {
4923                 if (*scaler_id >= 0) {
4924                         scaler_state->scaler_users &= ~(1 << scaler_user);
4925                         scaler_state->scalers[*scaler_id].in_use = 0;
4926
4927                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4928                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4929                                 intel_crtc->pipe, scaler_user, *scaler_id,
4930                                 scaler_state->scaler_users);
4931                         *scaler_id = -1;
4932                 }
4933                 return 0;
4934         }
4935
4936         if (plane_scaler_check && pixel_format == DRM_FORMAT_NV12 &&
4937             (src_h < SKL_MIN_YUV_420_SRC_H || src_w < SKL_MIN_YUV_420_SRC_W)) {
4938                 DRM_DEBUG_KMS("NV12: src dimensions not met\n");
4939                 return -EINVAL;
4940         }
4941
4942         /* range checks */
4943         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4944             dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4945             (IS_GEN11(dev_priv) &&
4946              (src_w > ICL_MAX_SRC_W || src_h > ICL_MAX_SRC_H ||
4947               dst_w > ICL_MAX_DST_W || dst_h > ICL_MAX_DST_H)) ||
4948             (!IS_GEN11(dev_priv) &&
4949              (src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4950               dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H))) {
4951                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4952                         "size is out of scaler range\n",
4953                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4954                 return -EINVAL;
4955         }
4956
4957         /* mark this plane as a scaler user in crtc_state */
4958         scaler_state->scaler_users |= (1 << scaler_user);
4959         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4960                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4961                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4962                 scaler_state->scaler_users);
4963
4964         return 0;
4965 }
4966
4967 /**
4968  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4969  *
4970  * @state: crtc's scaler state
4971  *
4972  * Return
4973  *     0 - scaler_usage updated successfully
4974  *    error - requested scaling cannot be supported or other error condition
4975  */
4976 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4977 {
4978         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4979
4980         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4981                                  &state->scaler_state.scaler_id,
4982                                  state->pipe_src_w, state->pipe_src_h,
4983                                  adjusted_mode->crtc_hdisplay,
4984                                  adjusted_mode->crtc_vdisplay, false, 0);
4985 }
4986
4987 /**
4988  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4989  * @crtc_state: crtc's scaler state
4990  * @plane_state: atomic plane state to update
4991  *
4992  * Return
4993  *     0 - scaler_usage updated successfully
4994  *    error - requested scaling cannot be supported or other error condition
4995  */
4996 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4997                                    struct intel_plane_state *plane_state)
4998 {
4999
5000         struct intel_plane *intel_plane =
5001                 to_intel_plane(plane_state->base.plane);
5002         struct drm_framebuffer *fb = plane_state->base.fb;
5003         int ret;
5004
5005         bool force_detach = !fb || !plane_state->base.visible;
5006
5007         ret = skl_update_scaler(crtc_state, force_detach,
5008                                 drm_plane_index(&intel_plane->base),
5009                                 &plane_state->scaler_id,
5010                                 drm_rect_width(&plane_state->base.src) >> 16,
5011                                 drm_rect_height(&plane_state->base.src) >> 16,
5012                                 drm_rect_width(&plane_state->base.dst),
5013                                 drm_rect_height(&plane_state->base.dst),
5014                                 fb ? true : false, fb ? fb->format->format : 0);
5015
5016         if (ret || plane_state->scaler_id < 0)
5017                 return ret;
5018
5019         /* check colorkey */
5020         if (plane_state->ckey.flags) {
5021                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
5022                               intel_plane->base.base.id,
5023                               intel_plane->base.name);
5024                 return -EINVAL;
5025         }
5026
5027         /* Check src format */
5028         switch (fb->format->format) {
5029         case DRM_FORMAT_RGB565:
5030         case DRM_FORMAT_XBGR8888:
5031         case DRM_FORMAT_XRGB8888:
5032         case DRM_FORMAT_ABGR8888:
5033         case DRM_FORMAT_ARGB8888:
5034         case DRM_FORMAT_XRGB2101010:
5035         case DRM_FORMAT_XBGR2101010:
5036         case DRM_FORMAT_YUYV:
5037         case DRM_FORMAT_YVYU:
5038         case DRM_FORMAT_UYVY:
5039         case DRM_FORMAT_VYUY:
5040         case DRM_FORMAT_NV12:
5041                 break;
5042         default:
5043                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
5044                               intel_plane->base.base.id, intel_plane->base.name,
5045                               fb->base.id, fb->format->format);
5046                 return -EINVAL;
5047         }
5048
5049         return 0;
5050 }
5051
5052 static void skylake_scaler_disable(struct intel_crtc *crtc)
5053 {
5054         int i;
5055
5056         for (i = 0; i < crtc->num_scalers; i++)
5057                 skl_detach_scaler(crtc, i);
5058 }
5059
5060 static void skylake_pfit_enable(struct intel_crtc *crtc)
5061 {
5062         struct drm_device *dev = crtc->base.dev;
5063         struct drm_i915_private *dev_priv = to_i915(dev);
5064         int pipe = crtc->pipe;
5065         struct intel_crtc_scaler_state *scaler_state =
5066                 &crtc->config->scaler_state;
5067
5068         if (crtc->config->pch_pfit.enabled) {
5069                 u16 uv_rgb_hphase, uv_rgb_vphase;
5070                 int id;
5071
5072                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
5073                         return;
5074
5075                 uv_rgb_hphase = skl_scaler_calc_phase(1, false);
5076                 uv_rgb_vphase = skl_scaler_calc_phase(1, false);
5077
5078                 id = scaler_state->scaler_id;
5079                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
5080                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
5081                 I915_WRITE_FW(SKL_PS_VPHASE(pipe, id),
5082                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_vphase));
5083                 I915_WRITE_FW(SKL_PS_HPHASE(pipe, id),
5084                               PS_Y_PHASE(0) | PS_UV_RGB_PHASE(uv_rgb_hphase));
5085                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
5086                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
5087         }
5088 }
5089
5090 static void ironlake_pfit_enable(struct intel_crtc *crtc)
5091 {
5092         struct drm_device *dev = crtc->base.dev;
5093         struct drm_i915_private *dev_priv = to_i915(dev);
5094         int pipe = crtc->pipe;
5095
5096         if (crtc->config->pch_pfit.enabled) {
5097                 /* Force use of hard-coded filter coefficients
5098                  * as some pre-programmed values are broken,
5099                  * e.g. x201.
5100                  */
5101                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
5102                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
5103                                                  PF_PIPE_SEL_IVB(pipe));
5104                 else
5105                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
5106                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
5107                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
5108         }
5109 }
5110
5111 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
5112 {
5113         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5114         struct drm_device *dev = crtc->base.dev;
5115         struct drm_i915_private *dev_priv = to_i915(dev);
5116
5117         if (!crtc_state->ips_enabled)
5118                 return;
5119
5120         /*
5121          * We can only enable IPS after we enable a plane and wait for a vblank
5122          * This function is called from post_plane_update, which is run after
5123          * a vblank wait.
5124          */
5125         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
5126
5127         if (IS_BROADWELL(dev_priv)) {
5128                 mutex_lock(&dev_priv->pcu_lock);
5129                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
5130                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
5131                 mutex_unlock(&dev_priv->pcu_lock);
5132                 /* Quoting Art Runyan: "its not safe to expect any particular
5133                  * value in IPS_CTL bit 31 after enabling IPS through the
5134                  * mailbox." Moreover, the mailbox may return a bogus state,
5135                  * so we need to just enable it and continue on.
5136                  */
5137         } else {
5138                 I915_WRITE(IPS_CTL, IPS_ENABLE);
5139                 /* The bit only becomes 1 in the next vblank, so this wait here
5140                  * is essentially intel_wait_for_vblank. If we don't have this
5141                  * and don't wait for vblanks until the end of crtc_enable, then
5142                  * the HW state readout code will complain that the expected
5143                  * IPS_CTL value is not the one we read. */
5144                 if (intel_wait_for_register(dev_priv,
5145                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
5146                                             50))
5147                         DRM_ERROR("Timed out waiting for IPS enable\n");
5148         }
5149 }
5150
5151 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
5152 {
5153         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
5154         struct drm_device *dev = crtc->base.dev;
5155         struct drm_i915_private *dev_priv = to_i915(dev);
5156
5157         if (!crtc_state->ips_enabled)
5158                 return;
5159
5160         if (IS_BROADWELL(dev_priv)) {
5161                 mutex_lock(&dev_priv->pcu_lock);
5162                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
5163                 mutex_unlock(&dev_priv->pcu_lock);
5164                 /*
5165                  * Wait for PCODE to finish disabling IPS. The BSpec specified
5166                  * 42ms timeout value leads to occasional timeouts so use 100ms
5167                  * instead.
5168                  */
5169                 if (intel_wait_for_register(dev_priv,
5170                                             IPS_CTL, IPS_ENABLE, 0,
5171                                             100))
5172                         DRM_ERROR("Timed out waiting for IPS disable\n");
5173         } else {
5174                 I915_WRITE(IPS_CTL, 0);
5175                 POSTING_READ(IPS_CTL);
5176         }
5177
5178         /* We need to wait for a vblank before we can disable the plane. */
5179         intel_wait_for_vblank(dev_priv, crtc->pipe);
5180 }
5181
5182 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
5183 {
5184         if (intel_crtc->overlay) {
5185                 struct drm_device *dev = intel_crtc->base.dev;
5186
5187                 mutex_lock(&dev->struct_mutex);
5188                 (void) intel_overlay_switch_off(intel_crtc->overlay);
5189                 mutex_unlock(&dev->struct_mutex);
5190         }
5191
5192         /* Let userspace switch the overlay on again. In most cases userspace
5193          * has to recompute where to put it anyway.
5194          */
5195 }
5196
5197 /**
5198  * intel_post_enable_primary - Perform operations after enabling primary plane
5199  * @crtc: the CRTC whose primary plane was just enabled
5200  * @new_crtc_state: the enabling state
5201  *
5202  * Performs potentially sleeping operations that must be done after the primary
5203  * plane is enabled, such as updating FBC and IPS.  Note that this may be
5204  * called due to an explicit primary plane update, or due to an implicit
5205  * re-enable that is caused when a sprite plane is updated to no longer
5206  * completely hide the primary plane.
5207  */
5208 static void
5209 intel_post_enable_primary(struct drm_crtc *crtc,
5210                           const struct intel_crtc_state *new_crtc_state)
5211 {
5212         struct drm_device *dev = crtc->dev;
5213         struct drm_i915_private *dev_priv = to_i915(dev);
5214         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5215         int pipe = intel_crtc->pipe;
5216
5217         /*
5218          * Gen2 reports pipe underruns whenever all planes are disabled.
5219          * So don't enable underrun reporting before at least some planes
5220          * are enabled.
5221          * FIXME: Need to fix the logic to work when we turn off all planes
5222          * but leave the pipe running.
5223          */
5224         if (IS_GEN2(dev_priv))
5225                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5226
5227         /* Underruns don't always raise interrupts, so check manually. */
5228         intel_check_cpu_fifo_underruns(dev_priv);
5229         intel_check_pch_fifo_underruns(dev_priv);
5230 }
5231
5232 /* FIXME get rid of this and use pre_plane_update */
5233 static void
5234 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5235 {
5236         struct drm_device *dev = crtc->dev;
5237         struct drm_i915_private *dev_priv = to_i915(dev);
5238         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5239         int pipe = intel_crtc->pipe;
5240
5241         /*
5242          * Gen2 reports pipe underruns whenever all planes are disabled.
5243          * So disable underrun reporting before all the planes get disabled.
5244          */
5245         if (IS_GEN2(dev_priv))
5246                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5247
5248         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5249
5250         /*
5251          * Vblank time updates from the shadow to live plane control register
5252          * are blocked if the memory self-refresh mode is active at that
5253          * moment. So to make sure the plane gets truly disabled, disable
5254          * first the self-refresh mode. The self-refresh enable bit in turn
5255          * will be checked/applied by the HW only at the next frame start
5256          * event which is after the vblank start event, so we need to have a
5257          * wait-for-vblank between disabling the plane and the pipe.
5258          */
5259         if (HAS_GMCH_DISPLAY(dev_priv) &&
5260             intel_set_memory_cxsr(dev_priv, false))
5261                 intel_wait_for_vblank(dev_priv, pipe);
5262 }
5263
5264 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5265                                        const struct intel_crtc_state *new_crtc_state)
5266 {
5267         if (!old_crtc_state->ips_enabled)
5268                 return false;
5269
5270         if (needs_modeset(&new_crtc_state->base))
5271                 return true;
5272
5273         return !new_crtc_state->ips_enabled;
5274 }
5275
5276 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5277                                        const struct intel_crtc_state *new_crtc_state)
5278 {
5279         if (!new_crtc_state->ips_enabled)
5280                 return false;
5281
5282         if (needs_modeset(&new_crtc_state->base))
5283                 return true;
5284
5285         /*
5286          * We can't read out IPS on broadwell, assume the worst and
5287          * forcibly enable IPS on the first fastset.
5288          */
5289         if (new_crtc_state->update_pipe &&
5290             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5291                 return true;
5292
5293         return !old_crtc_state->ips_enabled;
5294 }
5295
5296 static bool needs_nv12_wa(struct drm_i915_private *dev_priv,
5297                           const struct intel_crtc_state *crtc_state)
5298 {
5299         if (!crtc_state->nv12_planes)
5300                 return false;
5301
5302         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
5303                 return false;
5304
5305         if ((INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv)) ||
5306             IS_CANNONLAKE(dev_priv))
5307                 return true;
5308
5309         return false;
5310 }
5311
5312 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5313 {
5314         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5315         struct drm_device *dev = crtc->base.dev;
5316         struct drm_i915_private *dev_priv = to_i915(dev);
5317         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5318         struct intel_crtc_state *pipe_config =
5319                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5320                                                 crtc);
5321         struct drm_plane *primary = crtc->base.primary;
5322         struct drm_plane_state *old_primary_state =
5323                 drm_atomic_get_old_plane_state(old_state, primary);
5324
5325         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5326
5327         if (pipe_config->update_wm_post && pipe_config->base.active)
5328                 intel_update_watermarks(crtc);
5329
5330         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5331                 hsw_enable_ips(pipe_config);
5332
5333         if (old_primary_state) {
5334                 struct drm_plane_state *new_primary_state =
5335                         drm_atomic_get_new_plane_state(old_state, primary);
5336
5337                 intel_fbc_post_update(crtc);
5338
5339                 if (new_primary_state->visible &&
5340                     (needs_modeset(&pipe_config->base) ||
5341                      !old_primary_state->visible))
5342                         intel_post_enable_primary(&crtc->base, pipe_config);
5343         }
5344
5345         /* Display WA 827 */
5346         if (needs_nv12_wa(dev_priv, old_crtc_state) &&
5347             !needs_nv12_wa(dev_priv, pipe_config)) {
5348                 skl_wa_clkgate(dev_priv, crtc->pipe, false);
5349                 skl_wa_528(dev_priv, crtc->pipe, false);
5350         }
5351 }
5352
5353 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5354                                    struct intel_crtc_state *pipe_config)
5355 {
5356         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5357         struct drm_device *dev = crtc->base.dev;
5358         struct drm_i915_private *dev_priv = to_i915(dev);
5359         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5360         struct drm_plane *primary = crtc->base.primary;
5361         struct drm_plane_state *old_primary_state =
5362                 drm_atomic_get_old_plane_state(old_state, primary);
5363         bool modeset = needs_modeset(&pipe_config->base);
5364         struct intel_atomic_state *old_intel_state =
5365                 to_intel_atomic_state(old_state);
5366
5367         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5368                 hsw_disable_ips(old_crtc_state);
5369
5370         if (old_primary_state) {
5371                 struct intel_plane_state *new_primary_state =
5372                         intel_atomic_get_new_plane_state(old_intel_state,
5373                                                          to_intel_plane(primary));
5374
5375                 intel_fbc_pre_update(crtc, pipe_config, new_primary_state);
5376                 /*
5377                  * Gen2 reports pipe underruns whenever all planes are disabled.
5378                  * So disable underrun reporting before all the planes get disabled.
5379                  */
5380                 if (IS_GEN2(dev_priv) && old_primary_state->visible &&
5381                     (modeset || !new_primary_state->base.visible))
5382                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5383         }
5384
5385         /* Display WA 827 */
5386         if (!needs_nv12_wa(dev_priv, old_crtc_state) &&
5387             needs_nv12_wa(dev_priv, pipe_config)) {
5388                 skl_wa_clkgate(dev_priv, crtc->pipe, true);
5389                 skl_wa_528(dev_priv, crtc->pipe, true);
5390         }
5391
5392         /*
5393          * Vblank time updates from the shadow to live plane control register
5394          * are blocked if the memory self-refresh mode is active at that
5395          * moment. So to make sure the plane gets truly disabled, disable
5396          * first the self-refresh mode. The self-refresh enable bit in turn
5397          * will be checked/applied by the HW only at the next frame start
5398          * event which is after the vblank start event, so we need to have a
5399          * wait-for-vblank between disabling the plane and the pipe.
5400          */
5401         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5402             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5403                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5404
5405         /*
5406          * IVB workaround: must disable low power watermarks for at least
5407          * one frame before enabling scaling.  LP watermarks can be re-enabled
5408          * when scaling is disabled.
5409          *
5410          * WaCxSRDisabledForSpriteScaling:ivb
5411          */
5412         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5413                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5414
5415         /*
5416          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5417          * watermark programming here.
5418          */
5419         if (needs_modeset(&pipe_config->base))
5420                 return;
5421
5422         /*
5423          * For platforms that support atomic watermarks, program the
5424          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5425          * will be the intermediate values that are safe for both pre- and
5426          * post- vblank; when vblank happens, the 'active' values will be set
5427          * to the final 'target' values and we'll do this again to get the
5428          * optimal watermarks.  For gen9+ platforms, the values we program here
5429          * will be the final target values which will get automatically latched
5430          * at vblank time; no further programming will be necessary.
5431          *
5432          * If a platform hasn't been transitioned to atomic watermarks yet,
5433          * we'll continue to update watermarks the old way, if flags tell
5434          * us to.
5435          */
5436         if (dev_priv->display.initial_watermarks != NULL)
5437                 dev_priv->display.initial_watermarks(old_intel_state,
5438                                                      pipe_config);
5439         else if (pipe_config->update_wm_pre)
5440                 intel_update_watermarks(crtc);
5441 }
5442
5443 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5444 {
5445         struct drm_device *dev = crtc->dev;
5446         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5447         struct drm_plane *p;
5448         int pipe = intel_crtc->pipe;
5449
5450         intel_crtc_dpms_overlay_disable(intel_crtc);
5451
5452         drm_for_each_plane_mask(p, dev, plane_mask)
5453                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5454
5455         /*
5456          * FIXME: Once we grow proper nuclear flip support out of this we need
5457          * to compute the mask of flip planes precisely. For the time being
5458          * consider this a flip to a NULL plane.
5459          */
5460         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5461 }
5462
5463 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5464                                           struct intel_crtc_state *crtc_state,
5465                                           struct drm_atomic_state *old_state)
5466 {
5467         struct drm_connector_state *conn_state;
5468         struct drm_connector *conn;
5469         int i;
5470
5471         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5472                 struct intel_encoder *encoder =
5473                         to_intel_encoder(conn_state->best_encoder);
5474
5475                 if (conn_state->crtc != crtc)
5476                         continue;
5477
5478                 if (encoder->pre_pll_enable)
5479                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5480         }
5481 }
5482
5483 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5484                                       struct intel_crtc_state *crtc_state,
5485                                       struct drm_atomic_state *old_state)
5486 {
5487         struct drm_connector_state *conn_state;
5488         struct drm_connector *conn;
5489         int i;
5490
5491         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5492                 struct intel_encoder *encoder =
5493                         to_intel_encoder(conn_state->best_encoder);
5494
5495                 if (conn_state->crtc != crtc)
5496                         continue;
5497
5498                 if (encoder->pre_enable)
5499                         encoder->pre_enable(encoder, crtc_state, conn_state);
5500         }
5501 }
5502
5503 static void intel_encoders_enable(struct drm_crtc *crtc,
5504                                   struct intel_crtc_state *crtc_state,
5505                                   struct drm_atomic_state *old_state)
5506 {
5507         struct drm_connector_state *conn_state;
5508         struct drm_connector *conn;
5509         int i;
5510
5511         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5512                 struct intel_encoder *encoder =
5513                         to_intel_encoder(conn_state->best_encoder);
5514
5515                 if (conn_state->crtc != crtc)
5516                         continue;
5517
5518                 encoder->enable(encoder, crtc_state, conn_state);
5519                 intel_opregion_notify_encoder(encoder, true);
5520         }
5521 }
5522
5523 static void intel_encoders_disable(struct drm_crtc *crtc,
5524                                    struct intel_crtc_state *old_crtc_state,
5525                                    struct drm_atomic_state *old_state)
5526 {
5527         struct drm_connector_state *old_conn_state;
5528         struct drm_connector *conn;
5529         int i;
5530
5531         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5532                 struct intel_encoder *encoder =
5533                         to_intel_encoder(old_conn_state->best_encoder);
5534
5535                 if (old_conn_state->crtc != crtc)
5536                         continue;
5537
5538                 intel_opregion_notify_encoder(encoder, false);
5539                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5540         }
5541 }
5542
5543 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5544                                         struct intel_crtc_state *old_crtc_state,
5545                                         struct drm_atomic_state *old_state)
5546 {
5547         struct drm_connector_state *old_conn_state;
5548         struct drm_connector *conn;
5549         int i;
5550
5551         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5552                 struct intel_encoder *encoder =
5553                         to_intel_encoder(old_conn_state->best_encoder);
5554
5555                 if (old_conn_state->crtc != crtc)
5556                         continue;
5557
5558                 if (encoder->post_disable)
5559                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5560         }
5561 }
5562
5563 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5564                                             struct intel_crtc_state *old_crtc_state,
5565                                             struct drm_atomic_state *old_state)
5566 {
5567         struct drm_connector_state *old_conn_state;
5568         struct drm_connector *conn;
5569         int i;
5570
5571         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5572                 struct intel_encoder *encoder =
5573                         to_intel_encoder(old_conn_state->best_encoder);
5574
5575                 if (old_conn_state->crtc != crtc)
5576                         continue;
5577
5578                 if (encoder->post_pll_disable)
5579                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5580         }
5581 }
5582
5583 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5584                                  struct drm_atomic_state *old_state)
5585 {
5586         struct drm_crtc *crtc = pipe_config->base.crtc;
5587         struct drm_device *dev = crtc->dev;
5588         struct drm_i915_private *dev_priv = to_i915(dev);
5589         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5590         int pipe = intel_crtc->pipe;
5591         struct intel_atomic_state *old_intel_state =
5592                 to_intel_atomic_state(old_state);
5593
5594         if (WARN_ON(intel_crtc->active))
5595                 return;
5596
5597         /*
5598          * Sometimes spurious CPU pipe underruns happen during FDI
5599          * training, at least with VGA+HDMI cloning. Suppress them.
5600          *
5601          * On ILK we get an occasional spurious CPU pipe underruns
5602          * between eDP port A enable and vdd enable. Also PCH port
5603          * enable seems to result in the occasional CPU pipe underrun.
5604          *
5605          * Spurious PCH underruns also occur during PCH enabling.
5606          */
5607         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5608         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5609
5610         if (intel_crtc->config->has_pch_encoder)
5611                 intel_prepare_shared_dpll(intel_crtc);
5612
5613         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5614                 intel_dp_set_m_n(intel_crtc, M1_N1);
5615
5616         intel_set_pipe_timings(intel_crtc);
5617         intel_set_pipe_src_size(intel_crtc);
5618
5619         if (intel_crtc->config->has_pch_encoder) {
5620                 intel_cpu_transcoder_set_m_n(intel_crtc,
5621                                      &intel_crtc->config->fdi_m_n, NULL);
5622         }
5623
5624         ironlake_set_pipeconf(crtc);
5625
5626         intel_crtc->active = true;
5627
5628         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5629
5630         if (intel_crtc->config->has_pch_encoder) {
5631                 /* Note: FDI PLL enabling _must_ be done before we enable the
5632                  * cpu pipes, hence this is separate from all the other fdi/pch
5633                  * enabling. */
5634                 ironlake_fdi_pll_enable(intel_crtc);
5635         } else {
5636                 assert_fdi_tx_disabled(dev_priv, pipe);
5637                 assert_fdi_rx_disabled(dev_priv, pipe);
5638         }
5639
5640         ironlake_pfit_enable(intel_crtc);
5641
5642         /*
5643          * On ILK+ LUT must be loaded before the pipe is running but with
5644          * clocks enabled
5645          */
5646         intel_color_load_luts(&pipe_config->base);
5647
5648         if (dev_priv->display.initial_watermarks != NULL)
5649                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5650         intel_enable_pipe(pipe_config);
5651
5652         if (intel_crtc->config->has_pch_encoder)
5653                 ironlake_pch_enable(old_intel_state, pipe_config);
5654
5655         assert_vblank_disabled(crtc);
5656         drm_crtc_vblank_on(crtc);
5657
5658         intel_encoders_enable(crtc, pipe_config, old_state);
5659
5660         if (HAS_PCH_CPT(dev_priv))
5661                 cpt_verify_modeset(dev, intel_crtc->pipe);
5662
5663         /*
5664          * Must wait for vblank to avoid spurious PCH FIFO underruns.
5665          * And a second vblank wait is needed at least on ILK with
5666          * some interlaced HDMI modes. Let's do the double wait always
5667          * in case there are more corner cases we don't know about.
5668          */
5669         if (intel_crtc->config->has_pch_encoder) {
5670                 intel_wait_for_vblank(dev_priv, pipe);
5671                 intel_wait_for_vblank(dev_priv, pipe);
5672         }
5673         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5674         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5675 }
5676
5677 /* IPS only exists on ULT machines and is tied to pipe A. */
5678 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5679 {
5680         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5681 }
5682
5683 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5684                                             enum pipe pipe, bool apply)
5685 {
5686         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5687         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5688
5689         if (apply)
5690                 val |= mask;
5691         else
5692                 val &= ~mask;
5693
5694         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5695 }
5696
5697 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5698 {
5699         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5700         enum pipe pipe = crtc->pipe;
5701         uint32_t val;
5702
5703         val = MBUS_DBOX_BW_CREDIT(1) | MBUS_DBOX_A_CREDIT(2);
5704
5705         /* Program B credit equally to all pipes */
5706         val |= MBUS_DBOX_B_CREDIT(24 / INTEL_INFO(dev_priv)->num_pipes);
5707
5708         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5709 }
5710
5711 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5712                                 struct drm_atomic_state *old_state)
5713 {
5714         struct drm_crtc *crtc = pipe_config->base.crtc;
5715         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5716         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5717         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5718         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5719         struct intel_atomic_state *old_intel_state =
5720                 to_intel_atomic_state(old_state);
5721         bool psl_clkgate_wa;
5722         u32 pipe_chicken;
5723
5724         if (WARN_ON(intel_crtc->active))
5725                 return;
5726
5727         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5728
5729         if (intel_crtc->config->shared_dpll)
5730                 intel_enable_shared_dpll(intel_crtc);
5731
5732         if (INTEL_GEN(dev_priv) >= 11)
5733                 icl_map_plls_to_ports(crtc, pipe_config, old_state);
5734
5735         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5736
5737         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5738                 intel_dp_set_m_n(intel_crtc, M1_N1);
5739
5740         if (!transcoder_is_dsi(cpu_transcoder))
5741                 intel_set_pipe_timings(intel_crtc);
5742
5743         intel_set_pipe_src_size(intel_crtc);
5744
5745         if (cpu_transcoder != TRANSCODER_EDP &&
5746             !transcoder_is_dsi(cpu_transcoder)) {
5747                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5748                            intel_crtc->config->pixel_multiplier - 1);
5749         }
5750
5751         if (intel_crtc->config->has_pch_encoder) {
5752                 intel_cpu_transcoder_set_m_n(intel_crtc,
5753                                      &intel_crtc->config->fdi_m_n, NULL);
5754         }
5755
5756         if (!transcoder_is_dsi(cpu_transcoder))
5757                 haswell_set_pipeconf(crtc);
5758
5759         haswell_set_pipemisc(crtc);
5760
5761         intel_color_set_csc(&pipe_config->base);
5762
5763         intel_crtc->active = true;
5764
5765         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5766         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5767                          intel_crtc->config->pch_pfit.enabled;
5768         if (psl_clkgate_wa)
5769                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5770
5771         if (INTEL_GEN(dev_priv) >= 9)
5772                 skylake_pfit_enable(intel_crtc);
5773         else
5774                 ironlake_pfit_enable(intel_crtc);
5775
5776         /*
5777          * On ILK+ LUT must be loaded before the pipe is running but with
5778          * clocks enabled
5779          */
5780         intel_color_load_luts(&pipe_config->base);
5781
5782         /*
5783          * Display WA #1153: enable hardware to bypass the alpha math
5784          * and rounding for per-pixel values 00 and 0xff
5785          */
5786         if (INTEL_GEN(dev_priv) >= 11) {
5787                 pipe_chicken = I915_READ(PIPE_CHICKEN(pipe));
5788                 if (!(pipe_chicken & PER_PIXEL_ALPHA_BYPASS_EN))
5789                         I915_WRITE_FW(PIPE_CHICKEN(pipe),
5790                                       pipe_chicken | PER_PIXEL_ALPHA_BYPASS_EN);
5791         }
5792
5793         intel_ddi_set_pipe_settings(pipe_config);
5794         if (!transcoder_is_dsi(cpu_transcoder))
5795                 intel_ddi_enable_transcoder_func(pipe_config);
5796
5797         if (dev_priv->display.initial_watermarks != NULL)
5798                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5799
5800         if (INTEL_GEN(dev_priv) >= 11)
5801                 icl_pipe_mbus_enable(intel_crtc);
5802
5803         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5804         if (!transcoder_is_dsi(cpu_transcoder))
5805                 intel_enable_pipe(pipe_config);
5806
5807         if (intel_crtc->config->has_pch_encoder)
5808                 lpt_pch_enable(old_intel_state, pipe_config);
5809
5810         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5811                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5812
5813         assert_vblank_disabled(crtc);
5814         drm_crtc_vblank_on(crtc);
5815
5816         intel_encoders_enable(crtc, pipe_config, old_state);
5817
5818         if (psl_clkgate_wa) {
5819                 intel_wait_for_vblank(dev_priv, pipe);
5820                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5821         }
5822
5823         /* If we change the relative order between pipe/planes enabling, we need
5824          * to change the workaround. */
5825         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5826         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5827                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5828                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5829         }
5830 }
5831
5832 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5833 {
5834         struct drm_device *dev = crtc->base.dev;
5835         struct drm_i915_private *dev_priv = to_i915(dev);
5836         int pipe = crtc->pipe;
5837
5838         /* To avoid upsetting the power well on haswell only disable the pfit if
5839          * it's in use. The hw state code will make sure we get this right. */
5840         if (force || crtc->config->pch_pfit.enabled) {
5841                 I915_WRITE(PF_CTL(pipe), 0);
5842                 I915_WRITE(PF_WIN_POS(pipe), 0);
5843                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5844         }
5845 }
5846
5847 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5848                                   struct drm_atomic_state *old_state)
5849 {
5850         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5851         struct drm_device *dev = crtc->dev;
5852         struct drm_i915_private *dev_priv = to_i915(dev);
5853         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5854         int pipe = intel_crtc->pipe;
5855
5856         /*
5857          * Sometimes spurious CPU pipe underruns happen when the
5858          * pipe is already disabled, but FDI RX/TX is still enabled.
5859          * Happens at least with VGA+HDMI cloning. Suppress them.
5860          */
5861         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5862         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5863
5864         intel_encoders_disable(crtc, old_crtc_state, old_state);
5865
5866         drm_crtc_vblank_off(crtc);
5867         assert_vblank_disabled(crtc);
5868
5869         intel_disable_pipe(old_crtc_state);
5870
5871         ironlake_pfit_disable(intel_crtc, false);
5872
5873         if (intel_crtc->config->has_pch_encoder)
5874                 ironlake_fdi_disable(crtc);
5875
5876         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5877
5878         if (intel_crtc->config->has_pch_encoder) {
5879                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5880
5881                 if (HAS_PCH_CPT(dev_priv)) {
5882                         i915_reg_t reg;
5883                         u32 temp;
5884
5885                         /* disable TRANS_DP_CTL */
5886                         reg = TRANS_DP_CTL(pipe);
5887                         temp = I915_READ(reg);
5888                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5889                                   TRANS_DP_PORT_SEL_MASK);
5890                         temp |= TRANS_DP_PORT_SEL_NONE;
5891                         I915_WRITE(reg, temp);
5892
5893                         /* disable DPLL_SEL */
5894                         temp = I915_READ(PCH_DPLL_SEL);
5895                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5896                         I915_WRITE(PCH_DPLL_SEL, temp);
5897                 }
5898
5899                 ironlake_fdi_pll_disable(intel_crtc);
5900         }
5901
5902         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5903         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5904 }
5905
5906 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5907                                  struct drm_atomic_state *old_state)
5908 {
5909         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5910         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5911         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5912         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
5913
5914         intel_encoders_disable(crtc, old_crtc_state, old_state);
5915
5916         drm_crtc_vblank_off(crtc);
5917         assert_vblank_disabled(crtc);
5918
5919         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5920         if (!transcoder_is_dsi(cpu_transcoder))
5921                 intel_disable_pipe(old_crtc_state);
5922
5923         if (intel_crtc_has_type(old_crtc_state, INTEL_OUTPUT_DP_MST))
5924                 intel_ddi_set_vc_payload_alloc(old_crtc_state, false);
5925
5926         if (!transcoder_is_dsi(cpu_transcoder))
5927                 intel_ddi_disable_transcoder_func(old_crtc_state);
5928
5929         if (INTEL_GEN(dev_priv) >= 9)
5930                 skylake_scaler_disable(intel_crtc);
5931         else
5932                 ironlake_pfit_disable(intel_crtc, false);
5933
5934         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5935
5936         if (INTEL_GEN(dev_priv) >= 11)
5937                 icl_unmap_plls_to_ports(crtc, old_crtc_state, old_state);
5938 }
5939
5940 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5941 {
5942         struct drm_device *dev = crtc->base.dev;
5943         struct drm_i915_private *dev_priv = to_i915(dev);
5944         struct intel_crtc_state *pipe_config = crtc->config;
5945
5946         if (!pipe_config->gmch_pfit.control)
5947                 return;
5948
5949         /*
5950          * The panel fitter should only be adjusted whilst the pipe is disabled,
5951          * according to register description and PRM.
5952          */
5953         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5954         assert_pipe_disabled(dev_priv, crtc->pipe);
5955
5956         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5957         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5958
5959         /* Border color in case we don't scale up to the full screen. Black by
5960          * default, change to something else for debugging. */
5961         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5962 }
5963
5964 bool intel_port_is_combophy(struct drm_i915_private *dev_priv, enum port port)
5965 {
5966         if (port == PORT_NONE)
5967                 return false;
5968
5969         if (IS_ICELAKE(dev_priv))
5970                 return port <= PORT_B;
5971
5972         return false;
5973 }
5974
5975 bool intel_port_is_tc(struct drm_i915_private *dev_priv, enum port port)
5976 {
5977         if (IS_ICELAKE(dev_priv))
5978                 return port >= PORT_C && port <= PORT_F;
5979
5980         return false;
5981 }
5982
5983 enum tc_port intel_port_to_tc(struct drm_i915_private *dev_priv, enum port port)
5984 {
5985         if (!intel_port_is_tc(dev_priv, port))
5986                 return PORT_TC_NONE;
5987
5988         return port - PORT_C;
5989 }
5990
5991 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5992 {
5993         switch (port) {
5994         case PORT_A:
5995                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5996         case PORT_B:
5997                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5998         case PORT_C:
5999                 return POWER_DOMAIN_PORT_DDI_C_LANES;
6000         case PORT_D:
6001                 return POWER_DOMAIN_PORT_DDI_D_LANES;
6002         case PORT_E:
6003                 return POWER_DOMAIN_PORT_DDI_E_LANES;
6004         case PORT_F:
6005                 return POWER_DOMAIN_PORT_DDI_F_LANES;
6006         default:
6007                 MISSING_CASE(port);
6008                 return POWER_DOMAIN_PORT_OTHER;
6009         }
6010 }
6011
6012 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
6013                                   struct intel_crtc_state *crtc_state)
6014 {
6015         struct drm_device *dev = crtc->dev;
6016         struct drm_i915_private *dev_priv = to_i915(dev);
6017         struct drm_encoder *encoder;
6018         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6019         enum pipe pipe = intel_crtc->pipe;
6020         u64 mask;
6021         enum transcoder transcoder = crtc_state->cpu_transcoder;
6022
6023         if (!crtc_state->base.active)
6024                 return 0;
6025
6026         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
6027         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
6028         if (crtc_state->pch_pfit.enabled ||
6029             crtc_state->pch_pfit.force_thru)
6030                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
6031
6032         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
6033                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6034
6035                 mask |= BIT_ULL(intel_encoder->power_domain);
6036         }
6037
6038         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
6039                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
6040
6041         if (crtc_state->shared_dpll)
6042                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
6043
6044         return mask;
6045 }
6046
6047 static u64
6048 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
6049                                struct intel_crtc_state *crtc_state)
6050 {
6051         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6052         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6053         enum intel_display_power_domain domain;
6054         u64 domains, new_domains, old_domains;
6055
6056         old_domains = intel_crtc->enabled_power_domains;
6057         intel_crtc->enabled_power_domains = new_domains =
6058                 get_crtc_power_domains(crtc, crtc_state);
6059
6060         domains = new_domains & ~old_domains;
6061
6062         for_each_power_domain(domain, domains)
6063                 intel_display_power_get(dev_priv, domain);
6064
6065         return old_domains & ~new_domains;
6066 }
6067
6068 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
6069                                       u64 domains)
6070 {
6071         enum intel_display_power_domain domain;
6072
6073         for_each_power_domain(domain, domains)
6074                 intel_display_power_put(dev_priv, domain);
6075 }
6076
6077 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
6078                                    struct drm_atomic_state *old_state)
6079 {
6080         struct intel_atomic_state *old_intel_state =
6081                 to_intel_atomic_state(old_state);
6082         struct drm_crtc *crtc = pipe_config->base.crtc;
6083         struct drm_device *dev = crtc->dev;
6084         struct drm_i915_private *dev_priv = to_i915(dev);
6085         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6086         int pipe = intel_crtc->pipe;
6087
6088         if (WARN_ON(intel_crtc->active))
6089                 return;
6090
6091         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6092                 intel_dp_set_m_n(intel_crtc, M1_N1);
6093
6094         intel_set_pipe_timings(intel_crtc);
6095         intel_set_pipe_src_size(intel_crtc);
6096
6097         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
6098                 struct drm_i915_private *dev_priv = to_i915(dev);
6099
6100                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
6101                 I915_WRITE(CHV_CANVAS(pipe), 0);
6102         }
6103
6104         i9xx_set_pipeconf(intel_crtc);
6105
6106         intel_color_set_csc(&pipe_config->base);
6107
6108         intel_crtc->active = true;
6109
6110         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6111
6112         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
6113
6114         if (IS_CHERRYVIEW(dev_priv)) {
6115                 chv_prepare_pll(intel_crtc, intel_crtc->config);
6116                 chv_enable_pll(intel_crtc, intel_crtc->config);
6117         } else {
6118                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
6119                 vlv_enable_pll(intel_crtc, intel_crtc->config);
6120         }
6121
6122         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6123
6124         i9xx_pfit_enable(intel_crtc);
6125
6126         intel_color_load_luts(&pipe_config->base);
6127
6128         dev_priv->display.initial_watermarks(old_intel_state,
6129                                              pipe_config);
6130         intel_enable_pipe(pipe_config);
6131
6132         assert_vblank_disabled(crtc);
6133         drm_crtc_vblank_on(crtc);
6134
6135         intel_encoders_enable(crtc, pipe_config, old_state);
6136 }
6137
6138 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
6139 {
6140         struct drm_device *dev = crtc->base.dev;
6141         struct drm_i915_private *dev_priv = to_i915(dev);
6142
6143         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
6144         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
6145 }
6146
6147 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
6148                              struct drm_atomic_state *old_state)
6149 {
6150         struct intel_atomic_state *old_intel_state =
6151                 to_intel_atomic_state(old_state);
6152         struct drm_crtc *crtc = pipe_config->base.crtc;
6153         struct drm_device *dev = crtc->dev;
6154         struct drm_i915_private *dev_priv = to_i915(dev);
6155         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6156         enum pipe pipe = intel_crtc->pipe;
6157
6158         if (WARN_ON(intel_crtc->active))
6159                 return;
6160
6161         i9xx_set_pll_dividers(intel_crtc);
6162
6163         if (intel_crtc_has_dp_encoder(intel_crtc->config))
6164                 intel_dp_set_m_n(intel_crtc, M1_N1);
6165
6166         intel_set_pipe_timings(intel_crtc);
6167         intel_set_pipe_src_size(intel_crtc);
6168
6169         i9xx_set_pipeconf(intel_crtc);
6170
6171         intel_crtc->active = true;
6172
6173         if (!IS_GEN2(dev_priv))
6174                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
6175
6176         intel_encoders_pre_enable(crtc, pipe_config, old_state);
6177
6178         i9xx_enable_pll(intel_crtc, pipe_config);
6179
6180         i9xx_pfit_enable(intel_crtc);
6181
6182         intel_color_load_luts(&pipe_config->base);
6183
6184         if (dev_priv->display.initial_watermarks != NULL)
6185                 dev_priv->display.initial_watermarks(old_intel_state,
6186                                                      intel_crtc->config);
6187         else
6188                 intel_update_watermarks(intel_crtc);
6189         intel_enable_pipe(pipe_config);
6190
6191         assert_vblank_disabled(crtc);
6192         drm_crtc_vblank_on(crtc);
6193
6194         intel_encoders_enable(crtc, pipe_config, old_state);
6195 }
6196
6197 static void i9xx_pfit_disable(struct intel_crtc *crtc)
6198 {
6199         struct drm_device *dev = crtc->base.dev;
6200         struct drm_i915_private *dev_priv = to_i915(dev);
6201
6202         if (!crtc->config->gmch_pfit.control)
6203                 return;
6204
6205         assert_pipe_disabled(dev_priv, crtc->pipe);
6206
6207         DRM_DEBUG_KMS("disabling pfit, current: 0x%08x\n",
6208                       I915_READ(PFIT_CONTROL));
6209         I915_WRITE(PFIT_CONTROL, 0);
6210 }
6211
6212 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
6213                               struct drm_atomic_state *old_state)
6214 {
6215         struct drm_crtc *crtc = old_crtc_state->base.crtc;
6216         struct drm_device *dev = crtc->dev;
6217         struct drm_i915_private *dev_priv = to_i915(dev);
6218         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6219         int pipe = intel_crtc->pipe;
6220
6221         /*
6222          * On gen2 planes are double buffered but the pipe isn't, so we must
6223          * wait for planes to fully turn off before disabling the pipe.
6224          */
6225         if (IS_GEN2(dev_priv))
6226                 intel_wait_for_vblank(dev_priv, pipe);
6227
6228         intel_encoders_disable(crtc, old_crtc_state, old_state);
6229
6230         drm_crtc_vblank_off(crtc);
6231         assert_vblank_disabled(crtc);
6232
6233         intel_disable_pipe(old_crtc_state);
6234
6235         i9xx_pfit_disable(intel_crtc);
6236
6237         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
6238
6239         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
6240                 if (IS_CHERRYVIEW(dev_priv))
6241                         chv_disable_pll(dev_priv, pipe);
6242                 else if (IS_VALLEYVIEW(dev_priv))
6243                         vlv_disable_pll(dev_priv, pipe);
6244                 else
6245                         i9xx_disable_pll(intel_crtc);
6246         }
6247
6248         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
6249
6250         if (!IS_GEN2(dev_priv))
6251                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
6252
6253         if (!dev_priv->display.initial_watermarks)
6254                 intel_update_watermarks(intel_crtc);
6255
6256         /* clock the pipe down to 640x480@60 to potentially save power */
6257         if (IS_I830(dev_priv))
6258                 i830_enable_pipe(dev_priv, pipe);
6259 }
6260
6261 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
6262                                         struct drm_modeset_acquire_ctx *ctx)
6263 {
6264         struct intel_encoder *encoder;
6265         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
6266         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
6267         enum intel_display_power_domain domain;
6268         struct intel_plane *plane;
6269         u64 domains;
6270         struct drm_atomic_state *state;
6271         struct intel_crtc_state *crtc_state;
6272         int ret;
6273
6274         if (!intel_crtc->active)
6275                 return;
6276
6277         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6278                 const struct intel_plane_state *plane_state =
6279                         to_intel_plane_state(plane->base.state);
6280
6281                 if (plane_state->base.visible)
6282                         intel_plane_disable_noatomic(intel_crtc, plane);
6283         }
6284
6285         state = drm_atomic_state_alloc(crtc->dev);
6286         if (!state) {
6287                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6288                               crtc->base.id, crtc->name);
6289                 return;
6290         }
6291
6292         state->acquire_ctx = ctx;
6293
6294         /* Everything's already locked, -EDEADLK can't happen. */
6295         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6296         ret = drm_atomic_add_affected_connectors(state, crtc);
6297
6298         WARN_ON(IS_ERR(crtc_state) || ret);
6299
6300         dev_priv->display.crtc_disable(crtc_state, state);
6301
6302         drm_atomic_state_put(state);
6303
6304         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6305                       crtc->base.id, crtc->name);
6306
6307         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6308         crtc->state->active = false;
6309         intel_crtc->active = false;
6310         crtc->enabled = false;
6311         crtc->state->connector_mask = 0;
6312         crtc->state->encoder_mask = 0;
6313
6314         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6315                 encoder->base.crtc = NULL;
6316
6317         intel_fbc_disable(intel_crtc);
6318         intel_update_watermarks(intel_crtc);
6319         intel_disable_shared_dpll(intel_crtc);
6320
6321         domains = intel_crtc->enabled_power_domains;
6322         for_each_power_domain(domain, domains)
6323                 intel_display_power_put(dev_priv, domain);
6324         intel_crtc->enabled_power_domains = 0;
6325
6326         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6327         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6328         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6329 }
6330
6331 /*
6332  * turn all crtc's off, but do not adjust state
6333  * This has to be paired with a call to intel_modeset_setup_hw_state.
6334  */
6335 int intel_display_suspend(struct drm_device *dev)
6336 {
6337         struct drm_i915_private *dev_priv = to_i915(dev);
6338         struct drm_atomic_state *state;
6339         int ret;
6340
6341         state = drm_atomic_helper_suspend(dev);
6342         ret = PTR_ERR_OR_ZERO(state);
6343         if (ret)
6344                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6345         else
6346                 dev_priv->modeset_restore_state = state;
6347         return ret;
6348 }
6349
6350 void intel_encoder_destroy(struct drm_encoder *encoder)
6351 {
6352         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6353
6354         drm_encoder_cleanup(encoder);
6355         kfree(intel_encoder);
6356 }
6357
6358 /* Cross check the actual hw state with our own modeset state tracking (and it's
6359  * internal consistency). */
6360 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6361                                          struct drm_connector_state *conn_state)
6362 {
6363         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6364
6365         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6366                       connector->base.base.id,
6367                       connector->base.name);
6368
6369         if (connector->get_hw_state(connector)) {
6370                 struct intel_encoder *encoder = connector->encoder;
6371
6372                 I915_STATE_WARN(!crtc_state,
6373                          "connector enabled without attached crtc\n");
6374
6375                 if (!crtc_state)
6376                         return;
6377
6378                 I915_STATE_WARN(!crtc_state->active,
6379                       "connector is active, but attached crtc isn't\n");
6380
6381                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6382                         return;
6383
6384                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6385                         "atomic encoder doesn't match attached encoder\n");
6386
6387                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6388                         "attached encoder crtc differs from connector crtc\n");
6389         } else {
6390                 I915_STATE_WARN(crtc_state && crtc_state->active,
6391                         "attached crtc is active, but connector isn't\n");
6392                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6393                         "best encoder set without crtc!\n");
6394         }
6395 }
6396
6397 int intel_connector_init(struct intel_connector *connector)
6398 {
6399         struct intel_digital_connector_state *conn_state;
6400
6401         /*
6402          * Allocate enough memory to hold intel_digital_connector_state,
6403          * This might be a few bytes too many, but for connectors that don't
6404          * need it we'll free the state and allocate a smaller one on the first
6405          * succesful commit anyway.
6406          */
6407         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
6408         if (!conn_state)
6409                 return -ENOMEM;
6410
6411         __drm_atomic_helper_connector_reset(&connector->base,
6412                                             &conn_state->base);
6413
6414         return 0;
6415 }
6416
6417 struct intel_connector *intel_connector_alloc(void)
6418 {
6419         struct intel_connector *connector;
6420
6421         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6422         if (!connector)
6423                 return NULL;
6424
6425         if (intel_connector_init(connector) < 0) {
6426                 kfree(connector);
6427                 return NULL;
6428         }
6429
6430         return connector;
6431 }
6432
6433 /*
6434  * Free the bits allocated by intel_connector_alloc.
6435  * This should only be used after intel_connector_alloc has returned
6436  * successfully, and before drm_connector_init returns successfully.
6437  * Otherwise the destroy callbacks for the connector and the state should
6438  * take care of proper cleanup/free
6439  */
6440 void intel_connector_free(struct intel_connector *connector)
6441 {
6442         kfree(to_intel_digital_connector_state(connector->base.state));
6443         kfree(connector);
6444 }
6445
6446 /* Simple connector->get_hw_state implementation for encoders that support only
6447  * one connector and no cloning and hence the encoder state determines the state
6448  * of the connector. */
6449 bool intel_connector_get_hw_state(struct intel_connector *connector)
6450 {
6451         enum pipe pipe = 0;
6452         struct intel_encoder *encoder = connector->encoder;
6453
6454         return encoder->get_hw_state(encoder, &pipe);
6455 }
6456
6457 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6458 {
6459         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6460                 return crtc_state->fdi_lanes;
6461
6462         return 0;
6463 }
6464
6465 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6466                                      struct intel_crtc_state *pipe_config)
6467 {
6468         struct drm_i915_private *dev_priv = to_i915(dev);
6469         struct drm_atomic_state *state = pipe_config->base.state;
6470         struct intel_crtc *other_crtc;
6471         struct intel_crtc_state *other_crtc_state;
6472
6473         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6474                       pipe_name(pipe), pipe_config->fdi_lanes);
6475         if (pipe_config->fdi_lanes > 4) {
6476                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6477                               pipe_name(pipe), pipe_config->fdi_lanes);
6478                 return -EINVAL;
6479         }
6480
6481         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6482                 if (pipe_config->fdi_lanes > 2) {
6483                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6484                                       pipe_config->fdi_lanes);
6485                         return -EINVAL;
6486                 } else {
6487                         return 0;
6488                 }
6489         }
6490
6491         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6492                 return 0;
6493
6494         /* Ivybridge 3 pipe is really complicated */
6495         switch (pipe) {
6496         case PIPE_A:
6497                 return 0;
6498         case PIPE_B:
6499                 if (pipe_config->fdi_lanes <= 2)
6500                         return 0;
6501
6502                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6503                 other_crtc_state =
6504                         intel_atomic_get_crtc_state(state, other_crtc);
6505                 if (IS_ERR(other_crtc_state))
6506                         return PTR_ERR(other_crtc_state);
6507
6508                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6509                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6510                                       pipe_name(pipe), pipe_config->fdi_lanes);
6511                         return -EINVAL;
6512                 }
6513                 return 0;
6514         case PIPE_C:
6515                 if (pipe_config->fdi_lanes > 2) {
6516                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6517                                       pipe_name(pipe), pipe_config->fdi_lanes);
6518                         return -EINVAL;
6519                 }
6520
6521                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6522                 other_crtc_state =
6523                         intel_atomic_get_crtc_state(state, other_crtc);
6524                 if (IS_ERR(other_crtc_state))
6525                         return PTR_ERR(other_crtc_state);
6526
6527                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6528                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6529                         return -EINVAL;
6530                 }
6531                 return 0;
6532         default:
6533                 BUG();
6534         }
6535 }
6536
6537 #define RETRY 1
6538 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6539                                        struct intel_crtc_state *pipe_config)
6540 {
6541         struct drm_device *dev = intel_crtc->base.dev;
6542         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6543         int lane, link_bw, fdi_dotclock, ret;
6544         bool needs_recompute = false;
6545
6546 retry:
6547         /* FDI is a binary signal running at ~2.7GHz, encoding
6548          * each output octet as 10 bits. The actual frequency
6549          * is stored as a divider into a 100MHz clock, and the
6550          * mode pixel clock is stored in units of 1KHz.
6551          * Hence the bw of each lane in terms of the mode signal
6552          * is:
6553          */
6554         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6555
6556         fdi_dotclock = adjusted_mode->crtc_clock;
6557
6558         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6559                                            pipe_config->pipe_bpp);
6560
6561         pipe_config->fdi_lanes = lane;
6562
6563         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6564                                link_bw, &pipe_config->fdi_m_n, false);
6565
6566         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6567         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6568                 pipe_config->pipe_bpp -= 2*3;
6569                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6570                               pipe_config->pipe_bpp);
6571                 needs_recompute = true;
6572                 pipe_config->bw_constrained = true;
6573
6574                 goto retry;
6575         }
6576
6577         if (needs_recompute)
6578                 return RETRY;
6579
6580         return ret;
6581 }
6582
6583 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6584 {
6585         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6586         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6587
6588         /* IPS only exists on ULT machines and is tied to pipe A. */
6589         if (!hsw_crtc_supports_ips(crtc))
6590                 return false;
6591
6592         if (!i915_modparams.enable_ips)
6593                 return false;
6594
6595         if (crtc_state->pipe_bpp > 24)
6596                 return false;
6597
6598         /*
6599          * We compare against max which means we must take
6600          * the increased cdclk requirement into account when
6601          * calculating the new cdclk.
6602          *
6603          * Should measure whether using a lower cdclk w/o IPS
6604          */
6605         if (IS_BROADWELL(dev_priv) &&
6606             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6607                 return false;
6608
6609         return true;
6610 }
6611
6612 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6613 {
6614         struct drm_i915_private *dev_priv =
6615                 to_i915(crtc_state->base.crtc->dev);
6616         struct intel_atomic_state *intel_state =
6617                 to_intel_atomic_state(crtc_state->base.state);
6618
6619         if (!hsw_crtc_state_ips_capable(crtc_state))
6620                 return false;
6621
6622         if (crtc_state->ips_force_disable)
6623                 return false;
6624
6625         /* IPS should be fine as long as at least one plane is enabled. */
6626         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6627                 return false;
6628
6629         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6630         if (IS_BROADWELL(dev_priv) &&
6631             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6632                 return false;
6633
6634         return true;
6635 }
6636
6637 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6638 {
6639         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6640
6641         /* GDG double wide on either pipe, otherwise pipe A only */
6642         return INTEL_GEN(dev_priv) < 4 &&
6643                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6644 }
6645
6646 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6647 {
6648         uint32_t pixel_rate;
6649
6650         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6651
6652         /*
6653          * We only use IF-ID interlacing. If we ever use
6654          * PF-ID we'll need to adjust the pixel_rate here.
6655          */
6656
6657         if (pipe_config->pch_pfit.enabled) {
6658                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6659                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6660
6661                 pipe_w = pipe_config->pipe_src_w;
6662                 pipe_h = pipe_config->pipe_src_h;
6663
6664                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6665                 pfit_h = pfit_size & 0xFFFF;
6666                 if (pipe_w < pfit_w)
6667                         pipe_w = pfit_w;
6668                 if (pipe_h < pfit_h)
6669                         pipe_h = pfit_h;
6670
6671                 if (WARN_ON(!pfit_w || !pfit_h))
6672                         return pixel_rate;
6673
6674                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6675                                      pfit_w * pfit_h);
6676         }
6677
6678         return pixel_rate;
6679 }
6680
6681 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6682 {
6683         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6684
6685         if (HAS_GMCH_DISPLAY(dev_priv))
6686                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6687                 crtc_state->pixel_rate =
6688                         crtc_state->base.adjusted_mode.crtc_clock;
6689         else
6690                 crtc_state->pixel_rate =
6691                         ilk_pipe_pixel_rate(crtc_state);
6692 }
6693
6694 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6695                                      struct intel_crtc_state *pipe_config)
6696 {
6697         struct drm_device *dev = crtc->base.dev;
6698         struct drm_i915_private *dev_priv = to_i915(dev);
6699         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6700         int clock_limit = dev_priv->max_dotclk_freq;
6701
6702         if (INTEL_GEN(dev_priv) < 4) {
6703                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6704
6705                 /*
6706                  * Enable double wide mode when the dot clock
6707                  * is > 90% of the (display) core speed.
6708                  */
6709                 if (intel_crtc_supports_double_wide(crtc) &&
6710                     adjusted_mode->crtc_clock > clock_limit) {
6711                         clock_limit = dev_priv->max_dotclk_freq;
6712                         pipe_config->double_wide = true;
6713                 }
6714         }
6715
6716         if (adjusted_mode->crtc_clock > clock_limit) {
6717                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6718                               adjusted_mode->crtc_clock, clock_limit,
6719                               yesno(pipe_config->double_wide));
6720                 return -EINVAL;
6721         }
6722
6723         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6724                 /*
6725                  * There is only one pipe CSC unit per pipe, and we need that
6726                  * for output conversion from RGB->YCBCR. So if CTM is already
6727                  * applied we can't support YCBCR420 output.
6728                  */
6729                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6730                 return -EINVAL;
6731         }
6732
6733         /*
6734          * Pipe horizontal size must be even in:
6735          * - DVO ganged mode
6736          * - LVDS dual channel mode
6737          * - Double wide pipe
6738          */
6739         if (pipe_config->pipe_src_w & 1) {
6740                 if (pipe_config->double_wide) {
6741                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6742                         return -EINVAL;
6743                 }
6744
6745                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6746                     intel_is_dual_link_lvds(dev)) {
6747                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6748                         return -EINVAL;
6749                 }
6750         }
6751
6752         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6753          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6754          */
6755         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6756                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6757                 return -EINVAL;
6758
6759         intel_crtc_compute_pixel_rate(pipe_config);
6760
6761         if (pipe_config->has_pch_encoder)
6762                 return ironlake_fdi_compute_config(crtc, pipe_config);
6763
6764         return 0;
6765 }
6766
6767 static void
6768 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6769 {
6770         while (*num > DATA_LINK_M_N_MASK ||
6771                *den > DATA_LINK_M_N_MASK) {
6772                 *num >>= 1;
6773                 *den >>= 1;
6774         }
6775 }
6776
6777 static void compute_m_n(unsigned int m, unsigned int n,
6778                         uint32_t *ret_m, uint32_t *ret_n,
6779                         bool constant_n)
6780 {
6781         /*
6782          * Several DP dongles in particular seem to be fussy about
6783          * too large link M/N values. Give N value as 0x8000 that
6784          * should be acceptable by specific devices. 0x8000 is the
6785          * specified fixed N value for asynchronous clock mode,
6786          * which the devices expect also in synchronous clock mode.
6787          */
6788         if (constant_n)
6789                 *ret_n = 0x8000;
6790         else
6791                 *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6792
6793         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6794         intel_reduce_m_n_ratio(ret_m, ret_n);
6795 }
6796
6797 void
6798 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6799                        int pixel_clock, int link_clock,
6800                        struct intel_link_m_n *m_n,
6801                        bool constant_n)
6802 {
6803         m_n->tu = 64;
6804
6805         compute_m_n(bits_per_pixel * pixel_clock,
6806                     link_clock * nlanes * 8,
6807                     &m_n->gmch_m, &m_n->gmch_n,
6808                     constant_n);
6809
6810         compute_m_n(pixel_clock, link_clock,
6811                     &m_n->link_m, &m_n->link_n,
6812                     constant_n);
6813 }
6814
6815 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6816 {
6817         if (i915_modparams.panel_use_ssc >= 0)
6818                 return i915_modparams.panel_use_ssc != 0;
6819         return dev_priv->vbt.lvds_use_ssc
6820                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6821 }
6822
6823 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6824 {
6825         return (1 << dpll->n) << 16 | dpll->m2;
6826 }
6827
6828 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6829 {
6830         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6831 }
6832
6833 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6834                                      struct intel_crtc_state *crtc_state,
6835                                      struct dpll *reduced_clock)
6836 {
6837         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6838         u32 fp, fp2 = 0;
6839
6840         if (IS_PINEVIEW(dev_priv)) {
6841                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6842                 if (reduced_clock)
6843                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6844         } else {
6845                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6846                 if (reduced_clock)
6847                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6848         }
6849
6850         crtc_state->dpll_hw_state.fp0 = fp;
6851
6852         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6853             reduced_clock) {
6854                 crtc_state->dpll_hw_state.fp1 = fp2;
6855         } else {
6856                 crtc_state->dpll_hw_state.fp1 = fp;
6857         }
6858 }
6859
6860 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6861                 pipe)
6862 {
6863         u32 reg_val;
6864
6865         /*
6866          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6867          * and set it to a reasonable value instead.
6868          */
6869         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6870         reg_val &= 0xffffff00;
6871         reg_val |= 0x00000030;
6872         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6873
6874         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6875         reg_val &= 0x00ffffff;
6876         reg_val |= 0x8c000000;
6877         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6878
6879         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6880         reg_val &= 0xffffff00;
6881         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6882
6883         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6884         reg_val &= 0x00ffffff;
6885         reg_val |= 0xb0000000;
6886         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6887 }
6888
6889 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6890                                          struct intel_link_m_n *m_n)
6891 {
6892         struct drm_device *dev = crtc->base.dev;
6893         struct drm_i915_private *dev_priv = to_i915(dev);
6894         int pipe = crtc->pipe;
6895
6896         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6897         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6898         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6899         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6900 }
6901
6902 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6903                                          struct intel_link_m_n *m_n,
6904                                          struct intel_link_m_n *m2_n2)
6905 {
6906         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6907         int pipe = crtc->pipe;
6908         enum transcoder transcoder = crtc->config->cpu_transcoder;
6909
6910         if (INTEL_GEN(dev_priv) >= 5) {
6911                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6912                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6913                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6914                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6915                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6916                  * for gen < 8) and if DRRS is supported (to make sure the
6917                  * registers are not unnecessarily accessed).
6918                  */
6919                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6920                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6921                         I915_WRITE(PIPE_DATA_M2(transcoder),
6922                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6923                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6924                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6925                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6926                 }
6927         } else {
6928                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6929                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6930                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6931                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6932         }
6933 }
6934
6935 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6936 {
6937         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6938
6939         if (m_n == M1_N1) {
6940                 dp_m_n = &crtc->config->dp_m_n;
6941                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6942         } else if (m_n == M2_N2) {
6943
6944                 /*
6945                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6946                  * needs to be programmed into M1_N1.
6947                  */
6948                 dp_m_n = &crtc->config->dp_m2_n2;
6949         } else {
6950                 DRM_ERROR("Unsupported divider value\n");
6951                 return;
6952         }
6953
6954         if (crtc->config->has_pch_encoder)
6955                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6956         else
6957                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6958 }
6959
6960 static void vlv_compute_dpll(struct intel_crtc *crtc,
6961                              struct intel_crtc_state *pipe_config)
6962 {
6963         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6964                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6965         if (crtc->pipe != PIPE_A)
6966                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6967
6968         /* DPLL not used with DSI, but still need the rest set up */
6969         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6970                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6971                         DPLL_EXT_BUFFER_ENABLE_VLV;
6972
6973         pipe_config->dpll_hw_state.dpll_md =
6974                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6975 }
6976
6977 static void chv_compute_dpll(struct intel_crtc *crtc,
6978                              struct intel_crtc_state *pipe_config)
6979 {
6980         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6981                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6982         if (crtc->pipe != PIPE_A)
6983                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6984
6985         /* DPLL not used with DSI, but still need the rest set up */
6986         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6987                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6988
6989         pipe_config->dpll_hw_state.dpll_md =
6990                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6991 }
6992
6993 static void vlv_prepare_pll(struct intel_crtc *crtc,
6994                             const struct intel_crtc_state *pipe_config)
6995 {
6996         struct drm_device *dev = crtc->base.dev;
6997         struct drm_i915_private *dev_priv = to_i915(dev);
6998         enum pipe pipe = crtc->pipe;
6999         u32 mdiv;
7000         u32 bestn, bestm1, bestm2, bestp1, bestp2;
7001         u32 coreclk, reg_val;
7002
7003         /* Enable Refclk */
7004         I915_WRITE(DPLL(pipe),
7005                    pipe_config->dpll_hw_state.dpll &
7006                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
7007
7008         /* No need to actually set up the DPLL with DSI */
7009         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7010                 return;
7011
7012         mutex_lock(&dev_priv->sb_lock);
7013
7014         bestn = pipe_config->dpll.n;
7015         bestm1 = pipe_config->dpll.m1;
7016         bestm2 = pipe_config->dpll.m2;
7017         bestp1 = pipe_config->dpll.p1;
7018         bestp2 = pipe_config->dpll.p2;
7019
7020         /* See eDP HDMI DPIO driver vbios notes doc */
7021
7022         /* PLL B needs special handling */
7023         if (pipe == PIPE_B)
7024                 vlv_pllb_recal_opamp(dev_priv, pipe);
7025
7026         /* Set up Tx target for periodic Rcomp update */
7027         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
7028
7029         /* Disable target IRef on PLL */
7030         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
7031         reg_val &= 0x00ffffff;
7032         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
7033
7034         /* Disable fast lock */
7035         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
7036
7037         /* Set idtafcrecal before PLL is enabled */
7038         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
7039         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
7040         mdiv |= ((bestn << DPIO_N_SHIFT));
7041         mdiv |= (1 << DPIO_K_SHIFT);
7042
7043         /*
7044          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
7045          * but we don't support that).
7046          * Note: don't use the DAC post divider as it seems unstable.
7047          */
7048         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
7049         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7050
7051         mdiv |= DPIO_ENABLE_CALIBRATION;
7052         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
7053
7054         /* Set HBR and RBR LPF coefficients */
7055         if (pipe_config->port_clock == 162000 ||
7056             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
7057             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
7058                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7059                                  0x009f0003);
7060         else
7061                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
7062                                  0x00d0000f);
7063
7064         if (intel_crtc_has_dp_encoder(pipe_config)) {
7065                 /* Use SSC source */
7066                 if (pipe == PIPE_A)
7067                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7068                                          0x0df40000);
7069                 else
7070                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7071                                          0x0df70000);
7072         } else { /* HDMI or VGA */
7073                 /* Use bend source */
7074                 if (pipe == PIPE_A)
7075                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7076                                          0x0df70000);
7077                 else
7078                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
7079                                          0x0df40000);
7080         }
7081
7082         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
7083         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
7084         if (intel_crtc_has_dp_encoder(crtc->config))
7085                 coreclk |= 0x01000000;
7086         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
7087
7088         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
7089         mutex_unlock(&dev_priv->sb_lock);
7090 }
7091
7092 static void chv_prepare_pll(struct intel_crtc *crtc,
7093                             const struct intel_crtc_state *pipe_config)
7094 {
7095         struct drm_device *dev = crtc->base.dev;
7096         struct drm_i915_private *dev_priv = to_i915(dev);
7097         enum pipe pipe = crtc->pipe;
7098         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7099         u32 loopfilter, tribuf_calcntr;
7100         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
7101         u32 dpio_val;
7102         int vco;
7103
7104         /* Enable Refclk and SSC */
7105         I915_WRITE(DPLL(pipe),
7106                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
7107
7108         /* No need to actually set up the DPLL with DSI */
7109         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7110                 return;
7111
7112         bestn = pipe_config->dpll.n;
7113         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
7114         bestm1 = pipe_config->dpll.m1;
7115         bestm2 = pipe_config->dpll.m2 >> 22;
7116         bestp1 = pipe_config->dpll.p1;
7117         bestp2 = pipe_config->dpll.p2;
7118         vco = pipe_config->dpll.vco;
7119         dpio_val = 0;
7120         loopfilter = 0;
7121
7122         mutex_lock(&dev_priv->sb_lock);
7123
7124         /* p1 and p2 divider */
7125         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
7126                         5 << DPIO_CHV_S1_DIV_SHIFT |
7127                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
7128                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
7129                         1 << DPIO_CHV_K_DIV_SHIFT);
7130
7131         /* Feedback post-divider - m2 */
7132         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
7133
7134         /* Feedback refclk divider - n and m1 */
7135         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
7136                         DPIO_CHV_M1_DIV_BY_2 |
7137                         1 << DPIO_CHV_N_DIV_SHIFT);
7138
7139         /* M2 fraction division */
7140         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
7141
7142         /* M2 fraction division enable */
7143         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7144         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
7145         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
7146         if (bestm2_frac)
7147                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
7148         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
7149
7150         /* Program digital lock detect threshold */
7151         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
7152         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
7153                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
7154         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
7155         if (!bestm2_frac)
7156                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
7157         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
7158
7159         /* Loop filter */
7160         if (vco == 5400000) {
7161                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
7162                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
7163                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
7164                 tribuf_calcntr = 0x9;
7165         } else if (vco <= 6200000) {
7166                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
7167                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
7168                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7169                 tribuf_calcntr = 0x9;
7170         } else if (vco <= 6480000) {
7171                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7172                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7173                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7174                 tribuf_calcntr = 0x8;
7175         } else {
7176                 /* Not supported. Apply the same limits as in the max case */
7177                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
7178                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
7179                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
7180                 tribuf_calcntr = 0;
7181         }
7182         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
7183
7184         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
7185         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
7186         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
7187         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
7188
7189         /* AFC Recal */
7190         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
7191                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
7192                         DPIO_AFC_RECAL);
7193
7194         mutex_unlock(&dev_priv->sb_lock);
7195 }
7196
7197 /**
7198  * vlv_force_pll_on - forcibly enable just the PLL
7199  * @dev_priv: i915 private structure
7200  * @pipe: pipe PLL to enable
7201  * @dpll: PLL configuration
7202  *
7203  * Enable the PLL for @pipe using the supplied @dpll config. To be used
7204  * in cases where we need the PLL enabled even when @pipe is not going to
7205  * be enabled.
7206  */
7207 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
7208                      const struct dpll *dpll)
7209 {
7210         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
7211         struct intel_crtc_state *pipe_config;
7212
7213         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
7214         if (!pipe_config)
7215                 return -ENOMEM;
7216
7217         pipe_config->base.crtc = &crtc->base;
7218         pipe_config->pixel_multiplier = 1;
7219         pipe_config->dpll = *dpll;
7220
7221         if (IS_CHERRYVIEW(dev_priv)) {
7222                 chv_compute_dpll(crtc, pipe_config);
7223                 chv_prepare_pll(crtc, pipe_config);
7224                 chv_enable_pll(crtc, pipe_config);
7225         } else {
7226                 vlv_compute_dpll(crtc, pipe_config);
7227                 vlv_prepare_pll(crtc, pipe_config);
7228                 vlv_enable_pll(crtc, pipe_config);
7229         }
7230
7231         kfree(pipe_config);
7232
7233         return 0;
7234 }
7235
7236 /**
7237  * vlv_force_pll_off - forcibly disable just the PLL
7238  * @dev_priv: i915 private structure
7239  * @pipe: pipe PLL to disable
7240  *
7241  * Disable the PLL for @pipe. To be used in cases where we need
7242  * the PLL enabled even when @pipe is not going to be enabled.
7243  */
7244 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
7245 {
7246         if (IS_CHERRYVIEW(dev_priv))
7247                 chv_disable_pll(dev_priv, pipe);
7248         else
7249                 vlv_disable_pll(dev_priv, pipe);
7250 }
7251
7252 static void i9xx_compute_dpll(struct intel_crtc *crtc,
7253                               struct intel_crtc_state *crtc_state,
7254                               struct dpll *reduced_clock)
7255 {
7256         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7257         u32 dpll;
7258         struct dpll *clock = &crtc_state->dpll;
7259
7260         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7261
7262         dpll = DPLL_VGA_MODE_DIS;
7263
7264         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
7265                 dpll |= DPLLB_MODE_LVDS;
7266         else
7267                 dpll |= DPLLB_MODE_DAC_SERIAL;
7268
7269         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7270             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7271                 dpll |= (crtc_state->pixel_multiplier - 1)
7272                         << SDVO_MULTIPLIER_SHIFT_HIRES;
7273         }
7274
7275         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7276             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7277                 dpll |= DPLL_SDVO_HIGH_SPEED;
7278
7279         if (intel_crtc_has_dp_encoder(crtc_state))
7280                 dpll |= DPLL_SDVO_HIGH_SPEED;
7281
7282         /* compute bitmask from p1 value */
7283         if (IS_PINEVIEW(dev_priv))
7284                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7285         else {
7286                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7287                 if (IS_G4X(dev_priv) && reduced_clock)
7288                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7289         }
7290         switch (clock->p2) {
7291         case 5:
7292                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7293                 break;
7294         case 7:
7295                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7296                 break;
7297         case 10:
7298                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7299                 break;
7300         case 14:
7301                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7302                 break;
7303         }
7304         if (INTEL_GEN(dev_priv) >= 4)
7305                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7306
7307         if (crtc_state->sdvo_tv_clock)
7308                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7309         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7310                  intel_panel_use_ssc(dev_priv))
7311                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7312         else
7313                 dpll |= PLL_REF_INPUT_DREFCLK;
7314
7315         dpll |= DPLL_VCO_ENABLE;
7316         crtc_state->dpll_hw_state.dpll = dpll;
7317
7318         if (INTEL_GEN(dev_priv) >= 4) {
7319                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7320                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7321                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7322         }
7323 }
7324
7325 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7326                               struct intel_crtc_state *crtc_state,
7327                               struct dpll *reduced_clock)
7328 {
7329         struct drm_device *dev = crtc->base.dev;
7330         struct drm_i915_private *dev_priv = to_i915(dev);
7331         u32 dpll;
7332         struct dpll *clock = &crtc_state->dpll;
7333
7334         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7335
7336         dpll = DPLL_VGA_MODE_DIS;
7337
7338         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7339                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7340         } else {
7341                 if (clock->p1 == 2)
7342                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7343                 else
7344                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7345                 if (clock->p2 == 4)
7346                         dpll |= PLL_P2_DIVIDE_BY_4;
7347         }
7348
7349         if (!IS_I830(dev_priv) &&
7350             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7351                 dpll |= DPLL_DVO_2X_MODE;
7352
7353         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7354             intel_panel_use_ssc(dev_priv))
7355                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7356         else
7357                 dpll |= PLL_REF_INPUT_DREFCLK;
7358
7359         dpll |= DPLL_VCO_ENABLE;
7360         crtc_state->dpll_hw_state.dpll = dpll;
7361 }
7362
7363 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7364 {
7365         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7366         enum pipe pipe = intel_crtc->pipe;
7367         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7368         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7369         uint32_t crtc_vtotal, crtc_vblank_end;
7370         int vsyncshift = 0;
7371
7372         /* We need to be careful not to changed the adjusted mode, for otherwise
7373          * the hw state checker will get angry at the mismatch. */
7374         crtc_vtotal = adjusted_mode->crtc_vtotal;
7375         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7376
7377         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7378                 /* the chip adds 2 halflines automatically */
7379                 crtc_vtotal -= 1;
7380                 crtc_vblank_end -= 1;
7381
7382                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7383                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7384                 else
7385                         vsyncshift = adjusted_mode->crtc_hsync_start -
7386                                 adjusted_mode->crtc_htotal / 2;
7387                 if (vsyncshift < 0)
7388                         vsyncshift += adjusted_mode->crtc_htotal;
7389         }
7390
7391         if (INTEL_GEN(dev_priv) > 3)
7392                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7393
7394         I915_WRITE(HTOTAL(cpu_transcoder),
7395                    (adjusted_mode->crtc_hdisplay - 1) |
7396                    ((adjusted_mode->crtc_htotal - 1) << 16));
7397         I915_WRITE(HBLANK(cpu_transcoder),
7398                    (adjusted_mode->crtc_hblank_start - 1) |
7399                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7400         I915_WRITE(HSYNC(cpu_transcoder),
7401                    (adjusted_mode->crtc_hsync_start - 1) |
7402                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7403
7404         I915_WRITE(VTOTAL(cpu_transcoder),
7405                    (adjusted_mode->crtc_vdisplay - 1) |
7406                    ((crtc_vtotal - 1) << 16));
7407         I915_WRITE(VBLANK(cpu_transcoder),
7408                    (adjusted_mode->crtc_vblank_start - 1) |
7409                    ((crtc_vblank_end - 1) << 16));
7410         I915_WRITE(VSYNC(cpu_transcoder),
7411                    (adjusted_mode->crtc_vsync_start - 1) |
7412                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7413
7414         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7415          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7416          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7417          * bits. */
7418         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7419             (pipe == PIPE_B || pipe == PIPE_C))
7420                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7421
7422 }
7423
7424 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7425 {
7426         struct drm_device *dev = intel_crtc->base.dev;
7427         struct drm_i915_private *dev_priv = to_i915(dev);
7428         enum pipe pipe = intel_crtc->pipe;
7429
7430         /* pipesrc controls the size that is scaled from, which should
7431          * always be the user's requested size.
7432          */
7433         I915_WRITE(PIPESRC(pipe),
7434                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7435                    (intel_crtc->config->pipe_src_h - 1));
7436 }
7437
7438 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7439                                    struct intel_crtc_state *pipe_config)
7440 {
7441         struct drm_device *dev = crtc->base.dev;
7442         struct drm_i915_private *dev_priv = to_i915(dev);
7443         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7444         uint32_t tmp;
7445
7446         tmp = I915_READ(HTOTAL(cpu_transcoder));
7447         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7448         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7449         tmp = I915_READ(HBLANK(cpu_transcoder));
7450         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7451         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7452         tmp = I915_READ(HSYNC(cpu_transcoder));
7453         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7454         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7455
7456         tmp = I915_READ(VTOTAL(cpu_transcoder));
7457         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7458         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7459         tmp = I915_READ(VBLANK(cpu_transcoder));
7460         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7461         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7462         tmp = I915_READ(VSYNC(cpu_transcoder));
7463         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7464         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7465
7466         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7467                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7468                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7469                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7470         }
7471 }
7472
7473 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7474                                     struct intel_crtc_state *pipe_config)
7475 {
7476         struct drm_device *dev = crtc->base.dev;
7477         struct drm_i915_private *dev_priv = to_i915(dev);
7478         u32 tmp;
7479
7480         tmp = I915_READ(PIPESRC(crtc->pipe));
7481         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7482         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7483
7484         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7485         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7486 }
7487
7488 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7489                                  struct intel_crtc_state *pipe_config)
7490 {
7491         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7492         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7493         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7494         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7495
7496         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7497         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7498         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7499         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7500
7501         mode->flags = pipe_config->base.adjusted_mode.flags;
7502         mode->type = DRM_MODE_TYPE_DRIVER;
7503
7504         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7505
7506         mode->hsync = drm_mode_hsync(mode);
7507         mode->vrefresh = drm_mode_vrefresh(mode);
7508         drm_mode_set_name(mode);
7509 }
7510
7511 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7512 {
7513         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7514         uint32_t pipeconf;
7515
7516         pipeconf = 0;
7517
7518         /* we keep both pipes enabled on 830 */
7519         if (IS_I830(dev_priv))
7520                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7521
7522         if (intel_crtc->config->double_wide)
7523                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7524
7525         /* only g4x and later have fancy bpc/dither controls */
7526         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7527             IS_CHERRYVIEW(dev_priv)) {
7528                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7529                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7530                         pipeconf |= PIPECONF_DITHER_EN |
7531                                     PIPECONF_DITHER_TYPE_SP;
7532
7533                 switch (intel_crtc->config->pipe_bpp) {
7534                 case 18:
7535                         pipeconf |= PIPECONF_6BPC;
7536                         break;
7537                 case 24:
7538                         pipeconf |= PIPECONF_8BPC;
7539                         break;
7540                 case 30:
7541                         pipeconf |= PIPECONF_10BPC;
7542                         break;
7543                 default:
7544                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7545                         BUG();
7546                 }
7547         }
7548
7549         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7550                 if (INTEL_GEN(dev_priv) < 4 ||
7551                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7552                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7553                 else
7554                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7555         } else
7556                 pipeconf |= PIPECONF_PROGRESSIVE;
7557
7558         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7559              intel_crtc->config->limited_color_range)
7560                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7561
7562         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7563         POSTING_READ(PIPECONF(intel_crtc->pipe));
7564 }
7565
7566 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7567                                    struct intel_crtc_state *crtc_state)
7568 {
7569         struct drm_device *dev = crtc->base.dev;
7570         struct drm_i915_private *dev_priv = to_i915(dev);
7571         const struct intel_limit *limit;
7572         int refclk = 48000;
7573
7574         memset(&crtc_state->dpll_hw_state, 0,
7575                sizeof(crtc_state->dpll_hw_state));
7576
7577         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7578                 if (intel_panel_use_ssc(dev_priv)) {
7579                         refclk = dev_priv->vbt.lvds_ssc_freq;
7580                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7581                 }
7582
7583                 limit = &intel_limits_i8xx_lvds;
7584         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7585                 limit = &intel_limits_i8xx_dvo;
7586         } else {
7587                 limit = &intel_limits_i8xx_dac;
7588         }
7589
7590         if (!crtc_state->clock_set &&
7591             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7592                                  refclk, NULL, &crtc_state->dpll)) {
7593                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7594                 return -EINVAL;
7595         }
7596
7597         i8xx_compute_dpll(crtc, crtc_state, NULL);
7598
7599         return 0;
7600 }
7601
7602 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7603                                   struct intel_crtc_state *crtc_state)
7604 {
7605         struct drm_device *dev = crtc->base.dev;
7606         struct drm_i915_private *dev_priv = to_i915(dev);
7607         const struct intel_limit *limit;
7608         int refclk = 96000;
7609
7610         memset(&crtc_state->dpll_hw_state, 0,
7611                sizeof(crtc_state->dpll_hw_state));
7612
7613         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7614                 if (intel_panel_use_ssc(dev_priv)) {
7615                         refclk = dev_priv->vbt.lvds_ssc_freq;
7616                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7617                 }
7618
7619                 if (intel_is_dual_link_lvds(dev))
7620                         limit = &intel_limits_g4x_dual_channel_lvds;
7621                 else
7622                         limit = &intel_limits_g4x_single_channel_lvds;
7623         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7624                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7625                 limit = &intel_limits_g4x_hdmi;
7626         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7627                 limit = &intel_limits_g4x_sdvo;
7628         } else {
7629                 /* The option is for other outputs */
7630                 limit = &intel_limits_i9xx_sdvo;
7631         }
7632
7633         if (!crtc_state->clock_set &&
7634             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7635                                 refclk, NULL, &crtc_state->dpll)) {
7636                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7637                 return -EINVAL;
7638         }
7639
7640         i9xx_compute_dpll(crtc, crtc_state, NULL);
7641
7642         return 0;
7643 }
7644
7645 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7646                                   struct intel_crtc_state *crtc_state)
7647 {
7648         struct drm_device *dev = crtc->base.dev;
7649         struct drm_i915_private *dev_priv = to_i915(dev);
7650         const struct intel_limit *limit;
7651         int refclk = 96000;
7652
7653         memset(&crtc_state->dpll_hw_state, 0,
7654                sizeof(crtc_state->dpll_hw_state));
7655
7656         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7657                 if (intel_panel_use_ssc(dev_priv)) {
7658                         refclk = dev_priv->vbt.lvds_ssc_freq;
7659                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7660                 }
7661
7662                 limit = &intel_limits_pineview_lvds;
7663         } else {
7664                 limit = &intel_limits_pineview_sdvo;
7665         }
7666
7667         if (!crtc_state->clock_set &&
7668             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7669                                 refclk, NULL, &crtc_state->dpll)) {
7670                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7671                 return -EINVAL;
7672         }
7673
7674         i9xx_compute_dpll(crtc, crtc_state, NULL);
7675
7676         return 0;
7677 }
7678
7679 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7680                                    struct intel_crtc_state *crtc_state)
7681 {
7682         struct drm_device *dev = crtc->base.dev;
7683         struct drm_i915_private *dev_priv = to_i915(dev);
7684         const struct intel_limit *limit;
7685         int refclk = 96000;
7686
7687         memset(&crtc_state->dpll_hw_state, 0,
7688                sizeof(crtc_state->dpll_hw_state));
7689
7690         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7691                 if (intel_panel_use_ssc(dev_priv)) {
7692                         refclk = dev_priv->vbt.lvds_ssc_freq;
7693                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7694                 }
7695
7696                 limit = &intel_limits_i9xx_lvds;
7697         } else {
7698                 limit = &intel_limits_i9xx_sdvo;
7699         }
7700
7701         if (!crtc_state->clock_set &&
7702             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7703                                  refclk, NULL, &crtc_state->dpll)) {
7704                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7705                 return -EINVAL;
7706         }
7707
7708         i9xx_compute_dpll(crtc, crtc_state, NULL);
7709
7710         return 0;
7711 }
7712
7713 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7714                                   struct intel_crtc_state *crtc_state)
7715 {
7716         int refclk = 100000;
7717         const struct intel_limit *limit = &intel_limits_chv;
7718
7719         memset(&crtc_state->dpll_hw_state, 0,
7720                sizeof(crtc_state->dpll_hw_state));
7721
7722         if (!crtc_state->clock_set &&
7723             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7724                                 refclk, NULL, &crtc_state->dpll)) {
7725                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7726                 return -EINVAL;
7727         }
7728
7729         chv_compute_dpll(crtc, crtc_state);
7730
7731         return 0;
7732 }
7733
7734 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7735                                   struct intel_crtc_state *crtc_state)
7736 {
7737         int refclk = 100000;
7738         const struct intel_limit *limit = &intel_limits_vlv;
7739
7740         memset(&crtc_state->dpll_hw_state, 0,
7741                sizeof(crtc_state->dpll_hw_state));
7742
7743         if (!crtc_state->clock_set &&
7744             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7745                                 refclk, NULL, &crtc_state->dpll)) {
7746                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7747                 return -EINVAL;
7748         }
7749
7750         vlv_compute_dpll(crtc, crtc_state);
7751
7752         return 0;
7753 }
7754
7755 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7756                                  struct intel_crtc_state *pipe_config)
7757 {
7758         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7759         uint32_t tmp;
7760
7761         if (INTEL_GEN(dev_priv) <= 3 &&
7762             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7763                 return;
7764
7765         tmp = I915_READ(PFIT_CONTROL);
7766         if (!(tmp & PFIT_ENABLE))
7767                 return;
7768
7769         /* Check whether the pfit is attached to our pipe. */
7770         if (INTEL_GEN(dev_priv) < 4) {
7771                 if (crtc->pipe != PIPE_B)
7772                         return;
7773         } else {
7774                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7775                         return;
7776         }
7777
7778         pipe_config->gmch_pfit.control = tmp;
7779         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7780 }
7781
7782 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7783                                struct intel_crtc_state *pipe_config)
7784 {
7785         struct drm_device *dev = crtc->base.dev;
7786         struct drm_i915_private *dev_priv = to_i915(dev);
7787         int pipe = pipe_config->cpu_transcoder;
7788         struct dpll clock;
7789         u32 mdiv;
7790         int refclk = 100000;
7791
7792         /* In case of DSI, DPLL will not be used */
7793         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7794                 return;
7795
7796         mutex_lock(&dev_priv->sb_lock);
7797         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7798         mutex_unlock(&dev_priv->sb_lock);
7799
7800         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7801         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7802         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7803         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7804         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7805
7806         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7807 }
7808
7809 static void
7810 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7811                               struct intel_initial_plane_config *plane_config)
7812 {
7813         struct drm_device *dev = crtc->base.dev;
7814         struct drm_i915_private *dev_priv = to_i915(dev);
7815         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7816         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7817         enum pipe pipe;
7818         u32 val, base, offset;
7819         int fourcc, pixel_format;
7820         unsigned int aligned_height;
7821         struct drm_framebuffer *fb;
7822         struct intel_framebuffer *intel_fb;
7823
7824         if (!plane->get_hw_state(plane, &pipe))
7825                 return;
7826
7827         WARN_ON(pipe != crtc->pipe);
7828
7829         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7830         if (!intel_fb) {
7831                 DRM_DEBUG_KMS("failed to alloc fb\n");
7832                 return;
7833         }
7834
7835         fb = &intel_fb->base;
7836
7837         fb->dev = dev;
7838
7839         val = I915_READ(DSPCNTR(i9xx_plane));
7840
7841         if (INTEL_GEN(dev_priv) >= 4) {
7842                 if (val & DISPPLANE_TILED) {
7843                         plane_config->tiling = I915_TILING_X;
7844                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7845                 }
7846         }
7847
7848         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7849         fourcc = i9xx_format_to_fourcc(pixel_format);
7850         fb->format = drm_format_info(fourcc);
7851
7852         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7853                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7854                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7855         } else if (INTEL_GEN(dev_priv) >= 4) {
7856                 if (plane_config->tiling)
7857                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7858                 else
7859                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7860                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7861         } else {
7862                 base = I915_READ(DSPADDR(i9xx_plane));
7863         }
7864         plane_config->base = base;
7865
7866         val = I915_READ(PIPESRC(pipe));
7867         fb->width = ((val >> 16) & 0xfff) + 1;
7868         fb->height = ((val >> 0) & 0xfff) + 1;
7869
7870         val = I915_READ(DSPSTRIDE(i9xx_plane));
7871         fb->pitches[0] = val & 0xffffffc0;
7872
7873         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7874
7875         plane_config->size = fb->pitches[0] * aligned_height;
7876
7877         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7878                       crtc->base.name, plane->base.name, fb->width, fb->height,
7879                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7880                       plane_config->size);
7881
7882         plane_config->fb = intel_fb;
7883 }
7884
7885 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7886                                struct intel_crtc_state *pipe_config)
7887 {
7888         struct drm_device *dev = crtc->base.dev;
7889         struct drm_i915_private *dev_priv = to_i915(dev);
7890         int pipe = pipe_config->cpu_transcoder;
7891         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7892         struct dpll clock;
7893         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7894         int refclk = 100000;
7895
7896         /* In case of DSI, DPLL will not be used */
7897         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7898                 return;
7899
7900         mutex_lock(&dev_priv->sb_lock);
7901         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7902         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7903         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7904         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7905         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7906         mutex_unlock(&dev_priv->sb_lock);
7907
7908         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7909         clock.m2 = (pll_dw0 & 0xff) << 22;
7910         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7911                 clock.m2 |= pll_dw2 & 0x3fffff;
7912         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7913         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7914         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7915
7916         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7917 }
7918
7919 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7920                                  struct intel_crtc_state *pipe_config)
7921 {
7922         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7923         enum intel_display_power_domain power_domain;
7924         uint32_t tmp;
7925         bool ret;
7926
7927         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7928         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7929                 return false;
7930
7931         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7932         pipe_config->shared_dpll = NULL;
7933
7934         ret = false;
7935
7936         tmp = I915_READ(PIPECONF(crtc->pipe));
7937         if (!(tmp & PIPECONF_ENABLE))
7938                 goto out;
7939
7940         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7941             IS_CHERRYVIEW(dev_priv)) {
7942                 switch (tmp & PIPECONF_BPC_MASK) {
7943                 case PIPECONF_6BPC:
7944                         pipe_config->pipe_bpp = 18;
7945                         break;
7946                 case PIPECONF_8BPC:
7947                         pipe_config->pipe_bpp = 24;
7948                         break;
7949                 case PIPECONF_10BPC:
7950                         pipe_config->pipe_bpp = 30;
7951                         break;
7952                 default:
7953                         break;
7954                 }
7955         }
7956
7957         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7958             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7959                 pipe_config->limited_color_range = true;
7960
7961         if (INTEL_GEN(dev_priv) < 4)
7962                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7963
7964         intel_get_pipe_timings(crtc, pipe_config);
7965         intel_get_pipe_src_size(crtc, pipe_config);
7966
7967         i9xx_get_pfit_config(crtc, pipe_config);
7968
7969         if (INTEL_GEN(dev_priv) >= 4) {
7970                 /* No way to read it out on pipes B and C */
7971                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7972                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7973                 else
7974                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7975                 pipe_config->pixel_multiplier =
7976                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7977                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7978                 pipe_config->dpll_hw_state.dpll_md = tmp;
7979         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7980                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7981                 tmp = I915_READ(DPLL(crtc->pipe));
7982                 pipe_config->pixel_multiplier =
7983                         ((tmp & SDVO_MULTIPLIER_MASK)
7984                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7985         } else {
7986                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7987                  * port and will be fixed up in the encoder->get_config
7988                  * function. */
7989                 pipe_config->pixel_multiplier = 1;
7990         }
7991         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7992         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7993                 /*
7994                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7995                  * on 830. Filter it out here so that we don't
7996                  * report errors due to that.
7997                  */
7998                 if (IS_I830(dev_priv))
7999                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
8000
8001                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
8002                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
8003         } else {
8004                 /* Mask out read-only status bits. */
8005                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
8006                                                      DPLL_PORTC_READY_MASK |
8007                                                      DPLL_PORTB_READY_MASK);
8008         }
8009
8010         if (IS_CHERRYVIEW(dev_priv))
8011                 chv_crtc_clock_get(crtc, pipe_config);
8012         else if (IS_VALLEYVIEW(dev_priv))
8013                 vlv_crtc_clock_get(crtc, pipe_config);
8014         else
8015                 i9xx_crtc_clock_get(crtc, pipe_config);
8016
8017         /*
8018          * Normally the dotclock is filled in by the encoder .get_config()
8019          * but in case the pipe is enabled w/o any ports we need a sane
8020          * default.
8021          */
8022         pipe_config->base.adjusted_mode.crtc_clock =
8023                 pipe_config->port_clock / pipe_config->pixel_multiplier;
8024
8025         ret = true;
8026
8027 out:
8028         intel_display_power_put(dev_priv, power_domain);
8029
8030         return ret;
8031 }
8032
8033 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
8034 {
8035         struct intel_encoder *encoder;
8036         int i;
8037         u32 val, final;
8038         bool has_lvds = false;
8039         bool has_cpu_edp = false;
8040         bool has_panel = false;
8041         bool has_ck505 = false;
8042         bool can_ssc = false;
8043         bool using_ssc_source = false;
8044
8045         /* We need to take the global config into account */
8046         for_each_intel_encoder(&dev_priv->drm, encoder) {
8047                 switch (encoder->type) {
8048                 case INTEL_OUTPUT_LVDS:
8049                         has_panel = true;
8050                         has_lvds = true;
8051                         break;
8052                 case INTEL_OUTPUT_EDP:
8053                         has_panel = true;
8054                         if (encoder->port == PORT_A)
8055                                 has_cpu_edp = true;
8056                         break;
8057                 default:
8058                         break;
8059                 }
8060         }
8061
8062         if (HAS_PCH_IBX(dev_priv)) {
8063                 has_ck505 = dev_priv->vbt.display_clock_mode;
8064                 can_ssc = has_ck505;
8065         } else {
8066                 has_ck505 = false;
8067                 can_ssc = true;
8068         }
8069
8070         /* Check if any DPLLs are using the SSC source */
8071         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
8072                 u32 temp = I915_READ(PCH_DPLL(i));
8073
8074                 if (!(temp & DPLL_VCO_ENABLE))
8075                         continue;
8076
8077                 if ((temp & PLL_REF_INPUT_MASK) ==
8078                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
8079                         using_ssc_source = true;
8080                         break;
8081                 }
8082         }
8083
8084         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
8085                       has_panel, has_lvds, has_ck505, using_ssc_source);
8086
8087         /* Ironlake: try to setup display ref clock before DPLL
8088          * enabling. This is only under driver's control after
8089          * PCH B stepping, previous chipset stepping should be
8090          * ignoring this setting.
8091          */
8092         val = I915_READ(PCH_DREF_CONTROL);
8093
8094         /* As we must carefully and slowly disable/enable each source in turn,
8095          * compute the final state we want first and check if we need to
8096          * make any changes at all.
8097          */
8098         final = val;
8099         final &= ~DREF_NONSPREAD_SOURCE_MASK;
8100         if (has_ck505)
8101                 final |= DREF_NONSPREAD_CK505_ENABLE;
8102         else
8103                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
8104
8105         final &= ~DREF_SSC_SOURCE_MASK;
8106         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8107         final &= ~DREF_SSC1_ENABLE;
8108
8109         if (has_panel) {
8110                 final |= DREF_SSC_SOURCE_ENABLE;
8111
8112                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
8113                         final |= DREF_SSC1_ENABLE;
8114
8115                 if (has_cpu_edp) {
8116                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
8117                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8118                         else
8119                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8120                 } else
8121                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8122         } else if (using_ssc_source) {
8123                 final |= DREF_SSC_SOURCE_ENABLE;
8124                 final |= DREF_SSC1_ENABLE;
8125         }
8126
8127         if (final == val)
8128                 return;
8129
8130         /* Always enable nonspread source */
8131         val &= ~DREF_NONSPREAD_SOURCE_MASK;
8132
8133         if (has_ck505)
8134                 val |= DREF_NONSPREAD_CK505_ENABLE;
8135         else
8136                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
8137
8138         if (has_panel) {
8139                 val &= ~DREF_SSC_SOURCE_MASK;
8140                 val |= DREF_SSC_SOURCE_ENABLE;
8141
8142                 /* SSC must be turned on before enabling the CPU output  */
8143                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8144                         DRM_DEBUG_KMS("Using SSC on panel\n");
8145                         val |= DREF_SSC1_ENABLE;
8146                 } else
8147                         val &= ~DREF_SSC1_ENABLE;
8148
8149                 /* Get SSC going before enabling the outputs */
8150                 I915_WRITE(PCH_DREF_CONTROL, val);
8151                 POSTING_READ(PCH_DREF_CONTROL);
8152                 udelay(200);
8153
8154                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8155
8156                 /* Enable CPU source on CPU attached eDP */
8157                 if (has_cpu_edp) {
8158                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
8159                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
8160                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
8161                         } else
8162                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
8163                 } else
8164                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8165
8166                 I915_WRITE(PCH_DREF_CONTROL, val);
8167                 POSTING_READ(PCH_DREF_CONTROL);
8168                 udelay(200);
8169         } else {
8170                 DRM_DEBUG_KMS("Disabling CPU source output\n");
8171
8172                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
8173
8174                 /* Turn off CPU output */
8175                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
8176
8177                 I915_WRITE(PCH_DREF_CONTROL, val);
8178                 POSTING_READ(PCH_DREF_CONTROL);
8179                 udelay(200);
8180
8181                 if (!using_ssc_source) {
8182                         DRM_DEBUG_KMS("Disabling SSC source\n");
8183
8184                         /* Turn off the SSC source */
8185                         val &= ~DREF_SSC_SOURCE_MASK;
8186                         val |= DREF_SSC_SOURCE_DISABLE;
8187
8188                         /* Turn off SSC1 */
8189                         val &= ~DREF_SSC1_ENABLE;
8190
8191                         I915_WRITE(PCH_DREF_CONTROL, val);
8192                         POSTING_READ(PCH_DREF_CONTROL);
8193                         udelay(200);
8194                 }
8195         }
8196
8197         BUG_ON(val != final);
8198 }
8199
8200 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
8201 {
8202         uint32_t tmp;
8203
8204         tmp = I915_READ(SOUTH_CHICKEN2);
8205         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
8206         I915_WRITE(SOUTH_CHICKEN2, tmp);
8207
8208         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
8209                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
8210                 DRM_ERROR("FDI mPHY reset assert timeout\n");
8211
8212         tmp = I915_READ(SOUTH_CHICKEN2);
8213         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
8214         I915_WRITE(SOUTH_CHICKEN2, tmp);
8215
8216         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
8217                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
8218                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
8219 }
8220
8221 /* WaMPhyProgramming:hsw */
8222 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
8223 {
8224         uint32_t tmp;
8225
8226         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
8227         tmp &= ~(0xFF << 24);
8228         tmp |= (0x12 << 24);
8229         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
8230
8231         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
8232         tmp |= (1 << 11);
8233         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
8234
8235         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
8236         tmp |= (1 << 11);
8237         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
8238
8239         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
8240         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8241         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
8242
8243         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
8244         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
8245         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
8246
8247         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
8248         tmp &= ~(7 << 13);
8249         tmp |= (5 << 13);
8250         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
8251
8252         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
8253         tmp &= ~(7 << 13);
8254         tmp |= (5 << 13);
8255         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
8256
8257         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
8258         tmp &= ~0xFF;
8259         tmp |= 0x1C;
8260         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
8261
8262         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
8263         tmp &= ~0xFF;
8264         tmp |= 0x1C;
8265         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
8266
8267         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
8268         tmp &= ~(0xFF << 16);
8269         tmp |= (0x1C << 16);
8270         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
8271
8272         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
8273         tmp &= ~(0xFF << 16);
8274         tmp |= (0x1C << 16);
8275         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
8276
8277         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8278         tmp |= (1 << 27);
8279         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8280
8281         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8282         tmp |= (1 << 27);
8283         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8284
8285         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8286         tmp &= ~(0xF << 28);
8287         tmp |= (4 << 28);
8288         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8289
8290         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8291         tmp &= ~(0xF << 28);
8292         tmp |= (4 << 28);
8293         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8294 }
8295
8296 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8297  * Programming" based on the parameters passed:
8298  * - Sequence to enable CLKOUT_DP
8299  * - Sequence to enable CLKOUT_DP without spread
8300  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8301  */
8302 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8303                                  bool with_spread, bool with_fdi)
8304 {
8305         uint32_t reg, tmp;
8306
8307         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8308                 with_spread = true;
8309         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8310             with_fdi, "LP PCH doesn't have FDI\n"))
8311                 with_fdi = false;
8312
8313         mutex_lock(&dev_priv->sb_lock);
8314
8315         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8316         tmp &= ~SBI_SSCCTL_DISABLE;
8317         tmp |= SBI_SSCCTL_PATHALT;
8318         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8319
8320         udelay(24);
8321
8322         if (with_spread) {
8323                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8324                 tmp &= ~SBI_SSCCTL_PATHALT;
8325                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8326
8327                 if (with_fdi) {
8328                         lpt_reset_fdi_mphy(dev_priv);
8329                         lpt_program_fdi_mphy(dev_priv);
8330                 }
8331         }
8332
8333         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8334         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8335         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8336         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8337
8338         mutex_unlock(&dev_priv->sb_lock);
8339 }
8340
8341 /* Sequence to disable CLKOUT_DP */
8342 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8343 {
8344         uint32_t reg, tmp;
8345
8346         mutex_lock(&dev_priv->sb_lock);
8347
8348         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8349         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8350         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8351         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8352
8353         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8354         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8355                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8356                         tmp |= SBI_SSCCTL_PATHALT;
8357                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8358                         udelay(32);
8359                 }
8360                 tmp |= SBI_SSCCTL_DISABLE;
8361                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8362         }
8363
8364         mutex_unlock(&dev_priv->sb_lock);
8365 }
8366
8367 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8368
8369 static const uint16_t sscdivintphase[] = {
8370         [BEND_IDX( 50)] = 0x3B23,
8371         [BEND_IDX( 45)] = 0x3B23,
8372         [BEND_IDX( 40)] = 0x3C23,
8373         [BEND_IDX( 35)] = 0x3C23,
8374         [BEND_IDX( 30)] = 0x3D23,
8375         [BEND_IDX( 25)] = 0x3D23,
8376         [BEND_IDX( 20)] = 0x3E23,
8377         [BEND_IDX( 15)] = 0x3E23,
8378         [BEND_IDX( 10)] = 0x3F23,
8379         [BEND_IDX(  5)] = 0x3F23,
8380         [BEND_IDX(  0)] = 0x0025,
8381         [BEND_IDX( -5)] = 0x0025,
8382         [BEND_IDX(-10)] = 0x0125,
8383         [BEND_IDX(-15)] = 0x0125,
8384         [BEND_IDX(-20)] = 0x0225,
8385         [BEND_IDX(-25)] = 0x0225,
8386         [BEND_IDX(-30)] = 0x0325,
8387         [BEND_IDX(-35)] = 0x0325,
8388         [BEND_IDX(-40)] = 0x0425,
8389         [BEND_IDX(-45)] = 0x0425,
8390         [BEND_IDX(-50)] = 0x0525,
8391 };
8392
8393 /*
8394  * Bend CLKOUT_DP
8395  * steps -50 to 50 inclusive, in steps of 5
8396  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8397  * change in clock period = -(steps / 10) * 5.787 ps
8398  */
8399 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8400 {
8401         uint32_t tmp;
8402         int idx = BEND_IDX(steps);
8403
8404         if (WARN_ON(steps % 5 != 0))
8405                 return;
8406
8407         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8408                 return;
8409
8410         mutex_lock(&dev_priv->sb_lock);
8411
8412         if (steps % 10 != 0)
8413                 tmp = 0xAAAAAAAB;
8414         else
8415                 tmp = 0x00000000;
8416         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8417
8418         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8419         tmp &= 0xffff0000;
8420         tmp |= sscdivintphase[idx];
8421         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8422
8423         mutex_unlock(&dev_priv->sb_lock);
8424 }
8425
8426 #undef BEND_IDX
8427
8428 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8429 {
8430         struct intel_encoder *encoder;
8431         bool has_vga = false;
8432
8433         for_each_intel_encoder(&dev_priv->drm, encoder) {
8434                 switch (encoder->type) {
8435                 case INTEL_OUTPUT_ANALOG:
8436                         has_vga = true;
8437                         break;
8438                 default:
8439                         break;
8440                 }
8441         }
8442
8443         if (has_vga) {
8444                 lpt_bend_clkout_dp(dev_priv, 0);
8445                 lpt_enable_clkout_dp(dev_priv, true, true);
8446         } else {
8447                 lpt_disable_clkout_dp(dev_priv);
8448         }
8449 }
8450
8451 /*
8452  * Initialize reference clocks when the driver loads
8453  */
8454 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8455 {
8456         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8457                 ironlake_init_pch_refclk(dev_priv);
8458         else if (HAS_PCH_LPT(dev_priv))
8459                 lpt_init_pch_refclk(dev_priv);
8460 }
8461
8462 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8463 {
8464         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8465         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8466         int pipe = intel_crtc->pipe;
8467         uint32_t val;
8468
8469         val = 0;
8470
8471         switch (intel_crtc->config->pipe_bpp) {
8472         case 18:
8473                 val |= PIPECONF_6BPC;
8474                 break;
8475         case 24:
8476                 val |= PIPECONF_8BPC;
8477                 break;
8478         case 30:
8479                 val |= PIPECONF_10BPC;
8480                 break;
8481         case 36:
8482                 val |= PIPECONF_12BPC;
8483                 break;
8484         default:
8485                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8486                 BUG();
8487         }
8488
8489         if (intel_crtc->config->dither)
8490                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8491
8492         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8493                 val |= PIPECONF_INTERLACED_ILK;
8494         else
8495                 val |= PIPECONF_PROGRESSIVE;
8496
8497         if (intel_crtc->config->limited_color_range)
8498                 val |= PIPECONF_COLOR_RANGE_SELECT;
8499
8500         I915_WRITE(PIPECONF(pipe), val);
8501         POSTING_READ(PIPECONF(pipe));
8502 }
8503
8504 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8505 {
8506         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8507         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8508         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8509         u32 val = 0;
8510
8511         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8512                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8513
8514         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8515                 val |= PIPECONF_INTERLACED_ILK;
8516         else
8517                 val |= PIPECONF_PROGRESSIVE;
8518
8519         I915_WRITE(PIPECONF(cpu_transcoder), val);
8520         POSTING_READ(PIPECONF(cpu_transcoder));
8521 }
8522
8523 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8524 {
8525         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8526         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8527         struct intel_crtc_state *config = intel_crtc->config;
8528
8529         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8530                 u32 val = 0;
8531
8532                 switch (intel_crtc->config->pipe_bpp) {
8533                 case 18:
8534                         val |= PIPEMISC_DITHER_6_BPC;
8535                         break;
8536                 case 24:
8537                         val |= PIPEMISC_DITHER_8_BPC;
8538                         break;
8539                 case 30:
8540                         val |= PIPEMISC_DITHER_10_BPC;
8541                         break;
8542                 case 36:
8543                         val |= PIPEMISC_DITHER_12_BPC;
8544                         break;
8545                 default:
8546                         /* Case prevented by pipe_config_set_bpp. */
8547                         BUG();
8548                 }
8549
8550                 if (intel_crtc->config->dither)
8551                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8552
8553                 if (config->ycbcr420) {
8554                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8555                                 PIPEMISC_YUV420_ENABLE |
8556                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8557                 }
8558
8559                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8560         }
8561 }
8562
8563 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8564 {
8565         /*
8566          * Account for spread spectrum to avoid
8567          * oversubscribing the link. Max center spread
8568          * is 2.5%; use 5% for safety's sake.
8569          */
8570         u32 bps = target_clock * bpp * 21 / 20;
8571         return DIV_ROUND_UP(bps, link_bw * 8);
8572 }
8573
8574 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8575 {
8576         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8577 }
8578
8579 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8580                                   struct intel_crtc_state *crtc_state,
8581                                   struct dpll *reduced_clock)
8582 {
8583         struct drm_crtc *crtc = &intel_crtc->base;
8584         struct drm_device *dev = crtc->dev;
8585         struct drm_i915_private *dev_priv = to_i915(dev);
8586         u32 dpll, fp, fp2;
8587         int factor;
8588
8589         /* Enable autotuning of the PLL clock (if permissible) */
8590         factor = 21;
8591         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8592                 if ((intel_panel_use_ssc(dev_priv) &&
8593                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8594                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8595                         factor = 25;
8596         } else if (crtc_state->sdvo_tv_clock)
8597                 factor = 20;
8598
8599         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8600
8601         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8602                 fp |= FP_CB_TUNE;
8603
8604         if (reduced_clock) {
8605                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8606
8607                 if (reduced_clock->m < factor * reduced_clock->n)
8608                         fp2 |= FP_CB_TUNE;
8609         } else {
8610                 fp2 = fp;
8611         }
8612
8613         dpll = 0;
8614
8615         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8616                 dpll |= DPLLB_MODE_LVDS;
8617         else
8618                 dpll |= DPLLB_MODE_DAC_SERIAL;
8619
8620         dpll |= (crtc_state->pixel_multiplier - 1)
8621                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8622
8623         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8624             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8625                 dpll |= DPLL_SDVO_HIGH_SPEED;
8626
8627         if (intel_crtc_has_dp_encoder(crtc_state))
8628                 dpll |= DPLL_SDVO_HIGH_SPEED;
8629
8630         /*
8631          * The high speed IO clock is only really required for
8632          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8633          * possible to share the DPLL between CRT and HDMI. Enabling
8634          * the clock needlessly does no real harm, except use up a
8635          * bit of power potentially.
8636          *
8637          * We'll limit this to IVB with 3 pipes, since it has only two
8638          * DPLLs and so DPLL sharing is the only way to get three pipes
8639          * driving PCH ports at the same time. On SNB we could do this,
8640          * and potentially avoid enabling the second DPLL, but it's not
8641          * clear if it''s a win or loss power wise. No point in doing
8642          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8643          */
8644         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8645             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8646                 dpll |= DPLL_SDVO_HIGH_SPEED;
8647
8648         /* compute bitmask from p1 value */
8649         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8650         /* also FPA1 */
8651         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8652
8653         switch (crtc_state->dpll.p2) {
8654         case 5:
8655                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8656                 break;
8657         case 7:
8658                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8659                 break;
8660         case 10:
8661                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8662                 break;
8663         case 14:
8664                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8665                 break;
8666         }
8667
8668         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8669             intel_panel_use_ssc(dev_priv))
8670                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8671         else
8672                 dpll |= PLL_REF_INPUT_DREFCLK;
8673
8674         dpll |= DPLL_VCO_ENABLE;
8675
8676         crtc_state->dpll_hw_state.dpll = dpll;
8677         crtc_state->dpll_hw_state.fp0 = fp;
8678         crtc_state->dpll_hw_state.fp1 = fp2;
8679 }
8680
8681 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8682                                        struct intel_crtc_state *crtc_state)
8683 {
8684         struct drm_device *dev = crtc->base.dev;
8685         struct drm_i915_private *dev_priv = to_i915(dev);
8686         const struct intel_limit *limit;
8687         int refclk = 120000;
8688
8689         memset(&crtc_state->dpll_hw_state, 0,
8690                sizeof(crtc_state->dpll_hw_state));
8691
8692         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8693         if (!crtc_state->has_pch_encoder)
8694                 return 0;
8695
8696         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8697                 if (intel_panel_use_ssc(dev_priv)) {
8698                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8699                                       dev_priv->vbt.lvds_ssc_freq);
8700                         refclk = dev_priv->vbt.lvds_ssc_freq;
8701                 }
8702
8703                 if (intel_is_dual_link_lvds(dev)) {
8704                         if (refclk == 100000)
8705                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8706                         else
8707                                 limit = &intel_limits_ironlake_dual_lvds;
8708                 } else {
8709                         if (refclk == 100000)
8710                                 limit = &intel_limits_ironlake_single_lvds_100m;
8711                         else
8712                                 limit = &intel_limits_ironlake_single_lvds;
8713                 }
8714         } else {
8715                 limit = &intel_limits_ironlake_dac;
8716         }
8717
8718         if (!crtc_state->clock_set &&
8719             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8720                                 refclk, NULL, &crtc_state->dpll)) {
8721                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8722                 return -EINVAL;
8723         }
8724
8725         ironlake_compute_dpll(crtc, crtc_state, NULL);
8726
8727         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8728                 DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
8729                               pipe_name(crtc->pipe));
8730                 return -EINVAL;
8731         }
8732
8733         return 0;
8734 }
8735
8736 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8737                                          struct intel_link_m_n *m_n)
8738 {
8739         struct drm_device *dev = crtc->base.dev;
8740         struct drm_i915_private *dev_priv = to_i915(dev);
8741         enum pipe pipe = crtc->pipe;
8742
8743         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8744         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8745         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8746                 & ~TU_SIZE_MASK;
8747         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8748         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8749                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8750 }
8751
8752 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8753                                          enum transcoder transcoder,
8754                                          struct intel_link_m_n *m_n,
8755                                          struct intel_link_m_n *m2_n2)
8756 {
8757         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8758         enum pipe pipe = crtc->pipe;
8759
8760         if (INTEL_GEN(dev_priv) >= 5) {
8761                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8762                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8763                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8764                         & ~TU_SIZE_MASK;
8765                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8766                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8767                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8768                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8769                  * gen < 8) and if DRRS is supported (to make sure the
8770                  * registers are not unnecessarily read).
8771                  */
8772                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8773                         crtc->config->has_drrs) {
8774                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8775                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8776                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8777                                         & ~TU_SIZE_MASK;
8778                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8779                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8780                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8781                 }
8782         } else {
8783                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8784                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8785                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8786                         & ~TU_SIZE_MASK;
8787                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8788                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8789                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8790         }
8791 }
8792
8793 void intel_dp_get_m_n(struct intel_crtc *crtc,
8794                       struct intel_crtc_state *pipe_config)
8795 {
8796         if (pipe_config->has_pch_encoder)
8797                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8798         else
8799                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8800                                              &pipe_config->dp_m_n,
8801                                              &pipe_config->dp_m2_n2);
8802 }
8803
8804 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8805                                         struct intel_crtc_state *pipe_config)
8806 {
8807         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8808                                      &pipe_config->fdi_m_n, NULL);
8809 }
8810
8811 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8812                                     struct intel_crtc_state *pipe_config)
8813 {
8814         struct drm_device *dev = crtc->base.dev;
8815         struct drm_i915_private *dev_priv = to_i915(dev);
8816         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8817         uint32_t ps_ctrl = 0;
8818         int id = -1;
8819         int i;
8820
8821         /* find scaler attached to this pipe */
8822         for (i = 0; i < crtc->num_scalers; i++) {
8823                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8824                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8825                         id = i;
8826                         pipe_config->pch_pfit.enabled = true;
8827                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8828                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8829                         break;
8830                 }
8831         }
8832
8833         scaler_state->scaler_id = id;
8834         if (id >= 0) {
8835                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8836         } else {
8837                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8838         }
8839 }
8840
8841 static void
8842 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8843                                  struct intel_initial_plane_config *plane_config)
8844 {
8845         struct drm_device *dev = crtc->base.dev;
8846         struct drm_i915_private *dev_priv = to_i915(dev);
8847         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8848         enum plane_id plane_id = plane->id;
8849         enum pipe pipe;
8850         u32 val, base, offset, stride_mult, tiling, alpha;
8851         int fourcc, pixel_format;
8852         unsigned int aligned_height;
8853         struct drm_framebuffer *fb;
8854         struct intel_framebuffer *intel_fb;
8855
8856         if (!plane->get_hw_state(plane, &pipe))
8857                 return;
8858
8859         WARN_ON(pipe != crtc->pipe);
8860
8861         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8862         if (!intel_fb) {
8863                 DRM_DEBUG_KMS("failed to alloc fb\n");
8864                 return;
8865         }
8866
8867         fb = &intel_fb->base;
8868
8869         fb->dev = dev;
8870
8871         val = I915_READ(PLANE_CTL(pipe, plane_id));
8872
8873         if (INTEL_GEN(dev_priv) >= 11)
8874                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8875         else
8876                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8877
8878         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8879                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8880                 alpha &= PLANE_COLOR_ALPHA_MASK;
8881         } else {
8882                 alpha = val & PLANE_CTL_ALPHA_MASK;
8883         }
8884
8885         fourcc = skl_format_to_fourcc(pixel_format,
8886                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8887         fb->format = drm_format_info(fourcc);
8888
8889         tiling = val & PLANE_CTL_TILED_MASK;
8890         switch (tiling) {
8891         case PLANE_CTL_TILED_LINEAR:
8892                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8893                 break;
8894         case PLANE_CTL_TILED_X:
8895                 plane_config->tiling = I915_TILING_X;
8896                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8897                 break;
8898         case PLANE_CTL_TILED_Y:
8899                 plane_config->tiling = I915_TILING_Y;
8900                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8901                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8902                 else
8903                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8904                 break;
8905         case PLANE_CTL_TILED_YF:
8906                 if (val & PLANE_CTL_RENDER_DECOMPRESSION_ENABLE)
8907                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8908                 else
8909                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8910                 break;
8911         default:
8912                 MISSING_CASE(tiling);
8913                 goto error;
8914         }
8915
8916         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8917         plane_config->base = base;
8918
8919         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8920
8921         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8922         fb->height = ((val >> 16) & 0xfff) + 1;
8923         fb->width = ((val >> 0) & 0x1fff) + 1;
8924
8925         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8926         stride_mult = intel_fb_stride_alignment(fb, 0);
8927         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8928
8929         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8930
8931         plane_config->size = fb->pitches[0] * aligned_height;
8932
8933         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8934                       crtc->base.name, plane->base.name, fb->width, fb->height,
8935                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8936                       plane_config->size);
8937
8938         plane_config->fb = intel_fb;
8939         return;
8940
8941 error:
8942         kfree(intel_fb);
8943 }
8944
8945 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8946                                      struct intel_crtc_state *pipe_config)
8947 {
8948         struct drm_device *dev = crtc->base.dev;
8949         struct drm_i915_private *dev_priv = to_i915(dev);
8950         uint32_t tmp;
8951
8952         tmp = I915_READ(PF_CTL(crtc->pipe));
8953
8954         if (tmp & PF_ENABLE) {
8955                 pipe_config->pch_pfit.enabled = true;
8956                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8957                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8958
8959                 /* We currently do not free assignements of panel fitters on
8960                  * ivb/hsw (since we don't use the higher upscaling modes which
8961                  * differentiates them) so just WARN about this case for now. */
8962                 if (IS_GEN7(dev_priv)) {
8963                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8964                                 PF_PIPE_SEL_IVB(crtc->pipe));
8965                 }
8966         }
8967 }
8968
8969 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8970                                      struct intel_crtc_state *pipe_config)
8971 {
8972         struct drm_device *dev = crtc->base.dev;
8973         struct drm_i915_private *dev_priv = to_i915(dev);
8974         enum intel_display_power_domain power_domain;
8975         uint32_t tmp;
8976         bool ret;
8977
8978         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8979         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8980                 return false;
8981
8982         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8983         pipe_config->shared_dpll = NULL;
8984
8985         ret = false;
8986         tmp = I915_READ(PIPECONF(crtc->pipe));
8987         if (!(tmp & PIPECONF_ENABLE))
8988                 goto out;
8989
8990         switch (tmp & PIPECONF_BPC_MASK) {
8991         case PIPECONF_6BPC:
8992                 pipe_config->pipe_bpp = 18;
8993                 break;
8994         case PIPECONF_8BPC:
8995                 pipe_config->pipe_bpp = 24;
8996                 break;
8997         case PIPECONF_10BPC:
8998                 pipe_config->pipe_bpp = 30;
8999                 break;
9000         case PIPECONF_12BPC:
9001                 pipe_config->pipe_bpp = 36;
9002                 break;
9003         default:
9004                 break;
9005         }
9006
9007         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
9008                 pipe_config->limited_color_range = true;
9009
9010         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
9011                 struct intel_shared_dpll *pll;
9012                 enum intel_dpll_id pll_id;
9013
9014                 pipe_config->has_pch_encoder = true;
9015
9016                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
9017                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9018                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9019
9020                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9021
9022                 if (HAS_PCH_IBX(dev_priv)) {
9023                         /*
9024                          * The pipe->pch transcoder and pch transcoder->pll
9025                          * mapping is fixed.
9026                          */
9027                         pll_id = (enum intel_dpll_id) crtc->pipe;
9028                 } else {
9029                         tmp = I915_READ(PCH_DPLL_SEL);
9030                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
9031                                 pll_id = DPLL_ID_PCH_PLL_B;
9032                         else
9033                                 pll_id= DPLL_ID_PCH_PLL_A;
9034                 }
9035
9036                 pipe_config->shared_dpll =
9037                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
9038                 pll = pipe_config->shared_dpll;
9039
9040                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9041                                                 &pipe_config->dpll_hw_state));
9042
9043                 tmp = pipe_config->dpll_hw_state.dpll;
9044                 pipe_config->pixel_multiplier =
9045                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
9046                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
9047
9048                 ironlake_pch_clock_get(crtc, pipe_config);
9049         } else {
9050                 pipe_config->pixel_multiplier = 1;
9051         }
9052
9053         intel_get_pipe_timings(crtc, pipe_config);
9054         intel_get_pipe_src_size(crtc, pipe_config);
9055
9056         ironlake_get_pfit_config(crtc, pipe_config);
9057
9058         ret = true;
9059
9060 out:
9061         intel_display_power_put(dev_priv, power_domain);
9062
9063         return ret;
9064 }
9065
9066 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
9067 {
9068         struct drm_device *dev = &dev_priv->drm;
9069         struct intel_crtc *crtc;
9070
9071         for_each_intel_crtc(dev, crtc)
9072                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
9073                      pipe_name(crtc->pipe));
9074
9075         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL2),
9076                         "Display power well on\n");
9077         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
9078         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
9079         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
9080         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
9081         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
9082              "CPU PWM1 enabled\n");
9083         if (IS_HASWELL(dev_priv))
9084                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
9085                      "CPU PWM2 enabled\n");
9086         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
9087              "PCH PWM1 enabled\n");
9088         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
9089              "Utility pin enabled\n");
9090         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
9091
9092         /*
9093          * In theory we can still leave IRQs enabled, as long as only the HPD
9094          * interrupts remain enabled. We used to check for that, but since it's
9095          * gen-specific and since we only disable LCPLL after we fully disable
9096          * the interrupts, the check below should be enough.
9097          */
9098         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
9099 }
9100
9101 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
9102 {
9103         if (IS_HASWELL(dev_priv))
9104                 return I915_READ(D_COMP_HSW);
9105         else
9106                 return I915_READ(D_COMP_BDW);
9107 }
9108
9109 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
9110 {
9111         if (IS_HASWELL(dev_priv)) {
9112                 mutex_lock(&dev_priv->pcu_lock);
9113                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
9114                                             val))
9115                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
9116                 mutex_unlock(&dev_priv->pcu_lock);
9117         } else {
9118                 I915_WRITE(D_COMP_BDW, val);
9119                 POSTING_READ(D_COMP_BDW);
9120         }
9121 }
9122
9123 /*
9124  * This function implements pieces of two sequences from BSpec:
9125  * - Sequence for display software to disable LCPLL
9126  * - Sequence for display software to allow package C8+
9127  * The steps implemented here are just the steps that actually touch the LCPLL
9128  * register. Callers should take care of disabling all the display engine
9129  * functions, doing the mode unset, fixing interrupts, etc.
9130  */
9131 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
9132                               bool switch_to_fclk, bool allow_power_down)
9133 {
9134         uint32_t val;
9135
9136         assert_can_disable_lcpll(dev_priv);
9137
9138         val = I915_READ(LCPLL_CTL);
9139
9140         if (switch_to_fclk) {
9141                 val |= LCPLL_CD_SOURCE_FCLK;
9142                 I915_WRITE(LCPLL_CTL, val);
9143
9144                 if (wait_for_us(I915_READ(LCPLL_CTL) &
9145                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
9146                         DRM_ERROR("Switching to FCLK failed\n");
9147
9148                 val = I915_READ(LCPLL_CTL);
9149         }
9150
9151         val |= LCPLL_PLL_DISABLE;
9152         I915_WRITE(LCPLL_CTL, val);
9153         POSTING_READ(LCPLL_CTL);
9154
9155         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
9156                 DRM_ERROR("LCPLL still locked\n");
9157
9158         val = hsw_read_dcomp(dev_priv);
9159         val |= D_COMP_COMP_DISABLE;
9160         hsw_write_dcomp(dev_priv, val);
9161         ndelay(100);
9162
9163         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
9164                      1))
9165                 DRM_ERROR("D_COMP RCOMP still in progress\n");
9166
9167         if (allow_power_down) {
9168                 val = I915_READ(LCPLL_CTL);
9169                 val |= LCPLL_POWER_DOWN_ALLOW;
9170                 I915_WRITE(LCPLL_CTL, val);
9171                 POSTING_READ(LCPLL_CTL);
9172         }
9173 }
9174
9175 /*
9176  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
9177  * source.
9178  */
9179 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
9180 {
9181         uint32_t val;
9182
9183         val = I915_READ(LCPLL_CTL);
9184
9185         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
9186                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
9187                 return;
9188
9189         /*
9190          * Make sure we're not on PC8 state before disabling PC8, otherwise
9191          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
9192          */
9193         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
9194
9195         if (val & LCPLL_POWER_DOWN_ALLOW) {
9196                 val &= ~LCPLL_POWER_DOWN_ALLOW;
9197                 I915_WRITE(LCPLL_CTL, val);
9198                 POSTING_READ(LCPLL_CTL);
9199         }
9200
9201         val = hsw_read_dcomp(dev_priv);
9202         val |= D_COMP_COMP_FORCE;
9203         val &= ~D_COMP_COMP_DISABLE;
9204         hsw_write_dcomp(dev_priv, val);
9205
9206         val = I915_READ(LCPLL_CTL);
9207         val &= ~LCPLL_PLL_DISABLE;
9208         I915_WRITE(LCPLL_CTL, val);
9209
9210         if (intel_wait_for_register(dev_priv,
9211                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
9212                                     5))
9213                 DRM_ERROR("LCPLL not locked yet\n");
9214
9215         if (val & LCPLL_CD_SOURCE_FCLK) {
9216                 val = I915_READ(LCPLL_CTL);
9217                 val &= ~LCPLL_CD_SOURCE_FCLK;
9218                 I915_WRITE(LCPLL_CTL, val);
9219
9220                 if (wait_for_us((I915_READ(LCPLL_CTL) &
9221                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
9222                         DRM_ERROR("Switching back to LCPLL failed\n");
9223         }
9224
9225         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
9226
9227         intel_update_cdclk(dev_priv);
9228         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
9229 }
9230
9231 /*
9232  * Package states C8 and deeper are really deep PC states that can only be
9233  * reached when all the devices on the system allow it, so even if the graphics
9234  * device allows PC8+, it doesn't mean the system will actually get to these
9235  * states. Our driver only allows PC8+ when going into runtime PM.
9236  *
9237  * The requirements for PC8+ are that all the outputs are disabled, the power
9238  * well is disabled and most interrupts are disabled, and these are also
9239  * requirements for runtime PM. When these conditions are met, we manually do
9240  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
9241  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
9242  * hang the machine.
9243  *
9244  * When we really reach PC8 or deeper states (not just when we allow it) we lose
9245  * the state of some registers, so when we come back from PC8+ we need to
9246  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
9247  * need to take care of the registers kept by RC6. Notice that this happens even
9248  * if we don't put the device in PCI D3 state (which is what currently happens
9249  * because of the runtime PM support).
9250  *
9251  * For more, read "Display Sequences for Package C8" on the hardware
9252  * documentation.
9253  */
9254 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
9255 {
9256         uint32_t val;
9257
9258         DRM_DEBUG_KMS("Enabling package C8+\n");
9259
9260         if (HAS_PCH_LPT_LP(dev_priv)) {
9261                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9262                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
9263                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9264         }
9265
9266         lpt_disable_clkout_dp(dev_priv);
9267         hsw_disable_lcpll(dev_priv, true, true);
9268 }
9269
9270 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
9271 {
9272         uint32_t val;
9273
9274         DRM_DEBUG_KMS("Disabling package C8+\n");
9275
9276         hsw_restore_lcpll(dev_priv);
9277         lpt_init_pch_refclk(dev_priv);
9278
9279         if (HAS_PCH_LPT_LP(dev_priv)) {
9280                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9281                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9282                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9283         }
9284 }
9285
9286 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9287                                       struct intel_crtc_state *crtc_state)
9288 {
9289         struct intel_atomic_state *state =
9290                 to_intel_atomic_state(crtc_state->base.state);
9291
9292         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9293                 struct intel_encoder *encoder =
9294                         intel_get_crtc_new_encoder(state, crtc_state);
9295
9296                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9297                         DRM_DEBUG_KMS("failed to find PLL for pipe %c\n",
9298                                       pipe_name(crtc->pipe));
9299                         return -EINVAL;
9300                 }
9301         }
9302
9303         return 0;
9304 }
9305
9306 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9307                                    enum port port,
9308                                    struct intel_crtc_state *pipe_config)
9309 {
9310         enum intel_dpll_id id;
9311         u32 temp;
9312
9313         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9314         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9315
9316         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9317                 return;
9318
9319         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9320 }
9321
9322 static void icelake_get_ddi_pll(struct drm_i915_private *dev_priv,
9323                                 enum port port,
9324                                 struct intel_crtc_state *pipe_config)
9325 {
9326         enum intel_dpll_id id;
9327         u32 temp;
9328
9329         /* TODO: TBT pll not implemented. */
9330         switch (port) {
9331         case PORT_A:
9332         case PORT_B:
9333                 temp = I915_READ(DPCLKA_CFGCR0_ICL) &
9334                        DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9335                 id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9336
9337                 if (WARN_ON(id != DPLL_ID_ICL_DPLL0 && id != DPLL_ID_ICL_DPLL1))
9338                         return;
9339                 break;
9340         case PORT_C:
9341                 id = DPLL_ID_ICL_MGPLL1;
9342                 break;
9343         case PORT_D:
9344                 id = DPLL_ID_ICL_MGPLL2;
9345                 break;
9346         case PORT_E:
9347                 id = DPLL_ID_ICL_MGPLL3;
9348                 break;
9349         case PORT_F:
9350                 id = DPLL_ID_ICL_MGPLL4;
9351                 break;
9352         default:
9353                 MISSING_CASE(port);
9354                 return;
9355         }
9356
9357         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9358 }
9359
9360 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9361                                 enum port port,
9362                                 struct intel_crtc_state *pipe_config)
9363 {
9364         enum intel_dpll_id id;
9365
9366         switch (port) {
9367         case PORT_A:
9368                 id = DPLL_ID_SKL_DPLL0;
9369                 break;
9370         case PORT_B:
9371                 id = DPLL_ID_SKL_DPLL1;
9372                 break;
9373         case PORT_C:
9374                 id = DPLL_ID_SKL_DPLL2;
9375                 break;
9376         default:
9377                 DRM_ERROR("Incorrect port type\n");
9378                 return;
9379         }
9380
9381         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9382 }
9383
9384 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9385                                 enum port port,
9386                                 struct intel_crtc_state *pipe_config)
9387 {
9388         enum intel_dpll_id id;
9389         u32 temp;
9390
9391         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9392         id = temp >> (port * 3 + 1);
9393
9394         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9395                 return;
9396
9397         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9398 }
9399
9400 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9401                                 enum port port,
9402                                 struct intel_crtc_state *pipe_config)
9403 {
9404         enum intel_dpll_id id;
9405         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9406
9407         switch (ddi_pll_sel) {
9408         case PORT_CLK_SEL_WRPLL1:
9409                 id = DPLL_ID_WRPLL1;
9410                 break;
9411         case PORT_CLK_SEL_WRPLL2:
9412                 id = DPLL_ID_WRPLL2;
9413                 break;
9414         case PORT_CLK_SEL_SPLL:
9415                 id = DPLL_ID_SPLL;
9416                 break;
9417         case PORT_CLK_SEL_LCPLL_810:
9418                 id = DPLL_ID_LCPLL_810;
9419                 break;
9420         case PORT_CLK_SEL_LCPLL_1350:
9421                 id = DPLL_ID_LCPLL_1350;
9422                 break;
9423         case PORT_CLK_SEL_LCPLL_2700:
9424                 id = DPLL_ID_LCPLL_2700;
9425                 break;
9426         default:
9427                 MISSING_CASE(ddi_pll_sel);
9428                 /* fall through */
9429         case PORT_CLK_SEL_NONE:
9430                 return;
9431         }
9432
9433         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9434 }
9435
9436 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9437                                      struct intel_crtc_state *pipe_config,
9438                                      u64 *power_domain_mask)
9439 {
9440         struct drm_device *dev = crtc->base.dev;
9441         struct drm_i915_private *dev_priv = to_i915(dev);
9442         enum intel_display_power_domain power_domain;
9443         u32 tmp;
9444
9445         /*
9446          * The pipe->transcoder mapping is fixed with the exception of the eDP
9447          * transcoder handled below.
9448          */
9449         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9450
9451         /*
9452          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9453          * consistency and less surprising code; it's in always on power).
9454          */
9455         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9456         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9457                 enum pipe trans_edp_pipe;
9458                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9459                 default:
9460                         WARN(1, "unknown pipe linked to edp transcoder\n");
9461                         /* fall through */
9462                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9463                 case TRANS_DDI_EDP_INPUT_A_ON:
9464                         trans_edp_pipe = PIPE_A;
9465                         break;
9466                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9467                         trans_edp_pipe = PIPE_B;
9468                         break;
9469                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9470                         trans_edp_pipe = PIPE_C;
9471                         break;
9472                 }
9473
9474                 if (trans_edp_pipe == crtc->pipe)
9475                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9476         }
9477
9478         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9479         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9480                 return false;
9481         *power_domain_mask |= BIT_ULL(power_domain);
9482
9483         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9484
9485         return tmp & PIPECONF_ENABLE;
9486 }
9487
9488 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9489                                          struct intel_crtc_state *pipe_config,
9490                                          u64 *power_domain_mask)
9491 {
9492         struct drm_device *dev = crtc->base.dev;
9493         struct drm_i915_private *dev_priv = to_i915(dev);
9494         enum intel_display_power_domain power_domain;
9495         enum port port;
9496         enum transcoder cpu_transcoder;
9497         u32 tmp;
9498
9499         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9500                 if (port == PORT_A)
9501                         cpu_transcoder = TRANSCODER_DSI_A;
9502                 else
9503                         cpu_transcoder = TRANSCODER_DSI_C;
9504
9505                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9506                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9507                         continue;
9508                 *power_domain_mask |= BIT_ULL(power_domain);
9509
9510                 /*
9511                  * The PLL needs to be enabled with a valid divider
9512                  * configuration, otherwise accessing DSI registers will hang
9513                  * the machine. See BSpec North Display Engine
9514                  * registers/MIPI[BXT]. We can break out here early, since we
9515                  * need the same DSI PLL to be enabled for both DSI ports.
9516                  */
9517                 if (!bxt_dsi_pll_is_enabled(dev_priv))
9518                         break;
9519
9520                 /* XXX: this works for video mode only */
9521                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9522                 if (!(tmp & DPI_ENABLE))
9523                         continue;
9524
9525                 tmp = I915_READ(MIPI_CTRL(port));
9526                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9527                         continue;
9528
9529                 pipe_config->cpu_transcoder = cpu_transcoder;
9530                 break;
9531         }
9532
9533         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9534 }
9535
9536 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9537                                        struct intel_crtc_state *pipe_config)
9538 {
9539         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9540         struct intel_shared_dpll *pll;
9541         enum port port;
9542         uint32_t tmp;
9543
9544         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9545
9546         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9547
9548         if (IS_ICELAKE(dev_priv))
9549                 icelake_get_ddi_pll(dev_priv, port, pipe_config);
9550         else if (IS_CANNONLAKE(dev_priv))
9551                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9552         else if (IS_GEN9_BC(dev_priv))
9553                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9554         else if (IS_GEN9_LP(dev_priv))
9555                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9556         else
9557                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9558
9559         pll = pipe_config->shared_dpll;
9560         if (pll) {
9561                 WARN_ON(!pll->info->funcs->get_hw_state(dev_priv, pll,
9562                                                 &pipe_config->dpll_hw_state));
9563         }
9564
9565         /*
9566          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9567          * DDI E. So just check whether this pipe is wired to DDI E and whether
9568          * the PCH transcoder is on.
9569          */
9570         if (INTEL_GEN(dev_priv) < 9 &&
9571             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9572                 pipe_config->has_pch_encoder = true;
9573
9574                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9575                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9576                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9577
9578                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9579         }
9580 }
9581
9582 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9583                                     struct intel_crtc_state *pipe_config)
9584 {
9585         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9586         enum intel_display_power_domain power_domain;
9587         u64 power_domain_mask;
9588         bool active;
9589
9590         intel_crtc_init_scalers(crtc, pipe_config);
9591
9592         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9593         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9594                 return false;
9595         power_domain_mask = BIT_ULL(power_domain);
9596
9597         pipe_config->shared_dpll = NULL;
9598
9599         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9600
9601         if (IS_GEN9_LP(dev_priv) &&
9602             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9603                 WARN_ON(active);
9604                 active = true;
9605         }
9606
9607         if (!active)
9608                 goto out;
9609
9610         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9611                 haswell_get_ddi_port_state(crtc, pipe_config);
9612                 intel_get_pipe_timings(crtc, pipe_config);
9613         }
9614
9615         intel_get_pipe_src_size(crtc, pipe_config);
9616
9617         pipe_config->gamma_mode =
9618                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9619
9620         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
9621                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9622                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9623
9624                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10) {
9625                         bool blend_mode_420 = tmp &
9626                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9627
9628                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9629                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9630                             pipe_config->ycbcr420 != blend_mode_420)
9631                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9632                 } else if (clrspace_yuv) {
9633                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9634                 }
9635         }
9636
9637         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9638         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9639                 power_domain_mask |= BIT_ULL(power_domain);
9640                 if (INTEL_GEN(dev_priv) >= 9)
9641                         skylake_get_pfit_config(crtc, pipe_config);
9642                 else
9643                         ironlake_get_pfit_config(crtc, pipe_config);
9644         }
9645
9646         if (hsw_crtc_supports_ips(crtc)) {
9647                 if (IS_HASWELL(dev_priv))
9648                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9649                 else {
9650                         /*
9651                          * We cannot readout IPS state on broadwell, set to
9652                          * true so we can set it to a defined state on first
9653                          * commit.
9654                          */
9655                         pipe_config->ips_enabled = true;
9656                 }
9657         }
9658
9659         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9660             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9661                 pipe_config->pixel_multiplier =
9662                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9663         } else {
9664                 pipe_config->pixel_multiplier = 1;
9665         }
9666
9667 out:
9668         for_each_power_domain(power_domain, power_domain_mask)
9669                 intel_display_power_put(dev_priv, power_domain);
9670
9671         return active;
9672 }
9673
9674 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9675 {
9676         struct drm_i915_private *dev_priv =
9677                 to_i915(plane_state->base.plane->dev);
9678         const struct drm_framebuffer *fb = plane_state->base.fb;
9679         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9680         u32 base;
9681
9682         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9683                 base = obj->phys_handle->busaddr;
9684         else
9685                 base = intel_plane_ggtt_offset(plane_state);
9686
9687         base += plane_state->color_plane[0].offset;
9688
9689         /* ILK+ do this automagically */
9690         if (HAS_GMCH_DISPLAY(dev_priv) &&
9691             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9692                 base += (plane_state->base.crtc_h *
9693                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9694
9695         return base;
9696 }
9697
9698 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9699 {
9700         int x = plane_state->base.crtc_x;
9701         int y = plane_state->base.crtc_y;
9702         u32 pos = 0;
9703
9704         if (x < 0) {
9705                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9706                 x = -x;
9707         }
9708         pos |= x << CURSOR_X_SHIFT;
9709
9710         if (y < 0) {
9711                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9712                 y = -y;
9713         }
9714         pos |= y << CURSOR_Y_SHIFT;
9715
9716         return pos;
9717 }
9718
9719 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9720 {
9721         const struct drm_mode_config *config =
9722                 &plane_state->base.plane->dev->mode_config;
9723         int width = plane_state->base.crtc_w;
9724         int height = plane_state->base.crtc_h;
9725
9726         return width > 0 && width <= config->cursor_width &&
9727                 height > 0 && height <= config->cursor_height;
9728 }
9729
9730 static int intel_cursor_check_surface(struct intel_plane_state *plane_state)
9731 {
9732         const struct drm_framebuffer *fb = plane_state->base.fb;
9733         unsigned int rotation = plane_state->base.rotation;
9734         int src_x, src_y;
9735         u32 offset;
9736         int ret;
9737
9738         intel_fill_fb_ggtt_view(&plane_state->view, fb, rotation);
9739         plane_state->color_plane[0].stride = intel_fb_pitch(fb, 0, rotation);
9740
9741         ret = intel_plane_check_stride(plane_state);
9742         if (ret)
9743                 return ret;
9744
9745         src_x = plane_state->base.src_x >> 16;
9746         src_y = plane_state->base.src_y >> 16;
9747
9748         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9749         offset = intel_plane_compute_aligned_offset(&src_x, &src_y,
9750                                                     plane_state, 0);
9751
9752         if (src_x != 0 || src_y != 0) {
9753                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9754                 return -EINVAL;
9755         }
9756
9757         plane_state->color_plane[0].offset = offset;
9758
9759         return 0;
9760 }
9761
9762 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9763                               struct intel_plane_state *plane_state)
9764 {
9765         const struct drm_framebuffer *fb = plane_state->base.fb;
9766         int ret;
9767
9768         if (fb && fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9769                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9770                 return -EINVAL;
9771         }
9772
9773         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9774                                                   &crtc_state->base,
9775                                                   DRM_PLANE_HELPER_NO_SCALING,
9776                                                   DRM_PLANE_HELPER_NO_SCALING,
9777                                                   true, true);
9778         if (ret)
9779                 return ret;
9780
9781         if (!plane_state->base.visible)
9782                 return 0;
9783
9784         ret = intel_plane_check_src_coordinates(plane_state);
9785         if (ret)
9786                 return ret;
9787
9788         ret = intel_cursor_check_surface(plane_state);
9789         if (ret)
9790                 return ret;
9791
9792         return 0;
9793 }
9794
9795 static unsigned int
9796 i845_cursor_max_stride(struct intel_plane *plane,
9797                        u32 pixel_format, u64 modifier,
9798                        unsigned int rotation)
9799 {
9800         return 2048;
9801 }
9802
9803 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9804                            const struct intel_plane_state *plane_state)
9805 {
9806         return CURSOR_ENABLE |
9807                 CURSOR_GAMMA_ENABLE |
9808                 CURSOR_FORMAT_ARGB |
9809                 CURSOR_STRIDE(plane_state->color_plane[0].stride);
9810 }
9811
9812 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9813 {
9814         int width = plane_state->base.crtc_w;
9815
9816         /*
9817          * 845g/865g are only limited by the width of their cursors,
9818          * the height is arbitrary up to the precision of the register.
9819          */
9820         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9821 }
9822
9823 static int i845_check_cursor(struct intel_crtc_state *crtc_state,
9824                              struct intel_plane_state *plane_state)
9825 {
9826         const struct drm_framebuffer *fb = plane_state->base.fb;
9827         int ret;
9828
9829         ret = intel_check_cursor(crtc_state, plane_state);
9830         if (ret)
9831                 return ret;
9832
9833         /* if we want to turn off the cursor ignore width and height */
9834         if (!fb)
9835                 return 0;
9836
9837         /* Check for which cursor types we support */
9838         if (!i845_cursor_size_ok(plane_state)) {
9839                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9840                           plane_state->base.crtc_w,
9841                           plane_state->base.crtc_h);
9842                 return -EINVAL;
9843         }
9844
9845         WARN_ON(plane_state->base.visible &&
9846                 plane_state->color_plane[0].stride != fb->pitches[0]);
9847
9848         switch (fb->pitches[0]) {
9849         case 256:
9850         case 512:
9851         case 1024:
9852         case 2048:
9853                 break;
9854         default:
9855                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9856                               fb->pitches[0]);
9857                 return -EINVAL;
9858         }
9859
9860         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9861
9862         return 0;
9863 }
9864
9865 static void i845_update_cursor(struct intel_plane *plane,
9866                                const struct intel_crtc_state *crtc_state,
9867                                const struct intel_plane_state *plane_state)
9868 {
9869         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9870         u32 cntl = 0, base = 0, pos = 0, size = 0;
9871         unsigned long irqflags;
9872
9873         if (plane_state && plane_state->base.visible) {
9874                 unsigned int width = plane_state->base.crtc_w;
9875                 unsigned int height = plane_state->base.crtc_h;
9876
9877                 cntl = plane_state->ctl;
9878                 size = (height << 12) | width;
9879
9880                 base = intel_cursor_base(plane_state);
9881                 pos = intel_cursor_position(plane_state);
9882         }
9883
9884         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9885
9886         /* On these chipsets we can only modify the base/size/stride
9887          * whilst the cursor is disabled.
9888          */
9889         if (plane->cursor.base != base ||
9890             plane->cursor.size != size ||
9891             plane->cursor.cntl != cntl) {
9892                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9893                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9894                 I915_WRITE_FW(CURSIZE, size);
9895                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9896                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9897
9898                 plane->cursor.base = base;
9899                 plane->cursor.size = size;
9900                 plane->cursor.cntl = cntl;
9901         } else {
9902                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9903         }
9904
9905         POSTING_READ_FW(CURCNTR(PIPE_A));
9906
9907         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9908 }
9909
9910 static void i845_disable_cursor(struct intel_plane *plane,
9911                                 struct intel_crtc *crtc)
9912 {
9913         i845_update_cursor(plane, NULL, NULL);
9914 }
9915
9916 static bool i845_cursor_get_hw_state(struct intel_plane *plane,
9917                                      enum pipe *pipe)
9918 {
9919         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9920         enum intel_display_power_domain power_domain;
9921         bool ret;
9922
9923         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9924         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9925                 return false;
9926
9927         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9928
9929         *pipe = PIPE_A;
9930
9931         intel_display_power_put(dev_priv, power_domain);
9932
9933         return ret;
9934 }
9935
9936 static unsigned int
9937 i9xx_cursor_max_stride(struct intel_plane *plane,
9938                        u32 pixel_format, u64 modifier,
9939                        unsigned int rotation)
9940 {
9941         return plane->base.dev->mode_config.cursor_width * 4;
9942 }
9943
9944 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9945                            const struct intel_plane_state *plane_state)
9946 {
9947         struct drm_i915_private *dev_priv =
9948                 to_i915(plane_state->base.plane->dev);
9949         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9950         u32 cntl = 0;
9951
9952         if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
9953                 cntl |= MCURSOR_TRICKLE_FEED_DISABLE;
9954
9955         if (INTEL_GEN(dev_priv) <= 10) {
9956                 cntl |= MCURSOR_GAMMA_ENABLE;
9957
9958                 if (HAS_DDI(dev_priv))
9959                         cntl |= MCURSOR_PIPE_CSC_ENABLE;
9960         }
9961
9962         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
9963                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9964
9965         switch (plane_state->base.crtc_w) {
9966         case 64:
9967                 cntl |= MCURSOR_MODE_64_ARGB_AX;
9968                 break;
9969         case 128:
9970                 cntl |= MCURSOR_MODE_128_ARGB_AX;
9971                 break;
9972         case 256:
9973                 cntl |= MCURSOR_MODE_256_ARGB_AX;
9974                 break;
9975         default:
9976                 MISSING_CASE(plane_state->base.crtc_w);
9977                 return 0;
9978         }
9979
9980         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9981                 cntl |= MCURSOR_ROTATE_180;
9982
9983         return cntl;
9984 }
9985
9986 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9987 {
9988         struct drm_i915_private *dev_priv =
9989                 to_i915(plane_state->base.plane->dev);
9990         int width = plane_state->base.crtc_w;
9991         int height = plane_state->base.crtc_h;
9992
9993         if (!intel_cursor_size_ok(plane_state))
9994                 return false;
9995
9996         /* Cursor width is limited to a few power-of-two sizes */
9997         switch (width) {
9998         case 256:
9999         case 128:
10000         case 64:
10001                 break;
10002         default:
10003                 return false;
10004         }
10005
10006         /*
10007          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
10008          * height from 8 lines up to the cursor width, when the
10009          * cursor is not rotated. Everything else requires square
10010          * cursors.
10011          */
10012         if (HAS_CUR_FBC(dev_priv) &&
10013             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
10014                 if (height < 8 || height > width)
10015                         return false;
10016         } else {
10017                 if (height != width)
10018                         return false;
10019         }
10020
10021         return true;
10022 }
10023
10024 static int i9xx_check_cursor(struct intel_crtc_state *crtc_state,
10025                              struct intel_plane_state *plane_state)
10026 {
10027         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
10028         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10029         const struct drm_framebuffer *fb = plane_state->base.fb;
10030         enum pipe pipe = plane->pipe;
10031         int ret;
10032
10033         ret = intel_check_cursor(crtc_state, plane_state);
10034         if (ret)
10035                 return ret;
10036
10037         /* if we want to turn off the cursor ignore width and height */
10038         if (!fb)
10039                 return 0;
10040
10041         /* Check for which cursor types we support */
10042         if (!i9xx_cursor_size_ok(plane_state)) {
10043                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
10044                           plane_state->base.crtc_w,
10045                           plane_state->base.crtc_h);
10046                 return -EINVAL;
10047         }
10048
10049         WARN_ON(plane_state->base.visible &&
10050                 plane_state->color_plane[0].stride != fb->pitches[0]);
10051
10052         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
10053                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
10054                               fb->pitches[0], plane_state->base.crtc_w);
10055                 return -EINVAL;
10056         }
10057
10058         /*
10059          * There's something wrong with the cursor on CHV pipe C.
10060          * If it straddles the left edge of the screen then
10061          * moving it away from the edge or disabling it often
10062          * results in a pipe underrun, and often that can lead to
10063          * dead pipe (constant underrun reported, and it scans
10064          * out just a solid color). To recover from that, the
10065          * display power well must be turned off and on again.
10066          * Refuse the put the cursor into that compromised position.
10067          */
10068         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
10069             plane_state->base.visible && plane_state->base.crtc_x < 0) {
10070                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
10071                 return -EINVAL;
10072         }
10073
10074         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
10075
10076         return 0;
10077 }
10078
10079 static void i9xx_update_cursor(struct intel_plane *plane,
10080                                const struct intel_crtc_state *crtc_state,
10081                                const struct intel_plane_state *plane_state)
10082 {
10083         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10084         enum pipe pipe = plane->pipe;
10085         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
10086         unsigned long irqflags;
10087
10088         if (plane_state && plane_state->base.visible) {
10089                 cntl = plane_state->ctl;
10090
10091                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
10092                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
10093
10094                 base = intel_cursor_base(plane_state);
10095                 pos = intel_cursor_position(plane_state);
10096         }
10097
10098         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
10099
10100         /*
10101          * On some platforms writing CURCNTR first will also
10102          * cause CURPOS to be armed by the CURBASE write.
10103          * Without the CURCNTR write the CURPOS write would
10104          * arm itself. Thus we always start the full update
10105          * with a CURCNTR write.
10106          *
10107          * On other platforms CURPOS always requires the
10108          * CURBASE write to arm the update. Additonally
10109          * a write to any of the cursor register will cancel
10110          * an already armed cursor update. Thus leaving out
10111          * the CURBASE write after CURPOS could lead to a
10112          * cursor that doesn't appear to move, or even change
10113          * shape. Thus we always write CURBASE.
10114          *
10115          * CURCNTR and CUR_FBC_CTL are always
10116          * armed by the CURBASE write only.
10117          */
10118         if (plane->cursor.base != base ||
10119             plane->cursor.size != fbc_ctl ||
10120             plane->cursor.cntl != cntl) {
10121                 I915_WRITE_FW(CURCNTR(pipe), cntl);
10122                 if (HAS_CUR_FBC(dev_priv))
10123                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
10124                 I915_WRITE_FW(CURPOS(pipe), pos);
10125                 I915_WRITE_FW(CURBASE(pipe), base);
10126
10127                 plane->cursor.base = base;
10128                 plane->cursor.size = fbc_ctl;
10129                 plane->cursor.cntl = cntl;
10130         } else {
10131                 I915_WRITE_FW(CURPOS(pipe), pos);
10132                 I915_WRITE_FW(CURBASE(pipe), base);
10133         }
10134
10135         POSTING_READ_FW(CURBASE(pipe));
10136
10137         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
10138 }
10139
10140 static void i9xx_disable_cursor(struct intel_plane *plane,
10141                                 struct intel_crtc *crtc)
10142 {
10143         i9xx_update_cursor(plane, NULL, NULL);
10144 }
10145
10146 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane,
10147                                      enum pipe *pipe)
10148 {
10149         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
10150         enum intel_display_power_domain power_domain;
10151         bool ret;
10152         u32 val;
10153
10154         /*
10155          * Not 100% correct for planes that can move between pipes,
10156          * but that's only the case for gen2-3 which don't have any
10157          * display power wells.
10158          */
10159         power_domain = POWER_DOMAIN_PIPE(plane->pipe);
10160         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
10161                 return false;
10162
10163         val = I915_READ(CURCNTR(plane->pipe));
10164
10165         ret = val & MCURSOR_MODE;
10166
10167         if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
10168                 *pipe = plane->pipe;
10169         else
10170                 *pipe = (val & MCURSOR_PIPE_SELECT_MASK) >>
10171                         MCURSOR_PIPE_SELECT_SHIFT;
10172
10173         intel_display_power_put(dev_priv, power_domain);
10174
10175         return ret;
10176 }
10177
10178 /* VESA 640x480x72Hz mode to set on the pipe */
10179 static const struct drm_display_mode load_detect_mode = {
10180         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
10181                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
10182 };
10183
10184 struct drm_framebuffer *
10185 intel_framebuffer_create(struct drm_i915_gem_object *obj,
10186                          struct drm_mode_fb_cmd2 *mode_cmd)
10187 {
10188         struct intel_framebuffer *intel_fb;
10189         int ret;
10190
10191         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
10192         if (!intel_fb)
10193                 return ERR_PTR(-ENOMEM);
10194
10195         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
10196         if (ret)
10197                 goto err;
10198
10199         return &intel_fb->base;
10200
10201 err:
10202         kfree(intel_fb);
10203         return ERR_PTR(ret);
10204 }
10205
10206 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
10207                                         struct drm_crtc *crtc)
10208 {
10209         struct drm_plane *plane;
10210         struct drm_plane_state *plane_state;
10211         int ret, i;
10212
10213         ret = drm_atomic_add_affected_planes(state, crtc);
10214         if (ret)
10215                 return ret;
10216
10217         for_each_new_plane_in_state(state, plane, plane_state, i) {
10218                 if (plane_state->crtc != crtc)
10219                         continue;
10220
10221                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
10222                 if (ret)
10223                         return ret;
10224
10225                 drm_atomic_set_fb_for_plane(plane_state, NULL);
10226         }
10227
10228         return 0;
10229 }
10230
10231 int intel_get_load_detect_pipe(struct drm_connector *connector,
10232                                const struct drm_display_mode *mode,
10233                                struct intel_load_detect_pipe *old,
10234                                struct drm_modeset_acquire_ctx *ctx)
10235 {
10236         struct intel_crtc *intel_crtc;
10237         struct intel_encoder *intel_encoder =
10238                 intel_attached_encoder(connector);
10239         struct drm_crtc *possible_crtc;
10240         struct drm_encoder *encoder = &intel_encoder->base;
10241         struct drm_crtc *crtc = NULL;
10242         struct drm_device *dev = encoder->dev;
10243         struct drm_i915_private *dev_priv = to_i915(dev);
10244         struct drm_mode_config *config = &dev->mode_config;
10245         struct drm_atomic_state *state = NULL, *restore_state = NULL;
10246         struct drm_connector_state *connector_state;
10247         struct intel_crtc_state *crtc_state;
10248         int ret, i = -1;
10249
10250         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10251                       connector->base.id, connector->name,
10252                       encoder->base.id, encoder->name);
10253
10254         old->restore_state = NULL;
10255
10256         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
10257
10258         /*
10259          * Algorithm gets a little messy:
10260          *
10261          *   - if the connector already has an assigned crtc, use it (but make
10262          *     sure it's on first)
10263          *
10264          *   - try to find the first unused crtc that can drive this connector,
10265          *     and use that if we find one
10266          */
10267
10268         /* See if we already have a CRTC for this connector */
10269         if (connector->state->crtc) {
10270                 crtc = connector->state->crtc;
10271
10272                 ret = drm_modeset_lock(&crtc->mutex, ctx);
10273                 if (ret)
10274                         goto fail;
10275
10276                 /* Make sure the crtc and connector are running */
10277                 goto found;
10278         }
10279
10280         /* Find an unused one (if possible) */
10281         for_each_crtc(dev, possible_crtc) {
10282                 i++;
10283                 if (!(encoder->possible_crtcs & (1 << i)))
10284                         continue;
10285
10286                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
10287                 if (ret)
10288                         goto fail;
10289
10290                 if (possible_crtc->state->enable) {
10291                         drm_modeset_unlock(&possible_crtc->mutex);
10292                         continue;
10293                 }
10294
10295                 crtc = possible_crtc;
10296                 break;
10297         }
10298
10299         /*
10300          * If we didn't find an unused CRTC, don't use any.
10301          */
10302         if (!crtc) {
10303                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
10304                 ret = -ENODEV;
10305                 goto fail;
10306         }
10307
10308 found:
10309         intel_crtc = to_intel_crtc(crtc);
10310
10311         state = drm_atomic_state_alloc(dev);
10312         restore_state = drm_atomic_state_alloc(dev);
10313         if (!state || !restore_state) {
10314                 ret = -ENOMEM;
10315                 goto fail;
10316         }
10317
10318         state->acquire_ctx = ctx;
10319         restore_state->acquire_ctx = ctx;
10320
10321         connector_state = drm_atomic_get_connector_state(state, connector);
10322         if (IS_ERR(connector_state)) {
10323                 ret = PTR_ERR(connector_state);
10324                 goto fail;
10325         }
10326
10327         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
10328         if (ret)
10329                 goto fail;
10330
10331         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
10332         if (IS_ERR(crtc_state)) {
10333                 ret = PTR_ERR(crtc_state);
10334                 goto fail;
10335         }
10336
10337         crtc_state->base.active = crtc_state->base.enable = true;
10338
10339         if (!mode)
10340                 mode = &load_detect_mode;
10341
10342         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
10343         if (ret)
10344                 goto fail;
10345
10346         ret = intel_modeset_disable_planes(state, crtc);
10347         if (ret)
10348                 goto fail;
10349
10350         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
10351         if (!ret)
10352                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
10353         if (!ret)
10354                 ret = drm_atomic_add_affected_planes(restore_state, crtc);
10355         if (ret) {
10356                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
10357                 goto fail;
10358         }
10359
10360         ret = drm_atomic_commit(state);
10361         if (ret) {
10362                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
10363                 goto fail;
10364         }
10365
10366         old->restore_state = restore_state;
10367         drm_atomic_state_put(state);
10368
10369         /* let the connector get through one full cycle before testing */
10370         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
10371         return true;
10372
10373 fail:
10374         if (state) {
10375                 drm_atomic_state_put(state);
10376                 state = NULL;
10377         }
10378         if (restore_state) {
10379                 drm_atomic_state_put(restore_state);
10380                 restore_state = NULL;
10381         }
10382
10383         if (ret == -EDEADLK)
10384                 return ret;
10385
10386         return false;
10387 }
10388
10389 void intel_release_load_detect_pipe(struct drm_connector *connector,
10390                                     struct intel_load_detect_pipe *old,
10391                                     struct drm_modeset_acquire_ctx *ctx)
10392 {
10393         struct intel_encoder *intel_encoder =
10394                 intel_attached_encoder(connector);
10395         struct drm_encoder *encoder = &intel_encoder->base;
10396         struct drm_atomic_state *state = old->restore_state;
10397         int ret;
10398
10399         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10400                       connector->base.id, connector->name,
10401                       encoder->base.id, encoder->name);
10402
10403         if (!state)
10404                 return;
10405
10406         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10407         if (ret)
10408                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10409         drm_atomic_state_put(state);
10410 }
10411
10412 static int i9xx_pll_refclk(struct drm_device *dev,
10413                            const struct intel_crtc_state *pipe_config)
10414 {
10415         struct drm_i915_private *dev_priv = to_i915(dev);
10416         u32 dpll = pipe_config->dpll_hw_state.dpll;
10417
10418         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10419                 return dev_priv->vbt.lvds_ssc_freq;
10420         else if (HAS_PCH_SPLIT(dev_priv))
10421                 return 120000;
10422         else if (!IS_GEN2(dev_priv))
10423                 return 96000;
10424         else
10425                 return 48000;
10426 }
10427
10428 /* Returns the clock of the currently programmed mode of the given pipe. */
10429 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10430                                 struct intel_crtc_state *pipe_config)
10431 {
10432         struct drm_device *dev = crtc->base.dev;
10433         struct drm_i915_private *dev_priv = to_i915(dev);
10434         int pipe = pipe_config->cpu_transcoder;
10435         u32 dpll = pipe_config->dpll_hw_state.dpll;
10436         u32 fp;
10437         struct dpll clock;
10438         int port_clock;
10439         int refclk = i9xx_pll_refclk(dev, pipe_config);
10440
10441         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10442                 fp = pipe_config->dpll_hw_state.fp0;
10443         else
10444                 fp = pipe_config->dpll_hw_state.fp1;
10445
10446         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10447         if (IS_PINEVIEW(dev_priv)) {
10448                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10449                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10450         } else {
10451                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10452                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10453         }
10454
10455         if (!IS_GEN2(dev_priv)) {
10456                 if (IS_PINEVIEW(dev_priv))
10457                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10458                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10459                 else
10460                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10461                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10462
10463                 switch (dpll & DPLL_MODE_MASK) {
10464                 case DPLLB_MODE_DAC_SERIAL:
10465                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10466                                 5 : 10;
10467                         break;
10468                 case DPLLB_MODE_LVDS:
10469                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10470                                 7 : 14;
10471                         break;
10472                 default:
10473                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10474                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10475                         return;
10476                 }
10477
10478                 if (IS_PINEVIEW(dev_priv))
10479                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10480                 else
10481                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10482         } else {
10483                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10484                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10485
10486                 if (is_lvds) {
10487                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10488                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10489
10490                         if (lvds & LVDS_CLKB_POWER_UP)
10491                                 clock.p2 = 7;
10492                         else
10493                                 clock.p2 = 14;
10494                 } else {
10495                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10496                                 clock.p1 = 2;
10497                         else {
10498                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10499                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10500                         }
10501                         if (dpll & PLL_P2_DIVIDE_BY_4)
10502                                 clock.p2 = 4;
10503                         else
10504                                 clock.p2 = 2;
10505                 }
10506
10507                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10508         }
10509
10510         /*
10511          * This value includes pixel_multiplier. We will use
10512          * port_clock to compute adjusted_mode.crtc_clock in the
10513          * encoder's get_config() function.
10514          */
10515         pipe_config->port_clock = port_clock;
10516 }
10517
10518 int intel_dotclock_calculate(int link_freq,
10519                              const struct intel_link_m_n *m_n)
10520 {
10521         /*
10522          * The calculation for the data clock is:
10523          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10524          * But we want to avoid losing precison if possible, so:
10525          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10526          *
10527          * and the link clock is simpler:
10528          * link_clock = (m * link_clock) / n
10529          */
10530
10531         if (!m_n->link_n)
10532                 return 0;
10533
10534         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10535 }
10536
10537 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10538                                    struct intel_crtc_state *pipe_config)
10539 {
10540         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10541
10542         /* read out port_clock from the DPLL */
10543         i9xx_crtc_clock_get(crtc, pipe_config);
10544
10545         /*
10546          * In case there is an active pipe without active ports,
10547          * we may need some idea for the dotclock anyway.
10548          * Calculate one based on the FDI configuration.
10549          */
10550         pipe_config->base.adjusted_mode.crtc_clock =
10551                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10552                                          &pipe_config->fdi_m_n);
10553 }
10554
10555 /* Returns the currently programmed mode of the given encoder. */
10556 struct drm_display_mode *
10557 intel_encoder_current_mode(struct intel_encoder *encoder)
10558 {
10559         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10560         struct intel_crtc_state *crtc_state;
10561         struct drm_display_mode *mode;
10562         struct intel_crtc *crtc;
10563         enum pipe pipe;
10564
10565         if (!encoder->get_hw_state(encoder, &pipe))
10566                 return NULL;
10567
10568         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10569
10570         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10571         if (!mode)
10572                 return NULL;
10573
10574         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10575         if (!crtc_state) {
10576                 kfree(mode);
10577                 return NULL;
10578         }
10579
10580         crtc_state->base.crtc = &crtc->base;
10581
10582         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10583                 kfree(crtc_state);
10584                 kfree(mode);
10585                 return NULL;
10586         }
10587
10588         encoder->get_config(encoder, crtc_state);
10589
10590         intel_mode_from_pipe_config(mode, crtc_state);
10591
10592         kfree(crtc_state);
10593
10594         return mode;
10595 }
10596
10597 static void intel_crtc_destroy(struct drm_crtc *crtc)
10598 {
10599         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10600
10601         drm_crtc_cleanup(crtc);
10602         kfree(intel_crtc);
10603 }
10604
10605 /**
10606  * intel_wm_need_update - Check whether watermarks need updating
10607  * @plane: drm plane
10608  * @state: new plane state
10609  *
10610  * Check current plane state versus the new one to determine whether
10611  * watermarks need to be recalculated.
10612  *
10613  * Returns true or false.
10614  */
10615 static bool intel_wm_need_update(struct drm_plane *plane,
10616                                  struct drm_plane_state *state)
10617 {
10618         struct intel_plane_state *new = to_intel_plane_state(state);
10619         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10620
10621         /* Update watermarks on tiling or size changes. */
10622         if (new->base.visible != cur->base.visible)
10623                 return true;
10624
10625         if (!cur->base.fb || !new->base.fb)
10626                 return false;
10627
10628         if (cur->base.fb->modifier != new->base.fb->modifier ||
10629             cur->base.rotation != new->base.rotation ||
10630             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10631             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10632             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10633             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10634                 return true;
10635
10636         return false;
10637 }
10638
10639 static bool needs_scaling(const struct intel_plane_state *state)
10640 {
10641         int src_w = drm_rect_width(&state->base.src) >> 16;
10642         int src_h = drm_rect_height(&state->base.src) >> 16;
10643         int dst_w = drm_rect_width(&state->base.dst);
10644         int dst_h = drm_rect_height(&state->base.dst);
10645
10646         return (src_w != dst_w || src_h != dst_h);
10647 }
10648
10649 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10650                                     struct drm_crtc_state *crtc_state,
10651                                     const struct intel_plane_state *old_plane_state,
10652                                     struct drm_plane_state *plane_state)
10653 {
10654         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10655         struct drm_crtc *crtc = crtc_state->crtc;
10656         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10657         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10658         struct drm_device *dev = crtc->dev;
10659         struct drm_i915_private *dev_priv = to_i915(dev);
10660         bool mode_changed = needs_modeset(crtc_state);
10661         bool was_crtc_enabled = old_crtc_state->base.active;
10662         bool is_crtc_enabled = crtc_state->active;
10663         bool turn_off, turn_on, visible, was_visible;
10664         struct drm_framebuffer *fb = plane_state->fb;
10665         int ret;
10666
10667         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10668                 ret = skl_update_scaler_plane(
10669                         to_intel_crtc_state(crtc_state),
10670                         to_intel_plane_state(plane_state));
10671                 if (ret)
10672                         return ret;
10673         }
10674
10675         was_visible = old_plane_state->base.visible;
10676         visible = plane_state->visible;
10677
10678         if (!was_crtc_enabled && WARN_ON(was_visible))
10679                 was_visible = false;
10680
10681         /*
10682          * Visibility is calculated as if the crtc was on, but
10683          * after scaler setup everything depends on it being off
10684          * when the crtc isn't active.
10685          *
10686          * FIXME this is wrong for watermarks. Watermarks should also
10687          * be computed as if the pipe would be active. Perhaps move
10688          * per-plane wm computation to the .check_plane() hook, and
10689          * only combine the results from all planes in the current place?
10690          */
10691         if (!is_crtc_enabled) {
10692                 plane_state->visible = visible = false;
10693                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10694         }
10695
10696         if (!was_visible && !visible)
10697                 return 0;
10698
10699         if (fb != old_plane_state->base.fb)
10700                 pipe_config->fb_changed = true;
10701
10702         turn_off = was_visible && (!visible || mode_changed);
10703         turn_on = visible && (!was_visible || mode_changed);
10704
10705         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10706                          intel_crtc->base.base.id, intel_crtc->base.name,
10707                          plane->base.base.id, plane->base.name,
10708                          fb ? fb->base.id : -1);
10709
10710         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10711                          plane->base.base.id, plane->base.name,
10712                          was_visible, visible,
10713                          turn_off, turn_on, mode_changed);
10714
10715         if (turn_on) {
10716                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10717                         pipe_config->update_wm_pre = true;
10718
10719                 /* must disable cxsr around plane enable/disable */
10720                 if (plane->id != PLANE_CURSOR)
10721                         pipe_config->disable_cxsr = true;
10722         } else if (turn_off) {
10723                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10724                         pipe_config->update_wm_post = true;
10725
10726                 /* must disable cxsr around plane enable/disable */
10727                 if (plane->id != PLANE_CURSOR)
10728                         pipe_config->disable_cxsr = true;
10729         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10730                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10731                         /* FIXME bollocks */
10732                         pipe_config->update_wm_pre = true;
10733                         pipe_config->update_wm_post = true;
10734                 }
10735         }
10736
10737         if (visible || was_visible)
10738                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10739
10740         /*
10741          * WaCxSRDisabledForSpriteScaling:ivb
10742          *
10743          * cstate->update_wm was already set above, so this flag will
10744          * take effect when we commit and program watermarks.
10745          */
10746         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
10747             needs_scaling(to_intel_plane_state(plane_state)) &&
10748             !needs_scaling(old_plane_state))
10749                 pipe_config->disable_lp_wm = true;
10750
10751         return 0;
10752 }
10753
10754 static bool encoders_cloneable(const struct intel_encoder *a,
10755                                const struct intel_encoder *b)
10756 {
10757         /* masks could be asymmetric, so check both ways */
10758         return a == b || (a->cloneable & (1 << b->type) &&
10759                           b->cloneable & (1 << a->type));
10760 }
10761
10762 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10763                                          struct intel_crtc *crtc,
10764                                          struct intel_encoder *encoder)
10765 {
10766         struct intel_encoder *source_encoder;
10767         struct drm_connector *connector;
10768         struct drm_connector_state *connector_state;
10769         int i;
10770
10771         for_each_new_connector_in_state(state, connector, connector_state, i) {
10772                 if (connector_state->crtc != &crtc->base)
10773                         continue;
10774
10775                 source_encoder =
10776                         to_intel_encoder(connector_state->best_encoder);
10777                 if (!encoders_cloneable(encoder, source_encoder))
10778                         return false;
10779         }
10780
10781         return true;
10782 }
10783
10784 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10785                                    struct drm_crtc_state *crtc_state)
10786 {
10787         struct drm_device *dev = crtc->dev;
10788         struct drm_i915_private *dev_priv = to_i915(dev);
10789         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10790         struct intel_crtc_state *pipe_config =
10791                 to_intel_crtc_state(crtc_state);
10792         struct drm_atomic_state *state = crtc_state->state;
10793         int ret;
10794         bool mode_changed = needs_modeset(crtc_state);
10795
10796         if (mode_changed && !crtc_state->active)
10797                 pipe_config->update_wm_post = true;
10798
10799         if (mode_changed && crtc_state->enable &&
10800             dev_priv->display.crtc_compute_clock &&
10801             !WARN_ON(pipe_config->shared_dpll)) {
10802                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10803                                                            pipe_config);
10804                 if (ret)
10805                         return ret;
10806         }
10807
10808         if (crtc_state->color_mgmt_changed) {
10809                 ret = intel_color_check(crtc, crtc_state);
10810                 if (ret)
10811                         return ret;
10812
10813                 /*
10814                  * Changing color management on Intel hardware is
10815                  * handled as part of planes update.
10816                  */
10817                 crtc_state->planes_changed = true;
10818         }
10819
10820         ret = 0;
10821         if (dev_priv->display.compute_pipe_wm) {
10822                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10823                 if (ret) {
10824                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10825                         return ret;
10826                 }
10827         }
10828
10829         if (dev_priv->display.compute_intermediate_wm &&
10830             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10831                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10832                         return 0;
10833
10834                 /*
10835                  * Calculate 'intermediate' watermarks that satisfy both the
10836                  * old state and the new state.  We can program these
10837                  * immediately.
10838                  */
10839                 ret = dev_priv->display.compute_intermediate_wm(dev,
10840                                                                 intel_crtc,
10841                                                                 pipe_config);
10842                 if (ret) {
10843                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10844                         return ret;
10845                 }
10846         } else if (dev_priv->display.compute_intermediate_wm) {
10847                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10848                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10849         }
10850
10851         if (INTEL_GEN(dev_priv) >= 9) {
10852                 if (mode_changed)
10853                         ret = skl_update_scaler_crtc(pipe_config);
10854
10855                 if (!ret)
10856                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10857                                                             pipe_config);
10858                 if (!ret)
10859                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10860                                                          pipe_config);
10861         }
10862
10863         if (HAS_IPS(dev_priv))
10864                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10865
10866         return ret;
10867 }
10868
10869 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10870         .atomic_begin = intel_begin_crtc_commit,
10871         .atomic_flush = intel_finish_crtc_commit,
10872         .atomic_check = intel_crtc_atomic_check,
10873 };
10874
10875 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10876 {
10877         struct intel_connector *connector;
10878         struct drm_connector_list_iter conn_iter;
10879
10880         drm_connector_list_iter_begin(dev, &conn_iter);
10881         for_each_intel_connector_iter(connector, &conn_iter) {
10882                 if (connector->base.state->crtc)
10883                         drm_connector_put(&connector->base);
10884
10885                 if (connector->base.encoder) {
10886                         connector->base.state->best_encoder =
10887                                 connector->base.encoder;
10888                         connector->base.state->crtc =
10889                                 connector->base.encoder->crtc;
10890
10891                         drm_connector_get(&connector->base);
10892                 } else {
10893                         connector->base.state->best_encoder = NULL;
10894                         connector->base.state->crtc = NULL;
10895                 }
10896         }
10897         drm_connector_list_iter_end(&conn_iter);
10898 }
10899
10900 static void
10901 connected_sink_compute_bpp(struct intel_connector *connector,
10902                            struct intel_crtc_state *pipe_config)
10903 {
10904         const struct drm_display_info *info = &connector->base.display_info;
10905         int bpp = pipe_config->pipe_bpp;
10906
10907         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10908                       connector->base.base.id,
10909                       connector->base.name);
10910
10911         /* Don't use an invalid EDID bpc value */
10912         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10913                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10914                               bpp, info->bpc * 3);
10915                 pipe_config->pipe_bpp = info->bpc * 3;
10916         }
10917
10918         /* Clamp bpp to 8 on screens without EDID 1.4 */
10919         if (info->bpc == 0 && bpp > 24) {
10920                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10921                               bpp);
10922                 pipe_config->pipe_bpp = 24;
10923         }
10924 }
10925
10926 static int
10927 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10928                           struct intel_crtc_state *pipe_config)
10929 {
10930         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10931         struct drm_atomic_state *state;
10932         struct drm_connector *connector;
10933         struct drm_connector_state *connector_state;
10934         int bpp, i;
10935
10936         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10937             IS_CHERRYVIEW(dev_priv)))
10938                 bpp = 10*3;
10939         else if (INTEL_GEN(dev_priv) >= 5)
10940                 bpp = 12*3;
10941         else
10942                 bpp = 8*3;
10943
10944
10945         pipe_config->pipe_bpp = bpp;
10946
10947         state = pipe_config->base.state;
10948
10949         /* Clamp display bpp to EDID value */
10950         for_each_new_connector_in_state(state, connector, connector_state, i) {
10951                 if (connector_state->crtc != &crtc->base)
10952                         continue;
10953
10954                 connected_sink_compute_bpp(to_intel_connector(connector),
10955                                            pipe_config);
10956         }
10957
10958         return bpp;
10959 }
10960
10961 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10962 {
10963         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10964                         "type: 0x%x flags: 0x%x\n",
10965                 mode->crtc_clock,
10966                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10967                 mode->crtc_hsync_end, mode->crtc_htotal,
10968                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10969                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10970 }
10971
10972 static inline void
10973 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10974                       unsigned int lane_count, struct intel_link_m_n *m_n)
10975 {
10976         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10977                       id, lane_count,
10978                       m_n->gmch_m, m_n->gmch_n,
10979                       m_n->link_m, m_n->link_n, m_n->tu);
10980 }
10981
10982 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10983
10984 static const char * const output_type_str[] = {
10985         OUTPUT_TYPE(UNUSED),
10986         OUTPUT_TYPE(ANALOG),
10987         OUTPUT_TYPE(DVO),
10988         OUTPUT_TYPE(SDVO),
10989         OUTPUT_TYPE(LVDS),
10990         OUTPUT_TYPE(TVOUT),
10991         OUTPUT_TYPE(HDMI),
10992         OUTPUT_TYPE(DP),
10993         OUTPUT_TYPE(EDP),
10994         OUTPUT_TYPE(DSI),
10995         OUTPUT_TYPE(DDI),
10996         OUTPUT_TYPE(DP_MST),
10997 };
10998
10999 #undef OUTPUT_TYPE
11000
11001 static void snprintf_output_types(char *buf, size_t len,
11002                                   unsigned int output_types)
11003 {
11004         char *str = buf;
11005         int i;
11006
11007         str[0] = '\0';
11008
11009         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
11010                 int r;
11011
11012                 if ((output_types & BIT(i)) == 0)
11013                         continue;
11014
11015                 r = snprintf(str, len, "%s%s",
11016                              str != buf ? "," : "", output_type_str[i]);
11017                 if (r >= len)
11018                         break;
11019                 str += r;
11020                 len -= r;
11021
11022                 output_types &= ~BIT(i);
11023         }
11024
11025         WARN_ON_ONCE(output_types != 0);
11026 }
11027
11028 static void intel_dump_pipe_config(struct intel_crtc *crtc,
11029                                    struct intel_crtc_state *pipe_config,
11030                                    const char *context)
11031 {
11032         struct drm_device *dev = crtc->base.dev;
11033         struct drm_i915_private *dev_priv = to_i915(dev);
11034         struct drm_plane *plane;
11035         struct intel_plane *intel_plane;
11036         struct intel_plane_state *state;
11037         struct drm_framebuffer *fb;
11038         char buf[64];
11039
11040         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
11041                       crtc->base.base.id, crtc->base.name, context);
11042
11043         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
11044         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
11045                       buf, pipe_config->output_types);
11046
11047         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
11048                       transcoder_name(pipe_config->cpu_transcoder),
11049                       pipe_config->pipe_bpp, pipe_config->dither);
11050
11051         if (pipe_config->has_pch_encoder)
11052                 intel_dump_m_n_config(pipe_config, "fdi",
11053                                       pipe_config->fdi_lanes,
11054                                       &pipe_config->fdi_m_n);
11055
11056         if (pipe_config->ycbcr420)
11057                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
11058
11059         if (intel_crtc_has_dp_encoder(pipe_config)) {
11060                 intel_dump_m_n_config(pipe_config, "dp m_n",
11061                                 pipe_config->lane_count, &pipe_config->dp_m_n);
11062                 if (pipe_config->has_drrs)
11063                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
11064                                               pipe_config->lane_count,
11065                                               &pipe_config->dp_m2_n2);
11066         }
11067
11068         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
11069                       pipe_config->has_audio, pipe_config->has_infoframe);
11070
11071         DRM_DEBUG_KMS("requested mode:\n");
11072         drm_mode_debug_printmodeline(&pipe_config->base.mode);
11073         DRM_DEBUG_KMS("adjusted mode:\n");
11074         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
11075         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
11076         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
11077                       pipe_config->port_clock,
11078                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
11079                       pipe_config->pixel_rate);
11080
11081         if (INTEL_GEN(dev_priv) >= 9)
11082                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
11083                               crtc->num_scalers,
11084                               pipe_config->scaler_state.scaler_users,
11085                               pipe_config->scaler_state.scaler_id);
11086
11087         if (HAS_GMCH_DISPLAY(dev_priv))
11088                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
11089                               pipe_config->gmch_pfit.control,
11090                               pipe_config->gmch_pfit.pgm_ratios,
11091                               pipe_config->gmch_pfit.lvds_border_bits);
11092         else
11093                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
11094                               pipe_config->pch_pfit.pos,
11095                               pipe_config->pch_pfit.size,
11096                               enableddisabled(pipe_config->pch_pfit.enabled));
11097
11098         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
11099                       pipe_config->ips_enabled, pipe_config->double_wide);
11100
11101         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
11102
11103         DRM_DEBUG_KMS("planes on this crtc\n");
11104         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
11105                 struct drm_format_name_buf format_name;
11106                 intel_plane = to_intel_plane(plane);
11107                 if (intel_plane->pipe != crtc->pipe)
11108                         continue;
11109
11110                 state = to_intel_plane_state(plane->state);
11111                 fb = state->base.fb;
11112                 if (!fb) {
11113                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
11114                                       plane->base.id, plane->name, state->scaler_id);
11115                         continue;
11116                 }
11117
11118                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
11119                               plane->base.id, plane->name,
11120                               fb->base.id, fb->width, fb->height,
11121                               drm_get_format_name(fb->format->format, &format_name));
11122                 if (INTEL_GEN(dev_priv) >= 9)
11123                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
11124                                       state->scaler_id,
11125                                       state->base.src.x1 >> 16,
11126                                       state->base.src.y1 >> 16,
11127                                       drm_rect_width(&state->base.src) >> 16,
11128                                       drm_rect_height(&state->base.src) >> 16,
11129                                       state->base.dst.x1, state->base.dst.y1,
11130                                       drm_rect_width(&state->base.dst),
11131                                       drm_rect_height(&state->base.dst));
11132         }
11133 }
11134
11135 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
11136 {
11137         struct drm_device *dev = state->dev;
11138         struct drm_connector *connector;
11139         struct drm_connector_list_iter conn_iter;
11140         unsigned int used_ports = 0;
11141         unsigned int used_mst_ports = 0;
11142         bool ret = true;
11143
11144         /*
11145          * Walk the connector list instead of the encoder
11146          * list to detect the problem on ddi platforms
11147          * where there's just one encoder per digital port.
11148          */
11149         drm_connector_list_iter_begin(dev, &conn_iter);
11150         drm_for_each_connector_iter(connector, &conn_iter) {
11151                 struct drm_connector_state *connector_state;
11152                 struct intel_encoder *encoder;
11153
11154                 connector_state = drm_atomic_get_new_connector_state(state, connector);
11155                 if (!connector_state)
11156                         connector_state = connector->state;
11157
11158                 if (!connector_state->best_encoder)
11159                         continue;
11160
11161                 encoder = to_intel_encoder(connector_state->best_encoder);
11162
11163                 WARN_ON(!connector_state->crtc);
11164
11165                 switch (encoder->type) {
11166                         unsigned int port_mask;
11167                 case INTEL_OUTPUT_DDI:
11168                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
11169                                 break;
11170                         /* else: fall through */
11171                 case INTEL_OUTPUT_DP:
11172                 case INTEL_OUTPUT_HDMI:
11173                 case INTEL_OUTPUT_EDP:
11174                         port_mask = 1 << encoder->port;
11175
11176                         /* the same port mustn't appear more than once */
11177                         if (used_ports & port_mask)
11178                                 ret = false;
11179
11180                         used_ports |= port_mask;
11181                         break;
11182                 case INTEL_OUTPUT_DP_MST:
11183                         used_mst_ports |=
11184                                 1 << encoder->port;
11185                         break;
11186                 default:
11187                         break;
11188                 }
11189         }
11190         drm_connector_list_iter_end(&conn_iter);
11191
11192         /* can't mix MST and SST/HDMI on the same port */
11193         if (used_ports & used_mst_ports)
11194                 return false;
11195
11196         return ret;
11197 }
11198
11199 static void
11200 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
11201 {
11202         struct drm_i915_private *dev_priv =
11203                 to_i915(crtc_state->base.crtc->dev);
11204         struct intel_crtc_scaler_state scaler_state;
11205         struct intel_dpll_hw_state dpll_hw_state;
11206         struct intel_shared_dpll *shared_dpll;
11207         struct intel_crtc_wm_state wm_state;
11208         bool force_thru, ips_force_disable;
11209
11210         /* FIXME: before the switch to atomic started, a new pipe_config was
11211          * kzalloc'd. Code that depends on any field being zero should be
11212          * fixed, so that the crtc_state can be safely duplicated. For now,
11213          * only fields that are know to not cause problems are preserved. */
11214
11215         scaler_state = crtc_state->scaler_state;
11216         shared_dpll = crtc_state->shared_dpll;
11217         dpll_hw_state = crtc_state->dpll_hw_state;
11218         force_thru = crtc_state->pch_pfit.force_thru;
11219         ips_force_disable = crtc_state->ips_force_disable;
11220         if (IS_G4X(dev_priv) ||
11221             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11222                 wm_state = crtc_state->wm;
11223
11224         /* Keep base drm_crtc_state intact, only clear our extended struct */
11225         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
11226         memset(&crtc_state->base + 1, 0,
11227                sizeof(*crtc_state) - sizeof(crtc_state->base));
11228
11229         crtc_state->scaler_state = scaler_state;
11230         crtc_state->shared_dpll = shared_dpll;
11231         crtc_state->dpll_hw_state = dpll_hw_state;
11232         crtc_state->pch_pfit.force_thru = force_thru;
11233         crtc_state->ips_force_disable = ips_force_disable;
11234         if (IS_G4X(dev_priv) ||
11235             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11236                 crtc_state->wm = wm_state;
11237 }
11238
11239 static int
11240 intel_modeset_pipe_config(struct drm_crtc *crtc,
11241                           struct intel_crtc_state *pipe_config)
11242 {
11243         struct drm_atomic_state *state = pipe_config->base.state;
11244         struct intel_encoder *encoder;
11245         struct drm_connector *connector;
11246         struct drm_connector_state *connector_state;
11247         int base_bpp, ret = -EINVAL;
11248         int i;
11249         bool retry = true;
11250
11251         clear_intel_crtc_state(pipe_config);
11252
11253         pipe_config->cpu_transcoder =
11254                 (enum transcoder) to_intel_crtc(crtc)->pipe;
11255
11256         /*
11257          * Sanitize sync polarity flags based on requested ones. If neither
11258          * positive or negative polarity is requested, treat this as meaning
11259          * negative polarity.
11260          */
11261         if (!(pipe_config->base.adjusted_mode.flags &
11262               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
11263                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
11264
11265         if (!(pipe_config->base.adjusted_mode.flags &
11266               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
11267                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
11268
11269         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
11270                                              pipe_config);
11271         if (base_bpp < 0)
11272                 goto fail;
11273
11274         /*
11275          * Determine the real pipe dimensions. Note that stereo modes can
11276          * increase the actual pipe size due to the frame doubling and
11277          * insertion of additional space for blanks between the frame. This
11278          * is stored in the crtc timings. We use the requested mode to do this
11279          * computation to clearly distinguish it from the adjusted mode, which
11280          * can be changed by the connectors in the below retry loop.
11281          */
11282         drm_mode_get_hv_timing(&pipe_config->base.mode,
11283                                &pipe_config->pipe_src_w,
11284                                &pipe_config->pipe_src_h);
11285
11286         for_each_new_connector_in_state(state, connector, connector_state, i) {
11287                 if (connector_state->crtc != crtc)
11288                         continue;
11289
11290                 encoder = to_intel_encoder(connector_state->best_encoder);
11291
11292                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
11293                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
11294                         goto fail;
11295                 }
11296
11297                 /*
11298                  * Determine output_types before calling the .compute_config()
11299                  * hooks so that the hooks can use this information safely.
11300                  */
11301                 if (encoder->compute_output_type)
11302                         pipe_config->output_types |=
11303                                 BIT(encoder->compute_output_type(encoder, pipe_config,
11304                                                                  connector_state));
11305                 else
11306                         pipe_config->output_types |= BIT(encoder->type);
11307         }
11308
11309 encoder_retry:
11310         /* Ensure the port clock defaults are reset when retrying. */
11311         pipe_config->port_clock = 0;
11312         pipe_config->pixel_multiplier = 1;
11313
11314         /* Fill in default crtc timings, allow encoders to overwrite them. */
11315         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
11316                               CRTC_STEREO_DOUBLE);
11317
11318         /* Pass our mode to the connectors and the CRTC to give them a chance to
11319          * adjust it according to limitations or connector properties, and also
11320          * a chance to reject the mode entirely.
11321          */
11322         for_each_new_connector_in_state(state, connector, connector_state, i) {
11323                 if (connector_state->crtc != crtc)
11324                         continue;
11325
11326                 encoder = to_intel_encoder(connector_state->best_encoder);
11327
11328                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
11329                         DRM_DEBUG_KMS("Encoder config failure\n");
11330                         goto fail;
11331                 }
11332         }
11333
11334         /* Set default port clock if not overwritten by the encoder. Needs to be
11335          * done afterwards in case the encoder adjusts the mode. */
11336         if (!pipe_config->port_clock)
11337                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
11338                         * pipe_config->pixel_multiplier;
11339
11340         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
11341         if (ret < 0) {
11342                 DRM_DEBUG_KMS("CRTC fixup failed\n");
11343                 goto fail;
11344         }
11345
11346         if (ret == RETRY) {
11347                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
11348                         ret = -EINVAL;
11349                         goto fail;
11350                 }
11351
11352                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
11353                 retry = false;
11354                 goto encoder_retry;
11355         }
11356
11357         /* Dithering seems to not pass-through bits correctly when it should, so
11358          * only enable it on 6bpc panels and when its not a compliance
11359          * test requesting 6bpc video pattern.
11360          */
11361         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
11362                 !pipe_config->dither_force_disable;
11363         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
11364                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
11365
11366 fail:
11367         return ret;
11368 }
11369
11370 static bool intel_fuzzy_clock_check(int clock1, int clock2)
11371 {
11372         int diff;
11373
11374         if (clock1 == clock2)
11375                 return true;
11376
11377         if (!clock1 || !clock2)
11378                 return false;
11379
11380         diff = abs(clock1 - clock2);
11381
11382         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11383                 return true;
11384
11385         return false;
11386 }
11387
11388 static bool
11389 intel_compare_m_n(unsigned int m, unsigned int n,
11390                   unsigned int m2, unsigned int n2,
11391                   bool exact)
11392 {
11393         if (m == m2 && n == n2)
11394                 return true;
11395
11396         if (exact || !m || !n || !m2 || !n2)
11397                 return false;
11398
11399         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11400
11401         if (n > n2) {
11402                 while (n > n2) {
11403                         m2 <<= 1;
11404                         n2 <<= 1;
11405                 }
11406         } else if (n < n2) {
11407                 while (n < n2) {
11408                         m <<= 1;
11409                         n <<= 1;
11410                 }
11411         }
11412
11413         if (n != n2)
11414                 return false;
11415
11416         return intel_fuzzy_clock_check(m, m2);
11417 }
11418
11419 static bool
11420 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11421                        struct intel_link_m_n *m2_n2,
11422                        bool adjust)
11423 {
11424         if (m_n->tu == m2_n2->tu &&
11425             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11426                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11427             intel_compare_m_n(m_n->link_m, m_n->link_n,
11428                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11429                 if (adjust)
11430                         *m2_n2 = *m_n;
11431
11432                 return true;
11433         }
11434
11435         return false;
11436 }
11437
11438 static void __printf(3, 4)
11439 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11440 {
11441         struct va_format vaf;
11442         va_list args;
11443
11444         va_start(args, format);
11445         vaf.fmt = format;
11446         vaf.va = &args;
11447
11448         if (adjust)
11449                 drm_dbg(DRM_UT_KMS, "mismatch in %s %pV", name, &vaf);
11450         else
11451                 drm_err("mismatch in %s %pV", name, &vaf);
11452
11453         va_end(args);
11454 }
11455
11456 static bool
11457 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11458                           struct intel_crtc_state *current_config,
11459                           struct intel_crtc_state *pipe_config,
11460                           bool adjust)
11461 {
11462         bool ret = true;
11463         bool fixup_inherited = adjust &&
11464                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11465                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11466
11467 #define PIPE_CONF_CHECK_X(name) do { \
11468         if (current_config->name != pipe_config->name) { \
11469                 pipe_config_err(adjust, __stringify(name), \
11470                           "(expected 0x%08x, found 0x%08x)\n", \
11471                           current_config->name, \
11472                           pipe_config->name); \
11473                 ret = false; \
11474         } \
11475 } while (0)
11476
11477 #define PIPE_CONF_CHECK_I(name) do { \
11478         if (current_config->name != pipe_config->name) { \
11479                 pipe_config_err(adjust, __stringify(name), \
11480                           "(expected %i, found %i)\n", \
11481                           current_config->name, \
11482                           pipe_config->name); \
11483                 ret = false; \
11484         } \
11485 } while (0)
11486
11487 #define PIPE_CONF_CHECK_BOOL(name) do { \
11488         if (current_config->name != pipe_config->name) { \
11489                 pipe_config_err(adjust, __stringify(name), \
11490                           "(expected %s, found %s)\n", \
11491                           yesno(current_config->name), \
11492                           yesno(pipe_config->name)); \
11493                 ret = false; \
11494         } \
11495 } while (0)
11496
11497 /*
11498  * Checks state where we only read out the enabling, but not the entire
11499  * state itself (like full infoframes or ELD for audio). These states
11500  * require a full modeset on bootup to fix up.
11501  */
11502 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) do { \
11503         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11504                 PIPE_CONF_CHECK_BOOL(name); \
11505         } else { \
11506                 pipe_config_err(adjust, __stringify(name), \
11507                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11508                           yesno(current_config->name), \
11509                           yesno(pipe_config->name)); \
11510                 ret = false; \
11511         } \
11512 } while (0)
11513
11514 #define PIPE_CONF_CHECK_P(name) do { \
11515         if (current_config->name != pipe_config->name) { \
11516                 pipe_config_err(adjust, __stringify(name), \
11517                           "(expected %p, found %p)\n", \
11518                           current_config->name, \
11519                           pipe_config->name); \
11520                 ret = false; \
11521         } \
11522 } while (0)
11523
11524 #define PIPE_CONF_CHECK_M_N(name) do { \
11525         if (!intel_compare_link_m_n(&current_config->name, \
11526                                     &pipe_config->name,\
11527                                     adjust)) { \
11528                 pipe_config_err(adjust, __stringify(name), \
11529                           "(expected tu %i gmch %i/%i link %i/%i, " \
11530                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11531                           current_config->name.tu, \
11532                           current_config->name.gmch_m, \
11533                           current_config->name.gmch_n, \
11534                           current_config->name.link_m, \
11535                           current_config->name.link_n, \
11536                           pipe_config->name.tu, \
11537                           pipe_config->name.gmch_m, \
11538                           pipe_config->name.gmch_n, \
11539                           pipe_config->name.link_m, \
11540                           pipe_config->name.link_n); \
11541                 ret = false; \
11542         } \
11543 } while (0)
11544
11545 /* This is required for BDW+ where there is only one set of registers for
11546  * switching between high and low RR.
11547  * This macro can be used whenever a comparison has to be made between one
11548  * hw state and multiple sw state variables.
11549  */
11550 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) do { \
11551         if (!intel_compare_link_m_n(&current_config->name, \
11552                                     &pipe_config->name, adjust) && \
11553             !intel_compare_link_m_n(&current_config->alt_name, \
11554                                     &pipe_config->name, adjust)) { \
11555                 pipe_config_err(adjust, __stringify(name), \
11556                           "(expected tu %i gmch %i/%i link %i/%i, " \
11557                           "or tu %i gmch %i/%i link %i/%i, " \
11558                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11559                           current_config->name.tu, \
11560                           current_config->name.gmch_m, \
11561                           current_config->name.gmch_n, \
11562                           current_config->name.link_m, \
11563                           current_config->name.link_n, \
11564                           current_config->alt_name.tu, \
11565                           current_config->alt_name.gmch_m, \
11566                           current_config->alt_name.gmch_n, \
11567                           current_config->alt_name.link_m, \
11568                           current_config->alt_name.link_n, \
11569                           pipe_config->name.tu, \
11570                           pipe_config->name.gmch_m, \
11571                           pipe_config->name.gmch_n, \
11572                           pipe_config->name.link_m, \
11573                           pipe_config->name.link_n); \
11574                 ret = false; \
11575         } \
11576 } while (0)
11577
11578 #define PIPE_CONF_CHECK_FLAGS(name, mask) do { \
11579         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11580                 pipe_config_err(adjust, __stringify(name), \
11581                           "(%x) (expected %i, found %i)\n", \
11582                           (mask), \
11583                           current_config->name & (mask), \
11584                           pipe_config->name & (mask)); \
11585                 ret = false; \
11586         } \
11587 } while (0)
11588
11589 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) do { \
11590         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11591                 pipe_config_err(adjust, __stringify(name), \
11592                           "(expected %i, found %i)\n", \
11593                           current_config->name, \
11594                           pipe_config->name); \
11595                 ret = false; \
11596         } \
11597 } while (0)
11598
11599 #define PIPE_CONF_QUIRK(quirk)  \
11600         ((current_config->quirks | pipe_config->quirks) & (quirk))
11601
11602         PIPE_CONF_CHECK_I(cpu_transcoder);
11603
11604         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11605         PIPE_CONF_CHECK_I(fdi_lanes);
11606         PIPE_CONF_CHECK_M_N(fdi_m_n);
11607
11608         PIPE_CONF_CHECK_I(lane_count);
11609         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11610
11611         if (INTEL_GEN(dev_priv) < 8) {
11612                 PIPE_CONF_CHECK_M_N(dp_m_n);
11613
11614                 if (current_config->has_drrs)
11615                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11616         } else
11617                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11618
11619         PIPE_CONF_CHECK_X(output_types);
11620
11621         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11622         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11623         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11624         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11625         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11626         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11627
11628         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11629         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11630         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11631         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11632         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11633         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11634
11635         PIPE_CONF_CHECK_I(pixel_multiplier);
11636         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11637         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11638             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11639                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11640
11641         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11642         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11643         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11644         PIPE_CONF_CHECK_BOOL(ycbcr420);
11645
11646         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11647
11648         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11649                               DRM_MODE_FLAG_INTERLACE);
11650
11651         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11652                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11653                                       DRM_MODE_FLAG_PHSYNC);
11654                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11655                                       DRM_MODE_FLAG_NHSYNC);
11656                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11657                                       DRM_MODE_FLAG_PVSYNC);
11658                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11659                                       DRM_MODE_FLAG_NVSYNC);
11660         }
11661
11662         PIPE_CONF_CHECK_X(gmch_pfit.control);
11663         /* pfit ratios are autocomputed by the hw on gen4+ */
11664         if (INTEL_GEN(dev_priv) < 4)
11665                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11666         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11667
11668         if (!adjust) {
11669                 PIPE_CONF_CHECK_I(pipe_src_w);
11670                 PIPE_CONF_CHECK_I(pipe_src_h);
11671
11672                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11673                 if (current_config->pch_pfit.enabled) {
11674                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11675                         PIPE_CONF_CHECK_X(pch_pfit.size);
11676                 }
11677
11678                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11679                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11680         }
11681
11682         PIPE_CONF_CHECK_BOOL(double_wide);
11683
11684         PIPE_CONF_CHECK_P(shared_dpll);
11685         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11686         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11687         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11688         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11689         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11690         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11691         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11692         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11693         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11694         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11695         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11696         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11697         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11698         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11699         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11700         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11701         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11702         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11703         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11704         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11705         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11706         PIPE_CONF_CHECK_X(dpll_hw_state.mg_refclkin_ctl);
11707         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_coreclkctl1);
11708         PIPE_CONF_CHECK_X(dpll_hw_state.mg_clktop2_hsclkctl);
11709         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div0);
11710         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_div1);
11711         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_lf);
11712         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_frac_lock);
11713         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_ssc);
11714         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_bias);
11715         PIPE_CONF_CHECK_X(dpll_hw_state.mg_pll_tdc_coldst_bias);
11716
11717         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11718         PIPE_CONF_CHECK_X(dsi_pll.div);
11719
11720         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11721                 PIPE_CONF_CHECK_I(pipe_bpp);
11722
11723         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11724         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11725
11726         PIPE_CONF_CHECK_I(min_voltage_level);
11727
11728 #undef PIPE_CONF_CHECK_X
11729 #undef PIPE_CONF_CHECK_I
11730 #undef PIPE_CONF_CHECK_BOOL
11731 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11732 #undef PIPE_CONF_CHECK_P
11733 #undef PIPE_CONF_CHECK_FLAGS
11734 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11735 #undef PIPE_CONF_QUIRK
11736
11737         return ret;
11738 }
11739
11740 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11741                                            const struct intel_crtc_state *pipe_config)
11742 {
11743         if (pipe_config->has_pch_encoder) {
11744                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11745                                                             &pipe_config->fdi_m_n);
11746                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11747
11748                 /*
11749                  * FDI already provided one idea for the dotclock.
11750                  * Yell if the encoder disagrees.
11751                  */
11752                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11753                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11754                      fdi_dotclock, dotclock);
11755         }
11756 }
11757
11758 static void verify_wm_state(struct drm_crtc *crtc,
11759                             struct drm_crtc_state *new_state)
11760 {
11761         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11762         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11763         struct skl_pipe_wm hw_wm, *sw_wm;
11764         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11765         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11766         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11767         const enum pipe pipe = intel_crtc->pipe;
11768         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11769
11770         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11771                 return;
11772
11773         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11774         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11775
11776         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11777         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11778
11779         if (INTEL_GEN(dev_priv) >= 11)
11780                 if (hw_ddb.enabled_slices != sw_ddb->enabled_slices)
11781                         DRM_ERROR("mismatch in DBUF Slices (expected %u, got %u)\n",
11782                                   sw_ddb->enabled_slices,
11783                                   hw_ddb.enabled_slices);
11784         /* planes */
11785         for_each_universal_plane(dev_priv, pipe, plane) {
11786                 hw_plane_wm = &hw_wm.planes[plane];
11787                 sw_plane_wm = &sw_wm->planes[plane];
11788
11789                 /* Watermarks */
11790                 for (level = 0; level <= max_level; level++) {
11791                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11792                                                 &sw_plane_wm->wm[level]))
11793                                 continue;
11794
11795                         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",
11796                                   pipe_name(pipe), plane + 1, level,
11797                                   sw_plane_wm->wm[level].plane_en,
11798                                   sw_plane_wm->wm[level].plane_res_b,
11799                                   sw_plane_wm->wm[level].plane_res_l,
11800                                   hw_plane_wm->wm[level].plane_en,
11801                                   hw_plane_wm->wm[level].plane_res_b,
11802                                   hw_plane_wm->wm[level].plane_res_l);
11803                 }
11804
11805                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11806                                          &sw_plane_wm->trans_wm)) {
11807                         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",
11808                                   pipe_name(pipe), plane + 1,
11809                                   sw_plane_wm->trans_wm.plane_en,
11810                                   sw_plane_wm->trans_wm.plane_res_b,
11811                                   sw_plane_wm->trans_wm.plane_res_l,
11812                                   hw_plane_wm->trans_wm.plane_en,
11813                                   hw_plane_wm->trans_wm.plane_res_b,
11814                                   hw_plane_wm->trans_wm.plane_res_l);
11815                 }
11816
11817                 /* DDB */
11818                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11819                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11820
11821                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11822                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11823                                   pipe_name(pipe), plane + 1,
11824                                   sw_ddb_entry->start, sw_ddb_entry->end,
11825                                   hw_ddb_entry->start, hw_ddb_entry->end);
11826                 }
11827         }
11828
11829         /*
11830          * cursor
11831          * If the cursor plane isn't active, we may not have updated it's ddb
11832          * allocation. In that case since the ddb allocation will be updated
11833          * once the plane becomes visible, we can skip this check
11834          */
11835         if (1) {
11836                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11837                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11838
11839                 /* Watermarks */
11840                 for (level = 0; level <= max_level; level++) {
11841                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11842                                                 &sw_plane_wm->wm[level]))
11843                                 continue;
11844
11845                         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",
11846                                   pipe_name(pipe), level,
11847                                   sw_plane_wm->wm[level].plane_en,
11848                                   sw_plane_wm->wm[level].plane_res_b,
11849                                   sw_plane_wm->wm[level].plane_res_l,
11850                                   hw_plane_wm->wm[level].plane_en,
11851                                   hw_plane_wm->wm[level].plane_res_b,
11852                                   hw_plane_wm->wm[level].plane_res_l);
11853                 }
11854
11855                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11856                                          &sw_plane_wm->trans_wm)) {
11857                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11858                                   pipe_name(pipe),
11859                                   sw_plane_wm->trans_wm.plane_en,
11860                                   sw_plane_wm->trans_wm.plane_res_b,
11861                                   sw_plane_wm->trans_wm.plane_res_l,
11862                                   hw_plane_wm->trans_wm.plane_en,
11863                                   hw_plane_wm->trans_wm.plane_res_b,
11864                                   hw_plane_wm->trans_wm.plane_res_l);
11865                 }
11866
11867                 /* DDB */
11868                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11869                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11870
11871                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11872                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11873                                   pipe_name(pipe),
11874                                   sw_ddb_entry->start, sw_ddb_entry->end,
11875                                   hw_ddb_entry->start, hw_ddb_entry->end);
11876                 }
11877         }
11878 }
11879
11880 static void
11881 verify_connector_state(struct drm_device *dev,
11882                        struct drm_atomic_state *state,
11883                        struct drm_crtc *crtc)
11884 {
11885         struct drm_connector *connector;
11886         struct drm_connector_state *new_conn_state;
11887         int i;
11888
11889         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11890                 struct drm_encoder *encoder = connector->encoder;
11891                 struct drm_crtc_state *crtc_state = NULL;
11892
11893                 if (new_conn_state->crtc != crtc)
11894                         continue;
11895
11896                 if (crtc)
11897                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11898
11899                 intel_connector_verify_state(crtc_state, new_conn_state);
11900
11901                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11902                      "connector's atomic encoder doesn't match legacy encoder\n");
11903         }
11904 }
11905
11906 static void
11907 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11908 {
11909         struct intel_encoder *encoder;
11910         struct drm_connector *connector;
11911         struct drm_connector_state *old_conn_state, *new_conn_state;
11912         int i;
11913
11914         for_each_intel_encoder(dev, encoder) {
11915                 bool enabled = false, found = false;
11916                 enum pipe pipe;
11917
11918                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11919                               encoder->base.base.id,
11920                               encoder->base.name);
11921
11922                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11923                                                    new_conn_state, i) {
11924                         if (old_conn_state->best_encoder == &encoder->base)
11925                                 found = true;
11926
11927                         if (new_conn_state->best_encoder != &encoder->base)
11928                                 continue;
11929                         found = enabled = true;
11930
11931                         I915_STATE_WARN(new_conn_state->crtc !=
11932                                         encoder->base.crtc,
11933                              "connector's crtc doesn't match encoder crtc\n");
11934                 }
11935
11936                 if (!found)
11937                         continue;
11938
11939                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11940                      "encoder's enabled state mismatch "
11941                      "(expected %i, found %i)\n",
11942                      !!encoder->base.crtc, enabled);
11943
11944                 if (!encoder->base.crtc) {
11945                         bool active;
11946
11947                         active = encoder->get_hw_state(encoder, &pipe);
11948                         I915_STATE_WARN(active,
11949                              "encoder detached but still enabled on pipe %c.\n",
11950                              pipe_name(pipe));
11951                 }
11952         }
11953 }
11954
11955 static void
11956 verify_crtc_state(struct drm_crtc *crtc,
11957                   struct drm_crtc_state *old_crtc_state,
11958                   struct drm_crtc_state *new_crtc_state)
11959 {
11960         struct drm_device *dev = crtc->dev;
11961         struct drm_i915_private *dev_priv = to_i915(dev);
11962         struct intel_encoder *encoder;
11963         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11964         struct intel_crtc_state *pipe_config, *sw_config;
11965         struct drm_atomic_state *old_state;
11966         bool active;
11967
11968         old_state = old_crtc_state->state;
11969         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11970         pipe_config = to_intel_crtc_state(old_crtc_state);
11971         memset(pipe_config, 0, sizeof(*pipe_config));
11972         pipe_config->base.crtc = crtc;
11973         pipe_config->base.state = old_state;
11974
11975         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11976
11977         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11978
11979         /* we keep both pipes enabled on 830 */
11980         if (IS_I830(dev_priv))
11981                 active = new_crtc_state->active;
11982
11983         I915_STATE_WARN(new_crtc_state->active != active,
11984              "crtc active state doesn't match with hw state "
11985              "(expected %i, found %i)\n", new_crtc_state->active, active);
11986
11987         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11988              "transitional active state does not match atomic hw state "
11989              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11990
11991         for_each_encoder_on_crtc(dev, crtc, encoder) {
11992                 enum pipe pipe;
11993
11994                 active = encoder->get_hw_state(encoder, &pipe);
11995                 I915_STATE_WARN(active != new_crtc_state->active,
11996                         "[ENCODER:%i] active %i with crtc active %i\n",
11997                         encoder->base.base.id, active, new_crtc_state->active);
11998
11999                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
12000                                 "Encoder connected to wrong pipe %c\n",
12001                                 pipe_name(pipe));
12002
12003                 if (active)
12004                         encoder->get_config(encoder, pipe_config);
12005         }
12006
12007         intel_crtc_compute_pixel_rate(pipe_config);
12008
12009         if (!new_crtc_state->active)
12010                 return;
12011
12012         intel_pipe_config_sanity_check(dev_priv, pipe_config);
12013
12014         sw_config = to_intel_crtc_state(new_crtc_state);
12015         if (!intel_pipe_config_compare(dev_priv, sw_config,
12016                                        pipe_config, false)) {
12017                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
12018                 intel_dump_pipe_config(intel_crtc, pipe_config,
12019                                        "[hw state]");
12020                 intel_dump_pipe_config(intel_crtc, sw_config,
12021                                        "[sw state]");
12022         }
12023 }
12024
12025 static void
12026 intel_verify_planes(struct intel_atomic_state *state)
12027 {
12028         struct intel_plane *plane;
12029         const struct intel_plane_state *plane_state;
12030         int i;
12031
12032         for_each_new_intel_plane_in_state(state, plane,
12033                                           plane_state, i)
12034                 assert_plane(plane, plane_state->base.visible);
12035 }
12036
12037 static void
12038 verify_single_dpll_state(struct drm_i915_private *dev_priv,
12039                          struct intel_shared_dpll *pll,
12040                          struct drm_crtc *crtc,
12041                          struct drm_crtc_state *new_state)
12042 {
12043         struct intel_dpll_hw_state dpll_hw_state;
12044         unsigned int crtc_mask;
12045         bool active;
12046
12047         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
12048
12049         DRM_DEBUG_KMS("%s\n", pll->info->name);
12050
12051         active = pll->info->funcs->get_hw_state(dev_priv, pll, &dpll_hw_state);
12052
12053         if (!(pll->info->flags & INTEL_DPLL_ALWAYS_ON)) {
12054                 I915_STATE_WARN(!pll->on && pll->active_mask,
12055                      "pll in active use but not on in sw tracking\n");
12056                 I915_STATE_WARN(pll->on && !pll->active_mask,
12057                      "pll is on but not used by any active crtc\n");
12058                 I915_STATE_WARN(pll->on != active,
12059                      "pll on state mismatch (expected %i, found %i)\n",
12060                      pll->on, active);
12061         }
12062
12063         if (!crtc) {
12064                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
12065                                 "more active pll users than references: %x vs %x\n",
12066                                 pll->active_mask, pll->state.crtc_mask);
12067
12068                 return;
12069         }
12070
12071         crtc_mask = drm_crtc_mask(crtc);
12072
12073         if (new_state->active)
12074                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
12075                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
12076                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12077         else
12078                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12079                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
12080                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
12081
12082         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
12083                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
12084                         crtc_mask, pll->state.crtc_mask);
12085
12086         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
12087                                           &dpll_hw_state,
12088                                           sizeof(dpll_hw_state)),
12089                         "pll hw state mismatch\n");
12090 }
12091
12092 static void
12093 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
12094                          struct drm_crtc_state *old_crtc_state,
12095                          struct drm_crtc_state *new_crtc_state)
12096 {
12097         struct drm_i915_private *dev_priv = to_i915(dev);
12098         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
12099         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
12100
12101         if (new_state->shared_dpll)
12102                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
12103
12104         if (old_state->shared_dpll &&
12105             old_state->shared_dpll != new_state->shared_dpll) {
12106                 unsigned int crtc_mask = drm_crtc_mask(crtc);
12107                 struct intel_shared_dpll *pll = old_state->shared_dpll;
12108
12109                 I915_STATE_WARN(pll->active_mask & crtc_mask,
12110                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
12111                                 pipe_name(drm_crtc_index(crtc)));
12112                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
12113                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
12114                                 pipe_name(drm_crtc_index(crtc)));
12115         }
12116 }
12117
12118 static void
12119 intel_modeset_verify_crtc(struct drm_crtc *crtc,
12120                           struct drm_atomic_state *state,
12121                           struct drm_crtc_state *old_state,
12122                           struct drm_crtc_state *new_state)
12123 {
12124         if (!needs_modeset(new_state) &&
12125             !to_intel_crtc_state(new_state)->update_pipe)
12126                 return;
12127
12128         verify_wm_state(crtc, new_state);
12129         verify_connector_state(crtc->dev, state, crtc);
12130         verify_crtc_state(crtc, old_state, new_state);
12131         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
12132 }
12133
12134 static void
12135 verify_disabled_dpll_state(struct drm_device *dev)
12136 {
12137         struct drm_i915_private *dev_priv = to_i915(dev);
12138         int i;
12139
12140         for (i = 0; i < dev_priv->num_shared_dpll; i++)
12141                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
12142 }
12143
12144 static void
12145 intel_modeset_verify_disabled(struct drm_device *dev,
12146                               struct drm_atomic_state *state)
12147 {
12148         verify_encoder_state(dev, state);
12149         verify_connector_state(dev, state, NULL);
12150         verify_disabled_dpll_state(dev);
12151 }
12152
12153 static void update_scanline_offset(struct intel_crtc *crtc)
12154 {
12155         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
12156
12157         /*
12158          * The scanline counter increments at the leading edge of hsync.
12159          *
12160          * On most platforms it starts counting from vtotal-1 on the
12161          * first active line. That means the scanline counter value is
12162          * always one less than what we would expect. Ie. just after
12163          * start of vblank, which also occurs at start of hsync (on the
12164          * last active line), the scanline counter will read vblank_start-1.
12165          *
12166          * On gen2 the scanline counter starts counting from 1 instead
12167          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
12168          * to keep the value positive), instead of adding one.
12169          *
12170          * On HSW+ the behaviour of the scanline counter depends on the output
12171          * type. For DP ports it behaves like most other platforms, but on HDMI
12172          * there's an extra 1 line difference. So we need to add two instead of
12173          * one to the value.
12174          *
12175          * On VLV/CHV DSI the scanline counter would appear to increment
12176          * approx. 1/3 of a scanline before start of vblank. Unfortunately
12177          * that means we can't tell whether we're in vblank or not while
12178          * we're on that particular line. We must still set scanline_offset
12179          * to 1 so that the vblank timestamps come out correct when we query
12180          * the scanline counter from within the vblank interrupt handler.
12181          * However if queried just before the start of vblank we'll get an
12182          * answer that's slightly in the future.
12183          */
12184         if (IS_GEN2(dev_priv)) {
12185                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
12186                 int vtotal;
12187
12188                 vtotal = adjusted_mode->crtc_vtotal;
12189                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
12190                         vtotal /= 2;
12191
12192                 crtc->scanline_offset = vtotal - 1;
12193         } else if (HAS_DDI(dev_priv) &&
12194                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
12195                 crtc->scanline_offset = 2;
12196         } else
12197                 crtc->scanline_offset = 1;
12198 }
12199
12200 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
12201 {
12202         struct drm_device *dev = state->dev;
12203         struct drm_i915_private *dev_priv = to_i915(dev);
12204         struct drm_crtc *crtc;
12205         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12206         int i;
12207
12208         if (!dev_priv->display.crtc_compute_clock)
12209                 return;
12210
12211         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12212                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12213                 struct intel_shared_dpll *old_dpll =
12214                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
12215
12216                 if (!needs_modeset(new_crtc_state))
12217                         continue;
12218
12219                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
12220
12221                 if (!old_dpll)
12222                         continue;
12223
12224                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
12225         }
12226 }
12227
12228 /*
12229  * This implements the workaround described in the "notes" section of the mode
12230  * set sequence documentation. When going from no pipes or single pipe to
12231  * multiple pipes, and planes are enabled after the pipe, we need to wait at
12232  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
12233  */
12234 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
12235 {
12236         struct drm_crtc_state *crtc_state;
12237         struct intel_crtc *intel_crtc;
12238         struct drm_crtc *crtc;
12239         struct intel_crtc_state *first_crtc_state = NULL;
12240         struct intel_crtc_state *other_crtc_state = NULL;
12241         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
12242         int i;
12243
12244         /* look at all crtc's that are going to be enabled in during modeset */
12245         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
12246                 intel_crtc = to_intel_crtc(crtc);
12247
12248                 if (!crtc_state->active || !needs_modeset(crtc_state))
12249                         continue;
12250
12251                 if (first_crtc_state) {
12252                         other_crtc_state = to_intel_crtc_state(crtc_state);
12253                         break;
12254                 } else {
12255                         first_crtc_state = to_intel_crtc_state(crtc_state);
12256                         first_pipe = intel_crtc->pipe;
12257                 }
12258         }
12259
12260         /* No workaround needed? */
12261         if (!first_crtc_state)
12262                 return 0;
12263
12264         /* w/a possibly needed, check how many crtc's are already enabled. */
12265         for_each_intel_crtc(state->dev, intel_crtc) {
12266                 struct intel_crtc_state *pipe_config;
12267
12268                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
12269                 if (IS_ERR(pipe_config))
12270                         return PTR_ERR(pipe_config);
12271
12272                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
12273
12274                 if (!pipe_config->base.active ||
12275                     needs_modeset(&pipe_config->base))
12276                         continue;
12277
12278                 /* 2 or more enabled crtcs means no need for w/a */
12279                 if (enabled_pipe != INVALID_PIPE)
12280                         return 0;
12281
12282                 enabled_pipe = intel_crtc->pipe;
12283         }
12284
12285         if (enabled_pipe != INVALID_PIPE)
12286                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
12287         else if (other_crtc_state)
12288                 other_crtc_state->hsw_workaround_pipe = first_pipe;
12289
12290         return 0;
12291 }
12292
12293 static int intel_lock_all_pipes(struct drm_atomic_state *state)
12294 {
12295         struct drm_crtc *crtc;
12296
12297         /* Add all pipes to the state */
12298         for_each_crtc(state->dev, crtc) {
12299                 struct drm_crtc_state *crtc_state;
12300
12301                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12302                 if (IS_ERR(crtc_state))
12303                         return PTR_ERR(crtc_state);
12304         }
12305
12306         return 0;
12307 }
12308
12309 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
12310 {
12311         struct drm_crtc *crtc;
12312
12313         /*
12314          * Add all pipes to the state, and force
12315          * a modeset on all the active ones.
12316          */
12317         for_each_crtc(state->dev, crtc) {
12318                 struct drm_crtc_state *crtc_state;
12319                 int ret;
12320
12321                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
12322                 if (IS_ERR(crtc_state))
12323                         return PTR_ERR(crtc_state);
12324
12325                 if (!crtc_state->active || needs_modeset(crtc_state))
12326                         continue;
12327
12328                 crtc_state->mode_changed = true;
12329
12330                 ret = drm_atomic_add_affected_connectors(state, crtc);
12331                 if (ret)
12332                         return ret;
12333
12334                 ret = drm_atomic_add_affected_planes(state, crtc);
12335                 if (ret)
12336                         return ret;
12337         }
12338
12339         return 0;
12340 }
12341
12342 static int intel_modeset_checks(struct drm_atomic_state *state)
12343 {
12344         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12345         struct drm_i915_private *dev_priv = to_i915(state->dev);
12346         struct drm_crtc *crtc;
12347         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12348         int ret = 0, i;
12349
12350         if (!check_digital_port_conflicts(state)) {
12351                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
12352                 return -EINVAL;
12353         }
12354
12355         intel_state->modeset = true;
12356         intel_state->active_crtcs = dev_priv->active_crtcs;
12357         intel_state->cdclk.logical = dev_priv->cdclk.logical;
12358         intel_state->cdclk.actual = dev_priv->cdclk.actual;
12359
12360         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12361                 if (new_crtc_state->active)
12362                         intel_state->active_crtcs |= 1 << i;
12363                 else
12364                         intel_state->active_crtcs &= ~(1 << i);
12365
12366                 if (old_crtc_state->active != new_crtc_state->active)
12367                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
12368         }
12369
12370         /*
12371          * See if the config requires any additional preparation, e.g.
12372          * to adjust global state with pipes off.  We need to do this
12373          * here so we can get the modeset_pipe updated config for the new
12374          * mode set on this crtc.  For other crtcs we need to use the
12375          * adjusted_mode bits in the crtc directly.
12376          */
12377         if (dev_priv->display.modeset_calc_cdclk) {
12378                 ret = dev_priv->display.modeset_calc_cdclk(state);
12379                 if (ret < 0)
12380                         return ret;
12381
12382                 /*
12383                  * Writes to dev_priv->cdclk.logical must protected by
12384                  * holding all the crtc locks, even if we don't end up
12385                  * touching the hardware
12386                  */
12387                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
12388                                         &intel_state->cdclk.logical)) {
12389                         ret = intel_lock_all_pipes(state);
12390                         if (ret < 0)
12391                                 return ret;
12392                 }
12393
12394                 /* All pipes must be switched off while we change the cdclk. */
12395                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
12396                                               &intel_state->cdclk.actual)) {
12397                         ret = intel_modeset_all_pipes(state);
12398                         if (ret < 0)
12399                                 return ret;
12400                 }
12401
12402                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12403                               intel_state->cdclk.logical.cdclk,
12404                               intel_state->cdclk.actual.cdclk);
12405                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12406                               intel_state->cdclk.logical.voltage_level,
12407                               intel_state->cdclk.actual.voltage_level);
12408         } else {
12409                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12410         }
12411
12412         intel_modeset_clear_plls(state);
12413
12414         if (IS_HASWELL(dev_priv))
12415                 return haswell_mode_set_planes_workaround(state);
12416
12417         return 0;
12418 }
12419
12420 /*
12421  * Handle calculation of various watermark data at the end of the atomic check
12422  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12423  * handlers to ensure that all derived state has been updated.
12424  */
12425 static int calc_watermark_data(struct drm_atomic_state *state)
12426 {
12427         struct drm_device *dev = state->dev;
12428         struct drm_i915_private *dev_priv = to_i915(dev);
12429
12430         /* Is there platform-specific watermark information to calculate? */
12431         if (dev_priv->display.compute_global_watermarks)
12432                 return dev_priv->display.compute_global_watermarks(state);
12433
12434         return 0;
12435 }
12436
12437 /**
12438  * intel_atomic_check - validate state object
12439  * @dev: drm device
12440  * @state: state to validate
12441  */
12442 static int intel_atomic_check(struct drm_device *dev,
12443                               struct drm_atomic_state *state)
12444 {
12445         struct drm_i915_private *dev_priv = to_i915(dev);
12446         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12447         struct drm_crtc *crtc;
12448         struct drm_crtc_state *old_crtc_state, *crtc_state;
12449         int ret, i;
12450         bool any_ms = false;
12451
12452         /* Catch I915_MODE_FLAG_INHERITED */
12453         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
12454                                       crtc_state, i) {
12455                 if (crtc_state->mode.private_flags !=
12456                     old_crtc_state->mode.private_flags)
12457                         crtc_state->mode_changed = true;
12458         }
12459
12460         ret = drm_atomic_helper_check_modeset(dev, state);
12461         if (ret)
12462                 return ret;
12463
12464         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12465                 struct intel_crtc_state *pipe_config =
12466                         to_intel_crtc_state(crtc_state);
12467
12468                 if (!needs_modeset(crtc_state))
12469                         continue;
12470
12471                 if (!crtc_state->enable) {
12472                         any_ms = true;
12473                         continue;
12474                 }
12475
12476                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12477                 if (ret) {
12478                         intel_dump_pipe_config(to_intel_crtc(crtc),
12479                                                pipe_config, "[failed]");
12480                         return ret;
12481                 }
12482
12483                 if (i915_modparams.fastboot &&
12484                     intel_pipe_config_compare(dev_priv,
12485                                         to_intel_crtc_state(old_crtc_state),
12486                                         pipe_config, true)) {
12487                         crtc_state->mode_changed = false;
12488                         pipe_config->update_pipe = true;
12489                 }
12490
12491                 if (needs_modeset(crtc_state))
12492                         any_ms = true;
12493
12494                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12495                                        needs_modeset(crtc_state) ?
12496                                        "[modeset]" : "[fastset]");
12497         }
12498
12499         if (any_ms) {
12500                 ret = intel_modeset_checks(state);
12501
12502                 if (ret)
12503                         return ret;
12504         } else {
12505                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12506         }
12507
12508         ret = drm_atomic_helper_check_planes(dev, state);
12509         if (ret)
12510                 return ret;
12511
12512         intel_fbc_choose_crtc(dev_priv, intel_state);
12513         return calc_watermark_data(state);
12514 }
12515
12516 static int intel_atomic_prepare_commit(struct drm_device *dev,
12517                                        struct drm_atomic_state *state)
12518 {
12519         return drm_atomic_helper_prepare_planes(dev, state);
12520 }
12521
12522 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12523 {
12524         struct drm_device *dev = crtc->base.dev;
12525
12526         if (!dev->max_vblank_count)
12527                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12528
12529         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12530 }
12531
12532 static void intel_update_crtc(struct drm_crtc *crtc,
12533                               struct drm_atomic_state *state,
12534                               struct drm_crtc_state *old_crtc_state,
12535                               struct drm_crtc_state *new_crtc_state)
12536 {
12537         struct drm_device *dev = crtc->dev;
12538         struct drm_i915_private *dev_priv = to_i915(dev);
12539         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12540         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12541         bool modeset = needs_modeset(new_crtc_state);
12542         struct intel_plane_state *new_plane_state =
12543                 intel_atomic_get_new_plane_state(to_intel_atomic_state(state),
12544                                                  to_intel_plane(crtc->primary));
12545
12546         if (modeset) {
12547                 update_scanline_offset(intel_crtc);
12548                 dev_priv->display.crtc_enable(pipe_config, state);
12549
12550                 /* vblanks work again, re-enable pipe CRC. */
12551                 intel_crtc_enable_pipe_crc(intel_crtc);
12552         } else {
12553                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12554                                        pipe_config);
12555         }
12556
12557         if (new_plane_state)
12558                 intel_fbc_enable(intel_crtc, pipe_config, new_plane_state);
12559
12560         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12561 }
12562
12563 static void intel_update_crtcs(struct drm_atomic_state *state)
12564 {
12565         struct drm_crtc *crtc;
12566         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12567         int i;
12568
12569         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12570                 if (!new_crtc_state->active)
12571                         continue;
12572
12573                 intel_update_crtc(crtc, state, old_crtc_state,
12574                                   new_crtc_state);
12575         }
12576 }
12577
12578 static void skl_update_crtcs(struct drm_atomic_state *state)
12579 {
12580         struct drm_i915_private *dev_priv = to_i915(state->dev);
12581         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12582         struct drm_crtc *crtc;
12583         struct intel_crtc *intel_crtc;
12584         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12585         struct intel_crtc_state *cstate;
12586         unsigned int updated = 0;
12587         bool progress;
12588         enum pipe pipe;
12589         int i;
12590         u8 hw_enabled_slices = dev_priv->wm.skl_hw.ddb.enabled_slices;
12591         u8 required_slices = intel_state->wm_results.ddb.enabled_slices;
12592
12593         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12594
12595         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12596                 /* ignore allocations for crtc's that have been turned off. */
12597                 if (new_crtc_state->active)
12598                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12599
12600         /* If 2nd DBuf slice required, enable it here */
12601         if (INTEL_GEN(dev_priv) >= 11 && required_slices > hw_enabled_slices)
12602                 icl_dbuf_slices_update(dev_priv, required_slices);
12603
12604         /*
12605          * Whenever the number of active pipes changes, we need to make sure we
12606          * update the pipes in the right order so that their ddb allocations
12607          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12608          * cause pipe underruns and other bad stuff.
12609          */
12610         do {
12611                 progress = false;
12612
12613                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12614                         bool vbl_wait = false;
12615                         unsigned int cmask = drm_crtc_mask(crtc);
12616
12617                         intel_crtc = to_intel_crtc(crtc);
12618                         cstate = to_intel_crtc_state(new_crtc_state);
12619                         pipe = intel_crtc->pipe;
12620
12621                         if (updated & cmask || !cstate->base.active)
12622                                 continue;
12623
12624                         if (skl_ddb_allocation_overlaps(dev_priv,
12625                                                         entries,
12626                                                         &cstate->wm.skl.ddb,
12627                                                         i))
12628                                 continue;
12629
12630                         updated |= cmask;
12631                         entries[i] = &cstate->wm.skl.ddb;
12632
12633                         /*
12634                          * If this is an already active pipe, it's DDB changed,
12635                          * and this isn't the last pipe that needs updating
12636                          * then we need to wait for a vblank to pass for the
12637                          * new ddb allocation to take effect.
12638                          */
12639                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12640                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12641                             !new_crtc_state->active_changed &&
12642                             intel_state->wm_results.dirty_pipes != updated)
12643                                 vbl_wait = true;
12644
12645                         intel_update_crtc(crtc, state, old_crtc_state,
12646                                           new_crtc_state);
12647
12648                         if (vbl_wait)
12649                                 intel_wait_for_vblank(dev_priv, pipe);
12650
12651                         progress = true;
12652                 }
12653         } while (progress);
12654
12655         /* If 2nd DBuf slice is no more required disable it */
12656         if (INTEL_GEN(dev_priv) >= 11 && required_slices < hw_enabled_slices)
12657                 icl_dbuf_slices_update(dev_priv, required_slices);
12658 }
12659
12660 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12661 {
12662         struct intel_atomic_state *state, *next;
12663         struct llist_node *freed;
12664
12665         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12666         llist_for_each_entry_safe(state, next, freed, freed)
12667                 drm_atomic_state_put(&state->base);
12668 }
12669
12670 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12671 {
12672         struct drm_i915_private *dev_priv =
12673                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12674
12675         intel_atomic_helper_free_state(dev_priv);
12676 }
12677
12678 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12679 {
12680         struct wait_queue_entry wait_fence, wait_reset;
12681         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12682
12683         init_wait_entry(&wait_fence, 0);
12684         init_wait_entry(&wait_reset, 0);
12685         for (;;) {
12686                 prepare_to_wait(&intel_state->commit_ready.wait,
12687                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12688                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12689                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12690
12691
12692                 if (i915_sw_fence_done(&intel_state->commit_ready)
12693                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12694                         break;
12695
12696                 schedule();
12697         }
12698         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12699         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12700 }
12701
12702 static void intel_atomic_cleanup_work(struct work_struct *work)
12703 {
12704         struct drm_atomic_state *state =
12705                 container_of(work, struct drm_atomic_state, commit_work);
12706         struct drm_i915_private *i915 = to_i915(state->dev);
12707
12708         drm_atomic_helper_cleanup_planes(&i915->drm, state);
12709         drm_atomic_helper_commit_cleanup_done(state);
12710         drm_atomic_state_put(state);
12711
12712         intel_atomic_helper_free_state(i915);
12713 }
12714
12715 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12716 {
12717         struct drm_device *dev = state->dev;
12718         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12719         struct drm_i915_private *dev_priv = to_i915(dev);
12720         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12721         struct drm_crtc *crtc;
12722         struct intel_crtc_state *intel_cstate;
12723         u64 put_domains[I915_MAX_PIPES] = {};
12724         int i;
12725
12726         intel_atomic_commit_fence_wait(intel_state);
12727
12728         drm_atomic_helper_wait_for_dependencies(state);
12729
12730         if (intel_state->modeset)
12731                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12732
12733         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12734                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12735
12736                 if (needs_modeset(new_crtc_state) ||
12737                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12738
12739                         put_domains[to_intel_crtc(crtc)->pipe] =
12740                                 modeset_get_crtc_power_domains(crtc,
12741                                         to_intel_crtc_state(new_crtc_state));
12742                 }
12743
12744                 if (!needs_modeset(new_crtc_state))
12745                         continue;
12746
12747                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12748                                        to_intel_crtc_state(new_crtc_state));
12749
12750                 if (old_crtc_state->active) {
12751                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
12752
12753                         /*
12754                          * We need to disable pipe CRC before disabling the pipe,
12755                          * or we race against vblank off.
12756                          */
12757                         intel_crtc_disable_pipe_crc(intel_crtc);
12758
12759                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
12760                         intel_crtc->active = false;
12761                         intel_fbc_disable(intel_crtc);
12762                         intel_disable_shared_dpll(intel_crtc);
12763
12764                         /*
12765                          * Underruns don't always raise
12766                          * interrupts, so check manually.
12767                          */
12768                         intel_check_cpu_fifo_underruns(dev_priv);
12769                         intel_check_pch_fifo_underruns(dev_priv);
12770
12771                         if (!new_crtc_state->active) {
12772                                 /*
12773                                  * Make sure we don't call initial_watermarks
12774                                  * for ILK-style watermark updates.
12775                                  *
12776                                  * No clue what this is supposed to achieve.
12777                                  */
12778                                 if (INTEL_GEN(dev_priv) >= 9)
12779                                         dev_priv->display.initial_watermarks(intel_state,
12780                                                                              to_intel_crtc_state(new_crtc_state));
12781                         }
12782                 }
12783         }
12784
12785         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12786         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12787                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12788
12789         if (intel_state->modeset) {
12790                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12791
12792                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12793
12794                 /*
12795                  * SKL workaround: bspec recommends we disable the SAGV when we
12796                  * have more then one pipe enabled
12797                  */
12798                 if (!intel_can_enable_sagv(state))
12799                         intel_disable_sagv(dev_priv);
12800
12801                 intel_modeset_verify_disabled(dev, state);
12802         }
12803
12804         /* Complete the events for pipes that have now been disabled */
12805         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12806                 bool modeset = needs_modeset(new_crtc_state);
12807
12808                 /* Complete events for now disable pipes here. */
12809                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12810                         spin_lock_irq(&dev->event_lock);
12811                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12812                         spin_unlock_irq(&dev->event_lock);
12813
12814                         new_crtc_state->event = NULL;
12815                 }
12816         }
12817
12818         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12819         dev_priv->display.update_crtcs(state);
12820
12821         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12822          * already, but still need the state for the delayed optimization. To
12823          * fix this:
12824          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12825          * - schedule that vblank worker _before_ calling hw_done
12826          * - at the start of commit_tail, cancel it _synchrously
12827          * - switch over to the vblank wait helper in the core after that since
12828          *   we don't need out special handling any more.
12829          */
12830         drm_atomic_helper_wait_for_flip_done(dev, state);
12831
12832         /*
12833          * Now that the vblank has passed, we can go ahead and program the
12834          * optimal watermarks on platforms that need two-step watermark
12835          * programming.
12836          *
12837          * TODO: Move this (and other cleanup) to an async worker eventually.
12838          */
12839         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12840                 intel_cstate = to_intel_crtc_state(new_crtc_state);
12841
12842                 if (dev_priv->display.optimize_watermarks)
12843                         dev_priv->display.optimize_watermarks(intel_state,
12844                                                               intel_cstate);
12845         }
12846
12847         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12848                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12849
12850                 if (put_domains[i])
12851                         modeset_put_power_domains(dev_priv, put_domains[i]);
12852
12853                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12854         }
12855
12856         if (intel_state->modeset)
12857                 intel_verify_planes(intel_state);
12858
12859         if (intel_state->modeset && intel_can_enable_sagv(state))
12860                 intel_enable_sagv(dev_priv);
12861
12862         drm_atomic_helper_commit_hw_done(state);
12863
12864         if (intel_state->modeset) {
12865                 /* As one of the primary mmio accessors, KMS has a high
12866                  * likelihood of triggering bugs in unclaimed access. After we
12867                  * finish modesetting, see if an error has been flagged, and if
12868                  * so enable debugging for the next modeset - and hope we catch
12869                  * the culprit.
12870                  */
12871                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12872                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12873         }
12874
12875         /*
12876          * Defer the cleanup of the old state to a separate worker to not
12877          * impede the current task (userspace for blocking modesets) that
12878          * are executed inline. For out-of-line asynchronous modesets/flips,
12879          * deferring to a new worker seems overkill, but we would place a
12880          * schedule point (cond_resched()) here anyway to keep latencies
12881          * down.
12882          */
12883         INIT_WORK(&state->commit_work, intel_atomic_cleanup_work);
12884         queue_work(system_highpri_wq, &state->commit_work);
12885 }
12886
12887 static void intel_atomic_commit_work(struct work_struct *work)
12888 {
12889         struct drm_atomic_state *state =
12890                 container_of(work, struct drm_atomic_state, commit_work);
12891
12892         intel_atomic_commit_tail(state);
12893 }
12894
12895 static int __i915_sw_fence_call
12896 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12897                           enum i915_sw_fence_notify notify)
12898 {
12899         struct intel_atomic_state *state =
12900                 container_of(fence, struct intel_atomic_state, commit_ready);
12901
12902         switch (notify) {
12903         case FENCE_COMPLETE:
12904                 /* we do blocking waits in the worker, nothing to do here */
12905                 break;
12906         case FENCE_FREE:
12907                 {
12908                         struct intel_atomic_helper *helper =
12909                                 &to_i915(state->base.dev)->atomic_helper;
12910
12911                         if (llist_add(&state->freed, &helper->free_list))
12912                                 schedule_work(&helper->free_work);
12913                         break;
12914                 }
12915         }
12916
12917         return NOTIFY_DONE;
12918 }
12919
12920 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12921 {
12922         struct drm_plane_state *old_plane_state, *new_plane_state;
12923         struct drm_plane *plane;
12924         int i;
12925
12926         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12927                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12928                                   intel_fb_obj(new_plane_state->fb),
12929                                   to_intel_plane(plane)->frontbuffer_bit);
12930 }
12931
12932 /**
12933  * intel_atomic_commit - commit validated state object
12934  * @dev: DRM device
12935  * @state: the top-level driver state object
12936  * @nonblock: nonblocking commit
12937  *
12938  * This function commits a top-level state object that has been validated
12939  * with drm_atomic_helper_check().
12940  *
12941  * RETURNS
12942  * Zero for success or -errno.
12943  */
12944 static int intel_atomic_commit(struct drm_device *dev,
12945                                struct drm_atomic_state *state,
12946                                bool nonblock)
12947 {
12948         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12949         struct drm_i915_private *dev_priv = to_i915(dev);
12950         int ret = 0;
12951
12952         drm_atomic_state_get(state);
12953         i915_sw_fence_init(&intel_state->commit_ready,
12954                            intel_atomic_commit_ready);
12955
12956         /*
12957          * The intel_legacy_cursor_update() fast path takes care
12958          * of avoiding the vblank waits for simple cursor
12959          * movement and flips. For cursor on/off and size changes,
12960          * we want to perform the vblank waits so that watermark
12961          * updates happen during the correct frames. Gen9+ have
12962          * double buffered watermarks and so shouldn't need this.
12963          *
12964          * Unset state->legacy_cursor_update before the call to
12965          * drm_atomic_helper_setup_commit() because otherwise
12966          * drm_atomic_helper_wait_for_flip_done() is a noop and
12967          * we get FIFO underruns because we didn't wait
12968          * for vblank.
12969          *
12970          * FIXME doing watermarks and fb cleanup from a vblank worker
12971          * (assuming we had any) would solve these problems.
12972          */
12973         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12974                 struct intel_crtc_state *new_crtc_state;
12975                 struct intel_crtc *crtc;
12976                 int i;
12977
12978                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12979                         if (new_crtc_state->wm.need_postvbl_update ||
12980                             new_crtc_state->update_wm_post)
12981                                 state->legacy_cursor_update = false;
12982         }
12983
12984         ret = intel_atomic_prepare_commit(dev, state);
12985         if (ret) {
12986                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12987                 i915_sw_fence_commit(&intel_state->commit_ready);
12988                 return ret;
12989         }
12990
12991         ret = drm_atomic_helper_setup_commit(state, nonblock);
12992         if (!ret)
12993                 ret = drm_atomic_helper_swap_state(state, true);
12994
12995         if (ret) {
12996                 i915_sw_fence_commit(&intel_state->commit_ready);
12997
12998                 drm_atomic_helper_cleanup_planes(dev, state);
12999                 return ret;
13000         }
13001         dev_priv->wm.distrust_bios_wm = false;
13002         intel_shared_dpll_swap_state(state);
13003         intel_atomic_track_fbs(state);
13004
13005         if (intel_state->modeset) {
13006                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
13007                        sizeof(intel_state->min_cdclk));
13008                 memcpy(dev_priv->min_voltage_level,
13009                        intel_state->min_voltage_level,
13010                        sizeof(intel_state->min_voltage_level));
13011                 dev_priv->active_crtcs = intel_state->active_crtcs;
13012                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
13013                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
13014         }
13015
13016         drm_atomic_state_get(state);
13017         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
13018
13019         i915_sw_fence_commit(&intel_state->commit_ready);
13020         if (nonblock && intel_state->modeset) {
13021                 queue_work(dev_priv->modeset_wq, &state->commit_work);
13022         } else if (nonblock) {
13023                 queue_work(system_unbound_wq, &state->commit_work);
13024         } else {
13025                 if (intel_state->modeset)
13026                         flush_workqueue(dev_priv->modeset_wq);
13027                 intel_atomic_commit_tail(state);
13028         }
13029
13030         return 0;
13031 }
13032
13033 static const struct drm_crtc_funcs intel_crtc_funcs = {
13034         .gamma_set = drm_atomic_helper_legacy_gamma_set,
13035         .set_config = drm_atomic_helper_set_config,
13036         .destroy = intel_crtc_destroy,
13037         .page_flip = drm_atomic_helper_page_flip,
13038         .atomic_duplicate_state = intel_crtc_duplicate_state,
13039         .atomic_destroy_state = intel_crtc_destroy_state,
13040         .set_crc_source = intel_crtc_set_crc_source,
13041         .verify_crc_source = intel_crtc_verify_crc_source,
13042         .get_crc_sources = intel_crtc_get_crc_sources,
13043 };
13044
13045 struct wait_rps_boost {
13046         struct wait_queue_entry wait;
13047
13048         struct drm_crtc *crtc;
13049         struct i915_request *request;
13050 };
13051
13052 static int do_rps_boost(struct wait_queue_entry *_wait,
13053                         unsigned mode, int sync, void *key)
13054 {
13055         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
13056         struct i915_request *rq = wait->request;
13057
13058         /*
13059          * If we missed the vblank, but the request is already running it
13060          * is reasonable to assume that it will complete before the next
13061          * vblank without our intervention, so leave RPS alone.
13062          */
13063         if (!i915_request_started(rq))
13064                 gen6_rps_boost(rq, NULL);
13065         i915_request_put(rq);
13066
13067         drm_crtc_vblank_put(wait->crtc);
13068
13069         list_del(&wait->wait.entry);
13070         kfree(wait);
13071         return 1;
13072 }
13073
13074 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
13075                                        struct dma_fence *fence)
13076 {
13077         struct wait_rps_boost *wait;
13078
13079         if (!dma_fence_is_i915(fence))
13080                 return;
13081
13082         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
13083                 return;
13084
13085         if (drm_crtc_vblank_get(crtc))
13086                 return;
13087
13088         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
13089         if (!wait) {
13090                 drm_crtc_vblank_put(crtc);
13091                 return;
13092         }
13093
13094         wait->request = to_request(dma_fence_get(fence));
13095         wait->crtc = crtc;
13096
13097         wait->wait.func = do_rps_boost;
13098         wait->wait.flags = 0;
13099
13100         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
13101 }
13102
13103 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
13104 {
13105         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
13106         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
13107         struct drm_framebuffer *fb = plane_state->base.fb;
13108         struct i915_vma *vma;
13109
13110         if (plane->id == PLANE_CURSOR &&
13111             INTEL_INFO(dev_priv)->cursor_needs_physical) {
13112                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13113                 const int align = intel_cursor_alignment(dev_priv);
13114                 int err;
13115
13116                 err = i915_gem_object_attach_phys(obj, align);
13117                 if (err)
13118                         return err;
13119         }
13120
13121         vma = intel_pin_and_fence_fb_obj(fb,
13122                                          &plane_state->view,
13123                                          intel_plane_uses_fence(plane_state),
13124                                          &plane_state->flags);
13125         if (IS_ERR(vma))
13126                 return PTR_ERR(vma);
13127
13128         plane_state->vma = vma;
13129
13130         return 0;
13131 }
13132
13133 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
13134 {
13135         struct i915_vma *vma;
13136
13137         vma = fetch_and_zero(&old_plane_state->vma);
13138         if (vma)
13139                 intel_unpin_fb_vma(vma, old_plane_state->flags);
13140 }
13141
13142 static void fb_obj_bump_render_priority(struct drm_i915_gem_object *obj)
13143 {
13144         struct i915_sched_attr attr = {
13145                 .priority = I915_PRIORITY_DISPLAY,
13146         };
13147
13148         i915_gem_object_wait_priority(obj, 0, &attr);
13149 }
13150
13151 /**
13152  * intel_prepare_plane_fb - Prepare fb for usage on plane
13153  * @plane: drm plane to prepare for
13154  * @new_state: the plane state being prepared
13155  *
13156  * Prepares a framebuffer for usage on a display plane.  Generally this
13157  * involves pinning the underlying object and updating the frontbuffer tracking
13158  * bits.  Some older platforms need special physical address handling for
13159  * cursor planes.
13160  *
13161  * Must be called with struct_mutex held.
13162  *
13163  * Returns 0 on success, negative error code on failure.
13164  */
13165 int
13166 intel_prepare_plane_fb(struct drm_plane *plane,
13167                        struct drm_plane_state *new_state)
13168 {
13169         struct intel_atomic_state *intel_state =
13170                 to_intel_atomic_state(new_state->state);
13171         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13172         struct drm_framebuffer *fb = new_state->fb;
13173         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13174         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
13175         int ret;
13176
13177         if (old_obj) {
13178                 struct drm_crtc_state *crtc_state =
13179                         drm_atomic_get_new_crtc_state(new_state->state,
13180                                                       plane->state->crtc);
13181
13182                 /* Big Hammer, we also need to ensure that any pending
13183                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
13184                  * current scanout is retired before unpinning the old
13185                  * framebuffer. Note that we rely on userspace rendering
13186                  * into the buffer attached to the pipe they are waiting
13187                  * on. If not, userspace generates a GPU hang with IPEHR
13188                  * point to the MI_WAIT_FOR_EVENT.
13189                  *
13190                  * This should only fail upon a hung GPU, in which case we
13191                  * can safely continue.
13192                  */
13193                 if (needs_modeset(crtc_state)) {
13194                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13195                                                               old_obj->resv, NULL,
13196                                                               false, 0,
13197                                                               GFP_KERNEL);
13198                         if (ret < 0)
13199                                 return ret;
13200                 }
13201         }
13202
13203         if (new_state->fence) { /* explicit fencing */
13204                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
13205                                                     new_state->fence,
13206                                                     I915_FENCE_TIMEOUT,
13207                                                     GFP_KERNEL);
13208                 if (ret < 0)
13209                         return ret;
13210         }
13211
13212         if (!obj)
13213                 return 0;
13214
13215         ret = i915_gem_object_pin_pages(obj);
13216         if (ret)
13217                 return ret;
13218
13219         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13220         if (ret) {
13221                 i915_gem_object_unpin_pages(obj);
13222                 return ret;
13223         }
13224
13225         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
13226
13227         fb_obj_bump_render_priority(obj);
13228
13229         mutex_unlock(&dev_priv->drm.struct_mutex);
13230         i915_gem_object_unpin_pages(obj);
13231         if (ret)
13232                 return ret;
13233
13234         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13235
13236         if (!new_state->fence) { /* implicit fencing */
13237                 struct dma_fence *fence;
13238
13239                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
13240                                                       obj->resv, NULL,
13241                                                       false, I915_FENCE_TIMEOUT,
13242                                                       GFP_KERNEL);
13243                 if (ret < 0)
13244                         return ret;
13245
13246                 fence = reservation_object_get_excl_rcu(obj->resv);
13247                 if (fence) {
13248                         add_rps_boost_after_vblank(new_state->crtc, fence);
13249                         dma_fence_put(fence);
13250                 }
13251         } else {
13252                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
13253         }
13254
13255         /*
13256          * We declare pageflips to be interactive and so merit a small bias
13257          * towards upclocking to deliver the frame on time. By only changing
13258          * the RPS thresholds to sample more regularly and aim for higher
13259          * clocks we can hopefully deliver low power workloads (like kodi)
13260          * that are not quite steady state without resorting to forcing
13261          * maximum clocks following a vblank miss (see do_rps_boost()).
13262          */
13263         if (!intel_state->rps_interactive) {
13264                 intel_rps_mark_interactive(dev_priv, true);
13265                 intel_state->rps_interactive = true;
13266         }
13267
13268         return 0;
13269 }
13270
13271 /**
13272  * intel_cleanup_plane_fb - Cleans up an fb after plane use
13273  * @plane: drm plane to clean up for
13274  * @old_state: the state from the previous modeset
13275  *
13276  * Cleans up a framebuffer that has just been removed from a plane.
13277  *
13278  * Must be called with struct_mutex held.
13279  */
13280 void
13281 intel_cleanup_plane_fb(struct drm_plane *plane,
13282                        struct drm_plane_state *old_state)
13283 {
13284         struct intel_atomic_state *intel_state =
13285                 to_intel_atomic_state(old_state->state);
13286         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13287
13288         if (intel_state->rps_interactive) {
13289                 intel_rps_mark_interactive(dev_priv, false);
13290                 intel_state->rps_interactive = false;
13291         }
13292
13293         /* Should only be called after a successful intel_prepare_plane_fb()! */
13294         mutex_lock(&dev_priv->drm.struct_mutex);
13295         intel_plane_unpin_fb(to_intel_plane_state(old_state));
13296         mutex_unlock(&dev_priv->drm.struct_mutex);
13297 }
13298
13299 int
13300 skl_max_scale(const struct intel_crtc_state *crtc_state,
13301               u32 pixel_format)
13302 {
13303         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
13304         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13305         int max_scale, mult;
13306         int crtc_clock, max_dotclk, tmpclk1, tmpclk2;
13307
13308         if (!crtc_state->base.enable)
13309                 return DRM_PLANE_HELPER_NO_SCALING;
13310
13311         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
13312         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
13313
13314         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
13315                 max_dotclk *= 2;
13316
13317         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
13318                 return DRM_PLANE_HELPER_NO_SCALING;
13319
13320         /*
13321          * skl max scale is lower of:
13322          *    close to 3 but not 3, -1 is for that purpose
13323          *            or
13324          *    cdclk/crtc_clock
13325          */
13326         mult = pixel_format == DRM_FORMAT_NV12 ? 2 : 3;
13327         tmpclk1 = (1 << 16) * mult - 1;
13328         tmpclk2 = (1 << 8) * ((max_dotclk << 8) / crtc_clock);
13329         max_scale = min(tmpclk1, tmpclk2);
13330
13331         return max_scale;
13332 }
13333
13334 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
13335                                     struct drm_crtc_state *old_crtc_state)
13336 {
13337         struct drm_device *dev = crtc->dev;
13338         struct drm_i915_private *dev_priv = to_i915(dev);
13339         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13340         struct intel_crtc_state *old_intel_cstate =
13341                 to_intel_crtc_state(old_crtc_state);
13342         struct intel_atomic_state *old_intel_state =
13343                 to_intel_atomic_state(old_crtc_state->state);
13344         struct intel_crtc_state *intel_cstate =
13345                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13346         bool modeset = needs_modeset(&intel_cstate->base);
13347
13348         if (!modeset &&
13349             (intel_cstate->base.color_mgmt_changed ||
13350              intel_cstate->update_pipe)) {
13351                 intel_color_set_csc(&intel_cstate->base);
13352                 intel_color_load_luts(&intel_cstate->base);
13353         }
13354
13355         /* Perform vblank evasion around commit operation */
13356         intel_pipe_update_start(intel_cstate);
13357
13358         if (modeset)
13359                 goto out;
13360
13361         if (intel_cstate->update_pipe)
13362                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
13363         else if (INTEL_GEN(dev_priv) >= 9)
13364                 skl_detach_scalers(intel_crtc);
13365
13366 out:
13367         if (dev_priv->display.atomic_update_watermarks)
13368                 dev_priv->display.atomic_update_watermarks(old_intel_state,
13369                                                            intel_cstate);
13370 }
13371
13372 void intel_crtc_arm_fifo_underrun(struct intel_crtc *crtc,
13373                                   struct intel_crtc_state *crtc_state)
13374 {
13375         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13376
13377         if (!IS_GEN2(dev_priv))
13378                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
13379
13380         if (crtc_state->has_pch_encoder) {
13381                 enum pipe pch_transcoder =
13382                         intel_crtc_pch_transcoder(crtc);
13383
13384                 intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
13385         }
13386 }
13387
13388 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
13389                                      struct drm_crtc_state *old_crtc_state)
13390 {
13391         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
13392         struct intel_atomic_state *old_intel_state =
13393                 to_intel_atomic_state(old_crtc_state->state);
13394         struct intel_crtc_state *new_crtc_state =
13395                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
13396
13397         intel_pipe_update_end(new_crtc_state);
13398
13399         if (new_crtc_state->update_pipe &&
13400             !needs_modeset(&new_crtc_state->base) &&
13401             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED)
13402                 intel_crtc_arm_fifo_underrun(intel_crtc, new_crtc_state);
13403 }
13404
13405 /**
13406  * intel_plane_destroy - destroy a plane
13407  * @plane: plane to destroy
13408  *
13409  * Common destruction function for all types of planes (primary, cursor,
13410  * sprite).
13411  */
13412 void intel_plane_destroy(struct drm_plane *plane)
13413 {
13414         drm_plane_cleanup(plane);
13415         kfree(to_intel_plane(plane));
13416 }
13417
13418 static bool i8xx_plane_format_mod_supported(struct drm_plane *_plane,
13419                                             u32 format, u64 modifier)
13420 {
13421         switch (modifier) {
13422         case DRM_FORMAT_MOD_LINEAR:
13423         case I915_FORMAT_MOD_X_TILED:
13424                 break;
13425         default:
13426                 return false;
13427         }
13428
13429         switch (format) {
13430         case DRM_FORMAT_C8:
13431         case DRM_FORMAT_RGB565:
13432         case DRM_FORMAT_XRGB1555:
13433         case DRM_FORMAT_XRGB8888:
13434                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13435                         modifier == I915_FORMAT_MOD_X_TILED;
13436         default:
13437                 return false;
13438         }
13439 }
13440
13441 static bool i965_plane_format_mod_supported(struct drm_plane *_plane,
13442                                             u32 format, u64 modifier)
13443 {
13444         switch (modifier) {
13445         case DRM_FORMAT_MOD_LINEAR:
13446         case I915_FORMAT_MOD_X_TILED:
13447                 break;
13448         default:
13449                 return false;
13450         }
13451
13452         switch (format) {
13453         case DRM_FORMAT_C8:
13454         case DRM_FORMAT_RGB565:
13455         case DRM_FORMAT_XRGB8888:
13456         case DRM_FORMAT_XBGR8888:
13457         case DRM_FORMAT_XRGB2101010:
13458         case DRM_FORMAT_XBGR2101010:
13459                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13460                         modifier == I915_FORMAT_MOD_X_TILED;
13461         default:
13462                 return false;
13463         }
13464 }
13465
13466 static bool skl_plane_format_mod_supported(struct drm_plane *_plane,
13467                                            u32 format, u64 modifier)
13468 {
13469         struct intel_plane *plane = to_intel_plane(_plane);
13470
13471         switch (modifier) {
13472         case DRM_FORMAT_MOD_LINEAR:
13473         case I915_FORMAT_MOD_X_TILED:
13474         case I915_FORMAT_MOD_Y_TILED:
13475         case I915_FORMAT_MOD_Yf_TILED:
13476                 break;
13477         case I915_FORMAT_MOD_Y_TILED_CCS:
13478         case I915_FORMAT_MOD_Yf_TILED_CCS:
13479                 if (!plane->has_ccs)
13480                         return false;
13481                 break;
13482         default:
13483                 return false;
13484         }
13485
13486         switch (format) {
13487         case DRM_FORMAT_XRGB8888:
13488         case DRM_FORMAT_XBGR8888:
13489         case DRM_FORMAT_ARGB8888:
13490         case DRM_FORMAT_ABGR8888:
13491                 if (is_ccs_modifier(modifier))
13492                         return true;
13493                 /* fall through */
13494         case DRM_FORMAT_RGB565:
13495         case DRM_FORMAT_XRGB2101010:
13496         case DRM_FORMAT_XBGR2101010:
13497         case DRM_FORMAT_YUYV:
13498         case DRM_FORMAT_YVYU:
13499         case DRM_FORMAT_UYVY:
13500         case DRM_FORMAT_VYUY:
13501         case DRM_FORMAT_NV12:
13502                 if (modifier == I915_FORMAT_MOD_Yf_TILED)
13503                         return true;
13504                 /* fall through */
13505         case DRM_FORMAT_C8:
13506                 if (modifier == DRM_FORMAT_MOD_LINEAR ||
13507                     modifier == I915_FORMAT_MOD_X_TILED ||
13508                     modifier == I915_FORMAT_MOD_Y_TILED)
13509                         return true;
13510                 /* fall through */
13511         default:
13512                 return false;
13513         }
13514 }
13515
13516 static bool intel_cursor_format_mod_supported(struct drm_plane *_plane,
13517                                               u32 format, u64 modifier)
13518 {
13519         return modifier == DRM_FORMAT_MOD_LINEAR &&
13520                 format == DRM_FORMAT_ARGB8888;
13521 }
13522
13523 static struct drm_plane_funcs skl_plane_funcs = {
13524         .update_plane = drm_atomic_helper_update_plane,
13525         .disable_plane = drm_atomic_helper_disable_plane,
13526         .destroy = intel_plane_destroy,
13527         .atomic_get_property = intel_plane_atomic_get_property,
13528         .atomic_set_property = intel_plane_atomic_set_property,
13529         .atomic_duplicate_state = intel_plane_duplicate_state,
13530         .atomic_destroy_state = intel_plane_destroy_state,
13531         .format_mod_supported = skl_plane_format_mod_supported,
13532 };
13533
13534 static struct drm_plane_funcs i965_plane_funcs = {
13535         .update_plane = drm_atomic_helper_update_plane,
13536         .disable_plane = drm_atomic_helper_disable_plane,
13537         .destroy = intel_plane_destroy,
13538         .atomic_get_property = intel_plane_atomic_get_property,
13539         .atomic_set_property = intel_plane_atomic_set_property,
13540         .atomic_duplicate_state = intel_plane_duplicate_state,
13541         .atomic_destroy_state = intel_plane_destroy_state,
13542         .format_mod_supported = i965_plane_format_mod_supported,
13543 };
13544
13545 static struct drm_plane_funcs i8xx_plane_funcs = {
13546         .update_plane = drm_atomic_helper_update_plane,
13547         .disable_plane = drm_atomic_helper_disable_plane,
13548         .destroy = intel_plane_destroy,
13549         .atomic_get_property = intel_plane_atomic_get_property,
13550         .atomic_set_property = intel_plane_atomic_set_property,
13551         .atomic_duplicate_state = intel_plane_duplicate_state,
13552         .atomic_destroy_state = intel_plane_destroy_state,
13553         .format_mod_supported = i8xx_plane_format_mod_supported,
13554 };
13555
13556 static int
13557 intel_legacy_cursor_update(struct drm_plane *plane,
13558                            struct drm_crtc *crtc,
13559                            struct drm_framebuffer *fb,
13560                            int crtc_x, int crtc_y,
13561                            unsigned int crtc_w, unsigned int crtc_h,
13562                            uint32_t src_x, uint32_t src_y,
13563                            uint32_t src_w, uint32_t src_h,
13564                            struct drm_modeset_acquire_ctx *ctx)
13565 {
13566         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13567         int ret;
13568         struct drm_plane_state *old_plane_state, *new_plane_state;
13569         struct intel_plane *intel_plane = to_intel_plane(plane);
13570         struct drm_framebuffer *old_fb;
13571         struct drm_crtc_state *crtc_state = crtc->state;
13572
13573         /*
13574          * When crtc is inactive or there is a modeset pending,
13575          * wait for it to complete in the slowpath
13576          */
13577         if (!crtc_state->active || needs_modeset(crtc_state) ||
13578             to_intel_crtc_state(crtc_state)->update_pipe)
13579                 goto slow;
13580
13581         old_plane_state = plane->state;
13582         /*
13583          * Don't do an async update if there is an outstanding commit modifying
13584          * the plane.  This prevents our async update's changes from getting
13585          * overridden by a previous synchronous update's state.
13586          */
13587         if (old_plane_state->commit &&
13588             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13589                 goto slow;
13590
13591         /*
13592          * If any parameters change that may affect watermarks,
13593          * take the slowpath. Only changing fb or position should be
13594          * in the fastpath.
13595          */
13596         if (old_plane_state->crtc != crtc ||
13597             old_plane_state->src_w != src_w ||
13598             old_plane_state->src_h != src_h ||
13599             old_plane_state->crtc_w != crtc_w ||
13600             old_plane_state->crtc_h != crtc_h ||
13601             !old_plane_state->fb != !fb)
13602                 goto slow;
13603
13604         new_plane_state = intel_plane_duplicate_state(plane);
13605         if (!new_plane_state)
13606                 return -ENOMEM;
13607
13608         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13609
13610         new_plane_state->src_x = src_x;
13611         new_plane_state->src_y = src_y;
13612         new_plane_state->src_w = src_w;
13613         new_plane_state->src_h = src_h;
13614         new_plane_state->crtc_x = crtc_x;
13615         new_plane_state->crtc_y = crtc_y;
13616         new_plane_state->crtc_w = crtc_w;
13617         new_plane_state->crtc_h = crtc_h;
13618
13619         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13620                                                   to_intel_crtc_state(crtc->state), /* FIXME need a new crtc state? */
13621                                                   to_intel_plane_state(plane->state),
13622                                                   to_intel_plane_state(new_plane_state));
13623         if (ret)
13624                 goto out_free;
13625
13626         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13627         if (ret)
13628                 goto out_free;
13629
13630         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13631         if (ret)
13632                 goto out_unlock;
13633
13634         intel_fb_obj_flush(intel_fb_obj(fb), ORIGIN_FLIP);
13635
13636         old_fb = old_plane_state->fb;
13637         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13638                           intel_plane->frontbuffer_bit);
13639
13640         /* Swap plane state */
13641         plane->state = new_plane_state;
13642
13643         if (plane->state->visible) {
13644                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13645                 intel_plane->update_plane(intel_plane,
13646                                           to_intel_crtc_state(crtc->state),
13647                                           to_intel_plane_state(plane->state));
13648         } else {
13649                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13650                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13651         }
13652
13653         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13654
13655 out_unlock:
13656         mutex_unlock(&dev_priv->drm.struct_mutex);
13657 out_free:
13658         if (ret)
13659                 intel_plane_destroy_state(plane, new_plane_state);
13660         else
13661                 intel_plane_destroy_state(plane, old_plane_state);
13662         return ret;
13663
13664 slow:
13665         return drm_atomic_helper_update_plane(plane, crtc, fb,
13666                                               crtc_x, crtc_y, crtc_w, crtc_h,
13667                                               src_x, src_y, src_w, src_h, ctx);
13668 }
13669
13670 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13671         .update_plane = intel_legacy_cursor_update,
13672         .disable_plane = drm_atomic_helper_disable_plane,
13673         .destroy = intel_plane_destroy,
13674         .atomic_get_property = intel_plane_atomic_get_property,
13675         .atomic_set_property = intel_plane_atomic_set_property,
13676         .atomic_duplicate_state = intel_plane_duplicate_state,
13677         .atomic_destroy_state = intel_plane_destroy_state,
13678         .format_mod_supported = intel_cursor_format_mod_supported,
13679 };
13680
13681 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13682                                enum i9xx_plane_id i9xx_plane)
13683 {
13684         if (!HAS_FBC(dev_priv))
13685                 return false;
13686
13687         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13688                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13689         else if (IS_IVYBRIDGE(dev_priv))
13690                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13691                         i9xx_plane == PLANE_C;
13692         else if (INTEL_GEN(dev_priv) >= 4)
13693                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13694         else
13695                 return i9xx_plane == PLANE_A;
13696 }
13697
13698 static bool skl_plane_has_fbc(struct drm_i915_private *dev_priv,
13699                               enum pipe pipe, enum plane_id plane_id)
13700 {
13701         if (!HAS_FBC(dev_priv))
13702                 return false;
13703
13704         return pipe == PIPE_A && plane_id == PLANE_PRIMARY;
13705 }
13706
13707 bool skl_plane_has_planar(struct drm_i915_private *dev_priv,
13708                           enum pipe pipe, enum plane_id plane_id)
13709 {
13710         /*
13711          * FIXME: ICL requires two hardware planes for scanning out NV12
13712          * framebuffers. Do not advertize support until this is implemented.
13713          */
13714         if (INTEL_GEN(dev_priv) >= 11)
13715                 return false;
13716
13717         if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv))
13718                 return false;
13719
13720         if (INTEL_GEN(dev_priv) == 9 && !IS_GEMINILAKE(dev_priv) && pipe == PIPE_C)
13721                 return false;
13722
13723         if (plane_id != PLANE_PRIMARY && plane_id != PLANE_SPRITE0)
13724                 return false;
13725
13726         return true;
13727 }
13728
13729 static struct intel_plane *
13730 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13731 {
13732         struct intel_plane *primary = NULL;
13733         struct intel_plane_state *state = NULL;
13734         const struct drm_plane_funcs *plane_funcs;
13735         const uint32_t *intel_primary_formats;
13736         unsigned int supported_rotations;
13737         unsigned int num_formats;
13738         const uint64_t *modifiers;
13739         int ret;
13740
13741         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13742         if (!primary) {
13743                 ret = -ENOMEM;
13744                 goto fail;
13745         }
13746
13747         state = intel_create_plane_state(&primary->base);
13748         if (!state) {
13749                 ret = -ENOMEM;
13750                 goto fail;
13751         }
13752
13753         primary->base.state = &state->base;
13754
13755         if (INTEL_GEN(dev_priv) >= 9)
13756                 state->scaler_id = -1;
13757         primary->pipe = pipe;
13758         /*
13759          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13760          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13761          */
13762         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13763                 primary->i9xx_plane = (enum i9xx_plane_id) !pipe;
13764         else
13765                 primary->i9xx_plane = (enum i9xx_plane_id) pipe;
13766         primary->id = PLANE_PRIMARY;
13767         primary->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, primary->id);
13768
13769         if (INTEL_GEN(dev_priv) >= 9)
13770                 primary->has_fbc = skl_plane_has_fbc(dev_priv,
13771                                                      primary->pipe,
13772                                                      primary->id);
13773         else
13774                 primary->has_fbc = i9xx_plane_has_fbc(dev_priv,
13775                                                       primary->i9xx_plane);
13776
13777         if (primary->has_fbc) {
13778                 struct intel_fbc *fbc = &dev_priv->fbc;
13779
13780                 fbc->possible_framebuffer_bits |= primary->frontbuffer_bit;
13781         }
13782
13783         if (INTEL_GEN(dev_priv) >= 9) {
13784                 primary->has_ccs = skl_plane_has_ccs(dev_priv, pipe,
13785                                                      PLANE_PRIMARY);
13786
13787                 if (skl_plane_has_planar(dev_priv, pipe, PLANE_PRIMARY)) {
13788                         intel_primary_formats = skl_pri_planar_formats;
13789                         num_formats = ARRAY_SIZE(skl_pri_planar_formats);
13790                 } else {
13791                         intel_primary_formats = skl_primary_formats;
13792                         num_formats = ARRAY_SIZE(skl_primary_formats);
13793                 }
13794
13795                 if (primary->has_ccs)
13796                         modifiers = skl_format_modifiers_ccs;
13797                 else
13798                         modifiers = skl_format_modifiers_noccs;
13799
13800                 primary->max_stride = skl_plane_max_stride;
13801                 primary->update_plane = skl_update_plane;
13802                 primary->disable_plane = skl_disable_plane;
13803                 primary->get_hw_state = skl_plane_get_hw_state;
13804                 primary->check_plane = skl_plane_check;
13805
13806                 plane_funcs = &skl_plane_funcs;
13807         } else if (INTEL_GEN(dev_priv) >= 4) {
13808                 intel_primary_formats = i965_primary_formats;
13809                 num_formats = ARRAY_SIZE(i965_primary_formats);
13810                 modifiers = i9xx_format_modifiers;
13811
13812                 primary->max_stride = i9xx_plane_max_stride;
13813                 primary->update_plane = i9xx_update_plane;
13814                 primary->disable_plane = i9xx_disable_plane;
13815                 primary->get_hw_state = i9xx_plane_get_hw_state;
13816                 primary->check_plane = i9xx_plane_check;
13817
13818                 plane_funcs = &i965_plane_funcs;
13819         } else {
13820                 intel_primary_formats = i8xx_primary_formats;
13821                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13822                 modifiers = i9xx_format_modifiers;
13823
13824                 primary->max_stride = i9xx_plane_max_stride;
13825                 primary->update_plane = i9xx_update_plane;
13826                 primary->disable_plane = i9xx_disable_plane;
13827                 primary->get_hw_state = i9xx_plane_get_hw_state;
13828                 primary->check_plane = i9xx_plane_check;
13829
13830                 plane_funcs = &i8xx_plane_funcs;
13831         }
13832
13833         if (INTEL_GEN(dev_priv) >= 9)
13834                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13835                                                0, plane_funcs,
13836                                                intel_primary_formats, num_formats,
13837                                                modifiers,
13838                                                DRM_PLANE_TYPE_PRIMARY,
13839                                                "plane 1%c", pipe_name(pipe));
13840         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13841                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13842                                                0, plane_funcs,
13843                                                intel_primary_formats, num_formats,
13844                                                modifiers,
13845                                                DRM_PLANE_TYPE_PRIMARY,
13846                                                "primary %c", pipe_name(pipe));
13847         else
13848                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13849                                                0, plane_funcs,
13850                                                intel_primary_formats, num_formats,
13851                                                modifiers,
13852                                                DRM_PLANE_TYPE_PRIMARY,
13853                                                "plane %c",
13854                                                plane_name(primary->i9xx_plane));
13855         if (ret)
13856                 goto fail;
13857
13858         if (INTEL_GEN(dev_priv) >= 10) {
13859                 supported_rotations =
13860                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13861                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270 |
13862                         DRM_MODE_REFLECT_X;
13863         } else if (INTEL_GEN(dev_priv) >= 9) {
13864                 supported_rotations =
13865                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13866                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13867         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13868                 supported_rotations =
13869                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13870                         DRM_MODE_REFLECT_X;
13871         } else if (INTEL_GEN(dev_priv) >= 4) {
13872                 supported_rotations =
13873                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13874         } else {
13875                 supported_rotations = DRM_MODE_ROTATE_0;
13876         }
13877
13878         if (INTEL_GEN(dev_priv) >= 4)
13879                 drm_plane_create_rotation_property(&primary->base,
13880                                                    DRM_MODE_ROTATE_0,
13881                                                    supported_rotations);
13882
13883         if (INTEL_GEN(dev_priv) >= 9)
13884                 drm_plane_create_color_properties(&primary->base,
13885                                                   BIT(DRM_COLOR_YCBCR_BT601) |
13886                                                   BIT(DRM_COLOR_YCBCR_BT709),
13887                                                   BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
13888                                                   BIT(DRM_COLOR_YCBCR_FULL_RANGE),
13889                                                   DRM_COLOR_YCBCR_BT709,
13890                                                   DRM_COLOR_YCBCR_LIMITED_RANGE);
13891
13892         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13893
13894         return primary;
13895
13896 fail:
13897         kfree(state);
13898         kfree(primary);
13899
13900         return ERR_PTR(ret);
13901 }
13902
13903 static struct intel_plane *
13904 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13905                           enum pipe pipe)
13906 {
13907         struct intel_plane *cursor = NULL;
13908         struct intel_plane_state *state = NULL;
13909         int ret;
13910
13911         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13912         if (!cursor) {
13913                 ret = -ENOMEM;
13914                 goto fail;
13915         }
13916
13917         state = intel_create_plane_state(&cursor->base);
13918         if (!state) {
13919                 ret = -ENOMEM;
13920                 goto fail;
13921         }
13922
13923         cursor->base.state = &state->base;
13924
13925         cursor->pipe = pipe;
13926         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13927         cursor->id = PLANE_CURSOR;
13928         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13929
13930         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13931                 cursor->max_stride = i845_cursor_max_stride;
13932                 cursor->update_plane = i845_update_cursor;
13933                 cursor->disable_plane = i845_disable_cursor;
13934                 cursor->get_hw_state = i845_cursor_get_hw_state;
13935                 cursor->check_plane = i845_check_cursor;
13936         } else {
13937                 cursor->max_stride = i9xx_cursor_max_stride;
13938                 cursor->update_plane = i9xx_update_cursor;
13939                 cursor->disable_plane = i9xx_disable_cursor;
13940                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13941                 cursor->check_plane = i9xx_check_cursor;
13942         }
13943
13944         cursor->cursor.base = ~0;
13945         cursor->cursor.cntl = ~0;
13946
13947         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13948                 cursor->cursor.size = ~0;
13949
13950         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13951                                        0, &intel_cursor_plane_funcs,
13952                                        intel_cursor_formats,
13953                                        ARRAY_SIZE(intel_cursor_formats),
13954                                        cursor_format_modifiers,
13955                                        DRM_PLANE_TYPE_CURSOR,
13956                                        "cursor %c", pipe_name(pipe));
13957         if (ret)
13958                 goto fail;
13959
13960         if (INTEL_GEN(dev_priv) >= 4)
13961                 drm_plane_create_rotation_property(&cursor->base,
13962                                                    DRM_MODE_ROTATE_0,
13963                                                    DRM_MODE_ROTATE_0 |
13964                                                    DRM_MODE_ROTATE_180);
13965
13966         if (INTEL_GEN(dev_priv) >= 9)
13967                 state->scaler_id = -1;
13968
13969         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13970
13971         return cursor;
13972
13973 fail:
13974         kfree(state);
13975         kfree(cursor);
13976
13977         return ERR_PTR(ret);
13978 }
13979
13980 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13981                                     struct intel_crtc_state *crtc_state)
13982 {
13983         struct intel_crtc_scaler_state *scaler_state =
13984                 &crtc_state->scaler_state;
13985         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13986         int i;
13987
13988         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13989         if (!crtc->num_scalers)
13990                 return;
13991
13992         for (i = 0; i < crtc->num_scalers; i++) {
13993                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13994
13995                 scaler->in_use = 0;
13996                 scaler->mode = PS_SCALER_MODE_DYN;
13997         }
13998
13999         scaler_state->scaler_id = -1;
14000 }
14001
14002 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
14003 {
14004         struct intel_crtc *intel_crtc;
14005         struct intel_crtc_state *crtc_state = NULL;
14006         struct intel_plane *primary = NULL;
14007         struct intel_plane *cursor = NULL;
14008         int sprite, ret;
14009
14010         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
14011         if (!intel_crtc)
14012                 return -ENOMEM;
14013
14014         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
14015         if (!crtc_state) {
14016                 ret = -ENOMEM;
14017                 goto fail;
14018         }
14019         intel_crtc->config = crtc_state;
14020         intel_crtc->base.state = &crtc_state->base;
14021         crtc_state->base.crtc = &intel_crtc->base;
14022
14023         primary = intel_primary_plane_create(dev_priv, pipe);
14024         if (IS_ERR(primary)) {
14025                 ret = PTR_ERR(primary);
14026                 goto fail;
14027         }
14028         intel_crtc->plane_ids_mask |= BIT(primary->id);
14029
14030         for_each_sprite(dev_priv, pipe, sprite) {
14031                 struct intel_plane *plane;
14032
14033                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
14034                 if (IS_ERR(plane)) {
14035                         ret = PTR_ERR(plane);
14036                         goto fail;
14037                 }
14038                 intel_crtc->plane_ids_mask |= BIT(plane->id);
14039         }
14040
14041         cursor = intel_cursor_plane_create(dev_priv, pipe);
14042         if (IS_ERR(cursor)) {
14043                 ret = PTR_ERR(cursor);
14044                 goto fail;
14045         }
14046         intel_crtc->plane_ids_mask |= BIT(cursor->id);
14047
14048         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
14049                                         &primary->base, &cursor->base,
14050                                         &intel_crtc_funcs,
14051                                         "pipe %c", pipe_name(pipe));
14052         if (ret)
14053                 goto fail;
14054
14055         intel_crtc->pipe = pipe;
14056
14057         /* initialize shared scalers */
14058         intel_crtc_init_scalers(intel_crtc, crtc_state);
14059
14060         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->pipe_to_crtc_mapping) ||
14061                dev_priv->pipe_to_crtc_mapping[pipe] != NULL);
14062         dev_priv->pipe_to_crtc_mapping[pipe] = intel_crtc;
14063
14064         if (INTEL_GEN(dev_priv) < 9) {
14065                 enum i9xx_plane_id i9xx_plane = primary->i9xx_plane;
14066
14067                 BUG_ON(i9xx_plane >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
14068                        dev_priv->plane_to_crtc_mapping[i9xx_plane] != NULL);
14069                 dev_priv->plane_to_crtc_mapping[i9xx_plane] = intel_crtc;
14070         }
14071
14072         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
14073
14074         intel_color_init(&intel_crtc->base);
14075
14076         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
14077
14078         return 0;
14079
14080 fail:
14081         /*
14082          * drm_mode_config_cleanup() will free up any
14083          * crtcs/planes already initialized.
14084          */
14085         kfree(crtc_state);
14086         kfree(intel_crtc);
14087
14088         return ret;
14089 }
14090
14091 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
14092 {
14093         struct drm_device *dev = connector->base.dev;
14094
14095         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
14096
14097         if (!connector->base.state->crtc)
14098                 return INVALID_PIPE;
14099
14100         return to_intel_crtc(connector->base.state->crtc)->pipe;
14101 }
14102
14103 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
14104                                       struct drm_file *file)
14105 {
14106         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
14107         struct drm_crtc *drmmode_crtc;
14108         struct intel_crtc *crtc;
14109
14110         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
14111         if (!drmmode_crtc)
14112                 return -ENOENT;
14113
14114         crtc = to_intel_crtc(drmmode_crtc);
14115         pipe_from_crtc_id->pipe = crtc->pipe;
14116
14117         return 0;
14118 }
14119
14120 static int intel_encoder_clones(struct intel_encoder *encoder)
14121 {
14122         struct drm_device *dev = encoder->base.dev;
14123         struct intel_encoder *source_encoder;
14124         int index_mask = 0;
14125         int entry = 0;
14126
14127         for_each_intel_encoder(dev, source_encoder) {
14128                 if (encoders_cloneable(encoder, source_encoder))
14129                         index_mask |= (1 << entry);
14130
14131                 entry++;
14132         }
14133
14134         return index_mask;
14135 }
14136
14137 static bool has_edp_a(struct drm_i915_private *dev_priv)
14138 {
14139         if (!IS_MOBILE(dev_priv))
14140                 return false;
14141
14142         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
14143                 return false;
14144
14145         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
14146                 return false;
14147
14148         return true;
14149 }
14150
14151 static bool intel_crt_present(struct drm_i915_private *dev_priv)
14152 {
14153         if (INTEL_GEN(dev_priv) >= 9)
14154                 return false;
14155
14156         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
14157                 return false;
14158
14159         if (IS_CHERRYVIEW(dev_priv))
14160                 return false;
14161
14162         if (HAS_PCH_LPT_H(dev_priv) &&
14163             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
14164                 return false;
14165
14166         /* DDI E can't be used if DDI A requires 4 lanes */
14167         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
14168                 return false;
14169
14170         if (!dev_priv->vbt.int_crt_support)
14171                 return false;
14172
14173         return true;
14174 }
14175
14176 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
14177 {
14178         int pps_num;
14179         int pps_idx;
14180
14181         if (HAS_DDI(dev_priv))
14182                 return;
14183         /*
14184          * This w/a is needed at least on CPT/PPT, but to be sure apply it
14185          * everywhere where registers can be write protected.
14186          */
14187         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14188                 pps_num = 2;
14189         else
14190                 pps_num = 1;
14191
14192         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
14193                 u32 val = I915_READ(PP_CONTROL(pps_idx));
14194
14195                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
14196                 I915_WRITE(PP_CONTROL(pps_idx), val);
14197         }
14198 }
14199
14200 static void intel_pps_init(struct drm_i915_private *dev_priv)
14201 {
14202         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
14203                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
14204         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
14205                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
14206         else
14207                 dev_priv->pps_mmio_base = PPS_BASE;
14208
14209         intel_pps_unlock_regs_wa(dev_priv);
14210 }
14211
14212 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
14213 {
14214         struct intel_encoder *encoder;
14215         bool dpd_is_edp = false;
14216
14217         intel_pps_init(dev_priv);
14218
14219         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14220                 return;
14221
14222         /*
14223          * intel_edp_init_connector() depends on this completing first, to
14224          * prevent the registeration of both eDP and LVDS and the incorrect
14225          * sharing of the PPS.
14226          */
14227         intel_lvds_init(dev_priv);
14228
14229         if (intel_crt_present(dev_priv))
14230                 intel_crt_init(dev_priv);
14231
14232         if (IS_ICELAKE(dev_priv)) {
14233                 intel_ddi_init(dev_priv, PORT_A);
14234                 intel_ddi_init(dev_priv, PORT_B);
14235                 intel_ddi_init(dev_priv, PORT_C);
14236                 intel_ddi_init(dev_priv, PORT_D);
14237                 intel_ddi_init(dev_priv, PORT_E);
14238                 intel_ddi_init(dev_priv, PORT_F);
14239         } else if (IS_GEN9_LP(dev_priv)) {
14240                 /*
14241                  * FIXME: Broxton doesn't support port detection via the
14242                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
14243                  * detect the ports.
14244                  */
14245                 intel_ddi_init(dev_priv, PORT_A);
14246                 intel_ddi_init(dev_priv, PORT_B);
14247                 intel_ddi_init(dev_priv, PORT_C);
14248
14249                 vlv_dsi_init(dev_priv);
14250         } else if (HAS_DDI(dev_priv)) {
14251                 int found;
14252
14253                 /*
14254                  * Haswell uses DDI functions to detect digital outputs.
14255                  * On SKL pre-D0 the strap isn't connected, so we assume
14256                  * it's there.
14257                  */
14258                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
14259                 /* WaIgnoreDDIAStrap: skl */
14260                 if (found || IS_GEN9_BC(dev_priv))
14261                         intel_ddi_init(dev_priv, PORT_A);
14262
14263                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
14264                  * register */
14265                 found = I915_READ(SFUSE_STRAP);
14266
14267                 if (found & SFUSE_STRAP_DDIB_DETECTED)
14268                         intel_ddi_init(dev_priv, PORT_B);
14269                 if (found & SFUSE_STRAP_DDIC_DETECTED)
14270                         intel_ddi_init(dev_priv, PORT_C);
14271                 if (found & SFUSE_STRAP_DDID_DETECTED)
14272                         intel_ddi_init(dev_priv, PORT_D);
14273                 if (found & SFUSE_STRAP_DDIF_DETECTED)
14274                         intel_ddi_init(dev_priv, PORT_F);
14275                 /*
14276                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
14277                  */
14278                 if (IS_GEN9_BC(dev_priv) &&
14279                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
14280                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
14281                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
14282                         intel_ddi_init(dev_priv, PORT_E);
14283
14284         } else if (HAS_PCH_SPLIT(dev_priv)) {
14285                 int found;
14286                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
14287
14288                 if (has_edp_a(dev_priv))
14289                         intel_dp_init(dev_priv, DP_A, PORT_A);
14290
14291                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
14292                         /* PCH SDVOB multiplex with HDMIB */
14293                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
14294                         if (!found)
14295                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
14296                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
14297                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
14298                 }
14299
14300                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
14301                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
14302
14303                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
14304                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
14305
14306                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
14307                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
14308
14309                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
14310                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
14311         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
14312                 bool has_edp, has_port;
14313
14314                 /*
14315                  * The DP_DETECTED bit is the latched state of the DDC
14316                  * SDA pin at boot. However since eDP doesn't require DDC
14317                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
14318                  * eDP ports may have been muxed to an alternate function.
14319                  * Thus we can't rely on the DP_DETECTED bit alone to detect
14320                  * eDP ports. Consult the VBT as well as DP_DETECTED to
14321                  * detect eDP ports.
14322                  *
14323                  * Sadly the straps seem to be missing sometimes even for HDMI
14324                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
14325                  * and VBT for the presence of the port. Additionally we can't
14326                  * trust the port type the VBT declares as we've seen at least
14327                  * HDMI ports that the VBT claim are DP or eDP.
14328                  */
14329                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
14330                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
14331                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
14332                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
14333                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
14334                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
14335
14336                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
14337                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
14338                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
14339                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
14340                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
14341                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
14342
14343                 if (IS_CHERRYVIEW(dev_priv)) {
14344                         /*
14345                          * eDP not supported on port D,
14346                          * so no need to worry about it
14347                          */
14348                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
14349                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
14350                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
14351                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
14352                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
14353                 }
14354
14355                 vlv_dsi_init(dev_priv);
14356         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
14357                 bool found = false;
14358
14359                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14360                         DRM_DEBUG_KMS("probing SDVOB\n");
14361                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
14362                         if (!found && IS_G4X(dev_priv)) {
14363                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
14364                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
14365                         }
14366
14367                         if (!found && IS_G4X(dev_priv))
14368                                 intel_dp_init(dev_priv, DP_B, PORT_B);
14369                 }
14370
14371                 /* Before G4X SDVOC doesn't have its own detect register */
14372
14373                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
14374                         DRM_DEBUG_KMS("probing SDVOC\n");
14375                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
14376                 }
14377
14378                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
14379
14380                         if (IS_G4X(dev_priv)) {
14381                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
14382                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
14383                         }
14384                         if (IS_G4X(dev_priv))
14385                                 intel_dp_init(dev_priv, DP_C, PORT_C);
14386                 }
14387
14388                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
14389                         intel_dp_init(dev_priv, DP_D, PORT_D);
14390         } else if (IS_GEN2(dev_priv))
14391                 intel_dvo_init(dev_priv);
14392
14393         if (SUPPORTS_TV(dev_priv))
14394                 intel_tv_init(dev_priv);
14395
14396         intel_psr_init(dev_priv);
14397
14398         for_each_intel_encoder(&dev_priv->drm, encoder) {
14399                 encoder->base.possible_crtcs = encoder->crtc_mask;
14400                 encoder->base.possible_clones =
14401                         intel_encoder_clones(encoder);
14402         }
14403
14404         intel_init_pch_refclk(dev_priv);
14405
14406         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
14407 }
14408
14409 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
14410 {
14411         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
14412         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14413
14414         drm_framebuffer_cleanup(fb);
14415
14416         i915_gem_object_lock(obj);
14417         WARN_ON(!obj->framebuffer_references--);
14418         i915_gem_object_unlock(obj);
14419
14420         i915_gem_object_put(obj);
14421
14422         kfree(intel_fb);
14423 }
14424
14425 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
14426                                                 struct drm_file *file,
14427                                                 unsigned int *handle)
14428 {
14429         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14430
14431         if (obj->userptr.mm) {
14432                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
14433                 return -EINVAL;
14434         }
14435
14436         return drm_gem_handle_create(file, &obj->base, handle);
14437 }
14438
14439 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
14440                                         struct drm_file *file,
14441                                         unsigned flags, unsigned color,
14442                                         struct drm_clip_rect *clips,
14443                                         unsigned num_clips)
14444 {
14445         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
14446
14447         i915_gem_object_flush_if_display(obj);
14448         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
14449
14450         return 0;
14451 }
14452
14453 static const struct drm_framebuffer_funcs intel_fb_funcs = {
14454         .destroy = intel_user_framebuffer_destroy,
14455         .create_handle = intel_user_framebuffer_create_handle,
14456         .dirty = intel_user_framebuffer_dirty,
14457 };
14458
14459 static
14460 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
14461                          uint64_t fb_modifier, uint32_t pixel_format)
14462 {
14463         struct intel_crtc *crtc;
14464         struct intel_plane *plane;
14465
14466         /*
14467          * We assume the primary plane for pipe A has
14468          * the highest stride limits of them all.
14469          */
14470         crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_A);
14471         plane = to_intel_plane(crtc->base.primary);
14472
14473         return plane->max_stride(plane, pixel_format, fb_modifier,
14474                                  DRM_MODE_ROTATE_0);
14475 }
14476
14477 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
14478                                   struct drm_i915_gem_object *obj,
14479                                   struct drm_mode_fb_cmd2 *mode_cmd)
14480 {
14481         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
14482         struct drm_framebuffer *fb = &intel_fb->base;
14483         struct drm_format_name_buf format_name;
14484         u32 pitch_limit;
14485         unsigned int tiling, stride;
14486         int ret = -EINVAL;
14487         int i;
14488
14489         i915_gem_object_lock(obj);
14490         obj->framebuffer_references++;
14491         tiling = i915_gem_object_get_tiling(obj);
14492         stride = i915_gem_object_get_stride(obj);
14493         i915_gem_object_unlock(obj);
14494
14495         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
14496                 /*
14497                  * If there's a fence, enforce that
14498                  * the fb modifier and tiling mode match.
14499                  */
14500                 if (tiling != I915_TILING_NONE &&
14501                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14502                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14503                         goto err;
14504                 }
14505         } else {
14506                 if (tiling == I915_TILING_X) {
14507                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14508                 } else if (tiling == I915_TILING_Y) {
14509                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14510                         goto err;
14511                 }
14512         }
14513
14514         /* Passed in modifier sanity checking. */
14515         switch (mode_cmd->modifier[0]) {
14516         case I915_FORMAT_MOD_Y_TILED_CCS:
14517         case I915_FORMAT_MOD_Yf_TILED_CCS:
14518                 switch (mode_cmd->pixel_format) {
14519                 case DRM_FORMAT_XBGR8888:
14520                 case DRM_FORMAT_ABGR8888:
14521                 case DRM_FORMAT_XRGB8888:
14522                 case DRM_FORMAT_ARGB8888:
14523                         break;
14524                 default:
14525                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
14526                         goto err;
14527                 }
14528                 /* fall through */
14529         case I915_FORMAT_MOD_Y_TILED:
14530         case I915_FORMAT_MOD_Yf_TILED:
14531                 if (INTEL_GEN(dev_priv) < 9) {
14532                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14533                                       mode_cmd->modifier[0]);
14534                         goto err;
14535                 }
14536         case DRM_FORMAT_MOD_LINEAR:
14537         case I915_FORMAT_MOD_X_TILED:
14538                 break;
14539         default:
14540                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14541                               mode_cmd->modifier[0]);
14542                 goto err;
14543         }
14544
14545         /*
14546          * gen2/3 display engine uses the fence if present,
14547          * so the tiling mode must match the fb modifier exactly.
14548          */
14549         if (INTEL_GEN(dev_priv) < 4 &&
14550             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14551                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14552                 goto err;
14553         }
14554
14555         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14556                                            mode_cmd->pixel_format);
14557         if (mode_cmd->pitches[0] > pitch_limit) {
14558                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14559                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14560                               "tiled" : "linear",
14561                               mode_cmd->pitches[0], pitch_limit);
14562                 goto err;
14563         }
14564
14565         /*
14566          * If there's a fence, enforce that
14567          * the fb pitch and fence stride match.
14568          */
14569         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14570                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14571                               mode_cmd->pitches[0], stride);
14572                 goto err;
14573         }
14574
14575         /* Reject formats not supported by any plane early. */
14576         switch (mode_cmd->pixel_format) {
14577         case DRM_FORMAT_C8:
14578         case DRM_FORMAT_RGB565:
14579         case DRM_FORMAT_XRGB8888:
14580         case DRM_FORMAT_ARGB8888:
14581                 break;
14582         case DRM_FORMAT_XRGB1555:
14583                 if (INTEL_GEN(dev_priv) > 3) {
14584                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14585                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14586                         goto err;
14587                 }
14588                 break;
14589         case DRM_FORMAT_ABGR8888:
14590                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14591                     INTEL_GEN(dev_priv) < 9) {
14592                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14593                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14594                         goto err;
14595                 }
14596                 break;
14597         case DRM_FORMAT_XBGR8888:
14598         case DRM_FORMAT_XRGB2101010:
14599         case DRM_FORMAT_XBGR2101010:
14600                 if (INTEL_GEN(dev_priv) < 4) {
14601                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14602                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14603                         goto err;
14604                 }
14605                 break;
14606         case DRM_FORMAT_ABGR2101010:
14607                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14608                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14609                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14610                         goto err;
14611                 }
14612                 break;
14613         case DRM_FORMAT_YUYV:
14614         case DRM_FORMAT_UYVY:
14615         case DRM_FORMAT_YVYU:
14616         case DRM_FORMAT_VYUY:
14617                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14618                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14619                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14620                         goto err;
14621                 }
14622                 break;
14623         case DRM_FORMAT_NV12:
14624                 if (INTEL_GEN(dev_priv) < 9 || IS_SKYLAKE(dev_priv) ||
14625                     IS_BROXTON(dev_priv) || INTEL_GEN(dev_priv) >= 11) {
14626                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14627                                       drm_get_format_name(mode_cmd->pixel_format,
14628                                                           &format_name));
14629                         goto err;
14630                 }
14631                 break;
14632         default:
14633                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14634                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14635                 goto err;
14636         }
14637
14638         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14639         if (mode_cmd->offsets[0] != 0)
14640                 goto err;
14641
14642         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14643
14644         if (fb->format->format == DRM_FORMAT_NV12 &&
14645             (fb->width < SKL_MIN_YUV_420_SRC_W ||
14646              fb->height < SKL_MIN_YUV_420_SRC_H ||
14647              (fb->width % 4) != 0 || (fb->height % 4) != 0)) {
14648                 DRM_DEBUG_KMS("src dimensions not correct for NV12\n");
14649                 return -EINVAL;
14650         }
14651
14652         for (i = 0; i < fb->format->num_planes; i++) {
14653                 u32 stride_alignment;
14654
14655                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14656                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14657                         goto err;
14658                 }
14659
14660                 stride_alignment = intel_fb_stride_alignment(fb, i);
14661
14662                 /*
14663                  * Display WA #0531: skl,bxt,kbl,glk
14664                  *
14665                  * Render decompression and plane width > 3840
14666                  * combined with horizontal panning requires the
14667                  * plane stride to be a multiple of 4. We'll just
14668                  * require the entire fb to accommodate that to avoid
14669                  * potential runtime errors at plane configuration time.
14670                  */
14671                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14672                     is_ccs_modifier(fb->modifier))
14673                         stride_alignment *= 4;
14674
14675                 if (fb->pitches[i] & (stride_alignment - 1)) {
14676                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14677                                       i, fb->pitches[i], stride_alignment);
14678                         goto err;
14679                 }
14680
14681                 fb->obj[i] = &obj->base;
14682         }
14683
14684         ret = intel_fill_fb_info(dev_priv, fb);
14685         if (ret)
14686                 goto err;
14687
14688         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14689         if (ret) {
14690                 DRM_ERROR("framebuffer init failed %d\n", ret);
14691                 goto err;
14692         }
14693
14694         return 0;
14695
14696 err:
14697         i915_gem_object_lock(obj);
14698         obj->framebuffer_references--;
14699         i915_gem_object_unlock(obj);
14700         return ret;
14701 }
14702
14703 static struct drm_framebuffer *
14704 intel_user_framebuffer_create(struct drm_device *dev,
14705                               struct drm_file *filp,
14706                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14707 {
14708         struct drm_framebuffer *fb;
14709         struct drm_i915_gem_object *obj;
14710         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14711
14712         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14713         if (!obj)
14714                 return ERR_PTR(-ENOENT);
14715
14716         fb = intel_framebuffer_create(obj, &mode_cmd);
14717         if (IS_ERR(fb))
14718                 i915_gem_object_put(obj);
14719
14720         return fb;
14721 }
14722
14723 static void intel_atomic_state_free(struct drm_atomic_state *state)
14724 {
14725         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14726
14727         drm_atomic_state_default_release(state);
14728
14729         i915_sw_fence_fini(&intel_state->commit_ready);
14730
14731         kfree(state);
14732 }
14733
14734 static enum drm_mode_status
14735 intel_mode_valid(struct drm_device *dev,
14736                  const struct drm_display_mode *mode)
14737 {
14738         struct drm_i915_private *dev_priv = to_i915(dev);
14739         int hdisplay_max, htotal_max;
14740         int vdisplay_max, vtotal_max;
14741
14742         /*
14743          * Can't reject DBLSCAN here because Xorg ddxen can add piles
14744          * of DBLSCAN modes to the output's mode list when they detect
14745          * the scaling mode property on the connector. And they don't
14746          * ask the kernel to validate those modes in any way until
14747          * modeset time at which point the client gets a protocol error.
14748          * So in order to not upset those clients we silently ignore the
14749          * DBLSCAN flag on such connectors. For other connectors we will
14750          * reject modes with the DBLSCAN flag in encoder->compute_config().
14751          * And we always reject DBLSCAN modes in connector->mode_valid()
14752          * as we never want such modes on the connector's mode list.
14753          */
14754
14755         if (mode->vscan > 1)
14756                 return MODE_NO_VSCAN;
14757
14758         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14759                 return MODE_H_ILLEGAL;
14760
14761         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14762                            DRM_MODE_FLAG_NCSYNC |
14763                            DRM_MODE_FLAG_PCSYNC))
14764                 return MODE_HSYNC;
14765
14766         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14767                            DRM_MODE_FLAG_PIXMUX |
14768                            DRM_MODE_FLAG_CLKDIV2))
14769                 return MODE_BAD;
14770
14771         if (INTEL_GEN(dev_priv) >= 9 ||
14772             IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv)) {
14773                 hdisplay_max = 8192; /* FDI max 4096 handled elsewhere */
14774                 vdisplay_max = 4096;
14775                 htotal_max = 8192;
14776                 vtotal_max = 8192;
14777         } else if (INTEL_GEN(dev_priv) >= 3) {
14778                 hdisplay_max = 4096;
14779                 vdisplay_max = 4096;
14780                 htotal_max = 8192;
14781                 vtotal_max = 8192;
14782         } else {
14783                 hdisplay_max = 2048;
14784                 vdisplay_max = 2048;
14785                 htotal_max = 4096;
14786                 vtotal_max = 4096;
14787         }
14788
14789         if (mode->hdisplay > hdisplay_max ||
14790             mode->hsync_start > htotal_max ||
14791             mode->hsync_end > htotal_max ||
14792             mode->htotal > htotal_max)
14793                 return MODE_H_ILLEGAL;
14794
14795         if (mode->vdisplay > vdisplay_max ||
14796             mode->vsync_start > vtotal_max ||
14797             mode->vsync_end > vtotal_max ||
14798             mode->vtotal > vtotal_max)
14799                 return MODE_V_ILLEGAL;
14800
14801         return MODE_OK;
14802 }
14803
14804 static const struct drm_mode_config_funcs intel_mode_funcs = {
14805         .fb_create = intel_user_framebuffer_create,
14806         .get_format_info = intel_get_format_info,
14807         .output_poll_changed = intel_fbdev_output_poll_changed,
14808         .mode_valid = intel_mode_valid,
14809         .atomic_check = intel_atomic_check,
14810         .atomic_commit = intel_atomic_commit,
14811         .atomic_state_alloc = intel_atomic_state_alloc,
14812         .atomic_state_clear = intel_atomic_state_clear,
14813         .atomic_state_free = intel_atomic_state_free,
14814 };
14815
14816 /**
14817  * intel_init_display_hooks - initialize the display modesetting hooks
14818  * @dev_priv: device private
14819  */
14820 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14821 {
14822         intel_init_cdclk_hooks(dev_priv);
14823
14824         if (INTEL_GEN(dev_priv) >= 9) {
14825                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14826                 dev_priv->display.get_initial_plane_config =
14827                         skylake_get_initial_plane_config;
14828                 dev_priv->display.crtc_compute_clock =
14829                         haswell_crtc_compute_clock;
14830                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14831                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14832         } else if (HAS_DDI(dev_priv)) {
14833                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14834                 dev_priv->display.get_initial_plane_config =
14835                         i9xx_get_initial_plane_config;
14836                 dev_priv->display.crtc_compute_clock =
14837                         haswell_crtc_compute_clock;
14838                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14839                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14840         } else if (HAS_PCH_SPLIT(dev_priv)) {
14841                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14842                 dev_priv->display.get_initial_plane_config =
14843                         i9xx_get_initial_plane_config;
14844                 dev_priv->display.crtc_compute_clock =
14845                         ironlake_crtc_compute_clock;
14846                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14847                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14848         } else if (IS_CHERRYVIEW(dev_priv)) {
14849                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14850                 dev_priv->display.get_initial_plane_config =
14851                         i9xx_get_initial_plane_config;
14852                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14853                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14854                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14855         } else if (IS_VALLEYVIEW(dev_priv)) {
14856                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14857                 dev_priv->display.get_initial_plane_config =
14858                         i9xx_get_initial_plane_config;
14859                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14860                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14861                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14862         } else if (IS_G4X(dev_priv)) {
14863                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14864                 dev_priv->display.get_initial_plane_config =
14865                         i9xx_get_initial_plane_config;
14866                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14867                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14868                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14869         } else if (IS_PINEVIEW(dev_priv)) {
14870                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14871                 dev_priv->display.get_initial_plane_config =
14872                         i9xx_get_initial_plane_config;
14873                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14874                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14875                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14876         } else if (!IS_GEN2(dev_priv)) {
14877                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14878                 dev_priv->display.get_initial_plane_config =
14879                         i9xx_get_initial_plane_config;
14880                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14881                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14882                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14883         } else {
14884                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14885                 dev_priv->display.get_initial_plane_config =
14886                         i9xx_get_initial_plane_config;
14887                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14888                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14889                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14890         }
14891
14892         if (IS_GEN5(dev_priv)) {
14893                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14894         } else if (IS_GEN6(dev_priv)) {
14895                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14896         } else if (IS_IVYBRIDGE(dev_priv)) {
14897                 /* FIXME: detect B0+ stepping and use auto training */
14898                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14899         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14900                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14901         }
14902
14903         if (INTEL_GEN(dev_priv) >= 9)
14904                 dev_priv->display.update_crtcs = skl_update_crtcs;
14905         else
14906                 dev_priv->display.update_crtcs = intel_update_crtcs;
14907 }
14908
14909 /*
14910  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14911  */
14912 static void quirk_ssc_force_disable(struct drm_device *dev)
14913 {
14914         struct drm_i915_private *dev_priv = to_i915(dev);
14915         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14916         DRM_INFO("applying lvds SSC disable quirk\n");
14917 }
14918
14919 /*
14920  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14921  * brightness value
14922  */
14923 static void quirk_invert_brightness(struct drm_device *dev)
14924 {
14925         struct drm_i915_private *dev_priv = to_i915(dev);
14926         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14927         DRM_INFO("applying inverted panel brightness quirk\n");
14928 }
14929
14930 /* Some VBT's incorrectly indicate no backlight is present */
14931 static void quirk_backlight_present(struct drm_device *dev)
14932 {
14933         struct drm_i915_private *dev_priv = to_i915(dev);
14934         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14935         DRM_INFO("applying backlight present quirk\n");
14936 }
14937
14938 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14939  * which is 300 ms greater than eDP spec T12 min.
14940  */
14941 static void quirk_increase_t12_delay(struct drm_device *dev)
14942 {
14943         struct drm_i915_private *dev_priv = to_i915(dev);
14944
14945         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14946         DRM_INFO("Applying T12 delay quirk\n");
14947 }
14948
14949 /*
14950  * GeminiLake NUC HDMI outputs require additional off time
14951  * this allows the onboard retimer to correctly sync to signal
14952  */
14953 static void quirk_increase_ddi_disabled_time(struct drm_device *dev)
14954 {
14955         struct drm_i915_private *dev_priv = to_i915(dev);
14956
14957         dev_priv->quirks |= QUIRK_INCREASE_DDI_DISABLED_TIME;
14958         DRM_INFO("Applying Increase DDI Disabled quirk\n");
14959 }
14960
14961 struct intel_quirk {
14962         int device;
14963         int subsystem_vendor;
14964         int subsystem_device;
14965         void (*hook)(struct drm_device *dev);
14966 };
14967
14968 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14969 struct intel_dmi_quirk {
14970         void (*hook)(struct drm_device *dev);
14971         const struct dmi_system_id (*dmi_id_list)[];
14972 };
14973
14974 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14975 {
14976         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14977         return 1;
14978 }
14979
14980 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14981         {
14982                 .dmi_id_list = &(const struct dmi_system_id[]) {
14983                         {
14984                                 .callback = intel_dmi_reverse_brightness,
14985                                 .ident = "NCR Corporation",
14986                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14987                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14988                                 },
14989                         },
14990                         { }  /* terminating entry */
14991                 },
14992                 .hook = quirk_invert_brightness,
14993         },
14994 };
14995
14996 static struct intel_quirk intel_quirks[] = {
14997         /* Lenovo U160 cannot use SSC on LVDS */
14998         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14999
15000         /* Sony Vaio Y cannot use SSC on LVDS */
15001         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
15002
15003         /* Acer Aspire 5734Z must invert backlight brightness */
15004         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
15005
15006         /* Acer/eMachines G725 */
15007         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
15008
15009         /* Acer/eMachines e725 */
15010         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
15011
15012         /* Acer/Packard Bell NCL20 */
15013         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
15014
15015         /* Acer Aspire 4736Z */
15016         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
15017
15018         /* Acer Aspire 5336 */
15019         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
15020
15021         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
15022         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
15023
15024         /* Acer C720 Chromebook (Core i3 4005U) */
15025         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
15026
15027         /* Apple Macbook 2,1 (Core 2 T7400) */
15028         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
15029
15030         /* Apple Macbook 4,1 */
15031         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
15032
15033         /* Toshiba CB35 Chromebook (Celeron 2955U) */
15034         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
15035
15036         /* HP Chromebook 14 (Celeron 2955U) */
15037         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
15038
15039         /* Dell Chromebook 11 */
15040         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
15041
15042         /* Dell Chromebook 11 (2015 version) */
15043         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
15044
15045         /* Toshiba Satellite P50-C-18C */
15046         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
15047
15048         /* GeminiLake NUC */
15049         { 0x3185, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
15050         { 0x3184, 0x8086, 0x2072, quirk_increase_ddi_disabled_time },
15051         /* ASRock ITX*/
15052         { 0x3185, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
15053         { 0x3184, 0x1849, 0x2212, quirk_increase_ddi_disabled_time },
15054 };
15055
15056 static void intel_init_quirks(struct drm_device *dev)
15057 {
15058         struct pci_dev *d = dev->pdev;
15059         int i;
15060
15061         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
15062                 struct intel_quirk *q = &intel_quirks[i];
15063
15064                 if (d->device == q->device &&
15065                     (d->subsystem_vendor == q->subsystem_vendor ||
15066                      q->subsystem_vendor == PCI_ANY_ID) &&
15067                     (d->subsystem_device == q->subsystem_device ||
15068                      q->subsystem_device == PCI_ANY_ID))
15069                         q->hook(dev);
15070         }
15071         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
15072                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
15073                         intel_dmi_quirks[i].hook(dev);
15074         }
15075 }
15076
15077 /* Disable the VGA plane that we never use */
15078 static void i915_disable_vga(struct drm_i915_private *dev_priv)
15079 {
15080         struct pci_dev *pdev = dev_priv->drm.pdev;
15081         u8 sr1;
15082         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15083
15084         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
15085         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
15086         outb(SR01, VGA_SR_INDEX);
15087         sr1 = inb(VGA_SR_DATA);
15088         outb(sr1 | 1<<5, VGA_SR_DATA);
15089         vga_put(pdev, VGA_RSRC_LEGACY_IO);
15090         udelay(300);
15091
15092         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
15093         POSTING_READ(vga_reg);
15094 }
15095
15096 void intel_modeset_init_hw(struct drm_device *dev)
15097 {
15098         struct drm_i915_private *dev_priv = to_i915(dev);
15099
15100         intel_update_cdclk(dev_priv);
15101         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
15102         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
15103 }
15104
15105 /*
15106  * Calculate what we think the watermarks should be for the state we've read
15107  * out of the hardware and then immediately program those watermarks so that
15108  * we ensure the hardware settings match our internal state.
15109  *
15110  * We can calculate what we think WM's should be by creating a duplicate of the
15111  * current state (which was constructed during hardware readout) and running it
15112  * through the atomic check code to calculate new watermark values in the
15113  * state object.
15114  */
15115 static void sanitize_watermarks(struct drm_device *dev)
15116 {
15117         struct drm_i915_private *dev_priv = to_i915(dev);
15118         struct drm_atomic_state *state;
15119         struct intel_atomic_state *intel_state;
15120         struct drm_crtc *crtc;
15121         struct drm_crtc_state *cstate;
15122         struct drm_modeset_acquire_ctx ctx;
15123         int ret;
15124         int i;
15125
15126         /* Only supported on platforms that use atomic watermark design */
15127         if (!dev_priv->display.optimize_watermarks)
15128                 return;
15129
15130         /*
15131          * We need to hold connection_mutex before calling duplicate_state so
15132          * that the connector loop is protected.
15133          */
15134         drm_modeset_acquire_init(&ctx, 0);
15135 retry:
15136         ret = drm_modeset_lock_all_ctx(dev, &ctx);
15137         if (ret == -EDEADLK) {
15138                 drm_modeset_backoff(&ctx);
15139                 goto retry;
15140         } else if (WARN_ON(ret)) {
15141                 goto fail;
15142         }
15143
15144         state = drm_atomic_helper_duplicate_state(dev, &ctx);
15145         if (WARN_ON(IS_ERR(state)))
15146                 goto fail;
15147
15148         intel_state = to_intel_atomic_state(state);
15149
15150         /*
15151          * Hardware readout is the only time we don't want to calculate
15152          * intermediate watermarks (since we don't trust the current
15153          * watermarks).
15154          */
15155         if (!HAS_GMCH_DISPLAY(dev_priv))
15156                 intel_state->skip_intermediate_wm = true;
15157
15158         ret = intel_atomic_check(dev, state);
15159         if (ret) {
15160                 /*
15161                  * If we fail here, it means that the hardware appears to be
15162                  * programmed in a way that shouldn't be possible, given our
15163                  * understanding of watermark requirements.  This might mean a
15164                  * mistake in the hardware readout code or a mistake in the
15165                  * watermark calculations for a given platform.  Raise a WARN
15166                  * so that this is noticeable.
15167                  *
15168                  * If this actually happens, we'll have to just leave the
15169                  * BIOS-programmed watermarks untouched and hope for the best.
15170                  */
15171                 WARN(true, "Could not determine valid watermarks for inherited state\n");
15172                 goto put_state;
15173         }
15174
15175         /* Write calculated watermark values back */
15176         for_each_new_crtc_in_state(state, crtc, cstate, i) {
15177                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
15178
15179                 cs->wm.need_postvbl_update = true;
15180                 dev_priv->display.optimize_watermarks(intel_state, cs);
15181
15182                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
15183         }
15184
15185 put_state:
15186         drm_atomic_state_put(state);
15187 fail:
15188         drm_modeset_drop_locks(&ctx);
15189         drm_modeset_acquire_fini(&ctx);
15190 }
15191
15192 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
15193 {
15194         if (IS_GEN5(dev_priv)) {
15195                 u32 fdi_pll_clk =
15196                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
15197
15198                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
15199         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
15200                 dev_priv->fdi_pll_freq = 270000;
15201         } else {
15202                 return;
15203         }
15204
15205         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
15206 }
15207
15208 static int intel_initial_commit(struct drm_device *dev)
15209 {
15210         struct drm_atomic_state *state = NULL;
15211         struct drm_modeset_acquire_ctx ctx;
15212         struct drm_crtc *crtc;
15213         struct drm_crtc_state *crtc_state;
15214         int ret = 0;
15215
15216         state = drm_atomic_state_alloc(dev);
15217         if (!state)
15218                 return -ENOMEM;
15219
15220         drm_modeset_acquire_init(&ctx, 0);
15221
15222 retry:
15223         state->acquire_ctx = &ctx;
15224
15225         drm_for_each_crtc(crtc, dev) {
15226                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
15227                 if (IS_ERR(crtc_state)) {
15228                         ret = PTR_ERR(crtc_state);
15229                         goto out;
15230                 }
15231
15232                 if (crtc_state->active) {
15233                         ret = drm_atomic_add_affected_planes(state, crtc);
15234                         if (ret)
15235                                 goto out;
15236                 }
15237         }
15238
15239         ret = drm_atomic_commit(state);
15240
15241 out:
15242         if (ret == -EDEADLK) {
15243                 drm_atomic_state_clear(state);
15244                 drm_modeset_backoff(&ctx);
15245                 goto retry;
15246         }
15247
15248         drm_atomic_state_put(state);
15249
15250         drm_modeset_drop_locks(&ctx);
15251         drm_modeset_acquire_fini(&ctx);
15252
15253         return ret;
15254 }
15255
15256 int intel_modeset_init(struct drm_device *dev)
15257 {
15258         struct drm_i915_private *dev_priv = to_i915(dev);
15259         struct i915_ggtt *ggtt = &dev_priv->ggtt;
15260         enum pipe pipe;
15261         struct intel_crtc *crtc;
15262         int ret;
15263
15264         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
15265
15266         drm_mode_config_init(dev);
15267
15268         dev->mode_config.min_width = 0;
15269         dev->mode_config.min_height = 0;
15270
15271         dev->mode_config.preferred_depth = 24;
15272         dev->mode_config.prefer_shadow = 1;
15273
15274         dev->mode_config.allow_fb_modifiers = true;
15275
15276         dev->mode_config.funcs = &intel_mode_funcs;
15277
15278         init_llist_head(&dev_priv->atomic_helper.free_list);
15279         INIT_WORK(&dev_priv->atomic_helper.free_work,
15280                   intel_atomic_helper_free_state_worker);
15281
15282         intel_init_quirks(dev);
15283
15284         intel_init_pm(dev_priv);
15285
15286         /*
15287          * There may be no VBT; and if the BIOS enabled SSC we can
15288          * just keep using it to avoid unnecessary flicker.  Whereas if the
15289          * BIOS isn't using it, don't assume it will work even if the VBT
15290          * indicates as much.
15291          */
15292         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
15293                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
15294                                             DREF_SSC1_ENABLE);
15295
15296                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
15297                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
15298                                      bios_lvds_use_ssc ? "en" : "dis",
15299                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
15300                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
15301                 }
15302         }
15303
15304         /* maximum framebuffer dimensions */
15305         if (IS_GEN2(dev_priv)) {
15306                 dev->mode_config.max_width = 2048;
15307                 dev->mode_config.max_height = 2048;
15308         } else if (IS_GEN3(dev_priv)) {
15309                 dev->mode_config.max_width = 4096;
15310                 dev->mode_config.max_height = 4096;
15311         } else {
15312                 dev->mode_config.max_width = 8192;
15313                 dev->mode_config.max_height = 8192;
15314         }
15315
15316         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
15317                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
15318                 dev->mode_config.cursor_height = 1023;
15319         } else if (IS_GEN2(dev_priv)) {
15320                 dev->mode_config.cursor_width = 64;
15321                 dev->mode_config.cursor_height = 64;
15322         } else {
15323                 dev->mode_config.cursor_width = 256;
15324                 dev->mode_config.cursor_height = 256;
15325         }
15326
15327         dev->mode_config.fb_base = ggtt->gmadr.start;
15328
15329         DRM_DEBUG_KMS("%d display pipe%s available.\n",
15330                       INTEL_INFO(dev_priv)->num_pipes,
15331                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
15332
15333         for_each_pipe(dev_priv, pipe) {
15334                 ret = intel_crtc_init(dev_priv, pipe);
15335                 if (ret) {
15336                         drm_mode_config_cleanup(dev);
15337                         return ret;
15338                 }
15339         }
15340
15341         intel_shared_dpll_init(dev);
15342         intel_update_fdi_pll_freq(dev_priv);
15343
15344         intel_update_czclk(dev_priv);
15345         intel_modeset_init_hw(dev);
15346
15347         if (dev_priv->max_cdclk_freq == 0)
15348                 intel_update_max_cdclk(dev_priv);
15349
15350         /* Just disable it once at startup */
15351         i915_disable_vga(dev_priv);
15352         intel_setup_outputs(dev_priv);
15353
15354         drm_modeset_lock_all(dev);
15355         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
15356         drm_modeset_unlock_all(dev);
15357
15358         for_each_intel_crtc(dev, crtc) {
15359                 struct intel_initial_plane_config plane_config = {};
15360
15361                 if (!crtc->active)
15362                         continue;
15363
15364                 /*
15365                  * Note that reserving the BIOS fb up front prevents us
15366                  * from stuffing other stolen allocations like the ring
15367                  * on top.  This prevents some ugliness at boot time, and
15368                  * can even allow for smooth boot transitions if the BIOS
15369                  * fb is large enough for the active pipe configuration.
15370                  */
15371                 dev_priv->display.get_initial_plane_config(crtc,
15372                                                            &plane_config);
15373
15374                 /*
15375                  * If the fb is shared between multiple heads, we'll
15376                  * just get the first one.
15377                  */
15378                 intel_find_initial_plane_obj(crtc, &plane_config);
15379         }
15380
15381         /*
15382          * Make sure hardware watermarks really match the state we read out.
15383          * Note that we need to do this after reconstructing the BIOS fb's
15384          * since the watermark calculation done here will use pstate->fb.
15385          */
15386         if (!HAS_GMCH_DISPLAY(dev_priv))
15387                 sanitize_watermarks(dev);
15388
15389         /*
15390          * Force all active planes to recompute their states. So that on
15391          * mode_setcrtc after probe, all the intel_plane_state variables
15392          * are already calculated and there is no assert_plane warnings
15393          * during bootup.
15394          */
15395         ret = intel_initial_commit(dev);
15396         if (ret)
15397                 DRM_DEBUG_KMS("Initial commit in probe failed.\n");
15398
15399         return 0;
15400 }
15401
15402 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15403 {
15404         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15405         /* 640x480@60Hz, ~25175 kHz */
15406         struct dpll clock = {
15407                 .m1 = 18,
15408                 .m2 = 7,
15409                 .p1 = 13,
15410                 .p2 = 4,
15411                 .n = 2,
15412         };
15413         u32 dpll, fp;
15414         int i;
15415
15416         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
15417
15418         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
15419                       pipe_name(pipe), clock.vco, clock.dot);
15420
15421         fp = i9xx_dpll_compute_fp(&clock);
15422         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
15423                 DPLL_VGA_MODE_DIS |
15424                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
15425                 PLL_P2_DIVIDE_BY_4 |
15426                 PLL_REF_INPUT_DREFCLK |
15427                 DPLL_VCO_ENABLE;
15428
15429         I915_WRITE(FP0(pipe), fp);
15430         I915_WRITE(FP1(pipe), fp);
15431
15432         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
15433         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
15434         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
15435         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
15436         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
15437         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
15438         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
15439
15440         /*
15441          * Apparently we need to have VGA mode enabled prior to changing
15442          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
15443          * dividers, even though the register value does change.
15444          */
15445         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
15446         I915_WRITE(DPLL(pipe), dpll);
15447
15448         /* Wait for the clocks to stabilize. */
15449         POSTING_READ(DPLL(pipe));
15450         udelay(150);
15451
15452         /* The pixel multiplier can only be updated once the
15453          * DPLL is enabled and the clocks are stable.
15454          *
15455          * So write it again.
15456          */
15457         I915_WRITE(DPLL(pipe), dpll);
15458
15459         /* We do this three times for luck */
15460         for (i = 0; i < 3 ; i++) {
15461                 I915_WRITE(DPLL(pipe), dpll);
15462                 POSTING_READ(DPLL(pipe));
15463                 udelay(150); /* wait for warmup */
15464         }
15465
15466         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
15467         POSTING_READ(PIPECONF(pipe));
15468
15469         intel_wait_for_pipe_scanline_moving(crtc);
15470 }
15471
15472 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
15473 {
15474         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15475
15476         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
15477                       pipe_name(pipe));
15478
15479         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
15480         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
15481         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
15482         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & MCURSOR_MODE);
15483         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & MCURSOR_MODE);
15484
15485         I915_WRITE(PIPECONF(pipe), 0);
15486         POSTING_READ(PIPECONF(pipe));
15487
15488         intel_wait_for_pipe_scanline_stopped(crtc);
15489
15490         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
15491         POSTING_READ(DPLL(pipe));
15492 }
15493
15494 static void
15495 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
15496 {
15497         struct intel_crtc *crtc;
15498
15499         if (INTEL_GEN(dev_priv) >= 4)
15500                 return;
15501
15502         for_each_intel_crtc(&dev_priv->drm, crtc) {
15503                 struct intel_plane *plane =
15504                         to_intel_plane(crtc->base.primary);
15505                 struct intel_crtc *plane_crtc;
15506                 enum pipe pipe;
15507
15508                 if (!plane->get_hw_state(plane, &pipe))
15509                         continue;
15510
15511                 if (pipe == crtc->pipe)
15512                         continue;
15513
15514                 DRM_DEBUG_KMS("%s attached to the wrong pipe, disabling plane\n",
15515                               plane->base.name);
15516
15517                 plane_crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15518                 intel_plane_disable_noatomic(plane_crtc, plane);
15519         }
15520 }
15521
15522 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
15523 {
15524         struct drm_device *dev = crtc->base.dev;
15525         struct intel_encoder *encoder;
15526
15527         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
15528                 return true;
15529
15530         return false;
15531 }
15532
15533 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
15534 {
15535         struct drm_device *dev = encoder->base.dev;
15536         struct intel_connector *connector;
15537
15538         for_each_connector_on_encoder(dev, &encoder->base, connector)
15539                 return connector;
15540
15541         return NULL;
15542 }
15543
15544 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
15545                               enum pipe pch_transcoder)
15546 {
15547         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
15548                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
15549 }
15550
15551 static void intel_sanitize_crtc(struct intel_crtc *crtc,
15552                                 struct drm_modeset_acquire_ctx *ctx)
15553 {
15554         struct drm_device *dev = crtc->base.dev;
15555         struct drm_i915_private *dev_priv = to_i915(dev);
15556         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
15557
15558         /* Clear any frame start delays used for debugging left by the BIOS */
15559         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
15560                 i915_reg_t reg = PIPECONF(cpu_transcoder);
15561
15562                 I915_WRITE(reg,
15563                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
15564         }
15565
15566         if (crtc->active) {
15567                 struct intel_plane *plane;
15568
15569                 /* Disable everything but the primary plane */
15570                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
15571                         const struct intel_plane_state *plane_state =
15572                                 to_intel_plane_state(plane->base.state);
15573
15574                         if (plane_state->base.visible &&
15575                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
15576                                 intel_plane_disable_noatomic(crtc, plane);
15577                 }
15578         }
15579
15580         /* Adjust the state of the output pipe according to whether we
15581          * have active connectors/encoders. */
15582         if (crtc->active && !intel_crtc_has_encoders(crtc))
15583                 intel_crtc_disable_noatomic(&crtc->base, ctx);
15584
15585         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
15586                 /*
15587                  * We start out with underrun reporting disabled to avoid races.
15588                  * For correct bookkeeping mark this on active crtcs.
15589                  *
15590                  * Also on gmch platforms we dont have any hardware bits to
15591                  * disable the underrun reporting. Which means we need to start
15592                  * out with underrun reporting disabled also on inactive pipes,
15593                  * since otherwise we'll complain about the garbage we read when
15594                  * e.g. coming up after runtime pm.
15595                  *
15596                  * No protection against concurrent access is required - at
15597                  * worst a fifo underrun happens which also sets this to false.
15598                  */
15599                 crtc->cpu_fifo_underrun_disabled = true;
15600                 /*
15601                  * We track the PCH trancoder underrun reporting state
15602                  * within the crtc. With crtc for pipe A housing the underrun
15603                  * reporting state for PCH transcoder A, crtc for pipe B housing
15604                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
15605                  * and marking underrun reporting as disabled for the non-existing
15606                  * PCH transcoders B and C would prevent enabling the south
15607                  * error interrupt (see cpt_can_enable_serr_int()).
15608                  */
15609                 if (has_pch_trancoder(dev_priv, crtc->pipe))
15610                         crtc->pch_fifo_underrun_disabled = true;
15611         }
15612 }
15613
15614 static void intel_sanitize_encoder(struct intel_encoder *encoder)
15615 {
15616         struct intel_connector *connector;
15617
15618         /* We need to check both for a crtc link (meaning that the
15619          * encoder is active and trying to read from a pipe) and the
15620          * pipe itself being active. */
15621         bool has_active_crtc = encoder->base.crtc &&
15622                 to_intel_crtc(encoder->base.crtc)->active;
15623
15624         connector = intel_encoder_find_connector(encoder);
15625         if (connector && !has_active_crtc) {
15626                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15627                               encoder->base.base.id,
15628                               encoder->base.name);
15629
15630                 /* Connector is active, but has no active pipe. This is
15631                  * fallout from our resume register restoring. Disable
15632                  * the encoder manually again. */
15633                 if (encoder->base.crtc) {
15634                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15635
15636                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15637                                       encoder->base.base.id,
15638                                       encoder->base.name);
15639                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15640                         if (encoder->post_disable)
15641                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15642                 }
15643                 encoder->base.crtc = NULL;
15644
15645                 /* Inconsistent output/port/pipe state happens presumably due to
15646                  * a bug in one of the get_hw_state functions. Or someplace else
15647                  * in our code, like the register restore mess on resume. Clamp
15648                  * things to off as a safer default. */
15649
15650                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15651                 connector->base.encoder = NULL;
15652         }
15653
15654         /* notify opregion of the sanitized encoder state */
15655         intel_opregion_notify_encoder(encoder, connector && has_active_crtc);
15656 }
15657
15658 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15659 {
15660         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15661
15662         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15663                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15664                 i915_disable_vga(dev_priv);
15665         }
15666 }
15667
15668 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15669 {
15670         /* This function can be called both from intel_modeset_setup_hw_state or
15671          * at a very early point in our resume sequence, where the power well
15672          * structures are not yet restored. Since this function is at a very
15673          * paranoid "someone might have enabled VGA while we were not looking"
15674          * level, just check if the power well is enabled instead of trying to
15675          * follow the "don't touch the power well if we don't need it" policy
15676          * the rest of the driver uses. */
15677         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15678                 return;
15679
15680         i915_redisable_vga_power_on(dev_priv);
15681
15682         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15683 }
15684
15685 /* FIXME read out full plane state for all planes */
15686 static void readout_plane_state(struct drm_i915_private *dev_priv)
15687 {
15688         struct intel_plane *plane;
15689         struct intel_crtc *crtc;
15690
15691         for_each_intel_plane(&dev_priv->drm, plane) {
15692                 struct intel_plane_state *plane_state =
15693                         to_intel_plane_state(plane->base.state);
15694                 struct intel_crtc_state *crtc_state;
15695                 enum pipe pipe = PIPE_A;
15696                 bool visible;
15697
15698                 visible = plane->get_hw_state(plane, &pipe);
15699
15700                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15701                 crtc_state = to_intel_crtc_state(crtc->base.state);
15702
15703                 intel_set_plane_visible(crtc_state, plane_state, visible);
15704         }
15705
15706         for_each_intel_crtc(&dev_priv->drm, crtc) {
15707                 struct intel_crtc_state *crtc_state =
15708                         to_intel_crtc_state(crtc->base.state);
15709
15710                 fixup_active_planes(crtc_state);
15711         }
15712 }
15713
15714 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15715 {
15716         struct drm_i915_private *dev_priv = to_i915(dev);
15717         enum pipe pipe;
15718         struct intel_crtc *crtc;
15719         struct intel_encoder *encoder;
15720         struct intel_connector *connector;
15721         struct drm_connector_list_iter conn_iter;
15722         int i;
15723
15724         dev_priv->active_crtcs = 0;
15725
15726         for_each_intel_crtc(dev, crtc) {
15727                 struct intel_crtc_state *crtc_state =
15728                         to_intel_crtc_state(crtc->base.state);
15729
15730                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15731                 memset(crtc_state, 0, sizeof(*crtc_state));
15732                 crtc_state->base.crtc = &crtc->base;
15733
15734                 crtc_state->base.active = crtc_state->base.enable =
15735                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15736
15737                 crtc->base.enabled = crtc_state->base.enable;
15738                 crtc->active = crtc_state->base.active;
15739
15740                 if (crtc_state->base.active)
15741                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15742
15743                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15744                               crtc->base.base.id, crtc->base.name,
15745                               enableddisabled(crtc_state->base.active));
15746         }
15747
15748         readout_plane_state(dev_priv);
15749
15750         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15751                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15752
15753                 pll->on = pll->info->funcs->get_hw_state(dev_priv, pll,
15754                                                         &pll->state.hw_state);
15755                 pll->state.crtc_mask = 0;
15756                 for_each_intel_crtc(dev, crtc) {
15757                         struct intel_crtc_state *crtc_state =
15758                                 to_intel_crtc_state(crtc->base.state);
15759
15760                         if (crtc_state->base.active &&
15761                             crtc_state->shared_dpll == pll)
15762                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15763                 }
15764                 pll->active_mask = pll->state.crtc_mask;
15765
15766                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15767                               pll->info->name, pll->state.crtc_mask, pll->on);
15768         }
15769
15770         for_each_intel_encoder(dev, encoder) {
15771                 pipe = 0;
15772
15773                 if (encoder->get_hw_state(encoder, &pipe)) {
15774                         struct intel_crtc_state *crtc_state;
15775
15776                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15777                         crtc_state = to_intel_crtc_state(crtc->base.state);
15778
15779                         encoder->base.crtc = &crtc->base;
15780                         encoder->get_config(encoder, crtc_state);
15781                 } else {
15782                         encoder->base.crtc = NULL;
15783                 }
15784
15785                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15786                               encoder->base.base.id, encoder->base.name,
15787                               enableddisabled(encoder->base.crtc),
15788                               pipe_name(pipe));
15789         }
15790
15791         drm_connector_list_iter_begin(dev, &conn_iter);
15792         for_each_intel_connector_iter(connector, &conn_iter) {
15793                 if (connector->get_hw_state(connector)) {
15794                         connector->base.dpms = DRM_MODE_DPMS_ON;
15795
15796                         encoder = connector->encoder;
15797                         connector->base.encoder = &encoder->base;
15798
15799                         if (encoder->base.crtc &&
15800                             encoder->base.crtc->state->active) {
15801                                 /*
15802                                  * This has to be done during hardware readout
15803                                  * because anything calling .crtc_disable may
15804                                  * rely on the connector_mask being accurate.
15805                                  */
15806                                 encoder->base.crtc->state->connector_mask |=
15807                                         drm_connector_mask(&connector->base);
15808                                 encoder->base.crtc->state->encoder_mask |=
15809                                         drm_encoder_mask(&encoder->base);
15810                         }
15811
15812                 } else {
15813                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15814                         connector->base.encoder = NULL;
15815                 }
15816                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15817                               connector->base.base.id, connector->base.name,
15818                               enableddisabled(connector->base.encoder));
15819         }
15820         drm_connector_list_iter_end(&conn_iter);
15821
15822         for_each_intel_crtc(dev, crtc) {
15823                 struct intel_crtc_state *crtc_state =
15824                         to_intel_crtc_state(crtc->base.state);
15825                 int min_cdclk = 0;
15826
15827                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15828                 if (crtc_state->base.active) {
15829                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15830                         crtc->base.mode.hdisplay = crtc_state->pipe_src_w;
15831                         crtc->base.mode.vdisplay = crtc_state->pipe_src_h;
15832                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15833                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15834
15835                         /*
15836                          * The initial mode needs to be set in order to keep
15837                          * the atomic core happy. It wants a valid mode if the
15838                          * crtc's enabled, so we do the above call.
15839                          *
15840                          * But we don't set all the derived state fully, hence
15841                          * set a flag to indicate that a full recalculation is
15842                          * needed on the next commit.
15843                          */
15844                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15845
15846                         intel_crtc_compute_pixel_rate(crtc_state);
15847
15848                         if (dev_priv->display.modeset_calc_cdclk) {
15849                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15850                                 if (WARN_ON(min_cdclk < 0))
15851                                         min_cdclk = 0;
15852                         }
15853
15854                         drm_calc_timestamping_constants(&crtc->base,
15855                                                         &crtc_state->base.adjusted_mode);
15856                         update_scanline_offset(crtc);
15857                 }
15858
15859                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15860                 dev_priv->min_voltage_level[crtc->pipe] =
15861                         crtc_state->min_voltage_level;
15862
15863                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15864         }
15865 }
15866
15867 static void
15868 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15869 {
15870         struct intel_encoder *encoder;
15871
15872         for_each_intel_encoder(&dev_priv->drm, encoder) {
15873                 u64 get_domains;
15874                 enum intel_display_power_domain domain;
15875                 struct intel_crtc_state *crtc_state;
15876
15877                 if (!encoder->get_power_domains)
15878                         continue;
15879
15880                 /*
15881                  * MST-primary and inactive encoders don't have a crtc state
15882                  * and neither of these require any power domain references.
15883                  */
15884                 if (!encoder->base.crtc)
15885                         continue;
15886
15887                 crtc_state = to_intel_crtc_state(encoder->base.crtc->state);
15888                 get_domains = encoder->get_power_domains(encoder, crtc_state);
15889                 for_each_power_domain(domain, get_domains)
15890                         intel_display_power_get(dev_priv, domain);
15891         }
15892 }
15893
15894 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15895 {
15896         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15897         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15898                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15899                            DARBF_GATING_DIS);
15900
15901         if (IS_HASWELL(dev_priv)) {
15902                 /*
15903                  * WaRsPkgCStateDisplayPMReq:hsw
15904                  * System hang if this isn't done before disabling all planes!
15905                  */
15906                 I915_WRITE(CHICKEN_PAR1_1,
15907                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15908         }
15909 }
15910
15911 /* Scan out the current hw modeset state,
15912  * and sanitizes it to the current state
15913  */
15914 static void
15915 intel_modeset_setup_hw_state(struct drm_device *dev,
15916                              struct drm_modeset_acquire_ctx *ctx)
15917 {
15918         struct drm_i915_private *dev_priv = to_i915(dev);
15919         struct intel_crtc *crtc;
15920         struct intel_encoder *encoder;
15921         int i;
15922
15923         intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
15924
15925         intel_early_display_was(dev_priv);
15926         intel_modeset_readout_hw_state(dev);
15927
15928         /* HW state is read out, now we need to sanitize this mess. */
15929         get_encoder_power_domains(dev_priv);
15930
15931         /*
15932          * intel_sanitize_plane_mapping() may need to do vblank
15933          * waits, so we need vblank interrupts restored beforehand.
15934          */
15935         for_each_intel_crtc(&dev_priv->drm, crtc) {
15936                 drm_crtc_vblank_reset(&crtc->base);
15937
15938                 if (crtc->active)
15939                         drm_crtc_vblank_on(&crtc->base);
15940         }
15941
15942         intel_sanitize_plane_mapping(dev_priv);
15943
15944         for_each_intel_encoder(dev, encoder)
15945                 intel_sanitize_encoder(encoder);
15946
15947         for_each_intel_crtc(&dev_priv->drm, crtc) {
15948                 intel_sanitize_crtc(crtc, ctx);
15949                 intel_dump_pipe_config(crtc, crtc->config,
15950                                        "[setup_hw_state]");
15951         }
15952
15953         intel_modeset_update_connector_atomic_state(dev);
15954
15955         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15956                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15957
15958                 if (!pll->on || pll->active_mask)
15959                         continue;
15960
15961                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n",
15962                               pll->info->name);
15963
15964                 pll->info->funcs->disable(dev_priv, pll);
15965                 pll->on = false;
15966         }
15967
15968         if (IS_G4X(dev_priv)) {
15969                 g4x_wm_get_hw_state(dev);
15970                 g4x_wm_sanitize(dev_priv);
15971         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15972                 vlv_wm_get_hw_state(dev);
15973                 vlv_wm_sanitize(dev_priv);
15974         } else if (INTEL_GEN(dev_priv) >= 9) {
15975                 skl_wm_get_hw_state(dev);
15976         } else if (HAS_PCH_SPLIT(dev_priv)) {
15977                 ilk_wm_get_hw_state(dev);
15978         }
15979
15980         for_each_intel_crtc(dev, crtc) {
15981                 u64 put_domains;
15982
15983                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15984                 if (WARN_ON(put_domains))
15985                         modeset_put_power_domains(dev_priv, put_domains);
15986         }
15987
15988         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT);
15989
15990         intel_fbc_init_pipe_state(dev_priv);
15991 }
15992
15993 void intel_display_resume(struct drm_device *dev)
15994 {
15995         struct drm_i915_private *dev_priv = to_i915(dev);
15996         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15997         struct drm_modeset_acquire_ctx ctx;
15998         int ret;
15999
16000         dev_priv->modeset_restore_state = NULL;
16001         if (state)
16002                 state->acquire_ctx = &ctx;
16003
16004         drm_modeset_acquire_init(&ctx, 0);
16005
16006         while (1) {
16007                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
16008                 if (ret != -EDEADLK)
16009                         break;
16010
16011                 drm_modeset_backoff(&ctx);
16012         }
16013
16014         if (!ret)
16015                 ret = __intel_display_resume(dev, state, &ctx);
16016
16017         intel_enable_ipc(dev_priv);
16018         drm_modeset_drop_locks(&ctx);
16019         drm_modeset_acquire_fini(&ctx);
16020
16021         if (ret)
16022                 DRM_ERROR("Restoring old state failed with %i\n", ret);
16023         if (state)
16024                 drm_atomic_state_put(state);
16025 }
16026
16027 int intel_connector_register(struct drm_connector *connector)
16028 {
16029         struct intel_connector *intel_connector = to_intel_connector(connector);
16030         int ret;
16031
16032         ret = intel_backlight_device_register(intel_connector);
16033         if (ret)
16034                 goto err;
16035
16036         return 0;
16037
16038 err:
16039         return ret;
16040 }
16041
16042 void intel_connector_unregister(struct drm_connector *connector)
16043 {
16044         struct intel_connector *intel_connector = to_intel_connector(connector);
16045
16046         intel_backlight_device_unregister(intel_connector);
16047         intel_panel_destroy_backlight(connector);
16048 }
16049
16050 static void intel_hpd_poll_fini(struct drm_device *dev)
16051 {
16052         struct intel_connector *connector;
16053         struct drm_connector_list_iter conn_iter;
16054
16055         /* Kill all the work that may have been queued by hpd. */
16056         drm_connector_list_iter_begin(dev, &conn_iter);
16057         for_each_intel_connector_iter(connector, &conn_iter) {
16058                 if (connector->modeset_retry_work.func)
16059                         cancel_work_sync(&connector->modeset_retry_work);
16060                 if (connector->hdcp_shim) {
16061                         cancel_delayed_work_sync(&connector->hdcp_check_work);
16062                         cancel_work_sync(&connector->hdcp_prop_work);
16063                 }
16064         }
16065         drm_connector_list_iter_end(&conn_iter);
16066 }
16067
16068 void intel_modeset_cleanup(struct drm_device *dev)
16069 {
16070         struct drm_i915_private *dev_priv = to_i915(dev);
16071
16072         flush_workqueue(dev_priv->modeset_wq);
16073
16074         flush_work(&dev_priv->atomic_helper.free_work);
16075         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
16076
16077         /*
16078          * Interrupts and polling as the first thing to avoid creating havoc.
16079          * Too much stuff here (turning of connectors, ...) would
16080          * experience fancy races otherwise.
16081          */
16082         intel_irq_uninstall(dev_priv);
16083
16084         /*
16085          * Due to the hpd irq storm handling the hotplug work can re-arm the
16086          * poll handlers. Hence disable polling after hpd handling is shut down.
16087          */
16088         intel_hpd_poll_fini(dev);
16089
16090         /* poll work can call into fbdev, hence clean that up afterwards */
16091         intel_fbdev_fini(dev_priv);
16092
16093         intel_unregister_dsm_handler();
16094
16095         intel_fbc_global_disable(dev_priv);
16096
16097         /* flush any delayed tasks or pending work */
16098         flush_scheduled_work();
16099
16100         drm_mode_config_cleanup(dev);
16101
16102         intel_cleanup_overlay(dev_priv);
16103
16104         intel_teardown_gmbus(dev_priv);
16105
16106         destroy_workqueue(dev_priv->modeset_wq);
16107 }
16108
16109 void intel_connector_attach_encoder(struct intel_connector *connector,
16110                                     struct intel_encoder *encoder)
16111 {
16112         connector->encoder = encoder;
16113         drm_connector_attach_encoder(&connector->base, &encoder->base);
16114 }
16115
16116 /*
16117  * set vga decode state - true == enable VGA decode
16118  */
16119 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
16120 {
16121         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
16122         u16 gmch_ctrl;
16123
16124         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
16125                 DRM_ERROR("failed to read control word\n");
16126                 return -EIO;
16127         }
16128
16129         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
16130                 return 0;
16131
16132         if (state)
16133                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
16134         else
16135                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
16136
16137         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
16138                 DRM_ERROR("failed to write control word\n");
16139                 return -EIO;
16140         }
16141
16142         return 0;
16143 }
16144
16145 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
16146
16147 struct intel_display_error_state {
16148
16149         u32 power_well_driver;
16150
16151         int num_transcoders;
16152
16153         struct intel_cursor_error_state {
16154                 u32 control;
16155                 u32 position;
16156                 u32 base;
16157                 u32 size;
16158         } cursor[I915_MAX_PIPES];
16159
16160         struct intel_pipe_error_state {
16161                 bool power_domain_on;
16162                 u32 source;
16163                 u32 stat;
16164         } pipe[I915_MAX_PIPES];
16165
16166         struct intel_plane_error_state {
16167                 u32 control;
16168                 u32 stride;
16169                 u32 size;
16170                 u32 pos;
16171                 u32 addr;
16172                 u32 surface;
16173                 u32 tile_offset;
16174         } plane[I915_MAX_PIPES];
16175
16176         struct intel_transcoder_error_state {
16177                 bool power_domain_on;
16178                 enum transcoder cpu_transcoder;
16179
16180                 u32 conf;
16181
16182                 u32 htotal;
16183                 u32 hblank;
16184                 u32 hsync;
16185                 u32 vtotal;
16186                 u32 vblank;
16187                 u32 vsync;
16188         } transcoder[4];
16189 };
16190
16191 struct intel_display_error_state *
16192 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
16193 {
16194         struct intel_display_error_state *error;
16195         int transcoders[] = {
16196                 TRANSCODER_A,
16197                 TRANSCODER_B,
16198                 TRANSCODER_C,
16199                 TRANSCODER_EDP,
16200         };
16201         int i;
16202
16203         if (INTEL_INFO(dev_priv)->num_pipes == 0)
16204                 return NULL;
16205
16206         error = kzalloc(sizeof(*error), GFP_ATOMIC);
16207         if (error == NULL)
16208                 return NULL;
16209
16210         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16211                 error->power_well_driver = I915_READ(HSW_PWR_WELL_CTL2);
16212
16213         for_each_pipe(dev_priv, i) {
16214                 error->pipe[i].power_domain_on =
16215                         __intel_display_power_is_enabled(dev_priv,
16216                                                          POWER_DOMAIN_PIPE(i));
16217                 if (!error->pipe[i].power_domain_on)
16218                         continue;
16219
16220                 error->cursor[i].control = I915_READ(CURCNTR(i));
16221                 error->cursor[i].position = I915_READ(CURPOS(i));
16222                 error->cursor[i].base = I915_READ(CURBASE(i));
16223
16224                 error->plane[i].control = I915_READ(DSPCNTR(i));
16225                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
16226                 if (INTEL_GEN(dev_priv) <= 3) {
16227                         error->plane[i].size = I915_READ(DSPSIZE(i));
16228                         error->plane[i].pos = I915_READ(DSPPOS(i));
16229                 }
16230                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16231                         error->plane[i].addr = I915_READ(DSPADDR(i));
16232                 if (INTEL_GEN(dev_priv) >= 4) {
16233                         error->plane[i].surface = I915_READ(DSPSURF(i));
16234                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
16235                 }
16236
16237                 error->pipe[i].source = I915_READ(PIPESRC(i));
16238
16239                 if (HAS_GMCH_DISPLAY(dev_priv))
16240                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
16241         }
16242
16243         /* Note: this does not include DSI transcoders. */
16244         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
16245         if (HAS_DDI(dev_priv))
16246                 error->num_transcoders++; /* Account for eDP. */
16247
16248         for (i = 0; i < error->num_transcoders; i++) {
16249                 enum transcoder cpu_transcoder = transcoders[i];
16250
16251                 error->transcoder[i].power_domain_on =
16252                         __intel_display_power_is_enabled(dev_priv,
16253                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
16254                 if (!error->transcoder[i].power_domain_on)
16255                         continue;
16256
16257                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
16258
16259                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
16260                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
16261                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
16262                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
16263                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
16264                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
16265                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
16266         }
16267
16268         return error;
16269 }
16270
16271 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
16272
16273 void
16274 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
16275                                 struct intel_display_error_state *error)
16276 {
16277         struct drm_i915_private *dev_priv = m->i915;
16278         int i;
16279
16280         if (!error)
16281                 return;
16282
16283         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
16284         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
16285                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
16286                            error->power_well_driver);
16287         for_each_pipe(dev_priv, i) {
16288                 err_printf(m, "Pipe [%d]:\n", i);
16289                 err_printf(m, "  Power: %s\n",
16290                            onoff(error->pipe[i].power_domain_on));
16291                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
16292                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
16293
16294                 err_printf(m, "Plane [%d]:\n", i);
16295                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
16296                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
16297                 if (INTEL_GEN(dev_priv) <= 3) {
16298                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
16299                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
16300                 }
16301                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
16302                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
16303                 if (INTEL_GEN(dev_priv) >= 4) {
16304                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
16305                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
16306                 }
16307
16308                 err_printf(m, "Cursor [%d]:\n", i);
16309                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
16310                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
16311                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
16312         }
16313
16314         for (i = 0; i < error->num_transcoders; i++) {
16315                 err_printf(m, "CPU transcoder: %s\n",
16316                            transcoder_name(error->transcoder[i].cpu_transcoder));
16317                 err_printf(m, "  Power: %s\n",
16318                            onoff(error->transcoder[i].power_domain_on));
16319                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
16320                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
16321                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
16322                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
16323                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
16324                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
16325                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
16326         }
16327 }
16328
16329 #endif