Merge drm-next into drm-intel-next-queued (this time for real)
[linux-2.6-microblaze.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 <linux/dma_remapping.h>
50 #include <linux/reservation.h>
51
52 /* Primary plane formats for gen <= 3 */
53 static const uint32_t i8xx_primary_formats[] = {
54         DRM_FORMAT_C8,
55         DRM_FORMAT_RGB565,
56         DRM_FORMAT_XRGB1555,
57         DRM_FORMAT_XRGB8888,
58 };
59
60 /* Primary plane formats for gen >= 4 */
61 static const uint32_t i965_primary_formats[] = {
62         DRM_FORMAT_C8,
63         DRM_FORMAT_RGB565,
64         DRM_FORMAT_XRGB8888,
65         DRM_FORMAT_XBGR8888,
66         DRM_FORMAT_XRGB2101010,
67         DRM_FORMAT_XBGR2101010,
68 };
69
70 static const uint64_t i9xx_format_modifiers[] = {
71         I915_FORMAT_MOD_X_TILED,
72         DRM_FORMAT_MOD_LINEAR,
73         DRM_FORMAT_MOD_INVALID
74 };
75
76 static const uint32_t skl_primary_formats[] = {
77         DRM_FORMAT_C8,
78         DRM_FORMAT_RGB565,
79         DRM_FORMAT_XRGB8888,
80         DRM_FORMAT_XBGR8888,
81         DRM_FORMAT_ARGB8888,
82         DRM_FORMAT_ABGR8888,
83         DRM_FORMAT_XRGB2101010,
84         DRM_FORMAT_XBGR2101010,
85         DRM_FORMAT_YUYV,
86         DRM_FORMAT_YVYU,
87         DRM_FORMAT_UYVY,
88         DRM_FORMAT_VYUY,
89 };
90
91 static const uint64_t skl_format_modifiers_noccs[] = {
92         I915_FORMAT_MOD_Yf_TILED,
93         I915_FORMAT_MOD_Y_TILED,
94         I915_FORMAT_MOD_X_TILED,
95         DRM_FORMAT_MOD_LINEAR,
96         DRM_FORMAT_MOD_INVALID
97 };
98
99 static const uint64_t skl_format_modifiers_ccs[] = {
100         I915_FORMAT_MOD_Yf_TILED_CCS,
101         I915_FORMAT_MOD_Y_TILED_CCS,
102         I915_FORMAT_MOD_Yf_TILED,
103         I915_FORMAT_MOD_Y_TILED,
104         I915_FORMAT_MOD_X_TILED,
105         DRM_FORMAT_MOD_LINEAR,
106         DRM_FORMAT_MOD_INVALID
107 };
108
109 /* Cursor formats */
110 static const uint32_t intel_cursor_formats[] = {
111         DRM_FORMAT_ARGB8888,
112 };
113
114 static const uint64_t cursor_format_modifiers[] = {
115         DRM_FORMAT_MOD_LINEAR,
116         DRM_FORMAT_MOD_INVALID
117 };
118
119 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
120                                 struct intel_crtc_state *pipe_config);
121 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
122                                    struct intel_crtc_state *pipe_config);
123
124 static int intel_framebuffer_init(struct intel_framebuffer *ifb,
125                                   struct drm_i915_gem_object *obj,
126                                   struct drm_mode_fb_cmd2 *mode_cmd);
127 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc);
128 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc);
129 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc);
130 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
131                                          struct intel_link_m_n *m_n,
132                                          struct intel_link_m_n *m2_n2);
133 static void ironlake_set_pipeconf(struct drm_crtc *crtc);
134 static void haswell_set_pipeconf(struct drm_crtc *crtc);
135 static void haswell_set_pipemisc(struct drm_crtc *crtc);
136 static void vlv_prepare_pll(struct intel_crtc *crtc,
137                             const struct intel_crtc_state *pipe_config);
138 static void chv_prepare_pll(struct intel_crtc *crtc,
139                             const struct intel_crtc_state *pipe_config);
140 static void intel_begin_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
141 static void intel_finish_crtc_commit(struct drm_crtc *, struct drm_crtc_state *);
142 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
143                                     struct intel_crtc_state *crtc_state);
144 static void skylake_pfit_enable(struct intel_crtc *crtc);
145 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force);
146 static void ironlake_pfit_enable(struct intel_crtc *crtc);
147 static void intel_modeset_setup_hw_state(struct drm_device *dev,
148                                          struct drm_modeset_acquire_ctx *ctx);
149 static void intel_pre_disable_primary_noatomic(struct drm_crtc *crtc);
150
151 struct intel_limit {
152         struct {
153                 int min, max;
154         } dot, vco, n, m, m1, m2, p, p1;
155
156         struct {
157                 int dot_limit;
158                 int p2_slow, p2_fast;
159         } p2;
160 };
161
162 /* returns HPLL frequency in kHz */
163 int vlv_get_hpll_vco(struct drm_i915_private *dev_priv)
164 {
165         int hpll_freq, vco_freq[] = { 800, 1600, 2000, 2400 };
166
167         /* Obtain SKU information */
168         mutex_lock(&dev_priv->sb_lock);
169         hpll_freq = vlv_cck_read(dev_priv, CCK_FUSE_REG) &
170                 CCK_FUSE_HPLL_FREQ_MASK;
171         mutex_unlock(&dev_priv->sb_lock);
172
173         return vco_freq[hpll_freq] * 1000;
174 }
175
176 int vlv_get_cck_clock(struct drm_i915_private *dev_priv,
177                       const char *name, u32 reg, int ref_freq)
178 {
179         u32 val;
180         int divider;
181
182         mutex_lock(&dev_priv->sb_lock);
183         val = vlv_cck_read(dev_priv, reg);
184         mutex_unlock(&dev_priv->sb_lock);
185
186         divider = val & CCK_FREQUENCY_VALUES;
187
188         WARN((val & CCK_FREQUENCY_STATUS) !=
189              (divider << CCK_FREQUENCY_STATUS_SHIFT),
190              "%s change in progress\n", name);
191
192         return DIV_ROUND_CLOSEST(ref_freq << 1, divider + 1);
193 }
194
195 int vlv_get_cck_clock_hpll(struct drm_i915_private *dev_priv,
196                            const char *name, u32 reg)
197 {
198         if (dev_priv->hpll_freq == 0)
199                 dev_priv->hpll_freq = vlv_get_hpll_vco(dev_priv);
200
201         return vlv_get_cck_clock(dev_priv, name, reg,
202                                  dev_priv->hpll_freq);
203 }
204
205 static void intel_update_czclk(struct drm_i915_private *dev_priv)
206 {
207         if (!(IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)))
208                 return;
209
210         dev_priv->czclk_freq = vlv_get_cck_clock_hpll(dev_priv, "czclk",
211                                                       CCK_CZ_CLOCK_CONTROL);
212
213         DRM_DEBUG_DRIVER("CZ clock rate: %d kHz\n", dev_priv->czclk_freq);
214 }
215
216 static inline u32 /* units of 100MHz */
217 intel_fdi_link_freq(struct drm_i915_private *dev_priv,
218                     const struct intel_crtc_state *pipe_config)
219 {
220         if (HAS_DDI(dev_priv))
221                 return pipe_config->port_clock; /* SPLL */
222         else
223                 return dev_priv->fdi_pll_freq;
224 }
225
226 static const struct intel_limit intel_limits_i8xx_dac = {
227         .dot = { .min = 25000, .max = 350000 },
228         .vco = { .min = 908000, .max = 1512000 },
229         .n = { .min = 2, .max = 16 },
230         .m = { .min = 96, .max = 140 },
231         .m1 = { .min = 18, .max = 26 },
232         .m2 = { .min = 6, .max = 16 },
233         .p = { .min = 4, .max = 128 },
234         .p1 = { .min = 2, .max = 33 },
235         .p2 = { .dot_limit = 165000,
236                 .p2_slow = 4, .p2_fast = 2 },
237 };
238
239 static const struct intel_limit intel_limits_i8xx_dvo = {
240         .dot = { .min = 25000, .max = 350000 },
241         .vco = { .min = 908000, .max = 1512000 },
242         .n = { .min = 2, .max = 16 },
243         .m = { .min = 96, .max = 140 },
244         .m1 = { .min = 18, .max = 26 },
245         .m2 = { .min = 6, .max = 16 },
246         .p = { .min = 4, .max = 128 },
247         .p1 = { .min = 2, .max = 33 },
248         .p2 = { .dot_limit = 165000,
249                 .p2_slow = 4, .p2_fast = 4 },
250 };
251
252 static const struct intel_limit intel_limits_i8xx_lvds = {
253         .dot = { .min = 25000, .max = 350000 },
254         .vco = { .min = 908000, .max = 1512000 },
255         .n = { .min = 2, .max = 16 },
256         .m = { .min = 96, .max = 140 },
257         .m1 = { .min = 18, .max = 26 },
258         .m2 = { .min = 6, .max = 16 },
259         .p = { .min = 4, .max = 128 },
260         .p1 = { .min = 1, .max = 6 },
261         .p2 = { .dot_limit = 165000,
262                 .p2_slow = 14, .p2_fast = 7 },
263 };
264
265 static const struct intel_limit intel_limits_i9xx_sdvo = {
266         .dot = { .min = 20000, .max = 400000 },
267         .vco = { .min = 1400000, .max = 2800000 },
268         .n = { .min = 1, .max = 6 },
269         .m = { .min = 70, .max = 120 },
270         .m1 = { .min = 8, .max = 18 },
271         .m2 = { .min = 3, .max = 7 },
272         .p = { .min = 5, .max = 80 },
273         .p1 = { .min = 1, .max = 8 },
274         .p2 = { .dot_limit = 200000,
275                 .p2_slow = 10, .p2_fast = 5 },
276 };
277
278 static const struct intel_limit intel_limits_i9xx_lvds = {
279         .dot = { .min = 20000, .max = 400000 },
280         .vco = { .min = 1400000, .max = 2800000 },
281         .n = { .min = 1, .max = 6 },
282         .m = { .min = 70, .max = 120 },
283         .m1 = { .min = 8, .max = 18 },
284         .m2 = { .min = 3, .max = 7 },
285         .p = { .min = 7, .max = 98 },
286         .p1 = { .min = 1, .max = 8 },
287         .p2 = { .dot_limit = 112000,
288                 .p2_slow = 14, .p2_fast = 7 },
289 };
290
291
292 static const struct intel_limit intel_limits_g4x_sdvo = {
293         .dot = { .min = 25000, .max = 270000 },
294         .vco = { .min = 1750000, .max = 3500000},
295         .n = { .min = 1, .max = 4 },
296         .m = { .min = 104, .max = 138 },
297         .m1 = { .min = 17, .max = 23 },
298         .m2 = { .min = 5, .max = 11 },
299         .p = { .min = 10, .max = 30 },
300         .p1 = { .min = 1, .max = 3},
301         .p2 = { .dot_limit = 270000,
302                 .p2_slow = 10,
303                 .p2_fast = 10
304         },
305 };
306
307 static const struct intel_limit intel_limits_g4x_hdmi = {
308         .dot = { .min = 22000, .max = 400000 },
309         .vco = { .min = 1750000, .max = 3500000},
310         .n = { .min = 1, .max = 4 },
311         .m = { .min = 104, .max = 138 },
312         .m1 = { .min = 16, .max = 23 },
313         .m2 = { .min = 5, .max = 11 },
314         .p = { .min = 5, .max = 80 },
315         .p1 = { .min = 1, .max = 8},
316         .p2 = { .dot_limit = 165000,
317                 .p2_slow = 10, .p2_fast = 5 },
318 };
319
320 static const struct intel_limit intel_limits_g4x_single_channel_lvds = {
321         .dot = { .min = 20000, .max = 115000 },
322         .vco = { .min = 1750000, .max = 3500000 },
323         .n = { .min = 1, .max = 3 },
324         .m = { .min = 104, .max = 138 },
325         .m1 = { .min = 17, .max = 23 },
326         .m2 = { .min = 5, .max = 11 },
327         .p = { .min = 28, .max = 112 },
328         .p1 = { .min = 2, .max = 8 },
329         .p2 = { .dot_limit = 0,
330                 .p2_slow = 14, .p2_fast = 14
331         },
332 };
333
334 static const struct intel_limit intel_limits_g4x_dual_channel_lvds = {
335         .dot = { .min = 80000, .max = 224000 },
336         .vco = { .min = 1750000, .max = 3500000 },
337         .n = { .min = 1, .max = 3 },
338         .m = { .min = 104, .max = 138 },
339         .m1 = { .min = 17, .max = 23 },
340         .m2 = { .min = 5, .max = 11 },
341         .p = { .min = 14, .max = 42 },
342         .p1 = { .min = 2, .max = 6 },
343         .p2 = { .dot_limit = 0,
344                 .p2_slow = 7, .p2_fast = 7
345         },
346 };
347
348 static const struct intel_limit intel_limits_pineview_sdvo = {
349         .dot = { .min = 20000, .max = 400000},
350         .vco = { .min = 1700000, .max = 3500000 },
351         /* Pineview's Ncounter is a ring counter */
352         .n = { .min = 3, .max = 6 },
353         .m = { .min = 2, .max = 256 },
354         /* Pineview only has one combined m divider, which we treat as m2. */
355         .m1 = { .min = 0, .max = 0 },
356         .m2 = { .min = 0, .max = 254 },
357         .p = { .min = 5, .max = 80 },
358         .p1 = { .min = 1, .max = 8 },
359         .p2 = { .dot_limit = 200000,
360                 .p2_slow = 10, .p2_fast = 5 },
361 };
362
363 static const struct intel_limit intel_limits_pineview_lvds = {
364         .dot = { .min = 20000, .max = 400000 },
365         .vco = { .min = 1700000, .max = 3500000 },
366         .n = { .min = 3, .max = 6 },
367         .m = { .min = 2, .max = 256 },
368         .m1 = { .min = 0, .max = 0 },
369         .m2 = { .min = 0, .max = 254 },
370         .p = { .min = 7, .max = 112 },
371         .p1 = { .min = 1, .max = 8 },
372         .p2 = { .dot_limit = 112000,
373                 .p2_slow = 14, .p2_fast = 14 },
374 };
375
376 /* Ironlake / Sandybridge
377  *
378  * We calculate clock using (register_value + 2) for N/M1/M2, so here
379  * the range value for them is (actual_value - 2).
380  */
381 static const struct intel_limit intel_limits_ironlake_dac = {
382         .dot = { .min = 25000, .max = 350000 },
383         .vco = { .min = 1760000, .max = 3510000 },
384         .n = { .min = 1, .max = 5 },
385         .m = { .min = 79, .max = 127 },
386         .m1 = { .min = 12, .max = 22 },
387         .m2 = { .min = 5, .max = 9 },
388         .p = { .min = 5, .max = 80 },
389         .p1 = { .min = 1, .max = 8 },
390         .p2 = { .dot_limit = 225000,
391                 .p2_slow = 10, .p2_fast = 5 },
392 };
393
394 static const struct intel_limit intel_limits_ironlake_single_lvds = {
395         .dot = { .min = 25000, .max = 350000 },
396         .vco = { .min = 1760000, .max = 3510000 },
397         .n = { .min = 1, .max = 3 },
398         .m = { .min = 79, .max = 118 },
399         .m1 = { .min = 12, .max = 22 },
400         .m2 = { .min = 5, .max = 9 },
401         .p = { .min = 28, .max = 112 },
402         .p1 = { .min = 2, .max = 8 },
403         .p2 = { .dot_limit = 225000,
404                 .p2_slow = 14, .p2_fast = 14 },
405 };
406
407 static const struct intel_limit intel_limits_ironlake_dual_lvds = {
408         .dot = { .min = 25000, .max = 350000 },
409         .vco = { .min = 1760000, .max = 3510000 },
410         .n = { .min = 1, .max = 3 },
411         .m = { .min = 79, .max = 127 },
412         .m1 = { .min = 12, .max = 22 },
413         .m2 = { .min = 5, .max = 9 },
414         .p = { .min = 14, .max = 56 },
415         .p1 = { .min = 2, .max = 8 },
416         .p2 = { .dot_limit = 225000,
417                 .p2_slow = 7, .p2_fast = 7 },
418 };
419
420 /* LVDS 100mhz refclk limits. */
421 static const struct intel_limit intel_limits_ironlake_single_lvds_100m = {
422         .dot = { .min = 25000, .max = 350000 },
423         .vco = { .min = 1760000, .max = 3510000 },
424         .n = { .min = 1, .max = 2 },
425         .m = { .min = 79, .max = 126 },
426         .m1 = { .min = 12, .max = 22 },
427         .m2 = { .min = 5, .max = 9 },
428         .p = { .min = 28, .max = 112 },
429         .p1 = { .min = 2, .max = 8 },
430         .p2 = { .dot_limit = 225000,
431                 .p2_slow = 14, .p2_fast = 14 },
432 };
433
434 static const struct intel_limit intel_limits_ironlake_dual_lvds_100m = {
435         .dot = { .min = 25000, .max = 350000 },
436         .vco = { .min = 1760000, .max = 3510000 },
437         .n = { .min = 1, .max = 3 },
438         .m = { .min = 79, .max = 126 },
439         .m1 = { .min = 12, .max = 22 },
440         .m2 = { .min = 5, .max = 9 },
441         .p = { .min = 14, .max = 42 },
442         .p1 = { .min = 2, .max = 6 },
443         .p2 = { .dot_limit = 225000,
444                 .p2_slow = 7, .p2_fast = 7 },
445 };
446
447 static const struct intel_limit intel_limits_vlv = {
448          /*
449           * These are the data rate limits (measured in fast clocks)
450           * since those are the strictest limits we have. The fast
451           * clock and actual rate limits are more relaxed, so checking
452           * them would make no difference.
453           */
454         .dot = { .min = 25000 * 5, .max = 270000 * 5 },
455         .vco = { .min = 4000000, .max = 6000000 },
456         .n = { .min = 1, .max = 7 },
457         .m1 = { .min = 2, .max = 3 },
458         .m2 = { .min = 11, .max = 156 },
459         .p1 = { .min = 2, .max = 3 },
460         .p2 = { .p2_slow = 2, .p2_fast = 20 }, /* slow=min, fast=max */
461 };
462
463 static const struct intel_limit intel_limits_chv = {
464         /*
465          * These are the data rate limits (measured in fast clocks)
466          * since those are the strictest limits we have.  The fast
467          * clock and actual rate limits are more relaxed, so checking
468          * them would make no difference.
469          */
470         .dot = { .min = 25000 * 5, .max = 540000 * 5},
471         .vco = { .min = 4800000, .max = 6480000 },
472         .n = { .min = 1, .max = 1 },
473         .m1 = { .min = 2, .max = 2 },
474         .m2 = { .min = 24 << 22, .max = 175 << 22 },
475         .p1 = { .min = 2, .max = 4 },
476         .p2 = { .p2_slow = 1, .p2_fast = 14 },
477 };
478
479 static const struct intel_limit intel_limits_bxt = {
480         /* FIXME: find real dot limits */
481         .dot = { .min = 0, .max = INT_MAX },
482         .vco = { .min = 4800000, .max = 6700000 },
483         .n = { .min = 1, .max = 1 },
484         .m1 = { .min = 2, .max = 2 },
485         /* FIXME: find real m2 limits */
486         .m2 = { .min = 2 << 22, .max = 255 << 22 },
487         .p1 = { .min = 2, .max = 4 },
488         .p2 = { .p2_slow = 1, .p2_fast = 20 },
489 };
490
491 static bool
492 needs_modeset(const struct drm_crtc_state *state)
493 {
494         return drm_atomic_crtc_needs_modeset(state);
495 }
496
497 /*
498  * Platform specific helpers to calculate the port PLL loopback- (clock.m),
499  * and post-divider (clock.p) values, pre- (clock.vco) and post-divided fast
500  * (clock.dot) clock rates. This fast dot clock is fed to the port's IO logic.
501  * The helpers' return value is the rate of the clock that is fed to the
502  * display engine's pipe which can be the above fast dot clock rate or a
503  * divided-down version of it.
504  */
505 /* m1 is reserved as 0 in Pineview, n is a ring counter */
506 static int pnv_calc_dpll_params(int refclk, struct dpll *clock)
507 {
508         clock->m = clock->m2 + 2;
509         clock->p = clock->p1 * clock->p2;
510         if (WARN_ON(clock->n == 0 || clock->p == 0))
511                 return 0;
512         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
513         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
514
515         return clock->dot;
516 }
517
518 static uint32_t i9xx_dpll_compute_m(struct dpll *dpll)
519 {
520         return 5 * (dpll->m1 + 2) + (dpll->m2 + 2);
521 }
522
523 static int i9xx_calc_dpll_params(int refclk, struct dpll *clock)
524 {
525         clock->m = i9xx_dpll_compute_m(clock);
526         clock->p = clock->p1 * clock->p2;
527         if (WARN_ON(clock->n + 2 == 0 || clock->p == 0))
528                 return 0;
529         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n + 2);
530         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
531
532         return clock->dot;
533 }
534
535 static int vlv_calc_dpll_params(int refclk, struct dpll *clock)
536 {
537         clock->m = clock->m1 * clock->m2;
538         clock->p = clock->p1 * clock->p2;
539         if (WARN_ON(clock->n == 0 || clock->p == 0))
540                 return 0;
541         clock->vco = DIV_ROUND_CLOSEST(refclk * clock->m, clock->n);
542         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
543
544         return clock->dot / 5;
545 }
546
547 int chv_calc_dpll_params(int refclk, struct dpll *clock)
548 {
549         clock->m = clock->m1 * clock->m2;
550         clock->p = clock->p1 * clock->p2;
551         if (WARN_ON(clock->n == 0 || clock->p == 0))
552                 return 0;
553         clock->vco = DIV_ROUND_CLOSEST_ULL((uint64_t)refclk * clock->m,
554                         clock->n << 22);
555         clock->dot = DIV_ROUND_CLOSEST(clock->vco, clock->p);
556
557         return clock->dot / 5;
558 }
559
560 #define INTELPllInvalid(s)   do { /* DRM_DEBUG(s); */ return false; } while (0)
561
562 /*
563  * Returns whether the given set of divisors are valid for a given refclk with
564  * the given connectors.
565  */
566 static bool intel_PLL_is_valid(struct drm_i915_private *dev_priv,
567                                const struct intel_limit *limit,
568                                const struct dpll *clock)
569 {
570         if (clock->n   < limit->n.min   || limit->n.max   < clock->n)
571                 INTELPllInvalid("n out of range\n");
572         if (clock->p1  < limit->p1.min  || limit->p1.max  < clock->p1)
573                 INTELPllInvalid("p1 out of range\n");
574         if (clock->m2  < limit->m2.min  || limit->m2.max  < clock->m2)
575                 INTELPllInvalid("m2 out of range\n");
576         if (clock->m1  < limit->m1.min  || limit->m1.max  < clock->m1)
577                 INTELPllInvalid("m1 out of range\n");
578
579         if (!IS_PINEVIEW(dev_priv) && !IS_VALLEYVIEW(dev_priv) &&
580             !IS_CHERRYVIEW(dev_priv) && !IS_GEN9_LP(dev_priv))
581                 if (clock->m1 <= clock->m2)
582                         INTELPllInvalid("m1 <= m2\n");
583
584         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
585             !IS_GEN9_LP(dev_priv)) {
586                 if (clock->p < limit->p.min || limit->p.max < clock->p)
587                         INTELPllInvalid("p out of range\n");
588                 if (clock->m < limit->m.min || limit->m.max < clock->m)
589                         INTELPllInvalid("m out of range\n");
590         }
591
592         if (clock->vco < limit->vco.min || limit->vco.max < clock->vco)
593                 INTELPllInvalid("vco out of range\n");
594         /* XXX: We may need to be checking "Dot clock" depending on the multiplier,
595          * connector, etc., rather than just a single range.
596          */
597         if (clock->dot < limit->dot.min || limit->dot.max < clock->dot)
598                 INTELPllInvalid("dot out of range\n");
599
600         return true;
601 }
602
603 static int
604 i9xx_select_p2_div(const struct intel_limit *limit,
605                    const struct intel_crtc_state *crtc_state,
606                    int target)
607 {
608         struct drm_device *dev = crtc_state->base.crtc->dev;
609
610         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
611                 /*
612                  * For LVDS just rely on its current settings for dual-channel.
613                  * We haven't figured out how to reliably set up different
614                  * single/dual channel state, if we even can.
615                  */
616                 if (intel_is_dual_link_lvds(dev))
617                         return limit->p2.p2_fast;
618                 else
619                         return limit->p2.p2_slow;
620         } else {
621                 if (target < limit->p2.dot_limit)
622                         return limit->p2.p2_slow;
623                 else
624                         return limit->p2.p2_fast;
625         }
626 }
627
628 /*
629  * Returns a set of divisors for the desired target clock with the given
630  * refclk, or FALSE.  The returned values represent the clock equation:
631  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
632  *
633  * Target and reference clocks are specified in kHz.
634  *
635  * If match_clock is provided, then best_clock P divider must match the P
636  * divider from @match_clock used for LVDS downclocking.
637  */
638 static bool
639 i9xx_find_best_dpll(const struct intel_limit *limit,
640                     struct intel_crtc_state *crtc_state,
641                     int target, int refclk, struct dpll *match_clock,
642                     struct dpll *best_clock)
643 {
644         struct drm_device *dev = crtc_state->base.crtc->dev;
645         struct dpll clock;
646         int err = target;
647
648         memset(best_clock, 0, sizeof(*best_clock));
649
650         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
651
652         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
653              clock.m1++) {
654                 for (clock.m2 = limit->m2.min;
655                      clock.m2 <= limit->m2.max; clock.m2++) {
656                         if (clock.m2 >= clock.m1)
657                                 break;
658                         for (clock.n = limit->n.min;
659                              clock.n <= limit->n.max; clock.n++) {
660                                 for (clock.p1 = limit->p1.min;
661                                         clock.p1 <= limit->p1.max; clock.p1++) {
662                                         int this_err;
663
664                                         i9xx_calc_dpll_params(refclk, &clock);
665                                         if (!intel_PLL_is_valid(to_i915(dev),
666                                                                 limit,
667                                                                 &clock))
668                                                 continue;
669                                         if (match_clock &&
670                                             clock.p != match_clock->p)
671                                                 continue;
672
673                                         this_err = abs(clock.dot - target);
674                                         if (this_err < err) {
675                                                 *best_clock = clock;
676                                                 err = this_err;
677                                         }
678                                 }
679                         }
680                 }
681         }
682
683         return (err != target);
684 }
685
686 /*
687  * Returns a set of divisors for the desired target clock with the given
688  * refclk, or FALSE.  The returned values represent the clock equation:
689  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
690  *
691  * Target and reference clocks are specified in kHz.
692  *
693  * If match_clock is provided, then best_clock P divider must match the P
694  * divider from @match_clock used for LVDS downclocking.
695  */
696 static bool
697 pnv_find_best_dpll(const struct intel_limit *limit,
698                    struct intel_crtc_state *crtc_state,
699                    int target, int refclk, struct dpll *match_clock,
700                    struct dpll *best_clock)
701 {
702         struct drm_device *dev = crtc_state->base.crtc->dev;
703         struct dpll clock;
704         int err = target;
705
706         memset(best_clock, 0, sizeof(*best_clock));
707
708         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
709
710         for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max;
711              clock.m1++) {
712                 for (clock.m2 = limit->m2.min;
713                      clock.m2 <= limit->m2.max; clock.m2++) {
714                         for (clock.n = limit->n.min;
715                              clock.n <= limit->n.max; clock.n++) {
716                                 for (clock.p1 = limit->p1.min;
717                                         clock.p1 <= limit->p1.max; clock.p1++) {
718                                         int this_err;
719
720                                         pnv_calc_dpll_params(refclk, &clock);
721                                         if (!intel_PLL_is_valid(to_i915(dev),
722                                                                 limit,
723                                                                 &clock))
724                                                 continue;
725                                         if (match_clock &&
726                                             clock.p != match_clock->p)
727                                                 continue;
728
729                                         this_err = abs(clock.dot - target);
730                                         if (this_err < err) {
731                                                 *best_clock = clock;
732                                                 err = this_err;
733                                         }
734                                 }
735                         }
736                 }
737         }
738
739         return (err != target);
740 }
741
742 /*
743  * Returns a set of divisors for the desired target clock with the given
744  * refclk, or FALSE.  The returned values represent the clock equation:
745  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
746  *
747  * Target and reference clocks are specified in kHz.
748  *
749  * If match_clock is provided, then best_clock P divider must match the P
750  * divider from @match_clock used for LVDS downclocking.
751  */
752 static bool
753 g4x_find_best_dpll(const struct intel_limit *limit,
754                    struct intel_crtc_state *crtc_state,
755                    int target, int refclk, struct dpll *match_clock,
756                    struct dpll *best_clock)
757 {
758         struct drm_device *dev = crtc_state->base.crtc->dev;
759         struct dpll clock;
760         int max_n;
761         bool found = false;
762         /* approximately equals target * 0.00585 */
763         int err_most = (target >> 8) + (target >> 9);
764
765         memset(best_clock, 0, sizeof(*best_clock));
766
767         clock.p2 = i9xx_select_p2_div(limit, crtc_state, target);
768
769         max_n = limit->n.max;
770         /* based on hardware requirement, prefer smaller n to precision */
771         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
772                 /* based on hardware requirement, prefere larger m1,m2 */
773                 for (clock.m1 = limit->m1.max;
774                      clock.m1 >= limit->m1.min; clock.m1--) {
775                         for (clock.m2 = limit->m2.max;
776                              clock.m2 >= limit->m2.min; clock.m2--) {
777                                 for (clock.p1 = limit->p1.max;
778                                      clock.p1 >= limit->p1.min; clock.p1--) {
779                                         int this_err;
780
781                                         i9xx_calc_dpll_params(refclk, &clock);
782                                         if (!intel_PLL_is_valid(to_i915(dev),
783                                                                 limit,
784                                                                 &clock))
785                                                 continue;
786
787                                         this_err = abs(clock.dot - target);
788                                         if (this_err < err_most) {
789                                                 *best_clock = clock;
790                                                 err_most = this_err;
791                                                 max_n = clock.n;
792                                                 found = true;
793                                         }
794                                 }
795                         }
796                 }
797         }
798         return found;
799 }
800
801 /*
802  * Check if the calculated PLL configuration is more optimal compared to the
803  * best configuration and error found so far. Return the calculated error.
804  */
805 static bool vlv_PLL_is_optimal(struct drm_device *dev, int target_freq,
806                                const struct dpll *calculated_clock,
807                                const struct dpll *best_clock,
808                                unsigned int best_error_ppm,
809                                unsigned int *error_ppm)
810 {
811         /*
812          * For CHV ignore the error and consider only the P value.
813          * Prefer a bigger P value based on HW requirements.
814          */
815         if (IS_CHERRYVIEW(to_i915(dev))) {
816                 *error_ppm = 0;
817
818                 return calculated_clock->p > best_clock->p;
819         }
820
821         if (WARN_ON_ONCE(!target_freq))
822                 return false;
823
824         *error_ppm = div_u64(1000000ULL *
825                                 abs(target_freq - calculated_clock->dot),
826                              target_freq);
827         /*
828          * Prefer a better P value over a better (smaller) error if the error
829          * is small. Ensure this preference for future configurations too by
830          * setting the error to 0.
831          */
832         if (*error_ppm < 100 && calculated_clock->p > best_clock->p) {
833                 *error_ppm = 0;
834
835                 return true;
836         }
837
838         return *error_ppm + 10 < best_error_ppm;
839 }
840
841 /*
842  * Returns a set of divisors for the desired target clock with the given
843  * refclk, or FALSE.  The returned values represent the clock equation:
844  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
845  */
846 static bool
847 vlv_find_best_dpll(const struct intel_limit *limit,
848                    struct intel_crtc_state *crtc_state,
849                    int target, int refclk, struct dpll *match_clock,
850                    struct dpll *best_clock)
851 {
852         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
853         struct drm_device *dev = crtc->base.dev;
854         struct dpll clock;
855         unsigned int bestppm = 1000000;
856         /* min update 19.2 MHz */
857         int max_n = min(limit->n.max, refclk / 19200);
858         bool found = false;
859
860         target *= 5; /* fast clock */
861
862         memset(best_clock, 0, sizeof(*best_clock));
863
864         /* based on hardware requirement, prefer smaller n to precision */
865         for (clock.n = limit->n.min; clock.n <= max_n; clock.n++) {
866                 for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
867                         for (clock.p2 = limit->p2.p2_fast; clock.p2 >= limit->p2.p2_slow;
868                              clock.p2 -= clock.p2 > 10 ? 2 : 1) {
869                                 clock.p = clock.p1 * clock.p2;
870                                 /* based on hardware requirement, prefer bigger m1,m2 values */
871                                 for (clock.m1 = limit->m1.min; clock.m1 <= limit->m1.max; clock.m1++) {
872                                         unsigned int ppm;
873
874                                         clock.m2 = DIV_ROUND_CLOSEST(target * clock.p * clock.n,
875                                                                      refclk * clock.m1);
876
877                                         vlv_calc_dpll_params(refclk, &clock);
878
879                                         if (!intel_PLL_is_valid(to_i915(dev),
880                                                                 limit,
881                                                                 &clock))
882                                                 continue;
883
884                                         if (!vlv_PLL_is_optimal(dev, target,
885                                                                 &clock,
886                                                                 best_clock,
887                                                                 bestppm, &ppm))
888                                                 continue;
889
890                                         *best_clock = clock;
891                                         bestppm = ppm;
892                                         found = true;
893                                 }
894                         }
895                 }
896         }
897
898         return found;
899 }
900
901 /*
902  * Returns a set of divisors for the desired target clock with the given
903  * refclk, or FALSE.  The returned values represent the clock equation:
904  * reflck * (5 * (m1 + 2) + (m2 + 2)) / (n + 2) / p1 / p2.
905  */
906 static bool
907 chv_find_best_dpll(const struct intel_limit *limit,
908                    struct intel_crtc_state *crtc_state,
909                    int target, int refclk, struct dpll *match_clock,
910                    struct dpll *best_clock)
911 {
912         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
913         struct drm_device *dev = crtc->base.dev;
914         unsigned int best_error_ppm;
915         struct dpll clock;
916         uint64_t m2;
917         int found = false;
918
919         memset(best_clock, 0, sizeof(*best_clock));
920         best_error_ppm = 1000000;
921
922         /*
923          * Based on hardware doc, the n always set to 1, and m1 always
924          * set to 2.  If requires to support 200Mhz refclk, we need to
925          * revisit this because n may not 1 anymore.
926          */
927         clock.n = 1, clock.m1 = 2;
928         target *= 5;    /* fast clock */
929
930         for (clock.p1 = limit->p1.max; clock.p1 >= limit->p1.min; clock.p1--) {
931                 for (clock.p2 = limit->p2.p2_fast;
932                                 clock.p2 >= limit->p2.p2_slow;
933                                 clock.p2 -= clock.p2 > 10 ? 2 : 1) {
934                         unsigned int error_ppm;
935
936                         clock.p = clock.p1 * clock.p2;
937
938                         m2 = DIV_ROUND_CLOSEST_ULL(((uint64_t)target * clock.p *
939                                         clock.n) << 22, refclk * clock.m1);
940
941                         if (m2 > INT_MAX/clock.m1)
942                                 continue;
943
944                         clock.m2 = m2;
945
946                         chv_calc_dpll_params(refclk, &clock);
947
948                         if (!intel_PLL_is_valid(to_i915(dev), limit, &clock))
949                                 continue;
950
951                         if (!vlv_PLL_is_optimal(dev, target, &clock, best_clock,
952                                                 best_error_ppm, &error_ppm))
953                                 continue;
954
955                         *best_clock = clock;
956                         best_error_ppm = error_ppm;
957                         found = true;
958                 }
959         }
960
961         return found;
962 }
963
964 bool bxt_find_best_dpll(struct intel_crtc_state *crtc_state, int target_clock,
965                         struct dpll *best_clock)
966 {
967         int refclk = 100000;
968         const struct intel_limit *limit = &intel_limits_bxt;
969
970         return chv_find_best_dpll(limit, crtc_state,
971                                   target_clock, refclk, NULL, best_clock);
972 }
973
974 bool intel_crtc_active(struct intel_crtc *crtc)
975 {
976         /* Be paranoid as we can arrive here with only partial
977          * state retrieved from the hardware during setup.
978          *
979          * We can ditch the adjusted_mode.crtc_clock check as soon
980          * as Haswell has gained clock readout/fastboot support.
981          *
982          * We can ditch the crtc->primary->fb check as soon as we can
983          * properly reconstruct framebuffers.
984          *
985          * FIXME: The intel_crtc->active here should be switched to
986          * crtc->state->active once we have proper CRTC states wired up
987          * for atomic.
988          */
989         return crtc->active && crtc->base.primary->state->fb &&
990                 crtc->config->base.adjusted_mode.crtc_clock;
991 }
992
993 enum transcoder intel_pipe_to_cpu_transcoder(struct drm_i915_private *dev_priv,
994                                              enum pipe pipe)
995 {
996         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
997
998         return crtc->config->cpu_transcoder;
999 }
1000
1001 static bool pipe_scanline_is_moving(struct drm_i915_private *dev_priv,
1002                                     enum pipe pipe)
1003 {
1004         i915_reg_t reg = PIPEDSL(pipe);
1005         u32 line1, line2;
1006         u32 line_mask;
1007
1008         if (IS_GEN2(dev_priv))
1009                 line_mask = DSL_LINEMASK_GEN2;
1010         else
1011                 line_mask = DSL_LINEMASK_GEN3;
1012
1013         line1 = I915_READ(reg) & line_mask;
1014         msleep(5);
1015         line2 = I915_READ(reg) & line_mask;
1016
1017         return line1 != line2;
1018 }
1019
1020 static void wait_for_pipe_scanline_moving(struct intel_crtc *crtc, bool state)
1021 {
1022         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1023         enum pipe pipe = crtc->pipe;
1024
1025         /* Wait for the display line to settle/start moving */
1026         if (wait_for(pipe_scanline_is_moving(dev_priv, pipe) == state, 100))
1027                 DRM_ERROR("pipe %c scanline %s wait timed out\n",
1028                           pipe_name(pipe), onoff(state));
1029 }
1030
1031 static void intel_wait_for_pipe_scanline_stopped(struct intel_crtc *crtc)
1032 {
1033         wait_for_pipe_scanline_moving(crtc, false);
1034 }
1035
1036 static void intel_wait_for_pipe_scanline_moving(struct intel_crtc *crtc)
1037 {
1038         wait_for_pipe_scanline_moving(crtc, true);
1039 }
1040
1041 static void
1042 intel_wait_for_pipe_off(const struct intel_crtc_state *old_crtc_state)
1043 {
1044         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1045         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1046
1047         if (INTEL_GEN(dev_priv) >= 4) {
1048                 enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1049                 i915_reg_t reg = PIPECONF(cpu_transcoder);
1050
1051                 /* Wait for the Pipe State to go off */
1052                 if (intel_wait_for_register(dev_priv,
1053                                             reg, I965_PIPECONF_ACTIVE, 0,
1054                                             100))
1055                         WARN(1, "pipe_off wait timed out\n");
1056         } else {
1057                 intel_wait_for_pipe_scanline_stopped(crtc);
1058         }
1059 }
1060
1061 /* Only for pre-ILK configs */
1062 void assert_pll(struct drm_i915_private *dev_priv,
1063                 enum pipe pipe, bool state)
1064 {
1065         u32 val;
1066         bool cur_state;
1067
1068         val = I915_READ(DPLL(pipe));
1069         cur_state = !!(val & DPLL_VCO_ENABLE);
1070         I915_STATE_WARN(cur_state != state,
1071              "PLL state assertion failure (expected %s, current %s)\n",
1072                         onoff(state), onoff(cur_state));
1073 }
1074
1075 /* XXX: the dsi pll is shared between MIPI DSI ports */
1076 void assert_dsi_pll(struct drm_i915_private *dev_priv, bool state)
1077 {
1078         u32 val;
1079         bool cur_state;
1080
1081         mutex_lock(&dev_priv->sb_lock);
1082         val = vlv_cck_read(dev_priv, CCK_REG_DSI_PLL_CONTROL);
1083         mutex_unlock(&dev_priv->sb_lock);
1084
1085         cur_state = val & DSI_PLL_VCO_EN;
1086         I915_STATE_WARN(cur_state != state,
1087              "DSI PLL state assertion failure (expected %s, current %s)\n",
1088                         onoff(state), onoff(cur_state));
1089 }
1090
1091 static void assert_fdi_tx(struct drm_i915_private *dev_priv,
1092                           enum pipe pipe, bool state)
1093 {
1094         bool cur_state;
1095         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1096                                                                       pipe);
1097
1098         if (HAS_DDI(dev_priv)) {
1099                 /* DDI does not have a specific FDI_TX register */
1100                 u32 val = I915_READ(TRANS_DDI_FUNC_CTL(cpu_transcoder));
1101                 cur_state = !!(val & TRANS_DDI_FUNC_ENABLE);
1102         } else {
1103                 u32 val = I915_READ(FDI_TX_CTL(pipe));
1104                 cur_state = !!(val & FDI_TX_ENABLE);
1105         }
1106         I915_STATE_WARN(cur_state != state,
1107              "FDI TX state assertion failure (expected %s, current %s)\n",
1108                         onoff(state), onoff(cur_state));
1109 }
1110 #define assert_fdi_tx_enabled(d, p) assert_fdi_tx(d, p, true)
1111 #define assert_fdi_tx_disabled(d, p) assert_fdi_tx(d, p, false)
1112
1113 static void assert_fdi_rx(struct drm_i915_private *dev_priv,
1114                           enum pipe pipe, bool state)
1115 {
1116         u32 val;
1117         bool cur_state;
1118
1119         val = I915_READ(FDI_RX_CTL(pipe));
1120         cur_state = !!(val & FDI_RX_ENABLE);
1121         I915_STATE_WARN(cur_state != state,
1122              "FDI RX state assertion failure (expected %s, current %s)\n",
1123                         onoff(state), onoff(cur_state));
1124 }
1125 #define assert_fdi_rx_enabled(d, p) assert_fdi_rx(d, p, true)
1126 #define assert_fdi_rx_disabled(d, p) assert_fdi_rx(d, p, false)
1127
1128 static void assert_fdi_tx_pll_enabled(struct drm_i915_private *dev_priv,
1129                                       enum pipe pipe)
1130 {
1131         u32 val;
1132
1133         /* ILK FDI PLL is always enabled */
1134         if (IS_GEN5(dev_priv))
1135                 return;
1136
1137         /* On Haswell, DDI ports are responsible for the FDI PLL setup */
1138         if (HAS_DDI(dev_priv))
1139                 return;
1140
1141         val = I915_READ(FDI_TX_CTL(pipe));
1142         I915_STATE_WARN(!(val & FDI_TX_PLL_ENABLE), "FDI TX PLL assertion failure, should be active but is disabled\n");
1143 }
1144
1145 void assert_fdi_rx_pll(struct drm_i915_private *dev_priv,
1146                        enum pipe pipe, bool state)
1147 {
1148         u32 val;
1149         bool cur_state;
1150
1151         val = I915_READ(FDI_RX_CTL(pipe));
1152         cur_state = !!(val & FDI_RX_PLL_ENABLE);
1153         I915_STATE_WARN(cur_state != state,
1154              "FDI RX PLL assertion failure (expected %s, current %s)\n",
1155                         onoff(state), onoff(cur_state));
1156 }
1157
1158 void assert_panel_unlocked(struct drm_i915_private *dev_priv, enum pipe pipe)
1159 {
1160         i915_reg_t pp_reg;
1161         u32 val;
1162         enum pipe panel_pipe = PIPE_A;
1163         bool locked = true;
1164
1165         if (WARN_ON(HAS_DDI(dev_priv)))
1166                 return;
1167
1168         if (HAS_PCH_SPLIT(dev_priv)) {
1169                 u32 port_sel;
1170
1171                 pp_reg = PP_CONTROL(0);
1172                 port_sel = I915_READ(PP_ON_DELAYS(0)) & PANEL_PORT_SELECT_MASK;
1173
1174                 if (port_sel == PANEL_PORT_SELECT_LVDS &&
1175                     I915_READ(PCH_LVDS) & LVDS_PIPEB_SELECT)
1176                         panel_pipe = PIPE_B;
1177                 /* XXX: else fix for eDP */
1178         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1179                 /* presumably write lock depends on pipe, not port select */
1180                 pp_reg = PP_CONTROL(pipe);
1181                 panel_pipe = pipe;
1182         } else {
1183                 pp_reg = PP_CONTROL(0);
1184                 if (I915_READ(LVDS) & LVDS_PIPEB_SELECT)
1185                         panel_pipe = PIPE_B;
1186         }
1187
1188         val = I915_READ(pp_reg);
1189         if (!(val & PANEL_POWER_ON) ||
1190             ((val & PANEL_UNLOCK_MASK) == PANEL_UNLOCK_REGS))
1191                 locked = false;
1192
1193         I915_STATE_WARN(panel_pipe == pipe && locked,
1194              "panel assertion failure, pipe %c regs locked\n",
1195              pipe_name(pipe));
1196 }
1197
1198 void assert_pipe(struct drm_i915_private *dev_priv,
1199                  enum pipe pipe, bool state)
1200 {
1201         bool cur_state;
1202         enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv,
1203                                                                       pipe);
1204         enum intel_display_power_domain power_domain;
1205
1206         /* we keep both pipes enabled on 830 */
1207         if (IS_I830(dev_priv))
1208                 state = true;
1209
1210         power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
1211         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
1212                 u32 val = I915_READ(PIPECONF(cpu_transcoder));
1213                 cur_state = !!(val & PIPECONF_ENABLE);
1214
1215                 intel_display_power_put(dev_priv, power_domain);
1216         } else {
1217                 cur_state = false;
1218         }
1219
1220         I915_STATE_WARN(cur_state != state,
1221              "pipe %c assertion failure (expected %s, current %s)\n",
1222                         pipe_name(pipe), onoff(state), onoff(cur_state));
1223 }
1224
1225 static void assert_plane(struct intel_plane *plane, bool state)
1226 {
1227         bool cur_state = plane->get_hw_state(plane);
1228
1229         I915_STATE_WARN(cur_state != state,
1230                         "%s assertion failure (expected %s, current %s)\n",
1231                         plane->base.name, onoff(state), onoff(cur_state));
1232 }
1233
1234 #define assert_plane_enabled(p) assert_plane(p, true)
1235 #define assert_plane_disabled(p) assert_plane(p, false)
1236
1237 static void assert_planes_disabled(struct intel_crtc *crtc)
1238 {
1239         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1240         struct intel_plane *plane;
1241
1242         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane)
1243                 assert_plane_disabled(plane);
1244 }
1245
1246 static void assert_vblank_disabled(struct drm_crtc *crtc)
1247 {
1248         if (I915_STATE_WARN_ON(drm_crtc_vblank_get(crtc) == 0))
1249                 drm_crtc_vblank_put(crtc);
1250 }
1251
1252 void assert_pch_transcoder_disabled(struct drm_i915_private *dev_priv,
1253                                     enum pipe pipe)
1254 {
1255         u32 val;
1256         bool enabled;
1257
1258         val = I915_READ(PCH_TRANSCONF(pipe));
1259         enabled = !!(val & TRANS_ENABLE);
1260         I915_STATE_WARN(enabled,
1261              "transcoder assertion failed, should be off on pipe %c but is still active\n",
1262              pipe_name(pipe));
1263 }
1264
1265 static bool dp_pipe_enabled(struct drm_i915_private *dev_priv,
1266                             enum pipe pipe, u32 port_sel, u32 val)
1267 {
1268         if ((val & DP_PORT_EN) == 0)
1269                 return false;
1270
1271         if (HAS_PCH_CPT(dev_priv)) {
1272                 u32 trans_dp_ctl = I915_READ(TRANS_DP_CTL(pipe));
1273                 if ((trans_dp_ctl & TRANS_DP_PORT_SEL_MASK) != port_sel)
1274                         return false;
1275         } else if (IS_CHERRYVIEW(dev_priv)) {
1276                 if ((val & DP_PIPE_MASK_CHV) != DP_PIPE_SELECT_CHV(pipe))
1277                         return false;
1278         } else {
1279                 if ((val & DP_PIPE_MASK) != (pipe << 30))
1280                         return false;
1281         }
1282         return true;
1283 }
1284
1285 static bool hdmi_pipe_enabled(struct drm_i915_private *dev_priv,
1286                               enum pipe pipe, u32 val)
1287 {
1288         if ((val & SDVO_ENABLE) == 0)
1289                 return false;
1290
1291         if (HAS_PCH_CPT(dev_priv)) {
1292                 if ((val & SDVO_PIPE_SEL_MASK_CPT) != SDVO_PIPE_SEL_CPT(pipe))
1293                         return false;
1294         } else if (IS_CHERRYVIEW(dev_priv)) {
1295                 if ((val & SDVO_PIPE_SEL_MASK_CHV) != SDVO_PIPE_SEL_CHV(pipe))
1296                         return false;
1297         } else {
1298                 if ((val & SDVO_PIPE_SEL_MASK) != SDVO_PIPE_SEL(pipe))
1299                         return false;
1300         }
1301         return true;
1302 }
1303
1304 static bool lvds_pipe_enabled(struct drm_i915_private *dev_priv,
1305                               enum pipe pipe, u32 val)
1306 {
1307         if ((val & LVDS_PORT_EN) == 0)
1308                 return false;
1309
1310         if (HAS_PCH_CPT(dev_priv)) {
1311                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1312                         return false;
1313         } else {
1314                 if ((val & LVDS_PIPE_MASK) != LVDS_PIPE(pipe))
1315                         return false;
1316         }
1317         return true;
1318 }
1319
1320 static bool adpa_pipe_enabled(struct drm_i915_private *dev_priv,
1321                               enum pipe pipe, u32 val)
1322 {
1323         if ((val & ADPA_DAC_ENABLE) == 0)
1324                 return false;
1325         if (HAS_PCH_CPT(dev_priv)) {
1326                 if ((val & PORT_TRANS_SEL_MASK) != PORT_TRANS_SEL_CPT(pipe))
1327                         return false;
1328         } else {
1329                 if ((val & ADPA_PIPE_SELECT_MASK) != ADPA_PIPE_SELECT(pipe))
1330                         return false;
1331         }
1332         return true;
1333 }
1334
1335 static void assert_pch_dp_disabled(struct drm_i915_private *dev_priv,
1336                                    enum pipe pipe, i915_reg_t reg,
1337                                    u32 port_sel)
1338 {
1339         u32 val = I915_READ(reg);
1340         I915_STATE_WARN(dp_pipe_enabled(dev_priv, pipe, port_sel, val),
1341              "PCH DP (0x%08x) enabled on transcoder %c, should be disabled\n",
1342              i915_mmio_reg_offset(reg), pipe_name(pipe));
1343
1344         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & DP_PORT_EN) == 0
1345              && (val & DP_PIPEB_SELECT),
1346              "IBX PCH dp port still using transcoder B\n");
1347 }
1348
1349 static void assert_pch_hdmi_disabled(struct drm_i915_private *dev_priv,
1350                                      enum pipe pipe, i915_reg_t reg)
1351 {
1352         u32 val = I915_READ(reg);
1353         I915_STATE_WARN(hdmi_pipe_enabled(dev_priv, pipe, val),
1354              "PCH HDMI (0x%08x) enabled on transcoder %c, should be disabled\n",
1355              i915_mmio_reg_offset(reg), pipe_name(pipe));
1356
1357         I915_STATE_WARN(HAS_PCH_IBX(dev_priv) && (val & SDVO_ENABLE) == 0
1358              && (val & SDVO_PIPE_B_SELECT),
1359              "IBX PCH hdmi port still using transcoder B\n");
1360 }
1361
1362 static void assert_pch_ports_disabled(struct drm_i915_private *dev_priv,
1363                                       enum pipe pipe)
1364 {
1365         u32 val;
1366
1367         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_B, TRANS_DP_PORT_SEL_B);
1368         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_C, TRANS_DP_PORT_SEL_C);
1369         assert_pch_dp_disabled(dev_priv, pipe, PCH_DP_D, TRANS_DP_PORT_SEL_D);
1370
1371         val = I915_READ(PCH_ADPA);
1372         I915_STATE_WARN(adpa_pipe_enabled(dev_priv, pipe, val),
1373              "PCH VGA enabled on transcoder %c, should be disabled\n",
1374              pipe_name(pipe));
1375
1376         val = I915_READ(PCH_LVDS);
1377         I915_STATE_WARN(lvds_pipe_enabled(dev_priv, pipe, val),
1378              "PCH LVDS enabled on transcoder %c, should be disabled\n",
1379              pipe_name(pipe));
1380
1381         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIB);
1382         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMIC);
1383         assert_pch_hdmi_disabled(dev_priv, pipe, PCH_HDMID);
1384 }
1385
1386 static void _vlv_enable_pll(struct intel_crtc *crtc,
1387                             const struct intel_crtc_state *pipe_config)
1388 {
1389         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1390         enum pipe pipe = crtc->pipe;
1391
1392         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1393         POSTING_READ(DPLL(pipe));
1394         udelay(150);
1395
1396         if (intel_wait_for_register(dev_priv,
1397                                     DPLL(pipe),
1398                                     DPLL_LOCK_VLV,
1399                                     DPLL_LOCK_VLV,
1400                                     1))
1401                 DRM_ERROR("DPLL %d failed to lock\n", pipe);
1402 }
1403
1404 static void vlv_enable_pll(struct intel_crtc *crtc,
1405                            const struct intel_crtc_state *pipe_config)
1406 {
1407         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1408         enum pipe pipe = crtc->pipe;
1409
1410         assert_pipe_disabled(dev_priv, pipe);
1411
1412         /* PLL is protected by panel, make sure we can write it */
1413         assert_panel_unlocked(dev_priv, pipe);
1414
1415         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1416                 _vlv_enable_pll(crtc, pipe_config);
1417
1418         I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1419         POSTING_READ(DPLL_MD(pipe));
1420 }
1421
1422
1423 static void _chv_enable_pll(struct intel_crtc *crtc,
1424                             const struct intel_crtc_state *pipe_config)
1425 {
1426         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1427         enum pipe pipe = crtc->pipe;
1428         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1429         u32 tmp;
1430
1431         mutex_lock(&dev_priv->sb_lock);
1432
1433         /* Enable back the 10bit clock to display controller */
1434         tmp = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1435         tmp |= DPIO_DCLKP_EN;
1436         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), tmp);
1437
1438         mutex_unlock(&dev_priv->sb_lock);
1439
1440         /*
1441          * Need to wait > 100ns between dclkp clock enable bit and PLL enable.
1442          */
1443         udelay(1);
1444
1445         /* Enable PLL */
1446         I915_WRITE(DPLL(pipe), pipe_config->dpll_hw_state.dpll);
1447
1448         /* Check PLL is locked */
1449         if (intel_wait_for_register(dev_priv,
1450                                     DPLL(pipe), DPLL_LOCK_VLV, DPLL_LOCK_VLV,
1451                                     1))
1452                 DRM_ERROR("PLL %d failed to lock\n", pipe);
1453 }
1454
1455 static void chv_enable_pll(struct intel_crtc *crtc,
1456                            const struct intel_crtc_state *pipe_config)
1457 {
1458         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1459         enum pipe pipe = crtc->pipe;
1460
1461         assert_pipe_disabled(dev_priv, pipe);
1462
1463         /* PLL is protected by panel, make sure we can write it */
1464         assert_panel_unlocked(dev_priv, pipe);
1465
1466         if (pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE)
1467                 _chv_enable_pll(crtc, pipe_config);
1468
1469         if (pipe != PIPE_A) {
1470                 /*
1471                  * WaPixelRepeatModeFixForC0:chv
1472                  *
1473                  * DPLLCMD is AWOL. Use chicken bits to propagate
1474                  * the value from DPLLBMD to either pipe B or C.
1475                  */
1476                 I915_WRITE(CBR4_VLV, CBR_DPLLBMD_PIPE(pipe));
1477                 I915_WRITE(DPLL_MD(PIPE_B), pipe_config->dpll_hw_state.dpll_md);
1478                 I915_WRITE(CBR4_VLV, 0);
1479                 dev_priv->chv_dpll_md[pipe] = pipe_config->dpll_hw_state.dpll_md;
1480
1481                 /*
1482                  * DPLLB VGA mode also seems to cause problems.
1483                  * We should always have it disabled.
1484                  */
1485                 WARN_ON((I915_READ(DPLL(PIPE_B)) & DPLL_VGA_MODE_DIS) == 0);
1486         } else {
1487                 I915_WRITE(DPLL_MD(pipe), pipe_config->dpll_hw_state.dpll_md);
1488                 POSTING_READ(DPLL_MD(pipe));
1489         }
1490 }
1491
1492 static int intel_num_dvo_pipes(struct drm_i915_private *dev_priv)
1493 {
1494         struct intel_crtc *crtc;
1495         int count = 0;
1496
1497         for_each_intel_crtc(&dev_priv->drm, crtc) {
1498                 count += crtc->base.state->active &&
1499                         intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO);
1500         }
1501
1502         return count;
1503 }
1504
1505 static void i9xx_enable_pll(struct intel_crtc *crtc,
1506                             const struct intel_crtc_state *crtc_state)
1507 {
1508         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1509         i915_reg_t reg = DPLL(crtc->pipe);
1510         u32 dpll = crtc_state->dpll_hw_state.dpll;
1511         int i;
1512
1513         assert_pipe_disabled(dev_priv, crtc->pipe);
1514
1515         /* PLL is protected by panel, make sure we can write it */
1516         if (IS_MOBILE(dev_priv) && !IS_I830(dev_priv))
1517                 assert_panel_unlocked(dev_priv, crtc->pipe);
1518
1519         /* Enable DVO 2x clock on both PLLs if necessary */
1520         if (IS_I830(dev_priv) && intel_num_dvo_pipes(dev_priv) > 0) {
1521                 /*
1522                  * It appears to be important that we don't enable this
1523                  * for the current pipe before otherwise configuring the
1524                  * PLL. No idea how this should be handled if multiple
1525                  * DVO outputs are enabled simultaneosly.
1526                  */
1527                 dpll |= DPLL_DVO_2X_MODE;
1528                 I915_WRITE(DPLL(!crtc->pipe),
1529                            I915_READ(DPLL(!crtc->pipe)) | DPLL_DVO_2X_MODE);
1530         }
1531
1532         /*
1533          * Apparently we need to have VGA mode enabled prior to changing
1534          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
1535          * dividers, even though the register value does change.
1536          */
1537         I915_WRITE(reg, 0);
1538
1539         I915_WRITE(reg, dpll);
1540
1541         /* Wait for the clocks to stabilize. */
1542         POSTING_READ(reg);
1543         udelay(150);
1544
1545         if (INTEL_GEN(dev_priv) >= 4) {
1546                 I915_WRITE(DPLL_MD(crtc->pipe),
1547                            crtc_state->dpll_hw_state.dpll_md);
1548         } else {
1549                 /* The pixel multiplier can only be updated once the
1550                  * DPLL is enabled and the clocks are stable.
1551                  *
1552                  * So write it again.
1553                  */
1554                 I915_WRITE(reg, dpll);
1555         }
1556
1557         /* We do this three times for luck */
1558         for (i = 0; i < 3; i++) {
1559                 I915_WRITE(reg, dpll);
1560                 POSTING_READ(reg);
1561                 udelay(150); /* wait for warmup */
1562         }
1563 }
1564
1565 static void i9xx_disable_pll(struct intel_crtc *crtc)
1566 {
1567         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1568         enum pipe pipe = crtc->pipe;
1569
1570         /* Disable DVO 2x clock on both PLLs if necessary */
1571         if (IS_I830(dev_priv) &&
1572             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_DVO) &&
1573             !intel_num_dvo_pipes(dev_priv)) {
1574                 I915_WRITE(DPLL(PIPE_B),
1575                            I915_READ(DPLL(PIPE_B)) & ~DPLL_DVO_2X_MODE);
1576                 I915_WRITE(DPLL(PIPE_A),
1577                            I915_READ(DPLL(PIPE_A)) & ~DPLL_DVO_2X_MODE);
1578         }
1579
1580         /* Don't disable pipe or pipe PLLs if needed */
1581         if (IS_I830(dev_priv))
1582                 return;
1583
1584         /* Make sure the pipe isn't still relying on us */
1585         assert_pipe_disabled(dev_priv, pipe);
1586
1587         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
1588         POSTING_READ(DPLL(pipe));
1589 }
1590
1591 static void vlv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1592 {
1593         u32 val;
1594
1595         /* Make sure the pipe isn't still relying on us */
1596         assert_pipe_disabled(dev_priv, pipe);
1597
1598         val = DPLL_INTEGRATED_REF_CLK_VLV |
1599                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1600         if (pipe != PIPE_A)
1601                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1602
1603         I915_WRITE(DPLL(pipe), val);
1604         POSTING_READ(DPLL(pipe));
1605 }
1606
1607 static void chv_disable_pll(struct drm_i915_private *dev_priv, enum pipe pipe)
1608 {
1609         enum dpio_channel port = vlv_pipe_to_channel(pipe);
1610         u32 val;
1611
1612         /* Make sure the pipe isn't still relying on us */
1613         assert_pipe_disabled(dev_priv, pipe);
1614
1615         val = DPLL_SSC_REF_CLK_CHV |
1616                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
1617         if (pipe != PIPE_A)
1618                 val |= DPLL_INTEGRATED_CRI_CLK_VLV;
1619
1620         I915_WRITE(DPLL(pipe), val);
1621         POSTING_READ(DPLL(pipe));
1622
1623         mutex_lock(&dev_priv->sb_lock);
1624
1625         /* Disable 10bit clock to display controller */
1626         val = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port));
1627         val &= ~DPIO_DCLKP_EN;
1628         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port), val);
1629
1630         mutex_unlock(&dev_priv->sb_lock);
1631 }
1632
1633 void vlv_wait_port_ready(struct drm_i915_private *dev_priv,
1634                          struct intel_digital_port *dport,
1635                          unsigned int expected_mask)
1636 {
1637         u32 port_mask;
1638         i915_reg_t dpll_reg;
1639
1640         switch (dport->base.port) {
1641         case PORT_B:
1642                 port_mask = DPLL_PORTB_READY_MASK;
1643                 dpll_reg = DPLL(0);
1644                 break;
1645         case PORT_C:
1646                 port_mask = DPLL_PORTC_READY_MASK;
1647                 dpll_reg = DPLL(0);
1648                 expected_mask <<= 4;
1649                 break;
1650         case PORT_D:
1651                 port_mask = DPLL_PORTD_READY_MASK;
1652                 dpll_reg = DPIO_PHY_STATUS;
1653                 break;
1654         default:
1655                 BUG();
1656         }
1657
1658         if (intel_wait_for_register(dev_priv,
1659                                     dpll_reg, port_mask, expected_mask,
1660                                     1000))
1661                 WARN(1, "timed out waiting for port %c ready: got 0x%x, expected 0x%x\n",
1662                      port_name(dport->base.port),
1663                      I915_READ(dpll_reg) & port_mask, expected_mask);
1664 }
1665
1666 static void ironlake_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1667                                            enum pipe pipe)
1668 {
1669         struct intel_crtc *intel_crtc = intel_get_crtc_for_pipe(dev_priv,
1670                                                                 pipe);
1671         i915_reg_t reg;
1672         uint32_t val, pipeconf_val;
1673
1674         /* Make sure PCH DPLL is enabled */
1675         assert_shared_dpll_enabled(dev_priv, intel_crtc->config->shared_dpll);
1676
1677         /* FDI must be feeding us bits for PCH ports */
1678         assert_fdi_tx_enabled(dev_priv, pipe);
1679         assert_fdi_rx_enabled(dev_priv, pipe);
1680
1681         if (HAS_PCH_CPT(dev_priv)) {
1682                 /* Workaround: Set the timing override bit before enabling the
1683                  * pch transcoder. */
1684                 reg = TRANS_CHICKEN2(pipe);
1685                 val = I915_READ(reg);
1686                 val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1687                 I915_WRITE(reg, val);
1688         }
1689
1690         reg = PCH_TRANSCONF(pipe);
1691         val = I915_READ(reg);
1692         pipeconf_val = I915_READ(PIPECONF(pipe));
1693
1694         if (HAS_PCH_IBX(dev_priv)) {
1695                 /*
1696                  * Make the BPC in transcoder be consistent with
1697                  * that in pipeconf reg. For HDMI we must use 8bpc
1698                  * here for both 8bpc and 12bpc.
1699                  */
1700                 val &= ~PIPECONF_BPC_MASK;
1701                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_HDMI))
1702                         val |= PIPECONF_8BPC;
1703                 else
1704                         val |= pipeconf_val & PIPECONF_BPC_MASK;
1705         }
1706
1707         val &= ~TRANS_INTERLACE_MASK;
1708         if ((pipeconf_val & PIPECONF_INTERLACE_MASK) == PIPECONF_INTERLACED_ILK)
1709                 if (HAS_PCH_IBX(dev_priv) &&
1710                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
1711                         val |= TRANS_LEGACY_INTERLACED_ILK;
1712                 else
1713                         val |= TRANS_INTERLACED;
1714         else
1715                 val |= TRANS_PROGRESSIVE;
1716
1717         I915_WRITE(reg, val | TRANS_ENABLE);
1718         if (intel_wait_for_register(dev_priv,
1719                                     reg, TRANS_STATE_ENABLE, TRANS_STATE_ENABLE,
1720                                     100))
1721                 DRM_ERROR("failed to enable transcoder %c\n", pipe_name(pipe));
1722 }
1723
1724 static void lpt_enable_pch_transcoder(struct drm_i915_private *dev_priv,
1725                                       enum transcoder cpu_transcoder)
1726 {
1727         u32 val, pipeconf_val;
1728
1729         /* FDI must be feeding us bits for PCH ports */
1730         assert_fdi_tx_enabled(dev_priv, (enum pipe) cpu_transcoder);
1731         assert_fdi_rx_enabled(dev_priv, PIPE_A);
1732
1733         /* Workaround: set timing override bit. */
1734         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1735         val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
1736         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1737
1738         val = TRANS_ENABLE;
1739         pipeconf_val = I915_READ(PIPECONF(cpu_transcoder));
1740
1741         if ((pipeconf_val & PIPECONF_INTERLACE_MASK_HSW) ==
1742             PIPECONF_INTERLACED_ILK)
1743                 val |= TRANS_INTERLACED;
1744         else
1745                 val |= TRANS_PROGRESSIVE;
1746
1747         I915_WRITE(LPT_TRANSCONF, val);
1748         if (intel_wait_for_register(dev_priv,
1749                                     LPT_TRANSCONF,
1750                                     TRANS_STATE_ENABLE,
1751                                     TRANS_STATE_ENABLE,
1752                                     100))
1753                 DRM_ERROR("Failed to enable PCH transcoder\n");
1754 }
1755
1756 static void ironlake_disable_pch_transcoder(struct drm_i915_private *dev_priv,
1757                                             enum pipe pipe)
1758 {
1759         i915_reg_t reg;
1760         uint32_t val;
1761
1762         /* FDI relies on the transcoder */
1763         assert_fdi_tx_disabled(dev_priv, pipe);
1764         assert_fdi_rx_disabled(dev_priv, pipe);
1765
1766         /* Ports must be off as well */
1767         assert_pch_ports_disabled(dev_priv, pipe);
1768
1769         reg = PCH_TRANSCONF(pipe);
1770         val = I915_READ(reg);
1771         val &= ~TRANS_ENABLE;
1772         I915_WRITE(reg, val);
1773         /* wait for PCH transcoder off, transcoder state */
1774         if (intel_wait_for_register(dev_priv,
1775                                     reg, TRANS_STATE_ENABLE, 0,
1776                                     50))
1777                 DRM_ERROR("failed to disable transcoder %c\n", pipe_name(pipe));
1778
1779         if (HAS_PCH_CPT(dev_priv)) {
1780                 /* Workaround: Clear the timing override chicken bit again. */
1781                 reg = TRANS_CHICKEN2(pipe);
1782                 val = I915_READ(reg);
1783                 val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1784                 I915_WRITE(reg, val);
1785         }
1786 }
1787
1788 void lpt_disable_pch_transcoder(struct drm_i915_private *dev_priv)
1789 {
1790         u32 val;
1791
1792         val = I915_READ(LPT_TRANSCONF);
1793         val &= ~TRANS_ENABLE;
1794         I915_WRITE(LPT_TRANSCONF, val);
1795         /* wait for PCH transcoder off, transcoder state */
1796         if (intel_wait_for_register(dev_priv,
1797                                     LPT_TRANSCONF, TRANS_STATE_ENABLE, 0,
1798                                     50))
1799                 DRM_ERROR("Failed to disable PCH transcoder\n");
1800
1801         /* Workaround: clear timing override bit. */
1802         val = I915_READ(TRANS_CHICKEN2(PIPE_A));
1803         val &= ~TRANS_CHICKEN2_TIMING_OVERRIDE;
1804         I915_WRITE(TRANS_CHICKEN2(PIPE_A), val);
1805 }
1806
1807 enum pipe intel_crtc_pch_transcoder(struct intel_crtc *crtc)
1808 {
1809         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1810
1811         if (HAS_PCH_LPT(dev_priv))
1812                 return PIPE_A;
1813         else
1814                 return crtc->pipe;
1815 }
1816
1817 static void intel_enable_pipe(const struct intel_crtc_state *new_crtc_state)
1818 {
1819         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
1820         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1821         enum transcoder cpu_transcoder = new_crtc_state->cpu_transcoder;
1822         enum pipe pipe = crtc->pipe;
1823         i915_reg_t reg;
1824         u32 val;
1825
1826         DRM_DEBUG_KMS("enabling pipe %c\n", pipe_name(pipe));
1827
1828         assert_planes_disabled(crtc);
1829
1830         /*
1831          * A pipe without a PLL won't actually be able to drive bits from
1832          * a plane.  On ILK+ the pipe PLLs are integrated, so we don't
1833          * need the check.
1834          */
1835         if (HAS_GMCH_DISPLAY(dev_priv)) {
1836                 if (intel_crtc_has_type(new_crtc_state, INTEL_OUTPUT_DSI))
1837                         assert_dsi_pll_enabled(dev_priv);
1838                 else
1839                         assert_pll_enabled(dev_priv, pipe);
1840         } else {
1841                 if (new_crtc_state->has_pch_encoder) {
1842                         /* if driving the PCH, we need FDI enabled */
1843                         assert_fdi_rx_pll_enabled(dev_priv,
1844                                                   intel_crtc_pch_transcoder(crtc));
1845                         assert_fdi_tx_pll_enabled(dev_priv,
1846                                                   (enum pipe) cpu_transcoder);
1847                 }
1848                 /* FIXME: assert CPU port conditions for SNB+ */
1849         }
1850
1851         reg = PIPECONF(cpu_transcoder);
1852         val = I915_READ(reg);
1853         if (val & PIPECONF_ENABLE) {
1854                 /* we keep both pipes enabled on 830 */
1855                 WARN_ON(!IS_I830(dev_priv));
1856                 return;
1857         }
1858
1859         I915_WRITE(reg, val | PIPECONF_ENABLE);
1860         POSTING_READ(reg);
1861
1862         /*
1863          * Until the pipe starts PIPEDSL reads will return a stale value,
1864          * which causes an apparent vblank timestamp jump when PIPEDSL
1865          * resets to its proper value. That also messes up the frame count
1866          * when it's derived from the timestamps. So let's wait for the
1867          * pipe to start properly before we call drm_crtc_vblank_on()
1868          */
1869         if (dev_priv->drm.max_vblank_count == 0)
1870                 intel_wait_for_pipe_scanline_moving(crtc);
1871 }
1872
1873 static void intel_disable_pipe(const struct intel_crtc_state *old_crtc_state)
1874 {
1875         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
1876         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
1877         enum transcoder cpu_transcoder = old_crtc_state->cpu_transcoder;
1878         enum pipe pipe = crtc->pipe;
1879         i915_reg_t reg;
1880         u32 val;
1881
1882         DRM_DEBUG_KMS("disabling pipe %c\n", pipe_name(pipe));
1883
1884         /*
1885          * Make sure planes won't keep trying to pump pixels to us,
1886          * or we might hang the display.
1887          */
1888         assert_planes_disabled(crtc);
1889
1890         reg = PIPECONF(cpu_transcoder);
1891         val = I915_READ(reg);
1892         if ((val & PIPECONF_ENABLE) == 0)
1893                 return;
1894
1895         /*
1896          * Double wide has implications for planes
1897          * so best keep it disabled when not needed.
1898          */
1899         if (old_crtc_state->double_wide)
1900                 val &= ~PIPECONF_DOUBLE_WIDE;
1901
1902         /* Don't disable pipe or pipe PLLs if needed */
1903         if (!IS_I830(dev_priv))
1904                 val &= ~PIPECONF_ENABLE;
1905
1906         I915_WRITE(reg, val);
1907         if ((val & PIPECONF_ENABLE) == 0)
1908                 intel_wait_for_pipe_off(old_crtc_state);
1909 }
1910
1911 static unsigned int intel_tile_size(const struct drm_i915_private *dev_priv)
1912 {
1913         return IS_GEN2(dev_priv) ? 2048 : 4096;
1914 }
1915
1916 static unsigned int
1917 intel_tile_width_bytes(const struct drm_framebuffer *fb, int plane)
1918 {
1919         struct drm_i915_private *dev_priv = to_i915(fb->dev);
1920         unsigned int cpp = fb->format->cpp[plane];
1921
1922         switch (fb->modifier) {
1923         case DRM_FORMAT_MOD_LINEAR:
1924                 return cpp;
1925         case I915_FORMAT_MOD_X_TILED:
1926                 if (IS_GEN2(dev_priv))
1927                         return 128;
1928                 else
1929                         return 512;
1930         case I915_FORMAT_MOD_Y_TILED_CCS:
1931                 if (plane == 1)
1932                         return 128;
1933                 /* fall through */
1934         case I915_FORMAT_MOD_Y_TILED:
1935                 if (IS_GEN2(dev_priv) || HAS_128_BYTE_Y_TILING(dev_priv))
1936                         return 128;
1937                 else
1938                         return 512;
1939         case I915_FORMAT_MOD_Yf_TILED_CCS:
1940                 if (plane == 1)
1941                         return 128;
1942                 /* fall through */
1943         case I915_FORMAT_MOD_Yf_TILED:
1944                 switch (cpp) {
1945                 case 1:
1946                         return 64;
1947                 case 2:
1948                 case 4:
1949                         return 128;
1950                 case 8:
1951                 case 16:
1952                         return 256;
1953                 default:
1954                         MISSING_CASE(cpp);
1955                         return cpp;
1956                 }
1957                 break;
1958         default:
1959                 MISSING_CASE(fb->modifier);
1960                 return cpp;
1961         }
1962 }
1963
1964 static unsigned int
1965 intel_tile_height(const struct drm_framebuffer *fb, int plane)
1966 {
1967         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
1968                 return 1;
1969         else
1970                 return intel_tile_size(to_i915(fb->dev)) /
1971                         intel_tile_width_bytes(fb, plane);
1972 }
1973
1974 /* Return the tile dimensions in pixel units */
1975 static void intel_tile_dims(const struct drm_framebuffer *fb, int plane,
1976                             unsigned int *tile_width,
1977                             unsigned int *tile_height)
1978 {
1979         unsigned int tile_width_bytes = intel_tile_width_bytes(fb, plane);
1980         unsigned int cpp = fb->format->cpp[plane];
1981
1982         *tile_width = tile_width_bytes / cpp;
1983         *tile_height = intel_tile_size(to_i915(fb->dev)) / tile_width_bytes;
1984 }
1985
1986 unsigned int
1987 intel_fb_align_height(const struct drm_framebuffer *fb,
1988                       int plane, unsigned int height)
1989 {
1990         unsigned int tile_height = intel_tile_height(fb, plane);
1991
1992         return ALIGN(height, tile_height);
1993 }
1994
1995 unsigned int intel_rotation_info_size(const struct intel_rotation_info *rot_info)
1996 {
1997         unsigned int size = 0;
1998         int i;
1999
2000         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
2001                 size += rot_info->plane[i].width * rot_info->plane[i].height;
2002
2003         return size;
2004 }
2005
2006 static void
2007 intel_fill_fb_ggtt_view(struct i915_ggtt_view *view,
2008                         const struct drm_framebuffer *fb,
2009                         unsigned int rotation)
2010 {
2011         view->type = I915_GGTT_VIEW_NORMAL;
2012         if (drm_rotation_90_or_270(rotation)) {
2013                 view->type = I915_GGTT_VIEW_ROTATED;
2014                 view->rotated = to_intel_framebuffer(fb)->rot_info;
2015         }
2016 }
2017
2018 static unsigned int intel_cursor_alignment(const struct drm_i915_private *dev_priv)
2019 {
2020         if (IS_I830(dev_priv))
2021                 return 16 * 1024;
2022         else if (IS_I85X(dev_priv))
2023                 return 256;
2024         else if (IS_I845G(dev_priv) || IS_I865G(dev_priv))
2025                 return 32;
2026         else
2027                 return 4 * 1024;
2028 }
2029
2030 static unsigned int intel_linear_alignment(const struct drm_i915_private *dev_priv)
2031 {
2032         if (INTEL_GEN(dev_priv) >= 9)
2033                 return 256 * 1024;
2034         else if (IS_I965G(dev_priv) || IS_I965GM(dev_priv) ||
2035                  IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2036                 return 128 * 1024;
2037         else if (INTEL_GEN(dev_priv) >= 4)
2038                 return 4 * 1024;
2039         else
2040                 return 0;
2041 }
2042
2043 static unsigned int intel_surf_alignment(const struct drm_framebuffer *fb,
2044                                          int plane)
2045 {
2046         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2047
2048         /* AUX_DIST needs only 4K alignment */
2049         if (plane == 1)
2050                 return 4096;
2051
2052         switch (fb->modifier) {
2053         case DRM_FORMAT_MOD_LINEAR:
2054                 return intel_linear_alignment(dev_priv);
2055         case I915_FORMAT_MOD_X_TILED:
2056                 if (INTEL_GEN(dev_priv) >= 9)
2057                         return 256 * 1024;
2058                 return 0;
2059         case I915_FORMAT_MOD_Y_TILED_CCS:
2060         case I915_FORMAT_MOD_Yf_TILED_CCS:
2061         case I915_FORMAT_MOD_Y_TILED:
2062         case I915_FORMAT_MOD_Yf_TILED:
2063                 return 1 * 1024 * 1024;
2064         default:
2065                 MISSING_CASE(fb->modifier);
2066                 return 0;
2067         }
2068 }
2069
2070 static bool intel_plane_uses_fence(const struct intel_plane_state *plane_state)
2071 {
2072         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2073         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
2074
2075         return INTEL_GEN(dev_priv) < 4 || plane->has_fbc;
2076 }
2077
2078 struct i915_vma *
2079 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb,
2080                            unsigned int rotation,
2081                            bool uses_fence,
2082                            unsigned long *out_flags)
2083 {
2084         struct drm_device *dev = fb->dev;
2085         struct drm_i915_private *dev_priv = to_i915(dev);
2086         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2087         struct i915_ggtt_view view;
2088         struct i915_vma *vma;
2089         unsigned int pinctl;
2090         u32 alignment;
2091
2092         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2093
2094         alignment = intel_surf_alignment(fb, 0);
2095
2096         intel_fill_fb_ggtt_view(&view, fb, rotation);
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                         vma = ERR_PTR(ret);
2156                         goto err;
2157                 }
2158
2159                 if (ret == 0 && vma->fence)
2160                         *out_flags |= PLANE_HAS_FENCE;
2161         }
2162
2163         i915_vma_get(vma);
2164 err:
2165         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2166
2167         intel_runtime_pm_put(dev_priv);
2168         return vma;
2169 }
2170
2171 void intel_unpin_fb_vma(struct i915_vma *vma, unsigned long flags)
2172 {
2173         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2174
2175         if (flags & PLANE_HAS_FENCE)
2176                 i915_vma_unpin_fence(vma);
2177         i915_gem_object_unpin_from_display_plane(vma);
2178         i915_vma_put(vma);
2179 }
2180
2181 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2182                           unsigned int rotation)
2183 {
2184         if (drm_rotation_90_or_270(rotation))
2185                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2186         else
2187                 return fb->pitches[plane];
2188 }
2189
2190 /*
2191  * Convert the x/y offsets into a linear offset.
2192  * Only valid with 0/180 degree rotation, which is fine since linear
2193  * offset is only used with linear buffers on pre-hsw and tiled buffers
2194  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2195  */
2196 u32 intel_fb_xy_to_linear(int x, int y,
2197                           const struct intel_plane_state *state,
2198                           int plane)
2199 {
2200         const struct drm_framebuffer *fb = state->base.fb;
2201         unsigned int cpp = fb->format->cpp[plane];
2202         unsigned int pitch = fb->pitches[plane];
2203
2204         return y * pitch + x * cpp;
2205 }
2206
2207 /*
2208  * Add the x/y offsets derived from fb->offsets[] to the user
2209  * specified plane src x/y offsets. The resulting x/y offsets
2210  * specify the start of scanout from the beginning of the gtt mapping.
2211  */
2212 void intel_add_fb_offsets(int *x, int *y,
2213                           const struct intel_plane_state *state,
2214                           int plane)
2215
2216 {
2217         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2218         unsigned int rotation = state->base.rotation;
2219
2220         if (drm_rotation_90_or_270(rotation)) {
2221                 *x += intel_fb->rotated[plane].x;
2222                 *y += intel_fb->rotated[plane].y;
2223         } else {
2224                 *x += intel_fb->normal[plane].x;
2225                 *y += intel_fb->normal[plane].y;
2226         }
2227 }
2228
2229 static u32 __intel_adjust_tile_offset(int *x, int *y,
2230                                       unsigned int tile_width,
2231                                       unsigned int tile_height,
2232                                       unsigned int tile_size,
2233                                       unsigned int pitch_tiles,
2234                                       u32 old_offset,
2235                                       u32 new_offset)
2236 {
2237         unsigned int pitch_pixels = pitch_tiles * tile_width;
2238         unsigned int tiles;
2239
2240         WARN_ON(old_offset & (tile_size - 1));
2241         WARN_ON(new_offset & (tile_size - 1));
2242         WARN_ON(new_offset > old_offset);
2243
2244         tiles = (old_offset - new_offset) / tile_size;
2245
2246         *y += tiles / pitch_tiles * tile_height;
2247         *x += tiles % pitch_tiles * tile_width;
2248
2249         /* minimize x in case it got needlessly big */
2250         *y += *x / pitch_pixels * tile_height;
2251         *x %= pitch_pixels;
2252
2253         return new_offset;
2254 }
2255
2256 static u32 _intel_adjust_tile_offset(int *x, int *y,
2257                                      const struct drm_framebuffer *fb, int plane,
2258                                      unsigned int rotation,
2259                                      u32 old_offset, u32 new_offset)
2260 {
2261         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2262         unsigned int cpp = fb->format->cpp[plane];
2263         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2264
2265         WARN_ON(new_offset > old_offset);
2266
2267         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2268                 unsigned int tile_size, tile_width, tile_height;
2269                 unsigned int pitch_tiles;
2270
2271                 tile_size = intel_tile_size(dev_priv);
2272                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2273
2274                 if (drm_rotation_90_or_270(rotation)) {
2275                         pitch_tiles = pitch / tile_height;
2276                         swap(tile_width, tile_height);
2277                 } else {
2278                         pitch_tiles = pitch / (tile_width * cpp);
2279                 }
2280
2281                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2282                                            tile_size, pitch_tiles,
2283                                            old_offset, new_offset);
2284         } else {
2285                 old_offset += *y * pitch + *x * cpp;
2286
2287                 *y = (old_offset - new_offset) / pitch;
2288                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2289         }
2290
2291         return new_offset;
2292 }
2293
2294 /*
2295  * Adjust the tile offset by moving the difference into
2296  * the x/y offsets.
2297  */
2298 static u32 intel_adjust_tile_offset(int *x, int *y,
2299                                     const struct intel_plane_state *state, int plane,
2300                                     u32 old_offset, u32 new_offset)
2301 {
2302         return _intel_adjust_tile_offset(x, y, state->base.fb, plane,
2303                                          state->base.rotation,
2304                                          old_offset, new_offset);
2305 }
2306
2307 /*
2308  * Computes the linear offset to the base tile and adjusts
2309  * x, y. bytes per pixel is assumed to be a power-of-two.
2310  *
2311  * In the 90/270 rotated case, x and y are assumed
2312  * to be already rotated to match the rotated GTT view, and
2313  * pitch is the tile_height aligned framebuffer height.
2314  *
2315  * This function is used when computing the derived information
2316  * under intel_framebuffer, so using any of that information
2317  * here is not allowed. Anything under drm_framebuffer can be
2318  * used. This is why the user has to pass in the pitch since it
2319  * is specified in the rotated orientation.
2320  */
2321 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2322                                       int *x, int *y,
2323                                       const struct drm_framebuffer *fb, int plane,
2324                                       unsigned int pitch,
2325                                       unsigned int rotation,
2326                                       u32 alignment)
2327 {
2328         uint64_t fb_modifier = fb->modifier;
2329         unsigned int cpp = fb->format->cpp[plane];
2330         u32 offset, offset_aligned;
2331
2332         if (alignment)
2333                 alignment--;
2334
2335         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2336                 unsigned int tile_size, tile_width, tile_height;
2337                 unsigned int tile_rows, tiles, pitch_tiles;
2338
2339                 tile_size = intel_tile_size(dev_priv);
2340                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2341
2342                 if (drm_rotation_90_or_270(rotation)) {
2343                         pitch_tiles = pitch / tile_height;
2344                         swap(tile_width, tile_height);
2345                 } else {
2346                         pitch_tiles = pitch / (tile_width * cpp);
2347                 }
2348
2349                 tile_rows = *y / tile_height;
2350                 *y %= tile_height;
2351
2352                 tiles = *x / tile_width;
2353                 *x %= tile_width;
2354
2355                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2356                 offset_aligned = offset & ~alignment;
2357
2358                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2359                                            tile_size, pitch_tiles,
2360                                            offset, offset_aligned);
2361         } else {
2362                 offset = *y * pitch + *x * cpp;
2363                 offset_aligned = offset & ~alignment;
2364
2365                 *y = (offset & alignment) / pitch;
2366                 *x = ((offset & alignment) - *y * pitch) / cpp;
2367         }
2368
2369         return offset_aligned;
2370 }
2371
2372 u32 intel_compute_tile_offset(int *x, int *y,
2373                               const struct intel_plane_state *state,
2374                               int plane)
2375 {
2376         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2377         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2378         const struct drm_framebuffer *fb = state->base.fb;
2379         unsigned int rotation = state->base.rotation;
2380         int pitch = intel_fb_pitch(fb, plane, rotation);
2381         u32 alignment;
2382
2383         if (intel_plane->id == PLANE_CURSOR)
2384                 alignment = intel_cursor_alignment(dev_priv);
2385         else
2386                 alignment = intel_surf_alignment(fb, plane);
2387
2388         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2389                                           rotation, alignment);
2390 }
2391
2392 /* Convert the fb->offset[] into x/y offsets */
2393 static int intel_fb_offset_to_xy(int *x, int *y,
2394                                  const struct drm_framebuffer *fb, int plane)
2395 {
2396         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2397
2398         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2399             fb->offsets[plane] % intel_tile_size(dev_priv))
2400                 return -EINVAL;
2401
2402         *x = 0;
2403         *y = 0;
2404
2405         _intel_adjust_tile_offset(x, y,
2406                                   fb, plane, DRM_MODE_ROTATE_0,
2407                                   fb->offsets[plane], 0);
2408
2409         return 0;
2410 }
2411
2412 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2413 {
2414         switch (fb_modifier) {
2415         case I915_FORMAT_MOD_X_TILED:
2416                 return I915_TILING_X;
2417         case I915_FORMAT_MOD_Y_TILED:
2418         case I915_FORMAT_MOD_Y_TILED_CCS:
2419                 return I915_TILING_Y;
2420         default:
2421                 return I915_TILING_NONE;
2422         }
2423 }
2424
2425 /*
2426  * From the Sky Lake PRM:
2427  * "The Color Control Surface (CCS) contains the compression status of
2428  *  the cache-line pairs. The compression state of the cache-line pair
2429  *  is specified by 2 bits in the CCS. Each CCS cache-line represents
2430  *  an area on the main surface of 16 x16 sets of 128 byte Y-tiled
2431  *  cache-line-pairs. CCS is always Y tiled."
2432  *
2433  * Since cache line pairs refers to horizontally adjacent cache lines,
2434  * each cache line in the CCS corresponds to an area of 32x16 cache
2435  * lines on the main surface. Since each pixel is 4 bytes, this gives
2436  * us a ratio of one byte in the CCS for each 8x16 pixels in the
2437  * main surface.
2438  */
2439 static const struct drm_format_info ccs_formats[] = {
2440         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2441         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2442         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2443         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2444 };
2445
2446 static const struct drm_format_info *
2447 lookup_format_info(const struct drm_format_info formats[],
2448                    int num_formats, u32 format)
2449 {
2450         int i;
2451
2452         for (i = 0; i < num_formats; i++) {
2453                 if (formats[i].format == format)
2454                         return &formats[i];
2455         }
2456
2457         return NULL;
2458 }
2459
2460 static const struct drm_format_info *
2461 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2462 {
2463         switch (cmd->modifier[0]) {
2464         case I915_FORMAT_MOD_Y_TILED_CCS:
2465         case I915_FORMAT_MOD_Yf_TILED_CCS:
2466                 return lookup_format_info(ccs_formats,
2467                                           ARRAY_SIZE(ccs_formats),
2468                                           cmd->pixel_format);
2469         default:
2470                 return NULL;
2471         }
2472 }
2473
2474 static int
2475 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2476                    struct drm_framebuffer *fb)
2477 {
2478         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2479         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2480         u32 gtt_offset_rotated = 0;
2481         unsigned int max_size = 0;
2482         int i, num_planes = fb->format->num_planes;
2483         unsigned int tile_size = intel_tile_size(dev_priv);
2484
2485         for (i = 0; i < num_planes; i++) {
2486                 unsigned int width, height;
2487                 unsigned int cpp, size;
2488                 u32 offset;
2489                 int x, y;
2490                 int ret;
2491
2492                 cpp = fb->format->cpp[i];
2493                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2494                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2495
2496                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2497                 if (ret) {
2498                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2499                                       i, fb->offsets[i]);
2500                         return ret;
2501                 }
2502
2503                 if ((fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2504                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) && i == 1) {
2505                         int hsub = fb->format->hsub;
2506                         int vsub = fb->format->vsub;
2507                         int tile_width, tile_height;
2508                         int main_x, main_y;
2509                         int ccs_x, ccs_y;
2510
2511                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2512                         tile_width *= hsub;
2513                         tile_height *= vsub;
2514
2515                         ccs_x = (x * hsub) % tile_width;
2516                         ccs_y = (y * vsub) % tile_height;
2517                         main_x = intel_fb->normal[0].x % tile_width;
2518                         main_y = intel_fb->normal[0].y % tile_height;
2519
2520                         /*
2521                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2522                          * x/y offsets must match between CCS and the main surface.
2523                          */
2524                         if (main_x != ccs_x || main_y != ccs_y) {
2525                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2526                                               main_x, main_y,
2527                                               ccs_x, ccs_y,
2528                                               intel_fb->normal[0].x,
2529                                               intel_fb->normal[0].y,
2530                                               x, y);
2531                                 return -EINVAL;
2532                         }
2533                 }
2534
2535                 /*
2536                  * The fence (if used) is aligned to the start of the object
2537                  * so having the framebuffer wrap around across the edge of the
2538                  * fenced region doesn't really work. We have no API to configure
2539                  * the fence start offset within the object (nor could we probably
2540                  * on gen2/3). So it's just easier if we just require that the
2541                  * fb layout agrees with the fence layout. We already check that the
2542                  * fb stride matches the fence stride elsewhere.
2543                  */
2544                 if (i == 0 && i915_gem_object_is_tiled(intel_fb->obj) &&
2545                     (x + width) * cpp > fb->pitches[i]) {
2546                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2547                                       i, fb->offsets[i]);
2548                         return -EINVAL;
2549                 }
2550
2551                 /*
2552                  * First pixel of the framebuffer from
2553                  * the start of the normal gtt mapping.
2554                  */
2555                 intel_fb->normal[i].x = x;
2556                 intel_fb->normal[i].y = y;
2557
2558                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2559                                                     fb, i, fb->pitches[i],
2560                                                     DRM_MODE_ROTATE_0, tile_size);
2561                 offset /= tile_size;
2562
2563                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2564                         unsigned int tile_width, tile_height;
2565                         unsigned int pitch_tiles;
2566                         struct drm_rect r;
2567
2568                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2569
2570                         rot_info->plane[i].offset = offset;
2571                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2572                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2573                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2574
2575                         intel_fb->rotated[i].pitch =
2576                                 rot_info->plane[i].height * tile_height;
2577
2578                         /* how many tiles does this plane need */
2579                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2580                         /*
2581                          * If the plane isn't horizontally tile aligned,
2582                          * we need one more tile.
2583                          */
2584                         if (x != 0)
2585                                 size++;
2586
2587                         /* rotate the x/y offsets to match the GTT view */
2588                         r.x1 = x;
2589                         r.y1 = y;
2590                         r.x2 = x + width;
2591                         r.y2 = y + height;
2592                         drm_rect_rotate(&r,
2593                                         rot_info->plane[i].width * tile_width,
2594                                         rot_info->plane[i].height * tile_height,
2595                                         DRM_MODE_ROTATE_270);
2596                         x = r.x1;
2597                         y = r.y1;
2598
2599                         /* rotate the tile dimensions to match the GTT view */
2600                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2601                         swap(tile_width, tile_height);
2602
2603                         /*
2604                          * We only keep the x/y offsets, so push all of the
2605                          * gtt offset into the x/y offsets.
2606                          */
2607                         __intel_adjust_tile_offset(&x, &y,
2608                                                    tile_width, tile_height,
2609                                                    tile_size, pitch_tiles,
2610                                                    gtt_offset_rotated * tile_size, 0);
2611
2612                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2613
2614                         /*
2615                          * First pixel of the framebuffer from
2616                          * the start of the rotated gtt mapping.
2617                          */
2618                         intel_fb->rotated[i].x = x;
2619                         intel_fb->rotated[i].y = y;
2620                 } else {
2621                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2622                                             x * cpp, tile_size);
2623                 }
2624
2625                 /* how many tiles in total needed in the bo */
2626                 max_size = max(max_size, offset + size);
2627         }
2628
2629         if (max_size * tile_size > intel_fb->obj->base.size) {
2630                 DRM_DEBUG_KMS("fb too big for bo (need %u bytes, have %zu bytes)\n",
2631                               max_size * tile_size, intel_fb->obj->base.size);
2632                 return -EINVAL;
2633         }
2634
2635         return 0;
2636 }
2637
2638 static int i9xx_format_to_fourcc(int format)
2639 {
2640         switch (format) {
2641         case DISPPLANE_8BPP:
2642                 return DRM_FORMAT_C8;
2643         case DISPPLANE_BGRX555:
2644                 return DRM_FORMAT_XRGB1555;
2645         case DISPPLANE_BGRX565:
2646                 return DRM_FORMAT_RGB565;
2647         default:
2648         case DISPPLANE_BGRX888:
2649                 return DRM_FORMAT_XRGB8888;
2650         case DISPPLANE_RGBX888:
2651                 return DRM_FORMAT_XBGR8888;
2652         case DISPPLANE_BGRX101010:
2653                 return DRM_FORMAT_XRGB2101010;
2654         case DISPPLANE_RGBX101010:
2655                 return DRM_FORMAT_XBGR2101010;
2656         }
2657 }
2658
2659 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2660 {
2661         switch (format) {
2662         case PLANE_CTL_FORMAT_RGB_565:
2663                 return DRM_FORMAT_RGB565;
2664         default:
2665         case PLANE_CTL_FORMAT_XRGB_8888:
2666                 if (rgb_order) {
2667                         if (alpha)
2668                                 return DRM_FORMAT_ABGR8888;
2669                         else
2670                                 return DRM_FORMAT_XBGR8888;
2671                 } else {
2672                         if (alpha)
2673                                 return DRM_FORMAT_ARGB8888;
2674                         else
2675                                 return DRM_FORMAT_XRGB8888;
2676                 }
2677         case PLANE_CTL_FORMAT_XRGB_2101010:
2678                 if (rgb_order)
2679                         return DRM_FORMAT_XBGR2101010;
2680                 else
2681                         return DRM_FORMAT_XRGB2101010;
2682         }
2683 }
2684
2685 static bool
2686 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2687                               struct intel_initial_plane_config *plane_config)
2688 {
2689         struct drm_device *dev = crtc->base.dev;
2690         struct drm_i915_private *dev_priv = to_i915(dev);
2691         struct drm_i915_gem_object *obj = NULL;
2692         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2693         struct drm_framebuffer *fb = &plane_config->fb->base;
2694         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2695         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2696                                     PAGE_SIZE);
2697
2698         size_aligned -= base_aligned;
2699
2700         if (plane_config->size == 0)
2701                 return false;
2702
2703         /* If the FB is too big, just don't use it since fbdev is not very
2704          * important and we should probably use that space with FBC or other
2705          * features. */
2706         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2707                 return false;
2708
2709         mutex_lock(&dev->struct_mutex);
2710         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2711                                                              base_aligned,
2712                                                              base_aligned,
2713                                                              size_aligned);
2714         mutex_unlock(&dev->struct_mutex);
2715         if (!obj)
2716                 return false;
2717
2718         if (plane_config->tiling == I915_TILING_X)
2719                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2720
2721         mode_cmd.pixel_format = fb->format->format;
2722         mode_cmd.width = fb->width;
2723         mode_cmd.height = fb->height;
2724         mode_cmd.pitches[0] = fb->pitches[0];
2725         mode_cmd.modifier[0] = fb->modifier;
2726         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2727
2728         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2729                 DRM_DEBUG_KMS("intel fb init failed\n");
2730                 goto out_unref_obj;
2731         }
2732
2733
2734         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2735         return true;
2736
2737 out_unref_obj:
2738         i915_gem_object_put(obj);
2739         return false;
2740 }
2741
2742 static void
2743 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2744                         struct intel_plane_state *plane_state,
2745                         bool visible)
2746 {
2747         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2748
2749         plane_state->base.visible = visible;
2750
2751         /* FIXME pre-g4x don't work like this */
2752         if (visible) {
2753                 crtc_state->base.plane_mask |= BIT(drm_plane_index(&plane->base));
2754                 crtc_state->active_planes |= BIT(plane->id);
2755         } else {
2756                 crtc_state->base.plane_mask &= ~BIT(drm_plane_index(&plane->base));
2757                 crtc_state->active_planes &= ~BIT(plane->id);
2758         }
2759
2760         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2761                       crtc_state->base.crtc->name,
2762                       crtc_state->active_planes);
2763 }
2764
2765 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2766                                          struct intel_plane *plane)
2767 {
2768         struct intel_crtc_state *crtc_state =
2769                 to_intel_crtc_state(crtc->base.state);
2770         struct intel_plane_state *plane_state =
2771                 to_intel_plane_state(plane->base.state);
2772
2773         intel_set_plane_visible(crtc_state, plane_state, false);
2774
2775         if (plane->id == PLANE_PRIMARY)
2776                 intel_pre_disable_primary_noatomic(&crtc->base);
2777
2778         trace_intel_disable_plane(&plane->base, crtc);
2779         plane->disable_plane(plane, crtc);
2780 }
2781
2782 static void
2783 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2784                              struct intel_initial_plane_config *plane_config)
2785 {
2786         struct drm_device *dev = intel_crtc->base.dev;
2787         struct drm_i915_private *dev_priv = to_i915(dev);
2788         struct drm_crtc *c;
2789         struct drm_i915_gem_object *obj;
2790         struct drm_plane *primary = intel_crtc->base.primary;
2791         struct drm_plane_state *plane_state = primary->state;
2792         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2793         struct intel_plane *intel_plane = to_intel_plane(primary);
2794         struct intel_plane_state *intel_state =
2795                 to_intel_plane_state(plane_state);
2796         struct drm_framebuffer *fb;
2797
2798         if (!plane_config->fb)
2799                 return;
2800
2801         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2802                 fb = &plane_config->fb->base;
2803                 goto valid_fb;
2804         }
2805
2806         kfree(plane_config->fb);
2807
2808         /*
2809          * Failed to alloc the obj, check to see if we should share
2810          * an fb with another CRTC instead
2811          */
2812         for_each_crtc(dev, c) {
2813                 struct intel_plane_state *state;
2814
2815                 if (c == &intel_crtc->base)
2816                         continue;
2817
2818                 if (!to_intel_crtc(c)->active)
2819                         continue;
2820
2821                 state = to_intel_plane_state(c->primary->state);
2822                 if (!state->vma)
2823                         continue;
2824
2825                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2826                         fb = c->primary->fb;
2827                         drm_framebuffer_get(fb);
2828                         goto valid_fb;
2829                 }
2830         }
2831
2832         /*
2833          * We've failed to reconstruct the BIOS FB.  Current display state
2834          * indicates that the primary plane is visible, but has a NULL FB,
2835          * which will lead to problems later if we don't fix it up.  The
2836          * simplest solution is to just disable the primary plane now and
2837          * pretend the BIOS never had it enabled.
2838          */
2839         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2840
2841         return;
2842
2843 valid_fb:
2844         mutex_lock(&dev->struct_mutex);
2845         intel_state->vma =
2846                 intel_pin_and_fence_fb_obj(fb,
2847                                            primary->state->rotation,
2848                                            intel_plane_uses_fence(intel_state),
2849                                            &intel_state->flags);
2850         mutex_unlock(&dev->struct_mutex);
2851         if (IS_ERR(intel_state->vma)) {
2852                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2853                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2854
2855                 intel_state->vma = NULL;
2856                 drm_framebuffer_put(fb);
2857                 return;
2858         }
2859
2860         plane_state->src_x = 0;
2861         plane_state->src_y = 0;
2862         plane_state->src_w = fb->width << 16;
2863         plane_state->src_h = fb->height << 16;
2864
2865         plane_state->crtc_x = 0;
2866         plane_state->crtc_y = 0;
2867         plane_state->crtc_w = fb->width;
2868         plane_state->crtc_h = fb->height;
2869
2870         intel_state->base.src = drm_plane_state_src(plane_state);
2871         intel_state->base.dst = drm_plane_state_dest(plane_state);
2872
2873         obj = intel_fb_obj(fb);
2874         if (i915_gem_object_is_tiled(obj))
2875                 dev_priv->preserve_bios_swizzle = true;
2876
2877         drm_framebuffer_get(fb);
2878         primary->fb = primary->state->fb = fb;
2879         primary->crtc = primary->state->crtc = &intel_crtc->base;
2880
2881         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2882                                 to_intel_plane_state(plane_state),
2883                                 true);
2884
2885         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2886                   &obj->frontbuffer_bits);
2887 }
2888
2889 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2890                                unsigned int rotation)
2891 {
2892         int cpp = fb->format->cpp[plane];
2893
2894         switch (fb->modifier) {
2895         case DRM_FORMAT_MOD_LINEAR:
2896         case I915_FORMAT_MOD_X_TILED:
2897                 switch (cpp) {
2898                 case 8:
2899                         return 4096;
2900                 case 4:
2901                 case 2:
2902                 case 1:
2903                         return 8192;
2904                 default:
2905                         MISSING_CASE(cpp);
2906                         break;
2907                 }
2908                 break;
2909         case I915_FORMAT_MOD_Y_TILED_CCS:
2910         case I915_FORMAT_MOD_Yf_TILED_CCS:
2911                 /* FIXME AUX plane? */
2912         case I915_FORMAT_MOD_Y_TILED:
2913         case I915_FORMAT_MOD_Yf_TILED:
2914                 switch (cpp) {
2915                 case 8:
2916                         return 2048;
2917                 case 4:
2918                         return 4096;
2919                 case 2:
2920                 case 1:
2921                         return 8192;
2922                 default:
2923                         MISSING_CASE(cpp);
2924                         break;
2925                 }
2926                 break;
2927         default:
2928                 MISSING_CASE(fb->modifier);
2929         }
2930
2931         return 2048;
2932 }
2933
2934 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2935                                            int main_x, int main_y, u32 main_offset)
2936 {
2937         const struct drm_framebuffer *fb = plane_state->base.fb;
2938         int hsub = fb->format->hsub;
2939         int vsub = fb->format->vsub;
2940         int aux_x = plane_state->aux.x;
2941         int aux_y = plane_state->aux.y;
2942         u32 aux_offset = plane_state->aux.offset;
2943         u32 alignment = intel_surf_alignment(fb, 1);
2944
2945         while (aux_offset >= main_offset && aux_y <= main_y) {
2946                 int x, y;
2947
2948                 if (aux_x == main_x && aux_y == main_y)
2949                         break;
2950
2951                 if (aux_offset == 0)
2952                         break;
2953
2954                 x = aux_x / hsub;
2955                 y = aux_y / vsub;
2956                 aux_offset = intel_adjust_tile_offset(&x, &y, plane_state, 1,
2957                                                       aux_offset, aux_offset - alignment);
2958                 aux_x = x * hsub + aux_x % hsub;
2959                 aux_y = y * vsub + aux_y % vsub;
2960         }
2961
2962         if (aux_x != main_x || aux_y != main_y)
2963                 return false;
2964
2965         plane_state->aux.offset = aux_offset;
2966         plane_state->aux.x = aux_x;
2967         plane_state->aux.y = aux_y;
2968
2969         return true;
2970 }
2971
2972 static int skl_check_main_surface(const struct intel_crtc_state *crtc_state,
2973                                   struct intel_plane_state *plane_state)
2974 {
2975         struct drm_i915_private *dev_priv =
2976                 to_i915(plane_state->base.plane->dev);
2977         const struct drm_framebuffer *fb = plane_state->base.fb;
2978         unsigned int rotation = plane_state->base.rotation;
2979         int x = plane_state->base.src.x1 >> 16;
2980         int y = plane_state->base.src.y1 >> 16;
2981         int w = drm_rect_width(&plane_state->base.src) >> 16;
2982         int h = drm_rect_height(&plane_state->base.src) >> 16;
2983         int dst_x = plane_state->base.dst.x1;
2984         int pipe_src_w = crtc_state->pipe_src_w;
2985         int max_width = skl_max_plane_width(fb, 0, rotation);
2986         int max_height = 4096;
2987         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2988
2989         if (w > max_width || h > max_height) {
2990                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2991                               w, h, max_width, max_height);
2992                 return -EINVAL;
2993         }
2994
2995         /*
2996          * Display WA #1175: cnl,glk
2997          * Planes other than the cursor may cause FIFO underflow and display
2998          * corruption if starting less than 4 pixels from the right edge of
2999          * the screen.
3000          * Besides the above WA fix the similar problem, where planes other
3001          * than the cursor ending less than 4 pixels from the left edge of the
3002          * screen may cause FIFO underflow and display corruption.
3003          */
3004         if ((IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
3005             (dst_x + w < 4 || dst_x > pipe_src_w - 4)) {
3006                 DRM_DEBUG_KMS("requested plane X %s position %d invalid (valid range %d-%d)\n",
3007                               dst_x + w < 4 ? "end" : "start",
3008                               dst_x + w < 4 ? dst_x + w : dst_x,
3009                               4, pipe_src_w - 4);
3010                 return -ERANGE;
3011         }
3012
3013         intel_add_fb_offsets(&x, &y, plane_state, 0);
3014         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
3015         alignment = intel_surf_alignment(fb, 0);
3016
3017         /*
3018          * AUX surface offset is specified as the distance from the
3019          * main surface offset, and it must be non-negative. Make
3020          * sure that is what we will get.
3021          */
3022         if (offset > aux_offset)
3023                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3024                                                   offset, aux_offset & ~(alignment - 1));
3025
3026         /*
3027          * When using an X-tiled surface, the plane blows up
3028          * if the x offset + width exceed the stride.
3029          *
3030          * TODO: linear and Y-tiled seem fine, Yf untested,
3031          */
3032         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
3033                 int cpp = fb->format->cpp[0];
3034
3035                 while ((x + w) * cpp > fb->pitches[0]) {
3036                         if (offset == 0) {
3037                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
3038                                 return -EINVAL;
3039                         }
3040
3041                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3042                                                           offset, offset - alignment);
3043                 }
3044         }
3045
3046         /*
3047          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
3048          * they match with the main surface x/y offsets.
3049          */
3050         if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3051             fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3052                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
3053                         if (offset == 0)
3054                                 break;
3055
3056                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
3057                                                           offset, offset - alignment);
3058                 }
3059
3060                 if (x != plane_state->aux.x || y != plane_state->aux.y) {
3061                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
3062                         return -EINVAL;
3063                 }
3064         }
3065
3066         plane_state->main.offset = offset;
3067         plane_state->main.x = x;
3068         plane_state->main.y = y;
3069
3070         return 0;
3071 }
3072
3073 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
3074 {
3075         const struct drm_framebuffer *fb = plane_state->base.fb;
3076         unsigned int rotation = plane_state->base.rotation;
3077         int max_width = skl_max_plane_width(fb, 1, rotation);
3078         int max_height = 4096;
3079         int x = plane_state->base.src.x1 >> 17;
3080         int y = plane_state->base.src.y1 >> 17;
3081         int w = drm_rect_width(&plane_state->base.src) >> 17;
3082         int h = drm_rect_height(&plane_state->base.src) >> 17;
3083         u32 offset;
3084
3085         intel_add_fb_offsets(&x, &y, plane_state, 1);
3086         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3087
3088         /* FIXME not quite sure how/if these apply to the chroma plane */
3089         if (w > max_width || h > max_height) {
3090                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3091                               w, h, max_width, max_height);
3092                 return -EINVAL;
3093         }
3094
3095         plane_state->aux.offset = offset;
3096         plane_state->aux.x = x;
3097         plane_state->aux.y = y;
3098
3099         return 0;
3100 }
3101
3102 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3103 {
3104         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3105         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3106         struct intel_crtc *crtc = to_intel_crtc(plane_state->base.crtc);
3107         const struct drm_framebuffer *fb = plane_state->base.fb;
3108         int src_x = plane_state->base.src.x1 >> 16;
3109         int src_y = plane_state->base.src.y1 >> 16;
3110         int hsub = fb->format->hsub;
3111         int vsub = fb->format->vsub;
3112         int x = src_x / hsub;
3113         int y = src_y / vsub;
3114         u32 offset;
3115
3116         if (!skl_plane_has_ccs(dev_priv, crtc->pipe, plane->id)) {
3117                 DRM_DEBUG_KMS("No RC support on %s\n", plane->base.name);
3118                 return -EINVAL;
3119         }
3120
3121         if (plane_state->base.rotation & ~(DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180)) {
3122                 DRM_DEBUG_KMS("RC support only with 0/180 degree rotation %x\n",
3123                               plane_state->base.rotation);
3124                 return -EINVAL;
3125         }
3126
3127         intel_add_fb_offsets(&x, &y, plane_state, 1);
3128         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3129
3130         plane_state->aux.offset = offset;
3131         plane_state->aux.x = x * hsub + src_x % hsub;
3132         plane_state->aux.y = y * vsub + src_y % vsub;
3133
3134         return 0;
3135 }
3136
3137 int skl_check_plane_surface(const struct intel_crtc_state *crtc_state,
3138                             struct intel_plane_state *plane_state)
3139 {
3140         const struct drm_framebuffer *fb = plane_state->base.fb;
3141         unsigned int rotation = plane_state->base.rotation;
3142         int ret;
3143
3144         if (rotation & DRM_MODE_REFLECT_X &&
3145             fb->modifier == DRM_FORMAT_MOD_LINEAR) {
3146                 DRM_DEBUG_KMS("horizontal flip is not supported with linear surface formats\n");
3147                 return -EINVAL;
3148         }
3149
3150         if (!plane_state->base.visible)
3151                 return 0;
3152
3153         /* Rotate src coordinates to match rotated GTT view */
3154         if (drm_rotation_90_or_270(rotation))
3155                 drm_rect_rotate(&plane_state->base.src,
3156                                 fb->width << 16, fb->height << 16,
3157                                 DRM_MODE_ROTATE_270);
3158
3159         /*
3160          * Handle the AUX surface first since
3161          * the main surface setup depends on it.
3162          */
3163         if (fb->format->format == DRM_FORMAT_NV12) {
3164                 ret = skl_check_nv12_aux_surface(plane_state);
3165                 if (ret)
3166                         return ret;
3167         } else if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3168                    fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3169                 ret = skl_check_ccs_aux_surface(plane_state);
3170                 if (ret)
3171                         return ret;
3172         } else {
3173                 plane_state->aux.offset = ~0xfff;
3174                 plane_state->aux.x = 0;
3175                 plane_state->aux.y = 0;
3176         }
3177
3178         ret = skl_check_main_surface(crtc_state, plane_state);
3179         if (ret)
3180                 return ret;
3181
3182         return 0;
3183 }
3184
3185 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3186                           const struct intel_plane_state *plane_state)
3187 {
3188         struct drm_i915_private *dev_priv =
3189                 to_i915(plane_state->base.plane->dev);
3190         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3191         const struct drm_framebuffer *fb = plane_state->base.fb;
3192         unsigned int rotation = plane_state->base.rotation;
3193         u32 dspcntr;
3194
3195         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3196
3197         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3198             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3199                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3200
3201         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3202                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3203
3204         if (INTEL_GEN(dev_priv) < 5)
3205                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3206
3207         switch (fb->format->format) {
3208         case DRM_FORMAT_C8:
3209                 dspcntr |= DISPPLANE_8BPP;
3210                 break;
3211         case DRM_FORMAT_XRGB1555:
3212                 dspcntr |= DISPPLANE_BGRX555;
3213                 break;
3214         case DRM_FORMAT_RGB565:
3215                 dspcntr |= DISPPLANE_BGRX565;
3216                 break;
3217         case DRM_FORMAT_XRGB8888:
3218                 dspcntr |= DISPPLANE_BGRX888;
3219                 break;
3220         case DRM_FORMAT_XBGR8888:
3221                 dspcntr |= DISPPLANE_RGBX888;
3222                 break;
3223         case DRM_FORMAT_XRGB2101010:
3224                 dspcntr |= DISPPLANE_BGRX101010;
3225                 break;
3226         case DRM_FORMAT_XBGR2101010:
3227                 dspcntr |= DISPPLANE_RGBX101010;
3228                 break;
3229         default:
3230                 MISSING_CASE(fb->format->format);
3231                 return 0;
3232         }
3233
3234         if (INTEL_GEN(dev_priv) >= 4 &&
3235             fb->modifier == I915_FORMAT_MOD_X_TILED)
3236                 dspcntr |= DISPPLANE_TILED;
3237
3238         if (rotation & DRM_MODE_ROTATE_180)
3239                 dspcntr |= DISPPLANE_ROTATE_180;
3240
3241         if (rotation & DRM_MODE_REFLECT_X)
3242                 dspcntr |= DISPPLANE_MIRROR;
3243
3244         return dspcntr;
3245 }
3246
3247 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3248 {
3249         struct drm_i915_private *dev_priv =
3250                 to_i915(plane_state->base.plane->dev);
3251         int src_x = plane_state->base.src.x1 >> 16;
3252         int src_y = plane_state->base.src.y1 >> 16;
3253         u32 offset;
3254
3255         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3256
3257         if (INTEL_GEN(dev_priv) >= 4)
3258                 offset = intel_compute_tile_offset(&src_x, &src_y,
3259                                                    plane_state, 0);
3260         else
3261                 offset = 0;
3262
3263         /* HSW/BDW do this automagically in hardware */
3264         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3265                 unsigned int rotation = plane_state->base.rotation;
3266                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3267                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3268
3269                 if (rotation & DRM_MODE_ROTATE_180) {
3270                         src_x += src_w - 1;
3271                         src_y += src_h - 1;
3272                 } else if (rotation & DRM_MODE_REFLECT_X) {
3273                         src_x += src_w - 1;
3274                 }
3275         }
3276
3277         plane_state->main.offset = offset;
3278         plane_state->main.x = src_x;
3279         plane_state->main.y = src_y;
3280
3281         return 0;
3282 }
3283
3284 static void i9xx_update_plane(struct intel_plane *plane,
3285                               const struct intel_crtc_state *crtc_state,
3286                               const struct intel_plane_state *plane_state)
3287 {
3288         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3289         const struct drm_framebuffer *fb = plane_state->base.fb;
3290         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3291         u32 linear_offset;
3292         u32 dspcntr = plane_state->ctl;
3293         i915_reg_t reg = DSPCNTR(i9xx_plane);
3294         int x = plane_state->main.x;
3295         int y = plane_state->main.y;
3296         unsigned long irqflags;
3297         u32 dspaddr_offset;
3298
3299         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3300
3301         if (INTEL_GEN(dev_priv) >= 4)
3302                 dspaddr_offset = plane_state->main.offset;
3303         else
3304                 dspaddr_offset = linear_offset;
3305
3306         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3307
3308         if (INTEL_GEN(dev_priv) < 4) {
3309                 /* pipesrc and dspsize control the size that is scaled from,
3310                  * which should always be the user's requested size.
3311                  */
3312                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3313                               ((crtc_state->pipe_src_h - 1) << 16) |
3314                               (crtc_state->pipe_src_w - 1));
3315                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3316         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3317                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3318                               ((crtc_state->pipe_src_h - 1) << 16) |
3319                               (crtc_state->pipe_src_w - 1));
3320                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3321                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3322         }
3323
3324         I915_WRITE_FW(reg, dspcntr);
3325
3326         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), fb->pitches[0]);
3327         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3328                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3329                               intel_plane_ggtt_offset(plane_state) +
3330                               dspaddr_offset);
3331                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3332         } else if (INTEL_GEN(dev_priv) >= 4) {
3333                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3334                               intel_plane_ggtt_offset(plane_state) +
3335                               dspaddr_offset);
3336                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3337                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3338         } else {
3339                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3340                               intel_plane_ggtt_offset(plane_state) +
3341                               dspaddr_offset);
3342         }
3343         POSTING_READ_FW(reg);
3344
3345         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3346 }
3347
3348 static void i9xx_disable_plane(struct intel_plane *plane,
3349                                struct intel_crtc *crtc)
3350 {
3351         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3352         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3353         unsigned long irqflags;
3354
3355         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3356
3357         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3358         if (INTEL_GEN(dev_priv) >= 4)
3359                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3360         else
3361                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3362         POSTING_READ_FW(DSPCNTR(i9xx_plane));
3363
3364         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3365 }
3366
3367 static bool i9xx_plane_get_hw_state(struct intel_plane *plane)
3368 {
3369         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3370         enum intel_display_power_domain power_domain;
3371         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3372         enum pipe pipe = plane->pipe;
3373         bool ret;
3374
3375         /*
3376          * Not 100% correct for planes that can move between pipes,
3377          * but that's only the case for gen2-4 which don't have any
3378          * display power wells.
3379          */
3380         power_domain = POWER_DOMAIN_PIPE(pipe);
3381         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3382                 return false;
3383
3384         ret = I915_READ(DSPCNTR(i9xx_plane)) & DISPLAY_PLANE_ENABLE;
3385
3386         intel_display_power_put(dev_priv, power_domain);
3387
3388         return ret;
3389 }
3390
3391 static u32
3392 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int plane)
3393 {
3394         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3395                 return 64;
3396         else
3397                 return intel_tile_width_bytes(fb, plane);
3398 }
3399
3400 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3401 {
3402         struct drm_device *dev = intel_crtc->base.dev;
3403         struct drm_i915_private *dev_priv = to_i915(dev);
3404
3405         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3406         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3407         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3408 }
3409
3410 /*
3411  * This function detaches (aka. unbinds) unused scalers in hardware
3412  */
3413 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3414 {
3415         struct intel_crtc_scaler_state *scaler_state;
3416         int i;
3417
3418         scaler_state = &intel_crtc->config->scaler_state;
3419
3420         /* loop through and disable scalers that aren't in use */
3421         for (i = 0; i < intel_crtc->num_scalers; i++) {
3422                 if (!scaler_state->scalers[i].in_use)
3423                         skl_detach_scaler(intel_crtc, i);
3424         }
3425 }
3426
3427 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3428                      unsigned int rotation)
3429 {
3430         u32 stride;
3431
3432         if (plane >= fb->format->num_planes)
3433                 return 0;
3434
3435         stride = intel_fb_pitch(fb, plane, rotation);
3436
3437         /*
3438          * The stride is either expressed as a multiple of 64 bytes chunks for
3439          * linear buffers or in number of tiles for tiled buffers.
3440          */
3441         if (drm_rotation_90_or_270(rotation))
3442                 stride /= intel_tile_height(fb, plane);
3443         else
3444                 stride /= intel_fb_stride_alignment(fb, plane);
3445
3446         return stride;
3447 }
3448
3449 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3450 {
3451         switch (pixel_format) {
3452         case DRM_FORMAT_C8:
3453                 return PLANE_CTL_FORMAT_INDEXED;
3454         case DRM_FORMAT_RGB565:
3455                 return PLANE_CTL_FORMAT_RGB_565;
3456         case DRM_FORMAT_XBGR8888:
3457         case DRM_FORMAT_ABGR8888:
3458                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3459         case DRM_FORMAT_XRGB8888:
3460         case DRM_FORMAT_ARGB8888:
3461                 return PLANE_CTL_FORMAT_XRGB_8888;
3462         case DRM_FORMAT_XRGB2101010:
3463                 return PLANE_CTL_FORMAT_XRGB_2101010;
3464         case DRM_FORMAT_XBGR2101010:
3465                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3466         case DRM_FORMAT_YUYV:
3467                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3468         case DRM_FORMAT_YVYU:
3469                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3470         case DRM_FORMAT_UYVY:
3471                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3472         case DRM_FORMAT_VYUY:
3473                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3474         default:
3475                 MISSING_CASE(pixel_format);
3476         }
3477
3478         return 0;
3479 }
3480
3481 /*
3482  * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3483  * to be already pre-multiplied. We need to add a knob (or a different
3484  * DRM_FORMAT) for user-space to configure that.
3485  */
3486 static u32 skl_plane_ctl_alpha(uint32_t pixel_format)
3487 {
3488         switch (pixel_format) {
3489         case DRM_FORMAT_ABGR8888:
3490         case DRM_FORMAT_ARGB8888:
3491                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3492         default:
3493                 return PLANE_CTL_ALPHA_DISABLE;
3494         }
3495 }
3496
3497 static u32 glk_plane_color_ctl_alpha(uint32_t pixel_format)
3498 {
3499         switch (pixel_format) {
3500         case DRM_FORMAT_ABGR8888:
3501         case DRM_FORMAT_ARGB8888:
3502                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3503         default:
3504                 return PLANE_COLOR_ALPHA_DISABLE;
3505         }
3506 }
3507
3508 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3509 {
3510         switch (fb_modifier) {
3511         case DRM_FORMAT_MOD_LINEAR:
3512                 break;
3513         case I915_FORMAT_MOD_X_TILED:
3514                 return PLANE_CTL_TILED_X;
3515         case I915_FORMAT_MOD_Y_TILED:
3516                 return PLANE_CTL_TILED_Y;
3517         case I915_FORMAT_MOD_Y_TILED_CCS:
3518                 return PLANE_CTL_TILED_Y | PLANE_CTL_DECOMPRESSION_ENABLE;
3519         case I915_FORMAT_MOD_Yf_TILED:
3520                 return PLANE_CTL_TILED_YF;
3521         case I915_FORMAT_MOD_Yf_TILED_CCS:
3522                 return PLANE_CTL_TILED_YF | PLANE_CTL_DECOMPRESSION_ENABLE;
3523         default:
3524                 MISSING_CASE(fb_modifier);
3525         }
3526
3527         return 0;
3528 }
3529
3530 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3531 {
3532         switch (rotate) {
3533         case DRM_MODE_ROTATE_0:
3534                 break;
3535         /*
3536          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3537          * while i915 HW rotation is clockwise, thats why this swapping.
3538          */
3539         case DRM_MODE_ROTATE_90:
3540                 return PLANE_CTL_ROTATE_270;
3541         case DRM_MODE_ROTATE_180:
3542                 return PLANE_CTL_ROTATE_180;
3543         case DRM_MODE_ROTATE_270:
3544                 return PLANE_CTL_ROTATE_90;
3545         default:
3546                 MISSING_CASE(rotate);
3547         }
3548
3549         return 0;
3550 }
3551
3552 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3553 {
3554         switch (reflect) {
3555         case 0:
3556                 break;
3557         case DRM_MODE_REFLECT_X:
3558                 return PLANE_CTL_FLIP_HORIZONTAL;
3559         case DRM_MODE_REFLECT_Y:
3560         default:
3561                 MISSING_CASE(reflect);
3562         }
3563
3564         return 0;
3565 }
3566
3567 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3568                   const struct intel_plane_state *plane_state)
3569 {
3570         struct drm_i915_private *dev_priv =
3571                 to_i915(plane_state->base.plane->dev);
3572         const struct drm_framebuffer *fb = plane_state->base.fb;
3573         unsigned int rotation = plane_state->base.rotation;
3574         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3575         u32 plane_ctl;
3576
3577         plane_ctl = PLANE_CTL_ENABLE;
3578
3579         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3580                 plane_ctl |= skl_plane_ctl_alpha(fb->format->format);
3581                 plane_ctl |=
3582                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3583                         PLANE_CTL_PIPE_CSC_ENABLE |
3584                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3585         }
3586
3587         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3588         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3589         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3590
3591         if (INTEL_GEN(dev_priv) >= 10)
3592                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3593                                                 DRM_MODE_REFLECT_MASK);
3594
3595         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3596                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3597         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3598                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3599
3600         return plane_ctl;
3601 }
3602
3603 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3604                         const struct intel_plane_state *plane_state)
3605 {
3606         const struct drm_framebuffer *fb = plane_state->base.fb;
3607         u32 plane_color_ctl = 0;
3608
3609         plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3610         plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3611         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3612         plane_color_ctl |= glk_plane_color_ctl_alpha(fb->format->format);
3613
3614         return plane_color_ctl;
3615 }
3616
3617 static int
3618 __intel_display_resume(struct drm_device *dev,
3619                        struct drm_atomic_state *state,
3620                        struct drm_modeset_acquire_ctx *ctx)
3621 {
3622         struct drm_crtc_state *crtc_state;
3623         struct drm_crtc *crtc;
3624         int i, ret;
3625
3626         intel_modeset_setup_hw_state(dev, ctx);
3627         i915_redisable_vga(to_i915(dev));
3628
3629         if (!state)
3630                 return 0;
3631
3632         /*
3633          * We've duplicated the state, pointers to the old state are invalid.
3634          *
3635          * Don't attempt to use the old state until we commit the duplicated state.
3636          */
3637         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3638                 /*
3639                  * Force recalculation even if we restore
3640                  * current state. With fast modeset this may not result
3641                  * in a modeset when the state is compatible.
3642                  */
3643                 crtc_state->mode_changed = true;
3644         }
3645
3646         /* ignore any reset values/BIOS leftovers in the WM registers */
3647         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3648                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3649
3650         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3651
3652         WARN_ON(ret == -EDEADLK);
3653         return ret;
3654 }
3655
3656 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3657 {
3658         return intel_has_gpu_reset(dev_priv) &&
3659                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3660 }
3661
3662 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3663 {
3664         struct drm_device *dev = &dev_priv->drm;
3665         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3666         struct drm_atomic_state *state;
3667         int ret;
3668
3669
3670         /* reset doesn't touch the display */
3671         if (!i915_modparams.force_reset_modeset_test &&
3672             !gpu_reset_clobbers_display(dev_priv))
3673                 return;
3674
3675         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3676         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3677         wake_up_all(&dev_priv->gpu_error.wait_queue);
3678
3679         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3680                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3681                 i915_gem_set_wedged(dev_priv);
3682         }
3683
3684         /*
3685          * Need mode_config.mutex so that we don't
3686          * trample ongoing ->detect() and whatnot.
3687          */
3688         mutex_lock(&dev->mode_config.mutex);
3689         drm_modeset_acquire_init(ctx, 0);
3690         while (1) {
3691                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3692                 if (ret != -EDEADLK)
3693                         break;
3694
3695                 drm_modeset_backoff(ctx);
3696         }
3697         /*
3698          * Disabling the crtcs gracefully seems nicer. Also the
3699          * g33 docs say we should at least disable all the planes.
3700          */
3701         state = drm_atomic_helper_duplicate_state(dev, ctx);
3702         if (IS_ERR(state)) {
3703                 ret = PTR_ERR(state);
3704                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3705                 return;
3706         }
3707
3708         ret = drm_atomic_helper_disable_all(dev, ctx);
3709         if (ret) {
3710                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3711                 drm_atomic_state_put(state);
3712                 return;
3713         }
3714
3715         dev_priv->modeset_restore_state = state;
3716         state->acquire_ctx = ctx;
3717 }
3718
3719 void intel_finish_reset(struct drm_i915_private *dev_priv)
3720 {
3721         struct drm_device *dev = &dev_priv->drm;
3722         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3723         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3724         int ret;
3725
3726         /* reset doesn't touch the display */
3727         if (!i915_modparams.force_reset_modeset_test &&
3728             !gpu_reset_clobbers_display(dev_priv))
3729                 return;
3730
3731         if (!state)
3732                 goto unlock;
3733
3734         dev_priv->modeset_restore_state = NULL;
3735
3736         /* reset doesn't touch the display */
3737         if (!gpu_reset_clobbers_display(dev_priv)) {
3738                 /* for testing only restore the display */
3739                 ret = __intel_display_resume(dev, state, ctx);
3740                 if (ret)
3741                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3742         } else {
3743                 /*
3744                  * The display has been reset as well,
3745                  * so need a full re-initialization.
3746                  */
3747                 intel_runtime_pm_disable_interrupts(dev_priv);
3748                 intel_runtime_pm_enable_interrupts(dev_priv);
3749
3750                 intel_pps_unlock_regs_wa(dev_priv);
3751                 intel_modeset_init_hw(dev);
3752                 intel_init_clock_gating(dev_priv);
3753
3754                 spin_lock_irq(&dev_priv->irq_lock);
3755                 if (dev_priv->display.hpd_irq_setup)
3756                         dev_priv->display.hpd_irq_setup(dev_priv);
3757                 spin_unlock_irq(&dev_priv->irq_lock);
3758
3759                 ret = __intel_display_resume(dev, state, ctx);
3760                 if (ret)
3761                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3762
3763                 intel_hpd_init(dev_priv);
3764         }
3765
3766         drm_atomic_state_put(state);
3767 unlock:
3768         drm_modeset_drop_locks(ctx);
3769         drm_modeset_acquire_fini(ctx);
3770         mutex_unlock(&dev->mode_config.mutex);
3771
3772         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3773 }
3774
3775 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3776                                      const struct intel_crtc_state *new_crtc_state)
3777 {
3778         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3779         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3780
3781         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3782         crtc->base.mode = new_crtc_state->base.mode;
3783
3784         /*
3785          * Update pipe size and adjust fitter if needed: the reason for this is
3786          * that in compute_mode_changes we check the native mode (not the pfit
3787          * mode) to see if we can flip rather than do a full mode set. In the
3788          * fastboot case, we'll flip, but if we don't update the pipesrc and
3789          * pfit state, we'll end up with a big fb scanned out into the wrong
3790          * sized surface.
3791          */
3792
3793         I915_WRITE(PIPESRC(crtc->pipe),
3794                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3795                    (new_crtc_state->pipe_src_h - 1));
3796
3797         /* on skylake this is done by detaching scalers */
3798         if (INTEL_GEN(dev_priv) >= 9) {
3799                 skl_detach_scalers(crtc);
3800
3801                 if (new_crtc_state->pch_pfit.enabled)
3802                         skylake_pfit_enable(crtc);
3803         } else if (HAS_PCH_SPLIT(dev_priv)) {
3804                 if (new_crtc_state->pch_pfit.enabled)
3805                         ironlake_pfit_enable(crtc);
3806                 else if (old_crtc_state->pch_pfit.enabled)
3807                         ironlake_pfit_disable(crtc, true);
3808         }
3809 }
3810
3811 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3812 {
3813         struct drm_device *dev = crtc->base.dev;
3814         struct drm_i915_private *dev_priv = to_i915(dev);
3815         int pipe = crtc->pipe;
3816         i915_reg_t reg;
3817         u32 temp;
3818
3819         /* enable normal train */
3820         reg = FDI_TX_CTL(pipe);
3821         temp = I915_READ(reg);
3822         if (IS_IVYBRIDGE(dev_priv)) {
3823                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3824                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3825         } else {
3826                 temp &= ~FDI_LINK_TRAIN_NONE;
3827                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3828         }
3829         I915_WRITE(reg, temp);
3830
3831         reg = FDI_RX_CTL(pipe);
3832         temp = I915_READ(reg);
3833         if (HAS_PCH_CPT(dev_priv)) {
3834                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3835                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3836         } else {
3837                 temp &= ~FDI_LINK_TRAIN_NONE;
3838                 temp |= FDI_LINK_TRAIN_NONE;
3839         }
3840         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3841
3842         /* wait one idle pattern time */
3843         POSTING_READ(reg);
3844         udelay(1000);
3845
3846         /* IVB wants error correction enabled */
3847         if (IS_IVYBRIDGE(dev_priv))
3848                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3849                            FDI_FE_ERRC_ENABLE);
3850 }
3851
3852 /* The FDI link training functions for ILK/Ibexpeak. */
3853 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3854                                     const struct intel_crtc_state *crtc_state)
3855 {
3856         struct drm_device *dev = crtc->base.dev;
3857         struct drm_i915_private *dev_priv = to_i915(dev);
3858         int pipe = crtc->pipe;
3859         i915_reg_t reg;
3860         u32 temp, tries;
3861
3862         /* FDI needs bits from pipe first */
3863         assert_pipe_enabled(dev_priv, pipe);
3864
3865         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3866            for train result */
3867         reg = FDI_RX_IMR(pipe);
3868         temp = I915_READ(reg);
3869         temp &= ~FDI_RX_SYMBOL_LOCK;
3870         temp &= ~FDI_RX_BIT_LOCK;
3871         I915_WRITE(reg, temp);
3872         I915_READ(reg);
3873         udelay(150);
3874
3875         /* enable CPU FDI TX and PCH FDI RX */
3876         reg = FDI_TX_CTL(pipe);
3877         temp = I915_READ(reg);
3878         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3879         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3880         temp &= ~FDI_LINK_TRAIN_NONE;
3881         temp |= FDI_LINK_TRAIN_PATTERN_1;
3882         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3883
3884         reg = FDI_RX_CTL(pipe);
3885         temp = I915_READ(reg);
3886         temp &= ~FDI_LINK_TRAIN_NONE;
3887         temp |= FDI_LINK_TRAIN_PATTERN_1;
3888         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3889
3890         POSTING_READ(reg);
3891         udelay(150);
3892
3893         /* Ironlake workaround, enable clock pointer after FDI enable*/
3894         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3895         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3896                    FDI_RX_PHASE_SYNC_POINTER_EN);
3897
3898         reg = FDI_RX_IIR(pipe);
3899         for (tries = 0; tries < 5; tries++) {
3900                 temp = I915_READ(reg);
3901                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3902
3903                 if ((temp & FDI_RX_BIT_LOCK)) {
3904                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3905                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3906                         break;
3907                 }
3908         }
3909         if (tries == 5)
3910                 DRM_ERROR("FDI train 1 fail!\n");
3911
3912         /* Train 2 */
3913         reg = FDI_TX_CTL(pipe);
3914         temp = I915_READ(reg);
3915         temp &= ~FDI_LINK_TRAIN_NONE;
3916         temp |= FDI_LINK_TRAIN_PATTERN_2;
3917         I915_WRITE(reg, temp);
3918
3919         reg = FDI_RX_CTL(pipe);
3920         temp = I915_READ(reg);
3921         temp &= ~FDI_LINK_TRAIN_NONE;
3922         temp |= FDI_LINK_TRAIN_PATTERN_2;
3923         I915_WRITE(reg, temp);
3924
3925         POSTING_READ(reg);
3926         udelay(150);
3927
3928         reg = FDI_RX_IIR(pipe);
3929         for (tries = 0; tries < 5; tries++) {
3930                 temp = I915_READ(reg);
3931                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3932
3933                 if (temp & FDI_RX_SYMBOL_LOCK) {
3934                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3935                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3936                         break;
3937                 }
3938         }
3939         if (tries == 5)
3940                 DRM_ERROR("FDI train 2 fail!\n");
3941
3942         DRM_DEBUG_KMS("FDI train done\n");
3943
3944 }
3945
3946 static const int snb_b_fdi_train_param[] = {
3947         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3948         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3949         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3950         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3951 };
3952
3953 /* The FDI link training functions for SNB/Cougarpoint. */
3954 static void gen6_fdi_link_train(struct intel_crtc *crtc,
3955                                 const struct intel_crtc_state *crtc_state)
3956 {
3957         struct drm_device *dev = crtc->base.dev;
3958         struct drm_i915_private *dev_priv = to_i915(dev);
3959         int pipe = crtc->pipe;
3960         i915_reg_t reg;
3961         u32 temp, i, retry;
3962
3963         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3964            for train result */
3965         reg = FDI_RX_IMR(pipe);
3966         temp = I915_READ(reg);
3967         temp &= ~FDI_RX_SYMBOL_LOCK;
3968         temp &= ~FDI_RX_BIT_LOCK;
3969         I915_WRITE(reg, temp);
3970
3971         POSTING_READ(reg);
3972         udelay(150);
3973
3974         /* enable CPU FDI TX and PCH FDI RX */
3975         reg = FDI_TX_CTL(pipe);
3976         temp = I915_READ(reg);
3977         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3978         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3979         temp &= ~FDI_LINK_TRAIN_NONE;
3980         temp |= FDI_LINK_TRAIN_PATTERN_1;
3981         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3982         /* SNB-B */
3983         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3984         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3985
3986         I915_WRITE(FDI_RX_MISC(pipe),
3987                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3988
3989         reg = FDI_RX_CTL(pipe);
3990         temp = I915_READ(reg);
3991         if (HAS_PCH_CPT(dev_priv)) {
3992                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3993                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3994         } else {
3995                 temp &= ~FDI_LINK_TRAIN_NONE;
3996                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3997         }
3998         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3999
4000         POSTING_READ(reg);
4001         udelay(150);
4002
4003         for (i = 0; i < 4; i++) {
4004                 reg = FDI_TX_CTL(pipe);
4005                 temp = I915_READ(reg);
4006                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4007                 temp |= snb_b_fdi_train_param[i];
4008                 I915_WRITE(reg, temp);
4009
4010                 POSTING_READ(reg);
4011                 udelay(500);
4012
4013                 for (retry = 0; retry < 5; retry++) {
4014                         reg = FDI_RX_IIR(pipe);
4015                         temp = I915_READ(reg);
4016                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4017                         if (temp & FDI_RX_BIT_LOCK) {
4018                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4019                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
4020                                 break;
4021                         }
4022                         udelay(50);
4023                 }
4024                 if (retry < 5)
4025                         break;
4026         }
4027         if (i == 4)
4028                 DRM_ERROR("FDI train 1 fail!\n");
4029
4030         /* Train 2 */
4031         reg = FDI_TX_CTL(pipe);
4032         temp = I915_READ(reg);
4033         temp &= ~FDI_LINK_TRAIN_NONE;
4034         temp |= FDI_LINK_TRAIN_PATTERN_2;
4035         if (IS_GEN6(dev_priv)) {
4036                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4037                 /* SNB-B */
4038                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
4039         }
4040         I915_WRITE(reg, temp);
4041
4042         reg = FDI_RX_CTL(pipe);
4043         temp = I915_READ(reg);
4044         if (HAS_PCH_CPT(dev_priv)) {
4045                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4046                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4047         } else {
4048                 temp &= ~FDI_LINK_TRAIN_NONE;
4049                 temp |= FDI_LINK_TRAIN_PATTERN_2;
4050         }
4051         I915_WRITE(reg, temp);
4052
4053         POSTING_READ(reg);
4054         udelay(150);
4055
4056         for (i = 0; i < 4; i++) {
4057                 reg = FDI_TX_CTL(pipe);
4058                 temp = I915_READ(reg);
4059                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4060                 temp |= snb_b_fdi_train_param[i];
4061                 I915_WRITE(reg, temp);
4062
4063                 POSTING_READ(reg);
4064                 udelay(500);
4065
4066                 for (retry = 0; retry < 5; retry++) {
4067                         reg = FDI_RX_IIR(pipe);
4068                         temp = I915_READ(reg);
4069                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4070                         if (temp & FDI_RX_SYMBOL_LOCK) {
4071                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4072                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4073                                 break;
4074                         }
4075                         udelay(50);
4076                 }
4077                 if (retry < 5)
4078                         break;
4079         }
4080         if (i == 4)
4081                 DRM_ERROR("FDI train 2 fail!\n");
4082
4083         DRM_DEBUG_KMS("FDI train done.\n");
4084 }
4085
4086 /* Manual link training for Ivy Bridge A0 parts */
4087 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4088                                       const struct intel_crtc_state *crtc_state)
4089 {
4090         struct drm_device *dev = crtc->base.dev;
4091         struct drm_i915_private *dev_priv = to_i915(dev);
4092         int pipe = crtc->pipe;
4093         i915_reg_t reg;
4094         u32 temp, i, j;
4095
4096         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4097            for train result */
4098         reg = FDI_RX_IMR(pipe);
4099         temp = I915_READ(reg);
4100         temp &= ~FDI_RX_SYMBOL_LOCK;
4101         temp &= ~FDI_RX_BIT_LOCK;
4102         I915_WRITE(reg, temp);
4103
4104         POSTING_READ(reg);
4105         udelay(150);
4106
4107         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4108                       I915_READ(FDI_RX_IIR(pipe)));
4109
4110         /* Try each vswing and preemphasis setting twice before moving on */
4111         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4112                 /* disable first in case we need to retry */
4113                 reg = FDI_TX_CTL(pipe);
4114                 temp = I915_READ(reg);
4115                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4116                 temp &= ~FDI_TX_ENABLE;
4117                 I915_WRITE(reg, temp);
4118
4119                 reg = FDI_RX_CTL(pipe);
4120                 temp = I915_READ(reg);
4121                 temp &= ~FDI_LINK_TRAIN_AUTO;
4122                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4123                 temp &= ~FDI_RX_ENABLE;
4124                 I915_WRITE(reg, temp);
4125
4126                 /* enable CPU FDI TX and PCH FDI RX */
4127                 reg = FDI_TX_CTL(pipe);
4128                 temp = I915_READ(reg);
4129                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4130                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4131                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4132                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4133                 temp |= snb_b_fdi_train_param[j/2];
4134                 temp |= FDI_COMPOSITE_SYNC;
4135                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4136
4137                 I915_WRITE(FDI_RX_MISC(pipe),
4138                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4139
4140                 reg = FDI_RX_CTL(pipe);
4141                 temp = I915_READ(reg);
4142                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4143                 temp |= FDI_COMPOSITE_SYNC;
4144                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4145
4146                 POSTING_READ(reg);
4147                 udelay(1); /* should be 0.5us */
4148
4149                 for (i = 0; i < 4; i++) {
4150                         reg = FDI_RX_IIR(pipe);
4151                         temp = I915_READ(reg);
4152                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4153
4154                         if (temp & FDI_RX_BIT_LOCK ||
4155                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4156                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4157                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4158                                               i);
4159                                 break;
4160                         }
4161                         udelay(1); /* should be 0.5us */
4162                 }
4163                 if (i == 4) {
4164                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4165                         continue;
4166                 }
4167
4168                 /* Train 2 */
4169                 reg = FDI_TX_CTL(pipe);
4170                 temp = I915_READ(reg);
4171                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4172                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4173                 I915_WRITE(reg, temp);
4174
4175                 reg = FDI_RX_CTL(pipe);
4176                 temp = I915_READ(reg);
4177                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4178                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4179                 I915_WRITE(reg, temp);
4180
4181                 POSTING_READ(reg);
4182                 udelay(2); /* should be 1.5us */
4183
4184                 for (i = 0; i < 4; i++) {
4185                         reg = FDI_RX_IIR(pipe);
4186                         temp = I915_READ(reg);
4187                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4188
4189                         if (temp & FDI_RX_SYMBOL_LOCK ||
4190                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4191                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4192                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4193                                               i);
4194                                 goto train_done;
4195                         }
4196                         udelay(2); /* should be 1.5us */
4197                 }
4198                 if (i == 4)
4199                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4200         }
4201
4202 train_done:
4203         DRM_DEBUG_KMS("FDI train done.\n");
4204 }
4205
4206 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4207 {
4208         struct drm_device *dev = intel_crtc->base.dev;
4209         struct drm_i915_private *dev_priv = to_i915(dev);
4210         int pipe = intel_crtc->pipe;
4211         i915_reg_t reg;
4212         u32 temp;
4213
4214         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4215         reg = FDI_RX_CTL(pipe);
4216         temp = I915_READ(reg);
4217         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4218         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4219         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4220         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4221
4222         POSTING_READ(reg);
4223         udelay(200);
4224
4225         /* Switch from Rawclk to PCDclk */
4226         temp = I915_READ(reg);
4227         I915_WRITE(reg, temp | FDI_PCDCLK);
4228
4229         POSTING_READ(reg);
4230         udelay(200);
4231
4232         /* Enable CPU FDI TX PLL, always on for Ironlake */
4233         reg = FDI_TX_CTL(pipe);
4234         temp = I915_READ(reg);
4235         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4236                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4237
4238                 POSTING_READ(reg);
4239                 udelay(100);
4240         }
4241 }
4242
4243 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4244 {
4245         struct drm_device *dev = intel_crtc->base.dev;
4246         struct drm_i915_private *dev_priv = to_i915(dev);
4247         int pipe = intel_crtc->pipe;
4248         i915_reg_t reg;
4249         u32 temp;
4250
4251         /* Switch from PCDclk to Rawclk */
4252         reg = FDI_RX_CTL(pipe);
4253         temp = I915_READ(reg);
4254         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4255
4256         /* Disable CPU FDI TX PLL */
4257         reg = FDI_TX_CTL(pipe);
4258         temp = I915_READ(reg);
4259         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4260
4261         POSTING_READ(reg);
4262         udelay(100);
4263
4264         reg = FDI_RX_CTL(pipe);
4265         temp = I915_READ(reg);
4266         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4267
4268         /* Wait for the clocks to turn off. */
4269         POSTING_READ(reg);
4270         udelay(100);
4271 }
4272
4273 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4274 {
4275         struct drm_device *dev = crtc->dev;
4276         struct drm_i915_private *dev_priv = to_i915(dev);
4277         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4278         int pipe = intel_crtc->pipe;
4279         i915_reg_t reg;
4280         u32 temp;
4281
4282         /* disable CPU FDI tx and PCH FDI rx */
4283         reg = FDI_TX_CTL(pipe);
4284         temp = I915_READ(reg);
4285         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4286         POSTING_READ(reg);
4287
4288         reg = FDI_RX_CTL(pipe);
4289         temp = I915_READ(reg);
4290         temp &= ~(0x7 << 16);
4291         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4292         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4293
4294         POSTING_READ(reg);
4295         udelay(100);
4296
4297         /* Ironlake workaround, disable clock pointer after downing FDI */
4298         if (HAS_PCH_IBX(dev_priv))
4299                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4300
4301         /* still set train pattern 1 */
4302         reg = FDI_TX_CTL(pipe);
4303         temp = I915_READ(reg);
4304         temp &= ~FDI_LINK_TRAIN_NONE;
4305         temp |= FDI_LINK_TRAIN_PATTERN_1;
4306         I915_WRITE(reg, temp);
4307
4308         reg = FDI_RX_CTL(pipe);
4309         temp = I915_READ(reg);
4310         if (HAS_PCH_CPT(dev_priv)) {
4311                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4312                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4313         } else {
4314                 temp &= ~FDI_LINK_TRAIN_NONE;
4315                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4316         }
4317         /* BPC in FDI rx is consistent with that in PIPECONF */
4318         temp &= ~(0x07 << 16);
4319         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4320         I915_WRITE(reg, temp);
4321
4322         POSTING_READ(reg);
4323         udelay(100);
4324 }
4325
4326 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4327 {
4328         struct drm_crtc *crtc;
4329         bool cleanup_done;
4330
4331         drm_for_each_crtc(crtc, &dev_priv->drm) {
4332                 struct drm_crtc_commit *commit;
4333                 spin_lock(&crtc->commit_lock);
4334                 commit = list_first_entry_or_null(&crtc->commit_list,
4335                                                   struct drm_crtc_commit, commit_entry);
4336                 cleanup_done = commit ?
4337                         try_wait_for_completion(&commit->cleanup_done) : true;
4338                 spin_unlock(&crtc->commit_lock);
4339
4340                 if (cleanup_done)
4341                         continue;
4342
4343                 drm_crtc_wait_one_vblank(crtc);
4344
4345                 return true;
4346         }
4347
4348         return false;
4349 }
4350
4351 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4352 {
4353         u32 temp;
4354
4355         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4356
4357         mutex_lock(&dev_priv->sb_lock);
4358
4359         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4360         temp |= SBI_SSCCTL_DISABLE;
4361         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4362
4363         mutex_unlock(&dev_priv->sb_lock);
4364 }
4365
4366 /* Program iCLKIP clock to the desired frequency */
4367 static void lpt_program_iclkip(struct intel_crtc *crtc)
4368 {
4369         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4370         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4371         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4372         u32 temp;
4373
4374         lpt_disable_iclkip(dev_priv);
4375
4376         /* The iCLK virtual clock root frequency is in MHz,
4377          * but the adjusted_mode->crtc_clock in in KHz. To get the
4378          * divisors, it is necessary to divide one by another, so we
4379          * convert the virtual clock precision to KHz here for higher
4380          * precision.
4381          */
4382         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4383                 u32 iclk_virtual_root_freq = 172800 * 1000;
4384                 u32 iclk_pi_range = 64;
4385                 u32 desired_divisor;
4386
4387                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4388                                                     clock << auxdiv);
4389                 divsel = (desired_divisor / iclk_pi_range) - 2;
4390                 phaseinc = desired_divisor % iclk_pi_range;
4391
4392                 /*
4393                  * Near 20MHz is a corner case which is
4394                  * out of range for the 7-bit divisor
4395                  */
4396                 if (divsel <= 0x7f)
4397                         break;
4398         }
4399
4400         /* This should not happen with any sane values */
4401         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4402                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4403         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4404                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4405
4406         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4407                         clock,
4408                         auxdiv,
4409                         divsel,
4410                         phasedir,
4411                         phaseinc);
4412
4413         mutex_lock(&dev_priv->sb_lock);
4414
4415         /* Program SSCDIVINTPHASE6 */
4416         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4417         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4418         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4419         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4420         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4421         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4422         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4423         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4424
4425         /* Program SSCAUXDIV */
4426         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4427         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4428         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4429         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4430
4431         /* Enable modulator and associated divider */
4432         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4433         temp &= ~SBI_SSCCTL_DISABLE;
4434         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4435
4436         mutex_unlock(&dev_priv->sb_lock);
4437
4438         /* Wait for initialization time */
4439         udelay(24);
4440
4441         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4442 }
4443
4444 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4445 {
4446         u32 divsel, phaseinc, auxdiv;
4447         u32 iclk_virtual_root_freq = 172800 * 1000;
4448         u32 iclk_pi_range = 64;
4449         u32 desired_divisor;
4450         u32 temp;
4451
4452         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4453                 return 0;
4454
4455         mutex_lock(&dev_priv->sb_lock);
4456
4457         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4458         if (temp & SBI_SSCCTL_DISABLE) {
4459                 mutex_unlock(&dev_priv->sb_lock);
4460                 return 0;
4461         }
4462
4463         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4464         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4465                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4466         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4467                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4468
4469         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4470         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4471                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4472
4473         mutex_unlock(&dev_priv->sb_lock);
4474
4475         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4476
4477         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4478                                  desired_divisor << auxdiv);
4479 }
4480
4481 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4482                                                 enum pipe pch_transcoder)
4483 {
4484         struct drm_device *dev = crtc->base.dev;
4485         struct drm_i915_private *dev_priv = to_i915(dev);
4486         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4487
4488         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4489                    I915_READ(HTOTAL(cpu_transcoder)));
4490         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4491                    I915_READ(HBLANK(cpu_transcoder)));
4492         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4493                    I915_READ(HSYNC(cpu_transcoder)));
4494
4495         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4496                    I915_READ(VTOTAL(cpu_transcoder)));
4497         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4498                    I915_READ(VBLANK(cpu_transcoder)));
4499         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4500                    I915_READ(VSYNC(cpu_transcoder)));
4501         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4502                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4503 }
4504
4505 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4506 {
4507         struct drm_i915_private *dev_priv = to_i915(dev);
4508         uint32_t temp;
4509
4510         temp = I915_READ(SOUTH_CHICKEN1);
4511         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4512                 return;
4513
4514         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4515         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4516
4517         temp &= ~FDI_BC_BIFURCATION_SELECT;
4518         if (enable)
4519                 temp |= FDI_BC_BIFURCATION_SELECT;
4520
4521         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4522         I915_WRITE(SOUTH_CHICKEN1, temp);
4523         POSTING_READ(SOUTH_CHICKEN1);
4524 }
4525
4526 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4527 {
4528         struct drm_device *dev = intel_crtc->base.dev;
4529
4530         switch (intel_crtc->pipe) {
4531         case PIPE_A:
4532                 break;
4533         case PIPE_B:
4534                 if (intel_crtc->config->fdi_lanes > 2)
4535                         cpt_set_fdi_bc_bifurcation(dev, false);
4536                 else
4537                         cpt_set_fdi_bc_bifurcation(dev, true);
4538
4539                 break;
4540         case PIPE_C:
4541                 cpt_set_fdi_bc_bifurcation(dev, true);
4542
4543                 break;
4544         default:
4545                 BUG();
4546         }
4547 }
4548
4549 /* Return which DP Port should be selected for Transcoder DP control */
4550 static enum port
4551 intel_trans_dp_port_sel(struct intel_crtc *crtc)
4552 {
4553         struct drm_device *dev = crtc->base.dev;
4554         struct intel_encoder *encoder;
4555
4556         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
4557                 if (encoder->type == INTEL_OUTPUT_DP ||
4558                     encoder->type == INTEL_OUTPUT_EDP)
4559                         return encoder->port;
4560         }
4561
4562         return -1;
4563 }
4564
4565 /*
4566  * Enable PCH resources required for PCH ports:
4567  *   - PCH PLLs
4568  *   - FDI training & RX/TX
4569  *   - update transcoder timings
4570  *   - DP transcoding bits
4571  *   - transcoder
4572  */
4573 static void ironlake_pch_enable(const struct intel_crtc_state *crtc_state)
4574 {
4575         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4576         struct drm_device *dev = crtc->base.dev;
4577         struct drm_i915_private *dev_priv = to_i915(dev);
4578         int pipe = crtc->pipe;
4579         u32 temp;
4580
4581         assert_pch_transcoder_disabled(dev_priv, pipe);
4582
4583         if (IS_IVYBRIDGE(dev_priv))
4584                 ivybridge_update_fdi_bc_bifurcation(crtc);
4585
4586         /* Write the TU size bits before fdi link training, so that error
4587          * detection works. */
4588         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4589                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4590
4591         /* For PCH output, training FDI link */
4592         dev_priv->display.fdi_link_train(crtc, crtc_state);
4593
4594         /* We need to program the right clock selection before writing the pixel
4595          * mutliplier into the DPLL. */
4596         if (HAS_PCH_CPT(dev_priv)) {
4597                 u32 sel;
4598
4599                 temp = I915_READ(PCH_DPLL_SEL);
4600                 temp |= TRANS_DPLL_ENABLE(pipe);
4601                 sel = TRANS_DPLLB_SEL(pipe);
4602                 if (crtc_state->shared_dpll ==
4603                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4604                         temp |= sel;
4605                 else
4606                         temp &= ~sel;
4607                 I915_WRITE(PCH_DPLL_SEL, temp);
4608         }
4609
4610         /* XXX: pch pll's can be enabled any time before we enable the PCH
4611          * transcoder, and we actually should do this to not upset any PCH
4612          * transcoder that already use the clock when we share it.
4613          *
4614          * Note that enable_shared_dpll tries to do the right thing, but
4615          * get_shared_dpll unconditionally resets the pll - we need that to have
4616          * the right LVDS enable sequence. */
4617         intel_enable_shared_dpll(crtc);
4618
4619         /* set transcoder timing, panel must allow it */
4620         assert_panel_unlocked(dev_priv, pipe);
4621         ironlake_pch_transcoder_set_timings(crtc, pipe);
4622
4623         intel_fdi_normal_train(crtc);
4624
4625         /* For PCH DP, enable TRANS_DP_CTL */
4626         if (HAS_PCH_CPT(dev_priv) &&
4627             intel_crtc_has_dp_encoder(crtc_state)) {
4628                 const struct drm_display_mode *adjusted_mode =
4629                         &crtc_state->base.adjusted_mode;
4630                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4631                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4632                 temp = I915_READ(reg);
4633                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4634                           TRANS_DP_SYNC_MASK |
4635                           TRANS_DP_BPC_MASK);
4636                 temp |= TRANS_DP_OUTPUT_ENABLE;
4637                 temp |= bpc << 9; /* same format but at 11:9 */
4638
4639                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4640                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4641                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4642                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4643
4644                 switch (intel_trans_dp_port_sel(crtc)) {
4645                 case PORT_B:
4646                         temp |= TRANS_DP_PORT_SEL_B;
4647                         break;
4648                 case PORT_C:
4649                         temp |= TRANS_DP_PORT_SEL_C;
4650                         break;
4651                 case PORT_D:
4652                         temp |= TRANS_DP_PORT_SEL_D;
4653                         break;
4654                 default:
4655                         BUG();
4656                 }
4657
4658                 I915_WRITE(reg, temp);
4659         }
4660
4661         ironlake_enable_pch_transcoder(dev_priv, pipe);
4662 }
4663
4664 static void lpt_pch_enable(const struct intel_crtc_state *crtc_state)
4665 {
4666         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4667         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4668         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4669
4670         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4671
4672         lpt_program_iclkip(crtc);
4673
4674         /* Set transcoder timing. */
4675         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4676
4677         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4678 }
4679
4680 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4681 {
4682         struct drm_i915_private *dev_priv = to_i915(dev);
4683         i915_reg_t dslreg = PIPEDSL(pipe);
4684         u32 temp;
4685
4686         temp = I915_READ(dslreg);
4687         udelay(500);
4688         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4689                 if (wait_for(I915_READ(dslreg) != temp, 5))
4690                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4691         }
4692 }
4693
4694 static int
4695 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4696                   unsigned int scaler_user, int *scaler_id,
4697                   int src_w, int src_h, int dst_w, int dst_h)
4698 {
4699         struct intel_crtc_scaler_state *scaler_state =
4700                 &crtc_state->scaler_state;
4701         struct intel_crtc *intel_crtc =
4702                 to_intel_crtc(crtc_state->base.crtc);
4703         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4704         const struct drm_display_mode *adjusted_mode =
4705                 &crtc_state->base.adjusted_mode;
4706         int need_scaling;
4707
4708         /*
4709          * Src coordinates are already rotated by 270 degrees for
4710          * the 90/270 degree plane rotation cases (to match the
4711          * GTT mapping), hence no need to account for rotation here.
4712          */
4713         need_scaling = src_w != dst_w || src_h != dst_h;
4714
4715         if (crtc_state->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4716                 need_scaling = true;
4717
4718         /*
4719          * Scaling/fitting not supported in IF-ID mode in GEN9+
4720          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4721          * Once NV12 is enabled, handle it here while allocating scaler
4722          * for NV12.
4723          */
4724         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4725             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4726                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4727                 return -EINVAL;
4728         }
4729
4730         /*
4731          * if plane is being disabled or scaler is no more required or force detach
4732          *  - free scaler binded to this plane/crtc
4733          *  - in order to do this, update crtc->scaler_usage
4734          *
4735          * Here scaler state in crtc_state is set free so that
4736          * scaler can be assigned to other user. Actual register
4737          * update to free the scaler is done in plane/panel-fit programming.
4738          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4739          */
4740         if (force_detach || !need_scaling) {
4741                 if (*scaler_id >= 0) {
4742                         scaler_state->scaler_users &= ~(1 << scaler_user);
4743                         scaler_state->scalers[*scaler_id].in_use = 0;
4744
4745                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4746                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4747                                 intel_crtc->pipe, scaler_user, *scaler_id,
4748                                 scaler_state->scaler_users);
4749                         *scaler_id = -1;
4750                 }
4751                 return 0;
4752         }
4753
4754         /* range checks */
4755         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4756                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4757
4758                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4759                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4760                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4761                         "size is out of scaler range\n",
4762                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4763                 return -EINVAL;
4764         }
4765
4766         /* mark this plane as a scaler user in crtc_state */
4767         scaler_state->scaler_users |= (1 << scaler_user);
4768         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4769                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4770                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4771                 scaler_state->scaler_users);
4772
4773         return 0;
4774 }
4775
4776 /**
4777  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4778  *
4779  * @state: crtc's scaler state
4780  *
4781  * Return
4782  *     0 - scaler_usage updated successfully
4783  *    error - requested scaling cannot be supported or other error condition
4784  */
4785 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4786 {
4787         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4788
4789         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4790                 &state->scaler_state.scaler_id,
4791                 state->pipe_src_w, state->pipe_src_h,
4792                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4793 }
4794
4795 /**
4796  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4797  * @crtc_state: crtc's scaler state
4798  * @plane_state: atomic plane state to update
4799  *
4800  * Return
4801  *     0 - scaler_usage updated successfully
4802  *    error - requested scaling cannot be supported or other error condition
4803  */
4804 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4805                                    struct intel_plane_state *plane_state)
4806 {
4807
4808         struct intel_plane *intel_plane =
4809                 to_intel_plane(plane_state->base.plane);
4810         struct drm_framebuffer *fb = plane_state->base.fb;
4811         int ret;
4812
4813         bool force_detach = !fb || !plane_state->base.visible;
4814
4815         ret = skl_update_scaler(crtc_state, force_detach,
4816                                 drm_plane_index(&intel_plane->base),
4817                                 &plane_state->scaler_id,
4818                                 drm_rect_width(&plane_state->base.src) >> 16,
4819                                 drm_rect_height(&plane_state->base.src) >> 16,
4820                                 drm_rect_width(&plane_state->base.dst),
4821                                 drm_rect_height(&plane_state->base.dst));
4822
4823         if (ret || plane_state->scaler_id < 0)
4824                 return ret;
4825
4826         /* check colorkey */
4827         if (plane_state->ckey.flags) {
4828                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4829                               intel_plane->base.base.id,
4830                               intel_plane->base.name);
4831                 return -EINVAL;
4832         }
4833
4834         /* Check src format */
4835         switch (fb->format->format) {
4836         case DRM_FORMAT_RGB565:
4837         case DRM_FORMAT_XBGR8888:
4838         case DRM_FORMAT_XRGB8888:
4839         case DRM_FORMAT_ABGR8888:
4840         case DRM_FORMAT_ARGB8888:
4841         case DRM_FORMAT_XRGB2101010:
4842         case DRM_FORMAT_XBGR2101010:
4843         case DRM_FORMAT_YUYV:
4844         case DRM_FORMAT_YVYU:
4845         case DRM_FORMAT_UYVY:
4846         case DRM_FORMAT_VYUY:
4847                 break;
4848         default:
4849                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4850                               intel_plane->base.base.id, intel_plane->base.name,
4851                               fb->base.id, fb->format->format);
4852                 return -EINVAL;
4853         }
4854
4855         return 0;
4856 }
4857
4858 static void skylake_scaler_disable(struct intel_crtc *crtc)
4859 {
4860         int i;
4861
4862         for (i = 0; i < crtc->num_scalers; i++)
4863                 skl_detach_scaler(crtc, i);
4864 }
4865
4866 static void skylake_pfit_enable(struct intel_crtc *crtc)
4867 {
4868         struct drm_device *dev = crtc->base.dev;
4869         struct drm_i915_private *dev_priv = to_i915(dev);
4870         int pipe = crtc->pipe;
4871         struct intel_crtc_scaler_state *scaler_state =
4872                 &crtc->config->scaler_state;
4873
4874         if (crtc->config->pch_pfit.enabled) {
4875                 int id;
4876
4877                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4878                         return;
4879
4880                 id = scaler_state->scaler_id;
4881                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4882                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4883                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4884                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4885         }
4886 }
4887
4888 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4889 {
4890         struct drm_device *dev = crtc->base.dev;
4891         struct drm_i915_private *dev_priv = to_i915(dev);
4892         int pipe = crtc->pipe;
4893
4894         if (crtc->config->pch_pfit.enabled) {
4895                 /* Force use of hard-coded filter coefficients
4896                  * as some pre-programmed values are broken,
4897                  * e.g. x201.
4898                  */
4899                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4900                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4901                                                  PF_PIPE_SEL_IVB(pipe));
4902                 else
4903                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4904                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4905                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4906         }
4907 }
4908
4909 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
4910 {
4911         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4912         struct drm_device *dev = crtc->base.dev;
4913         struct drm_i915_private *dev_priv = to_i915(dev);
4914
4915         if (!crtc_state->ips_enabled)
4916                 return;
4917
4918         /*
4919          * We can only enable IPS after we enable a plane and wait for a vblank
4920          * This function is called from post_plane_update, which is run after
4921          * a vblank wait.
4922          */
4923         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
4924
4925         if (IS_BROADWELL(dev_priv)) {
4926                 mutex_lock(&dev_priv->pcu_lock);
4927                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
4928                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
4929                 mutex_unlock(&dev_priv->pcu_lock);
4930                 /* Quoting Art Runyan: "its not safe to expect any particular
4931                  * value in IPS_CTL bit 31 after enabling IPS through the
4932                  * mailbox." Moreover, the mailbox may return a bogus state,
4933                  * so we need to just enable it and continue on.
4934                  */
4935         } else {
4936                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4937                 /* The bit only becomes 1 in the next vblank, so this wait here
4938                  * is essentially intel_wait_for_vblank. If we don't have this
4939                  * and don't wait for vblanks until the end of crtc_enable, then
4940                  * the HW state readout code will complain that the expected
4941                  * IPS_CTL value is not the one we read. */
4942                 if (intel_wait_for_register(dev_priv,
4943                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4944                                             50))
4945                         DRM_ERROR("Timed out waiting for IPS enable\n");
4946         }
4947 }
4948
4949 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
4950 {
4951         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4952         struct drm_device *dev = crtc->base.dev;
4953         struct drm_i915_private *dev_priv = to_i915(dev);
4954
4955         if (!crtc_state->ips_enabled)
4956                 return;
4957
4958         if (IS_BROADWELL(dev_priv)) {
4959                 mutex_lock(&dev_priv->pcu_lock);
4960                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4961                 mutex_unlock(&dev_priv->pcu_lock);
4962                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4963                 if (intel_wait_for_register(dev_priv,
4964                                             IPS_CTL, IPS_ENABLE, 0,
4965                                             42))
4966                         DRM_ERROR("Timed out waiting for IPS disable\n");
4967         } else {
4968                 I915_WRITE(IPS_CTL, 0);
4969                 POSTING_READ(IPS_CTL);
4970         }
4971
4972         /* We need to wait for a vblank before we can disable the plane. */
4973         intel_wait_for_vblank(dev_priv, crtc->pipe);
4974 }
4975
4976 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4977 {
4978         if (intel_crtc->overlay) {
4979                 struct drm_device *dev = intel_crtc->base.dev;
4980
4981                 mutex_lock(&dev->struct_mutex);
4982                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4983                 mutex_unlock(&dev->struct_mutex);
4984         }
4985
4986         /* Let userspace switch the overlay on again. In most cases userspace
4987          * has to recompute where to put it anyway.
4988          */
4989 }
4990
4991 /**
4992  * intel_post_enable_primary - Perform operations after enabling primary plane
4993  * @crtc: the CRTC whose primary plane was just enabled
4994  * @new_crtc_state: the enabling state
4995  *
4996  * Performs potentially sleeping operations that must be done after the primary
4997  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4998  * called due to an explicit primary plane update, or due to an implicit
4999  * re-enable that is caused when a sprite plane is updated to no longer
5000  * completely hide the primary plane.
5001  */
5002 static void
5003 intel_post_enable_primary(struct drm_crtc *crtc,
5004                           const struct intel_crtc_state *new_crtc_state)
5005 {
5006         struct drm_device *dev = crtc->dev;
5007         struct drm_i915_private *dev_priv = to_i915(dev);
5008         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5009         int pipe = intel_crtc->pipe;
5010
5011         /*
5012          * Gen2 reports pipe underruns whenever all planes are disabled.
5013          * So don't enable underrun reporting before at least some planes
5014          * are enabled.
5015          * FIXME: Need to fix the logic to work when we turn off all planes
5016          * but leave the pipe running.
5017          */
5018         if (IS_GEN2(dev_priv))
5019                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5020
5021         /* Underruns don't always raise interrupts, so check manually. */
5022         intel_check_cpu_fifo_underruns(dev_priv);
5023         intel_check_pch_fifo_underruns(dev_priv);
5024 }
5025
5026 /* FIXME get rid of this and use pre_plane_update */
5027 static void
5028 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
5029 {
5030         struct drm_device *dev = crtc->dev;
5031         struct drm_i915_private *dev_priv = to_i915(dev);
5032         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5033         int pipe = intel_crtc->pipe;
5034
5035         /*
5036          * Gen2 reports pipe underruns whenever all planes are disabled.
5037          * So disable underrun reporting before all the planes get disabled.
5038          */
5039         if (IS_GEN2(dev_priv))
5040                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5041
5042         hsw_disable_ips(to_intel_crtc_state(crtc->state));
5043
5044         /*
5045          * Vblank time updates from the shadow to live plane control register
5046          * are blocked if the memory self-refresh mode is active at that
5047          * moment. So to make sure the plane gets truly disabled, disable
5048          * first the self-refresh mode. The self-refresh enable bit in turn
5049          * will be checked/applied by the HW only at the next frame start
5050          * event which is after the vblank start event, so we need to have a
5051          * wait-for-vblank between disabling the plane and the pipe.
5052          */
5053         if (HAS_GMCH_DISPLAY(dev_priv) &&
5054             intel_set_memory_cxsr(dev_priv, false))
5055                 intel_wait_for_vblank(dev_priv, pipe);
5056 }
5057
5058 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
5059                                        const struct intel_crtc_state *new_crtc_state)
5060 {
5061         if (!old_crtc_state->ips_enabled)
5062                 return false;
5063
5064         if (needs_modeset(&new_crtc_state->base))
5065                 return true;
5066
5067         return !new_crtc_state->ips_enabled;
5068 }
5069
5070 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5071                                        const struct intel_crtc_state *new_crtc_state)
5072 {
5073         if (!new_crtc_state->ips_enabled)
5074                 return false;
5075
5076         if (needs_modeset(&new_crtc_state->base))
5077                 return true;
5078
5079         /*
5080          * We can't read out IPS on broadwell, assume the worst and
5081          * forcibly enable IPS on the first fastset.
5082          */
5083         if (new_crtc_state->update_pipe &&
5084             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5085                 return true;
5086
5087         return !old_crtc_state->ips_enabled;
5088 }
5089
5090 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5091 {
5092         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5093         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5094         struct intel_crtc_state *pipe_config =
5095                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5096                                                 crtc);
5097         struct drm_plane *primary = crtc->base.primary;
5098         struct drm_plane_state *old_pri_state =
5099                 drm_atomic_get_existing_plane_state(old_state, primary);
5100
5101         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5102
5103         if (pipe_config->update_wm_post && pipe_config->base.active)
5104                 intel_update_watermarks(crtc);
5105
5106         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5107                 hsw_enable_ips(pipe_config);
5108
5109         if (old_pri_state) {
5110                 struct intel_plane_state *primary_state =
5111                         intel_atomic_get_new_plane_state(to_intel_atomic_state(old_state),
5112                                                          to_intel_plane(primary));
5113                 struct intel_plane_state *old_primary_state =
5114                         to_intel_plane_state(old_pri_state);
5115
5116                 intel_fbc_post_update(crtc);
5117
5118                 if (primary_state->base.visible &&
5119                     (needs_modeset(&pipe_config->base) ||
5120                      !old_primary_state->base.visible))
5121                         intel_post_enable_primary(&crtc->base, pipe_config);
5122         }
5123 }
5124
5125 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5126                                    struct intel_crtc_state *pipe_config)
5127 {
5128         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5129         struct drm_device *dev = crtc->base.dev;
5130         struct drm_i915_private *dev_priv = to_i915(dev);
5131         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5132         struct drm_plane *primary = crtc->base.primary;
5133         struct drm_plane_state *old_pri_state =
5134                 drm_atomic_get_existing_plane_state(old_state, primary);
5135         bool modeset = needs_modeset(&pipe_config->base);
5136         struct intel_atomic_state *old_intel_state =
5137                 to_intel_atomic_state(old_state);
5138
5139         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5140                 hsw_disable_ips(old_crtc_state);
5141
5142         if (old_pri_state) {
5143                 struct intel_plane_state *primary_state =
5144                         intel_atomic_get_new_plane_state(old_intel_state,
5145                                                          to_intel_plane(primary));
5146                 struct intel_plane_state *old_primary_state =
5147                         to_intel_plane_state(old_pri_state);
5148
5149                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5150                 /*
5151                  * Gen2 reports pipe underruns whenever all planes are disabled.
5152                  * So disable underrun reporting before all the planes get disabled.
5153                  */
5154                 if (IS_GEN2(dev_priv) && old_primary_state->base.visible &&
5155                     (modeset || !primary_state->base.visible))
5156                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5157         }
5158
5159         /*
5160          * Vblank time updates from the shadow to live plane control register
5161          * are blocked if the memory self-refresh mode is active at that
5162          * moment. So to make sure the plane gets truly disabled, disable
5163          * first the self-refresh mode. The self-refresh enable bit in turn
5164          * will be checked/applied by the HW only at the next frame start
5165          * event which is after the vblank start event, so we need to have a
5166          * wait-for-vblank between disabling the plane and the pipe.
5167          */
5168         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5169             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5170                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5171
5172         /*
5173          * IVB workaround: must disable low power watermarks for at least
5174          * one frame before enabling scaling.  LP watermarks can be re-enabled
5175          * when scaling is disabled.
5176          *
5177          * WaCxSRDisabledForSpriteScaling:ivb
5178          */
5179         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5180                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5181
5182         /*
5183          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5184          * watermark programming here.
5185          */
5186         if (needs_modeset(&pipe_config->base))
5187                 return;
5188
5189         /*
5190          * For platforms that support atomic watermarks, program the
5191          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5192          * will be the intermediate values that are safe for both pre- and
5193          * post- vblank; when vblank happens, the 'active' values will be set
5194          * to the final 'target' values and we'll do this again to get the
5195          * optimal watermarks.  For gen9+ platforms, the values we program here
5196          * will be the final target values which will get automatically latched
5197          * at vblank time; no further programming will be necessary.
5198          *
5199          * If a platform hasn't been transitioned to atomic watermarks yet,
5200          * we'll continue to update watermarks the old way, if flags tell
5201          * us to.
5202          */
5203         if (dev_priv->display.initial_watermarks != NULL)
5204                 dev_priv->display.initial_watermarks(old_intel_state,
5205                                                      pipe_config);
5206         else if (pipe_config->update_wm_pre)
5207                 intel_update_watermarks(crtc);
5208 }
5209
5210 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5211 {
5212         struct drm_device *dev = crtc->dev;
5213         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5214         struct drm_plane *p;
5215         int pipe = intel_crtc->pipe;
5216
5217         intel_crtc_dpms_overlay_disable(intel_crtc);
5218
5219         drm_for_each_plane_mask(p, dev, plane_mask)
5220                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5221
5222         /*
5223          * FIXME: Once we grow proper nuclear flip support out of this we need
5224          * to compute the mask of flip planes precisely. For the time being
5225          * consider this a flip to a NULL plane.
5226          */
5227         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5228 }
5229
5230 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5231                                           struct intel_crtc_state *crtc_state,
5232                                           struct drm_atomic_state *old_state)
5233 {
5234         struct drm_connector_state *conn_state;
5235         struct drm_connector *conn;
5236         int i;
5237
5238         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5239                 struct intel_encoder *encoder =
5240                         to_intel_encoder(conn_state->best_encoder);
5241
5242                 if (conn_state->crtc != crtc)
5243                         continue;
5244
5245                 if (encoder->pre_pll_enable)
5246                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5247         }
5248 }
5249
5250 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5251                                       struct intel_crtc_state *crtc_state,
5252                                       struct drm_atomic_state *old_state)
5253 {
5254         struct drm_connector_state *conn_state;
5255         struct drm_connector *conn;
5256         int i;
5257
5258         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5259                 struct intel_encoder *encoder =
5260                         to_intel_encoder(conn_state->best_encoder);
5261
5262                 if (conn_state->crtc != crtc)
5263                         continue;
5264
5265                 if (encoder->pre_enable)
5266                         encoder->pre_enable(encoder, crtc_state, conn_state);
5267         }
5268 }
5269
5270 static void intel_encoders_enable(struct drm_crtc *crtc,
5271                                   struct intel_crtc_state *crtc_state,
5272                                   struct drm_atomic_state *old_state)
5273 {
5274         struct drm_connector_state *conn_state;
5275         struct drm_connector *conn;
5276         int i;
5277
5278         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5279                 struct intel_encoder *encoder =
5280                         to_intel_encoder(conn_state->best_encoder);
5281
5282                 if (conn_state->crtc != crtc)
5283                         continue;
5284
5285                 encoder->enable(encoder, crtc_state, conn_state);
5286                 intel_opregion_notify_encoder(encoder, true);
5287         }
5288 }
5289
5290 static void intel_encoders_disable(struct drm_crtc *crtc,
5291                                    struct intel_crtc_state *old_crtc_state,
5292                                    struct drm_atomic_state *old_state)
5293 {
5294         struct drm_connector_state *old_conn_state;
5295         struct drm_connector *conn;
5296         int i;
5297
5298         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5299                 struct intel_encoder *encoder =
5300                         to_intel_encoder(old_conn_state->best_encoder);
5301
5302                 if (old_conn_state->crtc != crtc)
5303                         continue;
5304
5305                 intel_opregion_notify_encoder(encoder, false);
5306                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5307         }
5308 }
5309
5310 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5311                                         struct intel_crtc_state *old_crtc_state,
5312                                         struct drm_atomic_state *old_state)
5313 {
5314         struct drm_connector_state *old_conn_state;
5315         struct drm_connector *conn;
5316         int i;
5317
5318         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5319                 struct intel_encoder *encoder =
5320                         to_intel_encoder(old_conn_state->best_encoder);
5321
5322                 if (old_conn_state->crtc != crtc)
5323                         continue;
5324
5325                 if (encoder->post_disable)
5326                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5327         }
5328 }
5329
5330 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5331                                             struct intel_crtc_state *old_crtc_state,
5332                                             struct drm_atomic_state *old_state)
5333 {
5334         struct drm_connector_state *old_conn_state;
5335         struct drm_connector *conn;
5336         int i;
5337
5338         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5339                 struct intel_encoder *encoder =
5340                         to_intel_encoder(old_conn_state->best_encoder);
5341
5342                 if (old_conn_state->crtc != crtc)
5343                         continue;
5344
5345                 if (encoder->post_pll_disable)
5346                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5347         }
5348 }
5349
5350 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5351                                  struct drm_atomic_state *old_state)
5352 {
5353         struct drm_crtc *crtc = pipe_config->base.crtc;
5354         struct drm_device *dev = crtc->dev;
5355         struct drm_i915_private *dev_priv = to_i915(dev);
5356         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5357         int pipe = intel_crtc->pipe;
5358         struct intel_atomic_state *old_intel_state =
5359                 to_intel_atomic_state(old_state);
5360
5361         if (WARN_ON(intel_crtc->active))
5362                 return;
5363
5364         /*
5365          * Sometimes spurious CPU pipe underruns happen during FDI
5366          * training, at least with VGA+HDMI cloning. Suppress them.
5367          *
5368          * On ILK we get an occasional spurious CPU pipe underruns
5369          * between eDP port A enable and vdd enable. Also PCH port
5370          * enable seems to result in the occasional CPU pipe underrun.
5371          *
5372          * Spurious PCH underruns also occur during PCH enabling.
5373          */
5374         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5375                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5376         if (intel_crtc->config->has_pch_encoder)
5377                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5378
5379         if (intel_crtc->config->has_pch_encoder)
5380                 intel_prepare_shared_dpll(intel_crtc);
5381
5382         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5383                 intel_dp_set_m_n(intel_crtc, M1_N1);
5384
5385         intel_set_pipe_timings(intel_crtc);
5386         intel_set_pipe_src_size(intel_crtc);
5387
5388         if (intel_crtc->config->has_pch_encoder) {
5389                 intel_cpu_transcoder_set_m_n(intel_crtc,
5390                                      &intel_crtc->config->fdi_m_n, NULL);
5391         }
5392
5393         ironlake_set_pipeconf(crtc);
5394
5395         intel_crtc->active = true;
5396
5397         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5398
5399         if (intel_crtc->config->has_pch_encoder) {
5400                 /* Note: FDI PLL enabling _must_ be done before we enable the
5401                  * cpu pipes, hence this is separate from all the other fdi/pch
5402                  * enabling. */
5403                 ironlake_fdi_pll_enable(intel_crtc);
5404         } else {
5405                 assert_fdi_tx_disabled(dev_priv, pipe);
5406                 assert_fdi_rx_disabled(dev_priv, pipe);
5407         }
5408
5409         ironlake_pfit_enable(intel_crtc);
5410
5411         /*
5412          * On ILK+ LUT must be loaded before the pipe is running but with
5413          * clocks enabled
5414          */
5415         intel_color_load_luts(&pipe_config->base);
5416
5417         if (dev_priv->display.initial_watermarks != NULL)
5418                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5419         intel_enable_pipe(pipe_config);
5420
5421         if (intel_crtc->config->has_pch_encoder)
5422                 ironlake_pch_enable(pipe_config);
5423
5424         assert_vblank_disabled(crtc);
5425         drm_crtc_vblank_on(crtc);
5426
5427         intel_encoders_enable(crtc, pipe_config, old_state);
5428
5429         if (HAS_PCH_CPT(dev_priv))
5430                 cpt_verify_modeset(dev, intel_crtc->pipe);
5431
5432         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5433         if (intel_crtc->config->has_pch_encoder)
5434                 intel_wait_for_vblank(dev_priv, pipe);
5435         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5436         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5437 }
5438
5439 /* IPS only exists on ULT machines and is tied to pipe A. */
5440 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5441 {
5442         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5443 }
5444
5445 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5446                                             enum pipe pipe, bool apply)
5447 {
5448         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5449         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5450
5451         if (apply)
5452                 val |= mask;
5453         else
5454                 val &= ~mask;
5455
5456         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5457 }
5458
5459 static void icl_pipe_mbus_enable(struct intel_crtc *crtc)
5460 {
5461         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
5462         enum pipe pipe = crtc->pipe;
5463         uint32_t val;
5464
5465         val = MBUS_DBOX_BW_CREDIT(1) | MBUS_DBOX_A_CREDIT(2);
5466
5467         /* Program B credit equally to all pipes */
5468         val |= MBUS_DBOX_B_CREDIT(24 / INTEL_INFO(dev_priv)->num_pipes);
5469
5470         I915_WRITE(PIPE_MBUS_DBOX_CTL(pipe), val);
5471 }
5472
5473 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5474                                 struct drm_atomic_state *old_state)
5475 {
5476         struct drm_crtc *crtc = pipe_config->base.crtc;
5477         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5478         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5479         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5480         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5481         struct intel_atomic_state *old_intel_state =
5482                 to_intel_atomic_state(old_state);
5483         bool psl_clkgate_wa;
5484
5485         if (WARN_ON(intel_crtc->active))
5486                 return;
5487
5488         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5489
5490         if (intel_crtc->config->shared_dpll)
5491                 intel_enable_shared_dpll(intel_crtc);
5492
5493         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5494                 intel_dp_set_m_n(intel_crtc, M1_N1);
5495
5496         if (!transcoder_is_dsi(cpu_transcoder))
5497                 intel_set_pipe_timings(intel_crtc);
5498
5499         intel_set_pipe_src_size(intel_crtc);
5500
5501         if (cpu_transcoder != TRANSCODER_EDP &&
5502             !transcoder_is_dsi(cpu_transcoder)) {
5503                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5504                            intel_crtc->config->pixel_multiplier - 1);
5505         }
5506
5507         if (intel_crtc->config->has_pch_encoder) {
5508                 intel_cpu_transcoder_set_m_n(intel_crtc,
5509                                      &intel_crtc->config->fdi_m_n, NULL);
5510         }
5511
5512         if (!transcoder_is_dsi(cpu_transcoder))
5513                 haswell_set_pipeconf(crtc);
5514
5515         haswell_set_pipemisc(crtc);
5516
5517         intel_color_set_csc(&pipe_config->base);
5518
5519         intel_crtc->active = true;
5520
5521         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5522
5523         if (!transcoder_is_dsi(cpu_transcoder))
5524                 intel_ddi_enable_pipe_clock(pipe_config);
5525
5526         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5527         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5528                          intel_crtc->config->pch_pfit.enabled;
5529         if (psl_clkgate_wa)
5530                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5531
5532         if (INTEL_GEN(dev_priv) >= 9)
5533                 skylake_pfit_enable(intel_crtc);
5534         else
5535                 ironlake_pfit_enable(intel_crtc);
5536
5537         /*
5538          * On ILK+ LUT must be loaded before the pipe is running but with
5539          * clocks enabled
5540          */
5541         intel_color_load_luts(&pipe_config->base);
5542
5543         intel_ddi_set_pipe_settings(pipe_config);
5544         if (!transcoder_is_dsi(cpu_transcoder))
5545                 intel_ddi_enable_transcoder_func(pipe_config);
5546
5547         if (dev_priv->display.initial_watermarks != NULL)
5548                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5549
5550         if (INTEL_GEN(dev_priv) >= 11)
5551                 icl_pipe_mbus_enable(intel_crtc);
5552
5553         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5554         if (!transcoder_is_dsi(cpu_transcoder))
5555                 intel_enable_pipe(pipe_config);
5556
5557         if (intel_crtc->config->has_pch_encoder)
5558                 lpt_pch_enable(pipe_config);
5559
5560         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5561                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5562
5563         assert_vblank_disabled(crtc);
5564         drm_crtc_vblank_on(crtc);
5565
5566         intel_encoders_enable(crtc, pipe_config, old_state);
5567
5568         if (psl_clkgate_wa) {
5569                 intel_wait_for_vblank(dev_priv, pipe);
5570                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5571         }
5572
5573         /* If we change the relative order between pipe/planes enabling, we need
5574          * to change the workaround. */
5575         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5576         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5577                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5578                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5579         }
5580 }
5581
5582 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5583 {
5584         struct drm_device *dev = crtc->base.dev;
5585         struct drm_i915_private *dev_priv = to_i915(dev);
5586         int pipe = crtc->pipe;
5587
5588         /* To avoid upsetting the power well on haswell only disable the pfit if
5589          * it's in use. The hw state code will make sure we get this right. */
5590         if (force || crtc->config->pch_pfit.enabled) {
5591                 I915_WRITE(PF_CTL(pipe), 0);
5592                 I915_WRITE(PF_WIN_POS(pipe), 0);
5593                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5594         }
5595 }
5596
5597 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5598                                   struct drm_atomic_state *old_state)
5599 {
5600         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5601         struct drm_device *dev = crtc->dev;
5602         struct drm_i915_private *dev_priv = to_i915(dev);
5603         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5604         int pipe = intel_crtc->pipe;
5605
5606         /*
5607          * Sometimes spurious CPU pipe underruns happen when the
5608          * pipe is already disabled, but FDI RX/TX is still enabled.
5609          * Happens at least with VGA+HDMI cloning. Suppress them.
5610          */
5611         if (intel_crtc->config->has_pch_encoder) {
5612                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5613                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5614         }
5615
5616         intel_encoders_disable(crtc, old_crtc_state, old_state);
5617
5618         drm_crtc_vblank_off(crtc);
5619         assert_vblank_disabled(crtc);
5620
5621         intel_disable_pipe(old_crtc_state);
5622
5623         ironlake_pfit_disable(intel_crtc, false);
5624
5625         if (intel_crtc->config->has_pch_encoder)
5626                 ironlake_fdi_disable(crtc);
5627
5628         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5629
5630         if (intel_crtc->config->has_pch_encoder) {
5631                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5632
5633                 if (HAS_PCH_CPT(dev_priv)) {
5634                         i915_reg_t reg;
5635                         u32 temp;
5636
5637                         /* disable TRANS_DP_CTL */
5638                         reg = TRANS_DP_CTL(pipe);
5639                         temp = I915_READ(reg);
5640                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5641                                   TRANS_DP_PORT_SEL_MASK);
5642                         temp |= TRANS_DP_PORT_SEL_NONE;
5643                         I915_WRITE(reg, temp);
5644
5645                         /* disable DPLL_SEL */
5646                         temp = I915_READ(PCH_DPLL_SEL);
5647                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5648                         I915_WRITE(PCH_DPLL_SEL, temp);
5649                 }
5650
5651                 ironlake_fdi_pll_disable(intel_crtc);
5652         }
5653
5654         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5655         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5656 }
5657
5658 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5659                                  struct drm_atomic_state *old_state)
5660 {
5661         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5662         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5663         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5664         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5665
5666         intel_encoders_disable(crtc, old_crtc_state, old_state);
5667
5668         drm_crtc_vblank_off(crtc);
5669         assert_vblank_disabled(crtc);
5670
5671         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5672         if (!transcoder_is_dsi(cpu_transcoder))
5673                 intel_disable_pipe(old_crtc_state);
5674
5675         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5676                 intel_ddi_set_vc_payload_alloc(intel_crtc->config, false);
5677
5678         if (!transcoder_is_dsi(cpu_transcoder))
5679                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5680
5681         if (INTEL_GEN(dev_priv) >= 9)
5682                 skylake_scaler_disable(intel_crtc);
5683         else
5684                 ironlake_pfit_disable(intel_crtc, false);
5685
5686         if (!transcoder_is_dsi(cpu_transcoder))
5687                 intel_ddi_disable_pipe_clock(intel_crtc->config);
5688
5689         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5690 }
5691
5692 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5693 {
5694         struct drm_device *dev = crtc->base.dev;
5695         struct drm_i915_private *dev_priv = to_i915(dev);
5696         struct intel_crtc_state *pipe_config = crtc->config;
5697
5698         if (!pipe_config->gmch_pfit.control)
5699                 return;
5700
5701         /*
5702          * The panel fitter should only be adjusted whilst the pipe is disabled,
5703          * according to register description and PRM.
5704          */
5705         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5706         assert_pipe_disabled(dev_priv, crtc->pipe);
5707
5708         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5709         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5710
5711         /* Border color in case we don't scale up to the full screen. Black by
5712          * default, change to something else for debugging. */
5713         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5714 }
5715
5716 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5717 {
5718         switch (port) {
5719         case PORT_A:
5720                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5721         case PORT_B:
5722                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5723         case PORT_C:
5724                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5725         case PORT_D:
5726                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5727         case PORT_E:
5728                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5729         case PORT_F:
5730                 return POWER_DOMAIN_PORT_DDI_F_LANES;
5731         default:
5732                 MISSING_CASE(port);
5733                 return POWER_DOMAIN_PORT_OTHER;
5734         }
5735 }
5736
5737 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5738                                   struct intel_crtc_state *crtc_state)
5739 {
5740         struct drm_device *dev = crtc->dev;
5741         struct drm_i915_private *dev_priv = to_i915(dev);
5742         struct drm_encoder *encoder;
5743         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5744         enum pipe pipe = intel_crtc->pipe;
5745         u64 mask;
5746         enum transcoder transcoder = crtc_state->cpu_transcoder;
5747
5748         if (!crtc_state->base.active)
5749                 return 0;
5750
5751         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
5752         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
5753         if (crtc_state->pch_pfit.enabled ||
5754             crtc_state->pch_pfit.force_thru)
5755                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5756
5757         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5758                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5759
5760                 mask |= BIT_ULL(intel_encoder->power_domain);
5761         }
5762
5763         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5764                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
5765
5766         if (crtc_state->shared_dpll)
5767                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5768
5769         return mask;
5770 }
5771
5772 static u64
5773 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5774                                struct intel_crtc_state *crtc_state)
5775 {
5776         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5777         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5778         enum intel_display_power_domain domain;
5779         u64 domains, new_domains, old_domains;
5780
5781         old_domains = intel_crtc->enabled_power_domains;
5782         intel_crtc->enabled_power_domains = new_domains =
5783                 get_crtc_power_domains(crtc, crtc_state);
5784
5785         domains = new_domains & ~old_domains;
5786
5787         for_each_power_domain(domain, domains)
5788                 intel_display_power_get(dev_priv, domain);
5789
5790         return old_domains & ~new_domains;
5791 }
5792
5793 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5794                                       u64 domains)
5795 {
5796         enum intel_display_power_domain domain;
5797
5798         for_each_power_domain(domain, domains)
5799                 intel_display_power_put(dev_priv, domain);
5800 }
5801
5802 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5803                                    struct drm_atomic_state *old_state)
5804 {
5805         struct intel_atomic_state *old_intel_state =
5806                 to_intel_atomic_state(old_state);
5807         struct drm_crtc *crtc = pipe_config->base.crtc;
5808         struct drm_device *dev = crtc->dev;
5809         struct drm_i915_private *dev_priv = to_i915(dev);
5810         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5811         int pipe = intel_crtc->pipe;
5812
5813         if (WARN_ON(intel_crtc->active))
5814                 return;
5815
5816         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5817                 intel_dp_set_m_n(intel_crtc, M1_N1);
5818
5819         intel_set_pipe_timings(intel_crtc);
5820         intel_set_pipe_src_size(intel_crtc);
5821
5822         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
5823                 struct drm_i915_private *dev_priv = to_i915(dev);
5824
5825                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5826                 I915_WRITE(CHV_CANVAS(pipe), 0);
5827         }
5828
5829         i9xx_set_pipeconf(intel_crtc);
5830
5831         intel_crtc->active = true;
5832
5833         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5834
5835         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5836
5837         if (IS_CHERRYVIEW(dev_priv)) {
5838                 chv_prepare_pll(intel_crtc, intel_crtc->config);
5839                 chv_enable_pll(intel_crtc, intel_crtc->config);
5840         } else {
5841                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
5842                 vlv_enable_pll(intel_crtc, intel_crtc->config);
5843         }
5844
5845         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5846
5847         i9xx_pfit_enable(intel_crtc);
5848
5849         intel_color_load_luts(&pipe_config->base);
5850
5851         dev_priv->display.initial_watermarks(old_intel_state,
5852                                              pipe_config);
5853         intel_enable_pipe(pipe_config);
5854
5855         assert_vblank_disabled(crtc);
5856         drm_crtc_vblank_on(crtc);
5857
5858         intel_encoders_enable(crtc, pipe_config, old_state);
5859 }
5860
5861 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5862 {
5863         struct drm_device *dev = crtc->base.dev;
5864         struct drm_i915_private *dev_priv = to_i915(dev);
5865
5866         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5867         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5868 }
5869
5870 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
5871                              struct drm_atomic_state *old_state)
5872 {
5873         struct intel_atomic_state *old_intel_state =
5874                 to_intel_atomic_state(old_state);
5875         struct drm_crtc *crtc = pipe_config->base.crtc;
5876         struct drm_device *dev = crtc->dev;
5877         struct drm_i915_private *dev_priv = to_i915(dev);
5878         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5879         enum pipe pipe = intel_crtc->pipe;
5880
5881         if (WARN_ON(intel_crtc->active))
5882                 return;
5883
5884         i9xx_set_pll_dividers(intel_crtc);
5885
5886         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5887                 intel_dp_set_m_n(intel_crtc, M1_N1);
5888
5889         intel_set_pipe_timings(intel_crtc);
5890         intel_set_pipe_src_size(intel_crtc);
5891
5892         i9xx_set_pipeconf(intel_crtc);
5893
5894         intel_crtc->active = true;
5895
5896         if (!IS_GEN2(dev_priv))
5897                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5898
5899         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5900
5901         i9xx_enable_pll(intel_crtc, pipe_config);
5902
5903         i9xx_pfit_enable(intel_crtc);
5904
5905         intel_color_load_luts(&pipe_config->base);
5906
5907         if (dev_priv->display.initial_watermarks != NULL)
5908                 dev_priv->display.initial_watermarks(old_intel_state,
5909                                                      intel_crtc->config);
5910         else
5911                 intel_update_watermarks(intel_crtc);
5912         intel_enable_pipe(pipe_config);
5913
5914         assert_vblank_disabled(crtc);
5915         drm_crtc_vblank_on(crtc);
5916
5917         intel_encoders_enable(crtc, pipe_config, old_state);
5918 }
5919
5920 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5921 {
5922         struct drm_device *dev = crtc->base.dev;
5923         struct drm_i915_private *dev_priv = to_i915(dev);
5924
5925         if (!crtc->config->gmch_pfit.control)
5926                 return;
5927
5928         assert_pipe_disabled(dev_priv, crtc->pipe);
5929
5930         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5931                          I915_READ(PFIT_CONTROL));
5932         I915_WRITE(PFIT_CONTROL, 0);
5933 }
5934
5935 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
5936                               struct drm_atomic_state *old_state)
5937 {
5938         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5939         struct drm_device *dev = crtc->dev;
5940         struct drm_i915_private *dev_priv = to_i915(dev);
5941         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5942         int pipe = intel_crtc->pipe;
5943
5944         /*
5945          * On gen2 planes are double buffered but the pipe isn't, so we must
5946          * wait for planes to fully turn off before disabling the pipe.
5947          */
5948         if (IS_GEN2(dev_priv))
5949                 intel_wait_for_vblank(dev_priv, pipe);
5950
5951         intel_encoders_disable(crtc, old_crtc_state, old_state);
5952
5953         drm_crtc_vblank_off(crtc);
5954         assert_vblank_disabled(crtc);
5955
5956         intel_disable_pipe(old_crtc_state);
5957
5958         i9xx_pfit_disable(intel_crtc);
5959
5960         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5961
5962         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
5963                 if (IS_CHERRYVIEW(dev_priv))
5964                         chv_disable_pll(dev_priv, pipe);
5965                 else if (IS_VALLEYVIEW(dev_priv))
5966                         vlv_disable_pll(dev_priv, pipe);
5967                 else
5968                         i9xx_disable_pll(intel_crtc);
5969         }
5970
5971         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
5972
5973         if (!IS_GEN2(dev_priv))
5974                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5975
5976         if (!dev_priv->display.initial_watermarks)
5977                 intel_update_watermarks(intel_crtc);
5978
5979         /* clock the pipe down to 640x480@60 to potentially save power */
5980         if (IS_I830(dev_priv))
5981                 i830_enable_pipe(dev_priv, pipe);
5982 }
5983
5984 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
5985                                         struct drm_modeset_acquire_ctx *ctx)
5986 {
5987         struct intel_encoder *encoder;
5988         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5989         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5990         enum intel_display_power_domain domain;
5991         struct intel_plane *plane;
5992         u64 domains;
5993         struct drm_atomic_state *state;
5994         struct intel_crtc_state *crtc_state;
5995         int ret;
5996
5997         if (!intel_crtc->active)
5998                 return;
5999
6000         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
6001                 const struct intel_plane_state *plane_state =
6002                         to_intel_plane_state(plane->base.state);
6003
6004                 if (plane_state->base.visible)
6005                         intel_plane_disable_noatomic(intel_crtc, plane);
6006         }
6007
6008         state = drm_atomic_state_alloc(crtc->dev);
6009         if (!state) {
6010                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
6011                               crtc->base.id, crtc->name);
6012                 return;
6013         }
6014
6015         state->acquire_ctx = ctx;
6016
6017         /* Everything's already locked, -EDEADLK can't happen. */
6018         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
6019         ret = drm_atomic_add_affected_connectors(state, crtc);
6020
6021         WARN_ON(IS_ERR(crtc_state) || ret);
6022
6023         dev_priv->display.crtc_disable(crtc_state, state);
6024
6025         drm_atomic_state_put(state);
6026
6027         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
6028                       crtc->base.id, crtc->name);
6029
6030         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
6031         crtc->state->active = false;
6032         intel_crtc->active = false;
6033         crtc->enabled = false;
6034         crtc->state->connector_mask = 0;
6035         crtc->state->encoder_mask = 0;
6036
6037         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
6038                 encoder->base.crtc = NULL;
6039
6040         intel_fbc_disable(intel_crtc);
6041         intel_update_watermarks(intel_crtc);
6042         intel_disable_shared_dpll(intel_crtc);
6043
6044         domains = intel_crtc->enabled_power_domains;
6045         for_each_power_domain(domain, domains)
6046                 intel_display_power_put(dev_priv, domain);
6047         intel_crtc->enabled_power_domains = 0;
6048
6049         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
6050         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
6051         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
6052 }
6053
6054 /*
6055  * turn all crtc's off, but do not adjust state
6056  * This has to be paired with a call to intel_modeset_setup_hw_state.
6057  */
6058 int intel_display_suspend(struct drm_device *dev)
6059 {
6060         struct drm_i915_private *dev_priv = to_i915(dev);
6061         struct drm_atomic_state *state;
6062         int ret;
6063
6064         state = drm_atomic_helper_suspend(dev);
6065         ret = PTR_ERR_OR_ZERO(state);
6066         if (ret)
6067                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
6068         else
6069                 dev_priv->modeset_restore_state = state;
6070         return ret;
6071 }
6072
6073 void intel_encoder_destroy(struct drm_encoder *encoder)
6074 {
6075         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
6076
6077         drm_encoder_cleanup(encoder);
6078         kfree(intel_encoder);
6079 }
6080
6081 /* Cross check the actual hw state with our own modeset state tracking (and it's
6082  * internal consistency). */
6083 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
6084                                          struct drm_connector_state *conn_state)
6085 {
6086         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6087
6088         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6089                       connector->base.base.id,
6090                       connector->base.name);
6091
6092         if (connector->get_hw_state(connector)) {
6093                 struct intel_encoder *encoder = connector->encoder;
6094
6095                 I915_STATE_WARN(!crtc_state,
6096                          "connector enabled without attached crtc\n");
6097
6098                 if (!crtc_state)
6099                         return;
6100
6101                 I915_STATE_WARN(!crtc_state->active,
6102                       "connector is active, but attached crtc isn't\n");
6103
6104                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6105                         return;
6106
6107                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6108                         "atomic encoder doesn't match attached encoder\n");
6109
6110                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6111                         "attached encoder crtc differs from connector crtc\n");
6112         } else {
6113                 I915_STATE_WARN(crtc_state && crtc_state->active,
6114                         "attached crtc is active, but connector isn't\n");
6115                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6116                         "best encoder set without crtc!\n");
6117         }
6118 }
6119
6120 int intel_connector_init(struct intel_connector *connector)
6121 {
6122         struct intel_digital_connector_state *conn_state;
6123
6124         /*
6125          * Allocate enough memory to hold intel_digital_connector_state,
6126          * This might be a few bytes too many, but for connectors that don't
6127          * need it we'll free the state and allocate a smaller one on the first
6128          * succesful commit anyway.
6129          */
6130         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
6131         if (!conn_state)
6132                 return -ENOMEM;
6133
6134         __drm_atomic_helper_connector_reset(&connector->base,
6135                                             &conn_state->base);
6136
6137         return 0;
6138 }
6139
6140 struct intel_connector *intel_connector_alloc(void)
6141 {
6142         struct intel_connector *connector;
6143
6144         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6145         if (!connector)
6146                 return NULL;
6147
6148         if (intel_connector_init(connector) < 0) {
6149                 kfree(connector);
6150                 return NULL;
6151         }
6152
6153         return connector;
6154 }
6155
6156 /*
6157  * Free the bits allocated by intel_connector_alloc.
6158  * This should only be used after intel_connector_alloc has returned
6159  * successfully, and before drm_connector_init returns successfully.
6160  * Otherwise the destroy callbacks for the connector and the state should
6161  * take care of proper cleanup/free
6162  */
6163 void intel_connector_free(struct intel_connector *connector)
6164 {
6165         kfree(to_intel_digital_connector_state(connector->base.state));
6166         kfree(connector);
6167 }
6168
6169 /* Simple connector->get_hw_state implementation for encoders that support only
6170  * one connector and no cloning and hence the encoder state determines the state
6171  * of the connector. */
6172 bool intel_connector_get_hw_state(struct intel_connector *connector)
6173 {
6174         enum pipe pipe = 0;
6175         struct intel_encoder *encoder = connector->encoder;
6176
6177         return encoder->get_hw_state(encoder, &pipe);
6178 }
6179
6180 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6181 {
6182         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6183                 return crtc_state->fdi_lanes;
6184
6185         return 0;
6186 }
6187
6188 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6189                                      struct intel_crtc_state *pipe_config)
6190 {
6191         struct drm_i915_private *dev_priv = to_i915(dev);
6192         struct drm_atomic_state *state = pipe_config->base.state;
6193         struct intel_crtc *other_crtc;
6194         struct intel_crtc_state *other_crtc_state;
6195
6196         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6197                       pipe_name(pipe), pipe_config->fdi_lanes);
6198         if (pipe_config->fdi_lanes > 4) {
6199                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6200                               pipe_name(pipe), pipe_config->fdi_lanes);
6201                 return -EINVAL;
6202         }
6203
6204         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6205                 if (pipe_config->fdi_lanes > 2) {
6206                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6207                                       pipe_config->fdi_lanes);
6208                         return -EINVAL;
6209                 } else {
6210                         return 0;
6211                 }
6212         }
6213
6214         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6215                 return 0;
6216
6217         /* Ivybridge 3 pipe is really complicated */
6218         switch (pipe) {
6219         case PIPE_A:
6220                 return 0;
6221         case PIPE_B:
6222                 if (pipe_config->fdi_lanes <= 2)
6223                         return 0;
6224
6225                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6226                 other_crtc_state =
6227                         intel_atomic_get_crtc_state(state, other_crtc);
6228                 if (IS_ERR(other_crtc_state))
6229                         return PTR_ERR(other_crtc_state);
6230
6231                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6232                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6233                                       pipe_name(pipe), pipe_config->fdi_lanes);
6234                         return -EINVAL;
6235                 }
6236                 return 0;
6237         case PIPE_C:
6238                 if (pipe_config->fdi_lanes > 2) {
6239                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6240                                       pipe_name(pipe), pipe_config->fdi_lanes);
6241                         return -EINVAL;
6242                 }
6243
6244                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6245                 other_crtc_state =
6246                         intel_atomic_get_crtc_state(state, other_crtc);
6247                 if (IS_ERR(other_crtc_state))
6248                         return PTR_ERR(other_crtc_state);
6249
6250                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6251                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6252                         return -EINVAL;
6253                 }
6254                 return 0;
6255         default:
6256                 BUG();
6257         }
6258 }
6259
6260 #define RETRY 1
6261 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6262                                        struct intel_crtc_state *pipe_config)
6263 {
6264         struct drm_device *dev = intel_crtc->base.dev;
6265         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6266         int lane, link_bw, fdi_dotclock, ret;
6267         bool needs_recompute = false;
6268
6269 retry:
6270         /* FDI is a binary signal running at ~2.7GHz, encoding
6271          * each output octet as 10 bits. The actual frequency
6272          * is stored as a divider into a 100MHz clock, and the
6273          * mode pixel clock is stored in units of 1KHz.
6274          * Hence the bw of each lane in terms of the mode signal
6275          * is:
6276          */
6277         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6278
6279         fdi_dotclock = adjusted_mode->crtc_clock;
6280
6281         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6282                                            pipe_config->pipe_bpp);
6283
6284         pipe_config->fdi_lanes = lane;
6285
6286         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6287                                link_bw, &pipe_config->fdi_m_n, false);
6288
6289         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6290         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6291                 pipe_config->pipe_bpp -= 2*3;
6292                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6293                               pipe_config->pipe_bpp);
6294                 needs_recompute = true;
6295                 pipe_config->bw_constrained = true;
6296
6297                 goto retry;
6298         }
6299
6300         if (needs_recompute)
6301                 return RETRY;
6302
6303         return ret;
6304 }
6305
6306 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6307 {
6308         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6309         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6310
6311         /* IPS only exists on ULT machines and is tied to pipe A. */
6312         if (!hsw_crtc_supports_ips(crtc))
6313                 return false;
6314
6315         if (!i915_modparams.enable_ips)
6316                 return false;
6317
6318         if (crtc_state->pipe_bpp > 24)
6319                 return false;
6320
6321         /*
6322          * We compare against max which means we must take
6323          * the increased cdclk requirement into account when
6324          * calculating the new cdclk.
6325          *
6326          * Should measure whether using a lower cdclk w/o IPS
6327          */
6328         if (IS_BROADWELL(dev_priv) &&
6329             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6330                 return false;
6331
6332         return true;
6333 }
6334
6335 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6336 {
6337         struct drm_i915_private *dev_priv =
6338                 to_i915(crtc_state->base.crtc->dev);
6339         struct intel_atomic_state *intel_state =
6340                 to_intel_atomic_state(crtc_state->base.state);
6341
6342         if (!hsw_crtc_state_ips_capable(crtc_state))
6343                 return false;
6344
6345         if (crtc_state->ips_force_disable)
6346                 return false;
6347
6348         /* IPS should be fine as long as at least one plane is enabled. */
6349         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6350                 return false;
6351
6352         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6353         if (IS_BROADWELL(dev_priv) &&
6354             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6355                 return false;
6356
6357         return true;
6358 }
6359
6360 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6361 {
6362         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6363
6364         /* GDG double wide on either pipe, otherwise pipe A only */
6365         return INTEL_GEN(dev_priv) < 4 &&
6366                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6367 }
6368
6369 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6370 {
6371         uint32_t pixel_rate;
6372
6373         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6374
6375         /*
6376          * We only use IF-ID interlacing. If we ever use
6377          * PF-ID we'll need to adjust the pixel_rate here.
6378          */
6379
6380         if (pipe_config->pch_pfit.enabled) {
6381                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6382                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6383
6384                 pipe_w = pipe_config->pipe_src_w;
6385                 pipe_h = pipe_config->pipe_src_h;
6386
6387                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6388                 pfit_h = pfit_size & 0xFFFF;
6389                 if (pipe_w < pfit_w)
6390                         pipe_w = pfit_w;
6391                 if (pipe_h < pfit_h)
6392                         pipe_h = pfit_h;
6393
6394                 if (WARN_ON(!pfit_w || !pfit_h))
6395                         return pixel_rate;
6396
6397                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6398                                      pfit_w * pfit_h);
6399         }
6400
6401         return pixel_rate;
6402 }
6403
6404 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6405 {
6406         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6407
6408         if (HAS_GMCH_DISPLAY(dev_priv))
6409                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6410                 crtc_state->pixel_rate =
6411                         crtc_state->base.adjusted_mode.crtc_clock;
6412         else
6413                 crtc_state->pixel_rate =
6414                         ilk_pipe_pixel_rate(crtc_state);
6415 }
6416
6417 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6418                                      struct intel_crtc_state *pipe_config)
6419 {
6420         struct drm_device *dev = crtc->base.dev;
6421         struct drm_i915_private *dev_priv = to_i915(dev);
6422         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6423         int clock_limit = dev_priv->max_dotclk_freq;
6424
6425         if (INTEL_GEN(dev_priv) < 4) {
6426                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6427
6428                 /*
6429                  * Enable double wide mode when the dot clock
6430                  * is > 90% of the (display) core speed.
6431                  */
6432                 if (intel_crtc_supports_double_wide(crtc) &&
6433                     adjusted_mode->crtc_clock > clock_limit) {
6434                         clock_limit = dev_priv->max_dotclk_freq;
6435                         pipe_config->double_wide = true;
6436                 }
6437         }
6438
6439         if (adjusted_mode->crtc_clock > clock_limit) {
6440                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6441                               adjusted_mode->crtc_clock, clock_limit,
6442                               yesno(pipe_config->double_wide));
6443                 return -EINVAL;
6444         }
6445
6446         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6447                 /*
6448                  * There is only one pipe CSC unit per pipe, and we need that
6449                  * for output conversion from RGB->YCBCR. So if CTM is already
6450                  * applied we can't support YCBCR420 output.
6451                  */
6452                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6453                 return -EINVAL;
6454         }
6455
6456         /*
6457          * Pipe horizontal size must be even in:
6458          * - DVO ganged mode
6459          * - LVDS dual channel mode
6460          * - Double wide pipe
6461          */
6462         if (pipe_config->pipe_src_w & 1) {
6463                 if (pipe_config->double_wide) {
6464                         DRM_DEBUG_KMS("Odd pipe source width not supported with double wide pipe\n");
6465                         return -EINVAL;
6466                 }
6467
6468                 if (intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6469                     intel_is_dual_link_lvds(dev)) {
6470                         DRM_DEBUG_KMS("Odd pipe source width not supported with dual link LVDS\n");
6471                         return -EINVAL;
6472                 }
6473         }
6474
6475         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6476          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6477          */
6478         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6479                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6480                 return -EINVAL;
6481
6482         intel_crtc_compute_pixel_rate(pipe_config);
6483
6484         if (pipe_config->has_pch_encoder)
6485                 return ironlake_fdi_compute_config(crtc, pipe_config);
6486
6487         return 0;
6488 }
6489
6490 static void
6491 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6492 {
6493         while (*num > DATA_LINK_M_N_MASK ||
6494                *den > DATA_LINK_M_N_MASK) {
6495                 *num >>= 1;
6496                 *den >>= 1;
6497         }
6498 }
6499
6500 static void compute_m_n(unsigned int m, unsigned int n,
6501                         uint32_t *ret_m, uint32_t *ret_n,
6502                         bool reduce_m_n)
6503 {
6504         /*
6505          * Reduce M/N as much as possible without loss in precision. Several DP
6506          * dongles in particular seem to be fussy about too large *link* M/N
6507          * values. The passed in values are more likely to have the least
6508          * significant bits zero than M after rounding below, so do this first.
6509          */
6510         if (reduce_m_n) {
6511                 while ((m & 1) == 0 && (n & 1) == 0) {
6512                         m >>= 1;
6513                         n >>= 1;
6514                 }
6515         }
6516
6517         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6518         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6519         intel_reduce_m_n_ratio(ret_m, ret_n);
6520 }
6521
6522 void
6523 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6524                        int pixel_clock, int link_clock,
6525                        struct intel_link_m_n *m_n,
6526                        bool reduce_m_n)
6527 {
6528         m_n->tu = 64;
6529
6530         compute_m_n(bits_per_pixel * pixel_clock,
6531                     link_clock * nlanes * 8,
6532                     &m_n->gmch_m, &m_n->gmch_n,
6533                     reduce_m_n);
6534
6535         compute_m_n(pixel_clock, link_clock,
6536                     &m_n->link_m, &m_n->link_n,
6537                     reduce_m_n);
6538 }
6539
6540 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6541 {
6542         if (i915_modparams.panel_use_ssc >= 0)
6543                 return i915_modparams.panel_use_ssc != 0;
6544         return dev_priv->vbt.lvds_use_ssc
6545                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6546 }
6547
6548 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6549 {
6550         return (1 << dpll->n) << 16 | dpll->m2;
6551 }
6552
6553 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6554 {
6555         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6556 }
6557
6558 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6559                                      struct intel_crtc_state *crtc_state,
6560                                      struct dpll *reduced_clock)
6561 {
6562         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6563         u32 fp, fp2 = 0;
6564
6565         if (IS_PINEVIEW(dev_priv)) {
6566                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6567                 if (reduced_clock)
6568                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6569         } else {
6570                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6571                 if (reduced_clock)
6572                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6573         }
6574
6575         crtc_state->dpll_hw_state.fp0 = fp;
6576
6577         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6578             reduced_clock) {
6579                 crtc_state->dpll_hw_state.fp1 = fp2;
6580         } else {
6581                 crtc_state->dpll_hw_state.fp1 = fp;
6582         }
6583 }
6584
6585 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6586                 pipe)
6587 {
6588         u32 reg_val;
6589
6590         /*
6591          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6592          * and set it to a reasonable value instead.
6593          */
6594         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6595         reg_val &= 0xffffff00;
6596         reg_val |= 0x00000030;
6597         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6598
6599         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6600         reg_val &= 0x00ffffff;
6601         reg_val |= 0x8c000000;
6602         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6603
6604         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6605         reg_val &= 0xffffff00;
6606         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6607
6608         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6609         reg_val &= 0x00ffffff;
6610         reg_val |= 0xb0000000;
6611         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6612 }
6613
6614 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6615                                          struct intel_link_m_n *m_n)
6616 {
6617         struct drm_device *dev = crtc->base.dev;
6618         struct drm_i915_private *dev_priv = to_i915(dev);
6619         int pipe = crtc->pipe;
6620
6621         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6622         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6623         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6624         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6625 }
6626
6627 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6628                                          struct intel_link_m_n *m_n,
6629                                          struct intel_link_m_n *m2_n2)
6630 {
6631         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6632         int pipe = crtc->pipe;
6633         enum transcoder transcoder = crtc->config->cpu_transcoder;
6634
6635         if (INTEL_GEN(dev_priv) >= 5) {
6636                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6637                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6638                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6639                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6640                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6641                  * for gen < 8) and if DRRS is supported (to make sure the
6642                  * registers are not unnecessarily accessed).
6643                  */
6644                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6645                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6646                         I915_WRITE(PIPE_DATA_M2(transcoder),
6647                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6648                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6649                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6650                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6651                 }
6652         } else {
6653                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6654                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6655                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6656                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6657         }
6658 }
6659
6660 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6661 {
6662         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6663
6664         if (m_n == M1_N1) {
6665                 dp_m_n = &crtc->config->dp_m_n;
6666                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6667         } else if (m_n == M2_N2) {
6668
6669                 /*
6670                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6671                  * needs to be programmed into M1_N1.
6672                  */
6673                 dp_m_n = &crtc->config->dp_m2_n2;
6674         } else {
6675                 DRM_ERROR("Unsupported divider value\n");
6676                 return;
6677         }
6678
6679         if (crtc->config->has_pch_encoder)
6680                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6681         else
6682                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6683 }
6684
6685 static void vlv_compute_dpll(struct intel_crtc *crtc,
6686                              struct intel_crtc_state *pipe_config)
6687 {
6688         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6689                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6690         if (crtc->pipe != PIPE_A)
6691                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6692
6693         /* DPLL not used with DSI, but still need the rest set up */
6694         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6695                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6696                         DPLL_EXT_BUFFER_ENABLE_VLV;
6697
6698         pipe_config->dpll_hw_state.dpll_md =
6699                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6700 }
6701
6702 static void chv_compute_dpll(struct intel_crtc *crtc,
6703                              struct intel_crtc_state *pipe_config)
6704 {
6705         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6706                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6707         if (crtc->pipe != PIPE_A)
6708                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6709
6710         /* DPLL not used with DSI, but still need the rest set up */
6711         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6712                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6713
6714         pipe_config->dpll_hw_state.dpll_md =
6715                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6716 }
6717
6718 static void vlv_prepare_pll(struct intel_crtc *crtc,
6719                             const struct intel_crtc_state *pipe_config)
6720 {
6721         struct drm_device *dev = crtc->base.dev;
6722         struct drm_i915_private *dev_priv = to_i915(dev);
6723         enum pipe pipe = crtc->pipe;
6724         u32 mdiv;
6725         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6726         u32 coreclk, reg_val;
6727
6728         /* Enable Refclk */
6729         I915_WRITE(DPLL(pipe),
6730                    pipe_config->dpll_hw_state.dpll &
6731                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6732
6733         /* No need to actually set up the DPLL with DSI */
6734         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6735                 return;
6736
6737         mutex_lock(&dev_priv->sb_lock);
6738
6739         bestn = pipe_config->dpll.n;
6740         bestm1 = pipe_config->dpll.m1;
6741         bestm2 = pipe_config->dpll.m2;
6742         bestp1 = pipe_config->dpll.p1;
6743         bestp2 = pipe_config->dpll.p2;
6744
6745         /* See eDP HDMI DPIO driver vbios notes doc */
6746
6747         /* PLL B needs special handling */
6748         if (pipe == PIPE_B)
6749                 vlv_pllb_recal_opamp(dev_priv, pipe);
6750
6751         /* Set up Tx target for periodic Rcomp update */
6752         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6753
6754         /* Disable target IRef on PLL */
6755         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6756         reg_val &= 0x00ffffff;
6757         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6758
6759         /* Disable fast lock */
6760         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6761
6762         /* Set idtafcrecal before PLL is enabled */
6763         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6764         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6765         mdiv |= ((bestn << DPIO_N_SHIFT));
6766         mdiv |= (1 << DPIO_K_SHIFT);
6767
6768         /*
6769          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6770          * but we don't support that).
6771          * Note: don't use the DAC post divider as it seems unstable.
6772          */
6773         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6774         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6775
6776         mdiv |= DPIO_ENABLE_CALIBRATION;
6777         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6778
6779         /* Set HBR and RBR LPF coefficients */
6780         if (pipe_config->port_clock == 162000 ||
6781             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6782             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6783                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6784                                  0x009f0003);
6785         else
6786                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6787                                  0x00d0000f);
6788
6789         if (intel_crtc_has_dp_encoder(pipe_config)) {
6790                 /* Use SSC source */
6791                 if (pipe == PIPE_A)
6792                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6793                                          0x0df40000);
6794                 else
6795                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6796                                          0x0df70000);
6797         } else { /* HDMI or VGA */
6798                 /* Use bend source */
6799                 if (pipe == PIPE_A)
6800                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6801                                          0x0df70000);
6802                 else
6803                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6804                                          0x0df40000);
6805         }
6806
6807         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6808         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6809         if (intel_crtc_has_dp_encoder(crtc->config))
6810                 coreclk |= 0x01000000;
6811         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6812
6813         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6814         mutex_unlock(&dev_priv->sb_lock);
6815 }
6816
6817 static void chv_prepare_pll(struct intel_crtc *crtc,
6818                             const struct intel_crtc_state *pipe_config)
6819 {
6820         struct drm_device *dev = crtc->base.dev;
6821         struct drm_i915_private *dev_priv = to_i915(dev);
6822         enum pipe pipe = crtc->pipe;
6823         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6824         u32 loopfilter, tribuf_calcntr;
6825         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6826         u32 dpio_val;
6827         int vco;
6828
6829         /* Enable Refclk and SSC */
6830         I915_WRITE(DPLL(pipe),
6831                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6832
6833         /* No need to actually set up the DPLL with DSI */
6834         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6835                 return;
6836
6837         bestn = pipe_config->dpll.n;
6838         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6839         bestm1 = pipe_config->dpll.m1;
6840         bestm2 = pipe_config->dpll.m2 >> 22;
6841         bestp1 = pipe_config->dpll.p1;
6842         bestp2 = pipe_config->dpll.p2;
6843         vco = pipe_config->dpll.vco;
6844         dpio_val = 0;
6845         loopfilter = 0;
6846
6847         mutex_lock(&dev_priv->sb_lock);
6848
6849         /* p1 and p2 divider */
6850         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6851                         5 << DPIO_CHV_S1_DIV_SHIFT |
6852                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6853                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6854                         1 << DPIO_CHV_K_DIV_SHIFT);
6855
6856         /* Feedback post-divider - m2 */
6857         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6858
6859         /* Feedback refclk divider - n and m1 */
6860         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6861                         DPIO_CHV_M1_DIV_BY_2 |
6862                         1 << DPIO_CHV_N_DIV_SHIFT);
6863
6864         /* M2 fraction division */
6865         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6866
6867         /* M2 fraction division enable */
6868         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6869         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6870         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6871         if (bestm2_frac)
6872                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6873         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6874
6875         /* Program digital lock detect threshold */
6876         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6877         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6878                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6879         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6880         if (!bestm2_frac)
6881                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6882         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6883
6884         /* Loop filter */
6885         if (vco == 5400000) {
6886                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6887                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6888                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6889                 tribuf_calcntr = 0x9;
6890         } else if (vco <= 6200000) {
6891                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6892                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6893                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6894                 tribuf_calcntr = 0x9;
6895         } else if (vco <= 6480000) {
6896                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6897                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6898                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6899                 tribuf_calcntr = 0x8;
6900         } else {
6901                 /* Not supported. Apply the same limits as in the max case */
6902                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6903                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6904                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6905                 tribuf_calcntr = 0;
6906         }
6907         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6908
6909         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6910         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6911         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6912         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
6913
6914         /* AFC Recal */
6915         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6916                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6917                         DPIO_AFC_RECAL);
6918
6919         mutex_unlock(&dev_priv->sb_lock);
6920 }
6921
6922 /**
6923  * vlv_force_pll_on - forcibly enable just the PLL
6924  * @dev_priv: i915 private structure
6925  * @pipe: pipe PLL to enable
6926  * @dpll: PLL configuration
6927  *
6928  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6929  * in cases where we need the PLL enabled even when @pipe is not going to
6930  * be enabled.
6931  */
6932 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
6933                      const struct dpll *dpll)
6934 {
6935         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
6936         struct intel_crtc_state *pipe_config;
6937
6938         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
6939         if (!pipe_config)
6940                 return -ENOMEM;
6941
6942         pipe_config->base.crtc = &crtc->base;
6943         pipe_config->pixel_multiplier = 1;
6944         pipe_config->dpll = *dpll;
6945
6946         if (IS_CHERRYVIEW(dev_priv)) {
6947                 chv_compute_dpll(crtc, pipe_config);
6948                 chv_prepare_pll(crtc, pipe_config);
6949                 chv_enable_pll(crtc, pipe_config);
6950         } else {
6951                 vlv_compute_dpll(crtc, pipe_config);
6952                 vlv_prepare_pll(crtc, pipe_config);
6953                 vlv_enable_pll(crtc, pipe_config);
6954         }
6955
6956         kfree(pipe_config);
6957
6958         return 0;
6959 }
6960
6961 /**
6962  * vlv_force_pll_off - forcibly disable just the PLL
6963  * @dev_priv: i915 private structure
6964  * @pipe: pipe PLL to disable
6965  *
6966  * Disable the PLL for @pipe. To be used in cases where we need
6967  * the PLL enabled even when @pipe is not going to be enabled.
6968  */
6969 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
6970 {
6971         if (IS_CHERRYVIEW(dev_priv))
6972                 chv_disable_pll(dev_priv, pipe);
6973         else
6974                 vlv_disable_pll(dev_priv, pipe);
6975 }
6976
6977 static void i9xx_compute_dpll(struct intel_crtc *crtc,
6978                               struct intel_crtc_state *crtc_state,
6979                               struct dpll *reduced_clock)
6980 {
6981         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6982         u32 dpll;
6983         struct dpll *clock = &crtc_state->dpll;
6984
6985         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6986
6987         dpll = DPLL_VGA_MODE_DIS;
6988
6989         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
6990                 dpll |= DPLLB_MODE_LVDS;
6991         else
6992                 dpll |= DPLLB_MODE_DAC_SERIAL;
6993
6994         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
6995             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
6996                 dpll |= (crtc_state->pixel_multiplier - 1)
6997                         << SDVO_MULTIPLIER_SHIFT_HIRES;
6998         }
6999
7000         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
7001             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
7002                 dpll |= DPLL_SDVO_HIGH_SPEED;
7003
7004         if (intel_crtc_has_dp_encoder(crtc_state))
7005                 dpll |= DPLL_SDVO_HIGH_SPEED;
7006
7007         /* compute bitmask from p1 value */
7008         if (IS_PINEVIEW(dev_priv))
7009                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
7010         else {
7011                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7012                 if (IS_G4X(dev_priv) && reduced_clock)
7013                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
7014         }
7015         switch (clock->p2) {
7016         case 5:
7017                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
7018                 break;
7019         case 7:
7020                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
7021                 break;
7022         case 10:
7023                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
7024                 break;
7025         case 14:
7026                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
7027                 break;
7028         }
7029         if (INTEL_GEN(dev_priv) >= 4)
7030                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
7031
7032         if (crtc_state->sdvo_tv_clock)
7033                 dpll |= PLL_REF_INPUT_TVCLKINBC;
7034         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7035                  intel_panel_use_ssc(dev_priv))
7036                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7037         else
7038                 dpll |= PLL_REF_INPUT_DREFCLK;
7039
7040         dpll |= DPLL_VCO_ENABLE;
7041         crtc_state->dpll_hw_state.dpll = dpll;
7042
7043         if (INTEL_GEN(dev_priv) >= 4) {
7044                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
7045                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
7046                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
7047         }
7048 }
7049
7050 static void i8xx_compute_dpll(struct intel_crtc *crtc,
7051                               struct intel_crtc_state *crtc_state,
7052                               struct dpll *reduced_clock)
7053 {
7054         struct drm_device *dev = crtc->base.dev;
7055         struct drm_i915_private *dev_priv = to_i915(dev);
7056         u32 dpll;
7057         struct dpll *clock = &crtc_state->dpll;
7058
7059         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
7060
7061         dpll = DPLL_VGA_MODE_DIS;
7062
7063         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7064                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7065         } else {
7066                 if (clock->p1 == 2)
7067                         dpll |= PLL_P1_DIVIDE_BY_TWO;
7068                 else
7069                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
7070                 if (clock->p2 == 4)
7071                         dpll |= PLL_P2_DIVIDE_BY_4;
7072         }
7073
7074         if (!IS_I830(dev_priv) &&
7075             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
7076                 dpll |= DPLL_DVO_2X_MODE;
7077
7078         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
7079             intel_panel_use_ssc(dev_priv))
7080                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
7081         else
7082                 dpll |= PLL_REF_INPUT_DREFCLK;
7083
7084         dpll |= DPLL_VCO_ENABLE;
7085         crtc_state->dpll_hw_state.dpll = dpll;
7086 }
7087
7088 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
7089 {
7090         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7091         enum pipe pipe = intel_crtc->pipe;
7092         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
7093         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
7094         uint32_t crtc_vtotal, crtc_vblank_end;
7095         int vsyncshift = 0;
7096
7097         /* We need to be careful not to changed the adjusted mode, for otherwise
7098          * the hw state checker will get angry at the mismatch. */
7099         crtc_vtotal = adjusted_mode->crtc_vtotal;
7100         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7101
7102         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7103                 /* the chip adds 2 halflines automatically */
7104                 crtc_vtotal -= 1;
7105                 crtc_vblank_end -= 1;
7106
7107                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7108                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7109                 else
7110                         vsyncshift = adjusted_mode->crtc_hsync_start -
7111                                 adjusted_mode->crtc_htotal / 2;
7112                 if (vsyncshift < 0)
7113                         vsyncshift += adjusted_mode->crtc_htotal;
7114         }
7115
7116         if (INTEL_GEN(dev_priv) > 3)
7117                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7118
7119         I915_WRITE(HTOTAL(cpu_transcoder),
7120                    (adjusted_mode->crtc_hdisplay - 1) |
7121                    ((adjusted_mode->crtc_htotal - 1) << 16));
7122         I915_WRITE(HBLANK(cpu_transcoder),
7123                    (adjusted_mode->crtc_hblank_start - 1) |
7124                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7125         I915_WRITE(HSYNC(cpu_transcoder),
7126                    (adjusted_mode->crtc_hsync_start - 1) |
7127                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7128
7129         I915_WRITE(VTOTAL(cpu_transcoder),
7130                    (adjusted_mode->crtc_vdisplay - 1) |
7131                    ((crtc_vtotal - 1) << 16));
7132         I915_WRITE(VBLANK(cpu_transcoder),
7133                    (adjusted_mode->crtc_vblank_start - 1) |
7134                    ((crtc_vblank_end - 1) << 16));
7135         I915_WRITE(VSYNC(cpu_transcoder),
7136                    (adjusted_mode->crtc_vsync_start - 1) |
7137                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7138
7139         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7140          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7141          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7142          * bits. */
7143         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7144             (pipe == PIPE_B || pipe == PIPE_C))
7145                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7146
7147 }
7148
7149 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7150 {
7151         struct drm_device *dev = intel_crtc->base.dev;
7152         struct drm_i915_private *dev_priv = to_i915(dev);
7153         enum pipe pipe = intel_crtc->pipe;
7154
7155         /* pipesrc controls the size that is scaled from, which should
7156          * always be the user's requested size.
7157          */
7158         I915_WRITE(PIPESRC(pipe),
7159                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7160                    (intel_crtc->config->pipe_src_h - 1));
7161 }
7162
7163 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7164                                    struct intel_crtc_state *pipe_config)
7165 {
7166         struct drm_device *dev = crtc->base.dev;
7167         struct drm_i915_private *dev_priv = to_i915(dev);
7168         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7169         uint32_t tmp;
7170
7171         tmp = I915_READ(HTOTAL(cpu_transcoder));
7172         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7173         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7174         tmp = I915_READ(HBLANK(cpu_transcoder));
7175         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7176         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7177         tmp = I915_READ(HSYNC(cpu_transcoder));
7178         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7179         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7180
7181         tmp = I915_READ(VTOTAL(cpu_transcoder));
7182         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7183         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7184         tmp = I915_READ(VBLANK(cpu_transcoder));
7185         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7186         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7187         tmp = I915_READ(VSYNC(cpu_transcoder));
7188         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7189         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7190
7191         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7192                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7193                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7194                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7195         }
7196 }
7197
7198 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7199                                     struct intel_crtc_state *pipe_config)
7200 {
7201         struct drm_device *dev = crtc->base.dev;
7202         struct drm_i915_private *dev_priv = to_i915(dev);
7203         u32 tmp;
7204
7205         tmp = I915_READ(PIPESRC(crtc->pipe));
7206         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7207         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7208
7209         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7210         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7211 }
7212
7213 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7214                                  struct intel_crtc_state *pipe_config)
7215 {
7216         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7217         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7218         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7219         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7220
7221         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7222         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7223         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7224         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7225
7226         mode->flags = pipe_config->base.adjusted_mode.flags;
7227         mode->type = DRM_MODE_TYPE_DRIVER;
7228
7229         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7230
7231         mode->hsync = drm_mode_hsync(mode);
7232         mode->vrefresh = drm_mode_vrefresh(mode);
7233         drm_mode_set_name(mode);
7234 }
7235
7236 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7237 {
7238         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7239         uint32_t pipeconf;
7240
7241         pipeconf = 0;
7242
7243         /* we keep both pipes enabled on 830 */
7244         if (IS_I830(dev_priv))
7245                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7246
7247         if (intel_crtc->config->double_wide)
7248                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7249
7250         /* only g4x and later have fancy bpc/dither controls */
7251         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7252             IS_CHERRYVIEW(dev_priv)) {
7253                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7254                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7255                         pipeconf |= PIPECONF_DITHER_EN |
7256                                     PIPECONF_DITHER_TYPE_SP;
7257
7258                 switch (intel_crtc->config->pipe_bpp) {
7259                 case 18:
7260                         pipeconf |= PIPECONF_6BPC;
7261                         break;
7262                 case 24:
7263                         pipeconf |= PIPECONF_8BPC;
7264                         break;
7265                 case 30:
7266                         pipeconf |= PIPECONF_10BPC;
7267                         break;
7268                 default:
7269                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7270                         BUG();
7271                 }
7272         }
7273
7274         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7275                 if (INTEL_GEN(dev_priv) < 4 ||
7276                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7277                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7278                 else
7279                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7280         } else
7281                 pipeconf |= PIPECONF_PROGRESSIVE;
7282
7283         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7284              intel_crtc->config->limited_color_range)
7285                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7286
7287         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7288         POSTING_READ(PIPECONF(intel_crtc->pipe));
7289 }
7290
7291 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7292                                    struct intel_crtc_state *crtc_state)
7293 {
7294         struct drm_device *dev = crtc->base.dev;
7295         struct drm_i915_private *dev_priv = to_i915(dev);
7296         const struct intel_limit *limit;
7297         int refclk = 48000;
7298
7299         memset(&crtc_state->dpll_hw_state, 0,
7300                sizeof(crtc_state->dpll_hw_state));
7301
7302         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7303                 if (intel_panel_use_ssc(dev_priv)) {
7304                         refclk = dev_priv->vbt.lvds_ssc_freq;
7305                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7306                 }
7307
7308                 limit = &intel_limits_i8xx_lvds;
7309         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7310                 limit = &intel_limits_i8xx_dvo;
7311         } else {
7312                 limit = &intel_limits_i8xx_dac;
7313         }
7314
7315         if (!crtc_state->clock_set &&
7316             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7317                                  refclk, NULL, &crtc_state->dpll)) {
7318                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7319                 return -EINVAL;
7320         }
7321
7322         i8xx_compute_dpll(crtc, crtc_state, NULL);
7323
7324         return 0;
7325 }
7326
7327 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7328                                   struct intel_crtc_state *crtc_state)
7329 {
7330         struct drm_device *dev = crtc->base.dev;
7331         struct drm_i915_private *dev_priv = to_i915(dev);
7332         const struct intel_limit *limit;
7333         int refclk = 96000;
7334
7335         memset(&crtc_state->dpll_hw_state, 0,
7336                sizeof(crtc_state->dpll_hw_state));
7337
7338         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7339                 if (intel_panel_use_ssc(dev_priv)) {
7340                         refclk = dev_priv->vbt.lvds_ssc_freq;
7341                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7342                 }
7343
7344                 if (intel_is_dual_link_lvds(dev))
7345                         limit = &intel_limits_g4x_dual_channel_lvds;
7346                 else
7347                         limit = &intel_limits_g4x_single_channel_lvds;
7348         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7349                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7350                 limit = &intel_limits_g4x_hdmi;
7351         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7352                 limit = &intel_limits_g4x_sdvo;
7353         } else {
7354                 /* The option is for other outputs */
7355                 limit = &intel_limits_i9xx_sdvo;
7356         }
7357
7358         if (!crtc_state->clock_set &&
7359             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7360                                 refclk, NULL, &crtc_state->dpll)) {
7361                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7362                 return -EINVAL;
7363         }
7364
7365         i9xx_compute_dpll(crtc, crtc_state, NULL);
7366
7367         return 0;
7368 }
7369
7370 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7371                                   struct intel_crtc_state *crtc_state)
7372 {
7373         struct drm_device *dev = crtc->base.dev;
7374         struct drm_i915_private *dev_priv = to_i915(dev);
7375         const struct intel_limit *limit;
7376         int refclk = 96000;
7377
7378         memset(&crtc_state->dpll_hw_state, 0,
7379                sizeof(crtc_state->dpll_hw_state));
7380
7381         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7382                 if (intel_panel_use_ssc(dev_priv)) {
7383                         refclk = dev_priv->vbt.lvds_ssc_freq;
7384                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7385                 }
7386
7387                 limit = &intel_limits_pineview_lvds;
7388         } else {
7389                 limit = &intel_limits_pineview_sdvo;
7390         }
7391
7392         if (!crtc_state->clock_set &&
7393             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7394                                 refclk, NULL, &crtc_state->dpll)) {
7395                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7396                 return -EINVAL;
7397         }
7398
7399         i9xx_compute_dpll(crtc, crtc_state, NULL);
7400
7401         return 0;
7402 }
7403
7404 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7405                                    struct intel_crtc_state *crtc_state)
7406 {
7407         struct drm_device *dev = crtc->base.dev;
7408         struct drm_i915_private *dev_priv = to_i915(dev);
7409         const struct intel_limit *limit;
7410         int refclk = 96000;
7411
7412         memset(&crtc_state->dpll_hw_state, 0,
7413                sizeof(crtc_state->dpll_hw_state));
7414
7415         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7416                 if (intel_panel_use_ssc(dev_priv)) {
7417                         refclk = dev_priv->vbt.lvds_ssc_freq;
7418                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7419                 }
7420
7421                 limit = &intel_limits_i9xx_lvds;
7422         } else {
7423                 limit = &intel_limits_i9xx_sdvo;
7424         }
7425
7426         if (!crtc_state->clock_set &&
7427             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7428                                  refclk, NULL, &crtc_state->dpll)) {
7429                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7430                 return -EINVAL;
7431         }
7432
7433         i9xx_compute_dpll(crtc, crtc_state, NULL);
7434
7435         return 0;
7436 }
7437
7438 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7439                                   struct intel_crtc_state *crtc_state)
7440 {
7441         int refclk = 100000;
7442         const struct intel_limit *limit = &intel_limits_chv;
7443
7444         memset(&crtc_state->dpll_hw_state, 0,
7445                sizeof(crtc_state->dpll_hw_state));
7446
7447         if (!crtc_state->clock_set &&
7448             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7449                                 refclk, NULL, &crtc_state->dpll)) {
7450                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7451                 return -EINVAL;
7452         }
7453
7454         chv_compute_dpll(crtc, crtc_state);
7455
7456         return 0;
7457 }
7458
7459 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7460                                   struct intel_crtc_state *crtc_state)
7461 {
7462         int refclk = 100000;
7463         const struct intel_limit *limit = &intel_limits_vlv;
7464
7465         memset(&crtc_state->dpll_hw_state, 0,
7466                sizeof(crtc_state->dpll_hw_state));
7467
7468         if (!crtc_state->clock_set &&
7469             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7470                                 refclk, NULL, &crtc_state->dpll)) {
7471                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7472                 return -EINVAL;
7473         }
7474
7475         vlv_compute_dpll(crtc, crtc_state);
7476
7477         return 0;
7478 }
7479
7480 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7481                                  struct intel_crtc_state *pipe_config)
7482 {
7483         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7484         uint32_t tmp;
7485
7486         if (INTEL_GEN(dev_priv) <= 3 &&
7487             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7488                 return;
7489
7490         tmp = I915_READ(PFIT_CONTROL);
7491         if (!(tmp & PFIT_ENABLE))
7492                 return;
7493
7494         /* Check whether the pfit is attached to our pipe. */
7495         if (INTEL_GEN(dev_priv) < 4) {
7496                 if (crtc->pipe != PIPE_B)
7497                         return;
7498         } else {
7499                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7500                         return;
7501         }
7502
7503         pipe_config->gmch_pfit.control = tmp;
7504         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7505 }
7506
7507 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7508                                struct intel_crtc_state *pipe_config)
7509 {
7510         struct drm_device *dev = crtc->base.dev;
7511         struct drm_i915_private *dev_priv = to_i915(dev);
7512         int pipe = pipe_config->cpu_transcoder;
7513         struct dpll clock;
7514         u32 mdiv;
7515         int refclk = 100000;
7516
7517         /* In case of DSI, DPLL will not be used */
7518         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7519                 return;
7520
7521         mutex_lock(&dev_priv->sb_lock);
7522         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7523         mutex_unlock(&dev_priv->sb_lock);
7524
7525         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7526         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7527         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7528         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7529         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7530
7531         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7532 }
7533
7534 static void
7535 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7536                               struct intel_initial_plane_config *plane_config)
7537 {
7538         struct drm_device *dev = crtc->base.dev;
7539         struct drm_i915_private *dev_priv = to_i915(dev);
7540         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7541         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7542         enum pipe pipe = crtc->pipe;
7543         u32 val, base, offset;
7544         int fourcc, pixel_format;
7545         unsigned int aligned_height;
7546         struct drm_framebuffer *fb;
7547         struct intel_framebuffer *intel_fb;
7548
7549         if (!plane->get_hw_state(plane))
7550                 return;
7551
7552         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7553         if (!intel_fb) {
7554                 DRM_DEBUG_KMS("failed to alloc fb\n");
7555                 return;
7556         }
7557
7558         fb = &intel_fb->base;
7559
7560         fb->dev = dev;
7561
7562         val = I915_READ(DSPCNTR(i9xx_plane));
7563
7564         if (INTEL_GEN(dev_priv) >= 4) {
7565                 if (val & DISPPLANE_TILED) {
7566                         plane_config->tiling = I915_TILING_X;
7567                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7568                 }
7569         }
7570
7571         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7572         fourcc = i9xx_format_to_fourcc(pixel_format);
7573         fb->format = drm_format_info(fourcc);
7574
7575         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7576                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7577                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7578         } else if (INTEL_GEN(dev_priv) >= 4) {
7579                 if (plane_config->tiling)
7580                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7581                 else
7582                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7583                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7584         } else {
7585                 base = I915_READ(DSPADDR(i9xx_plane));
7586         }
7587         plane_config->base = base;
7588
7589         val = I915_READ(PIPESRC(pipe));
7590         fb->width = ((val >> 16) & 0xfff) + 1;
7591         fb->height = ((val >> 0) & 0xfff) + 1;
7592
7593         val = I915_READ(DSPSTRIDE(i9xx_plane));
7594         fb->pitches[0] = val & 0xffffffc0;
7595
7596         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7597
7598         plane_config->size = fb->pitches[0] * aligned_height;
7599
7600         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7601                       crtc->base.name, plane->base.name, fb->width, fb->height,
7602                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7603                       plane_config->size);
7604
7605         plane_config->fb = intel_fb;
7606 }
7607
7608 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7609                                struct intel_crtc_state *pipe_config)
7610 {
7611         struct drm_device *dev = crtc->base.dev;
7612         struct drm_i915_private *dev_priv = to_i915(dev);
7613         int pipe = pipe_config->cpu_transcoder;
7614         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7615         struct dpll clock;
7616         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7617         int refclk = 100000;
7618
7619         /* In case of DSI, DPLL will not be used */
7620         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7621                 return;
7622
7623         mutex_lock(&dev_priv->sb_lock);
7624         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7625         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7626         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7627         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7628         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7629         mutex_unlock(&dev_priv->sb_lock);
7630
7631         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7632         clock.m2 = (pll_dw0 & 0xff) << 22;
7633         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7634                 clock.m2 |= pll_dw2 & 0x3fffff;
7635         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7636         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7637         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7638
7639         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7640 }
7641
7642 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7643                                  struct intel_crtc_state *pipe_config)
7644 {
7645         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7646         enum intel_display_power_domain power_domain;
7647         uint32_t tmp;
7648         bool ret;
7649
7650         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7651         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7652                 return false;
7653
7654         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7655         pipe_config->shared_dpll = NULL;
7656
7657         ret = false;
7658
7659         tmp = I915_READ(PIPECONF(crtc->pipe));
7660         if (!(tmp & PIPECONF_ENABLE))
7661                 goto out;
7662
7663         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7664             IS_CHERRYVIEW(dev_priv)) {
7665                 switch (tmp & PIPECONF_BPC_MASK) {
7666                 case PIPECONF_6BPC:
7667                         pipe_config->pipe_bpp = 18;
7668                         break;
7669                 case PIPECONF_8BPC:
7670                         pipe_config->pipe_bpp = 24;
7671                         break;
7672                 case PIPECONF_10BPC:
7673                         pipe_config->pipe_bpp = 30;
7674                         break;
7675                 default:
7676                         break;
7677                 }
7678         }
7679
7680         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7681             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7682                 pipe_config->limited_color_range = true;
7683
7684         if (INTEL_GEN(dev_priv) < 4)
7685                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7686
7687         intel_get_pipe_timings(crtc, pipe_config);
7688         intel_get_pipe_src_size(crtc, pipe_config);
7689
7690         i9xx_get_pfit_config(crtc, pipe_config);
7691
7692         if (INTEL_GEN(dev_priv) >= 4) {
7693                 /* No way to read it out on pipes B and C */
7694                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7695                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7696                 else
7697                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7698                 pipe_config->pixel_multiplier =
7699                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7700                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7701                 pipe_config->dpll_hw_state.dpll_md = tmp;
7702         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7703                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7704                 tmp = I915_READ(DPLL(crtc->pipe));
7705                 pipe_config->pixel_multiplier =
7706                         ((tmp & SDVO_MULTIPLIER_MASK)
7707                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7708         } else {
7709                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7710                  * port and will be fixed up in the encoder->get_config
7711                  * function. */
7712                 pipe_config->pixel_multiplier = 1;
7713         }
7714         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7715         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7716                 /*
7717                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7718                  * on 830. Filter it out here so that we don't
7719                  * report errors due to that.
7720                  */
7721                 if (IS_I830(dev_priv))
7722                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7723
7724                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7725                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7726         } else {
7727                 /* Mask out read-only status bits. */
7728                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7729                                                      DPLL_PORTC_READY_MASK |
7730                                                      DPLL_PORTB_READY_MASK);
7731         }
7732
7733         if (IS_CHERRYVIEW(dev_priv))
7734                 chv_crtc_clock_get(crtc, pipe_config);
7735         else if (IS_VALLEYVIEW(dev_priv))
7736                 vlv_crtc_clock_get(crtc, pipe_config);
7737         else
7738                 i9xx_crtc_clock_get(crtc, pipe_config);
7739
7740         /*
7741          * Normally the dotclock is filled in by the encoder .get_config()
7742          * but in case the pipe is enabled w/o any ports we need a sane
7743          * default.
7744          */
7745         pipe_config->base.adjusted_mode.crtc_clock =
7746                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7747
7748         ret = true;
7749
7750 out:
7751         intel_display_power_put(dev_priv, power_domain);
7752
7753         return ret;
7754 }
7755
7756 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7757 {
7758         struct intel_encoder *encoder;
7759         int i;
7760         u32 val, final;
7761         bool has_lvds = false;
7762         bool has_cpu_edp = false;
7763         bool has_panel = false;
7764         bool has_ck505 = false;
7765         bool can_ssc = false;
7766         bool using_ssc_source = false;
7767
7768         /* We need to take the global config into account */
7769         for_each_intel_encoder(&dev_priv->drm, encoder) {
7770                 switch (encoder->type) {
7771                 case INTEL_OUTPUT_LVDS:
7772                         has_panel = true;
7773                         has_lvds = true;
7774                         break;
7775                 case INTEL_OUTPUT_EDP:
7776                         has_panel = true;
7777                         if (encoder->port == PORT_A)
7778                                 has_cpu_edp = true;
7779                         break;
7780                 default:
7781                         break;
7782                 }
7783         }
7784
7785         if (HAS_PCH_IBX(dev_priv)) {
7786                 has_ck505 = dev_priv->vbt.display_clock_mode;
7787                 can_ssc = has_ck505;
7788         } else {
7789                 has_ck505 = false;
7790                 can_ssc = true;
7791         }
7792
7793         /* Check if any DPLLs are using the SSC source */
7794         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7795                 u32 temp = I915_READ(PCH_DPLL(i));
7796
7797                 if (!(temp & DPLL_VCO_ENABLE))
7798                         continue;
7799
7800                 if ((temp & PLL_REF_INPUT_MASK) ==
7801                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7802                         using_ssc_source = true;
7803                         break;
7804                 }
7805         }
7806
7807         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7808                       has_panel, has_lvds, has_ck505, using_ssc_source);
7809
7810         /* Ironlake: try to setup display ref clock before DPLL
7811          * enabling. This is only under driver's control after
7812          * PCH B stepping, previous chipset stepping should be
7813          * ignoring this setting.
7814          */
7815         val = I915_READ(PCH_DREF_CONTROL);
7816
7817         /* As we must carefully and slowly disable/enable each source in turn,
7818          * compute the final state we want first and check if we need to
7819          * make any changes at all.
7820          */
7821         final = val;
7822         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7823         if (has_ck505)
7824                 final |= DREF_NONSPREAD_CK505_ENABLE;
7825         else
7826                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7827
7828         final &= ~DREF_SSC_SOURCE_MASK;
7829         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7830         final &= ~DREF_SSC1_ENABLE;
7831
7832         if (has_panel) {
7833                 final |= DREF_SSC_SOURCE_ENABLE;
7834
7835                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7836                         final |= DREF_SSC1_ENABLE;
7837
7838                 if (has_cpu_edp) {
7839                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7840                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7841                         else
7842                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7843                 } else
7844                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7845         } else if (using_ssc_source) {
7846                 final |= DREF_SSC_SOURCE_ENABLE;
7847                 final |= DREF_SSC1_ENABLE;
7848         }
7849
7850         if (final == val)
7851                 return;
7852
7853         /* Always enable nonspread source */
7854         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7855
7856         if (has_ck505)
7857                 val |= DREF_NONSPREAD_CK505_ENABLE;
7858         else
7859                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7860
7861         if (has_panel) {
7862                 val &= ~DREF_SSC_SOURCE_MASK;
7863                 val |= DREF_SSC_SOURCE_ENABLE;
7864
7865                 /* SSC must be turned on before enabling the CPU output  */
7866                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7867                         DRM_DEBUG_KMS("Using SSC on panel\n");
7868                         val |= DREF_SSC1_ENABLE;
7869                 } else
7870                         val &= ~DREF_SSC1_ENABLE;
7871
7872                 /* Get SSC going before enabling the outputs */
7873                 I915_WRITE(PCH_DREF_CONTROL, val);
7874                 POSTING_READ(PCH_DREF_CONTROL);
7875                 udelay(200);
7876
7877                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7878
7879                 /* Enable CPU source on CPU attached eDP */
7880                 if (has_cpu_edp) {
7881                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7882                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7883                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7884                         } else
7885                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7886                 } else
7887                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7888
7889                 I915_WRITE(PCH_DREF_CONTROL, val);
7890                 POSTING_READ(PCH_DREF_CONTROL);
7891                 udelay(200);
7892         } else {
7893                 DRM_DEBUG_KMS("Disabling CPU source output\n");
7894
7895                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7896
7897                 /* Turn off CPU output */
7898                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7899
7900                 I915_WRITE(PCH_DREF_CONTROL, val);
7901                 POSTING_READ(PCH_DREF_CONTROL);
7902                 udelay(200);
7903
7904                 if (!using_ssc_source) {
7905                         DRM_DEBUG_KMS("Disabling SSC source\n");
7906
7907                         /* Turn off the SSC source */
7908                         val &= ~DREF_SSC_SOURCE_MASK;
7909                         val |= DREF_SSC_SOURCE_DISABLE;
7910
7911                         /* Turn off SSC1 */
7912                         val &= ~DREF_SSC1_ENABLE;
7913
7914                         I915_WRITE(PCH_DREF_CONTROL, val);
7915                         POSTING_READ(PCH_DREF_CONTROL);
7916                         udelay(200);
7917                 }
7918         }
7919
7920         BUG_ON(val != final);
7921 }
7922
7923 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7924 {
7925         uint32_t tmp;
7926
7927         tmp = I915_READ(SOUTH_CHICKEN2);
7928         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7929         I915_WRITE(SOUTH_CHICKEN2, tmp);
7930
7931         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
7932                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7933                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7934
7935         tmp = I915_READ(SOUTH_CHICKEN2);
7936         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7937         I915_WRITE(SOUTH_CHICKEN2, tmp);
7938
7939         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
7940                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7941                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7942 }
7943
7944 /* WaMPhyProgramming:hsw */
7945 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7946 {
7947         uint32_t tmp;
7948
7949         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7950         tmp &= ~(0xFF << 24);
7951         tmp |= (0x12 << 24);
7952         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
7953
7954         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
7955         tmp |= (1 << 11);
7956         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
7957
7958         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
7959         tmp |= (1 << 11);
7960         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
7961
7962         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
7963         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7964         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
7965
7966         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
7967         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7968         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
7969
7970         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
7971         tmp &= ~(7 << 13);
7972         tmp |= (5 << 13);
7973         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
7974
7975         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
7976         tmp &= ~(7 << 13);
7977         tmp |= (5 << 13);
7978         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
7979
7980         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
7981         tmp &= ~0xFF;
7982         tmp |= 0x1C;
7983         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
7984
7985         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
7986         tmp &= ~0xFF;
7987         tmp |= 0x1C;
7988         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
7989
7990         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
7991         tmp &= ~(0xFF << 16);
7992         tmp |= (0x1C << 16);
7993         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
7994
7995         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
7996         tmp &= ~(0xFF << 16);
7997         tmp |= (0x1C << 16);
7998         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
7999
8000         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
8001         tmp |= (1 << 27);
8002         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
8003
8004         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
8005         tmp |= (1 << 27);
8006         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
8007
8008         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
8009         tmp &= ~(0xF << 28);
8010         tmp |= (4 << 28);
8011         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
8012
8013         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
8014         tmp &= ~(0xF << 28);
8015         tmp |= (4 << 28);
8016         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
8017 }
8018
8019 /* Implements 3 different sequences from BSpec chapter "Display iCLK
8020  * Programming" based on the parameters passed:
8021  * - Sequence to enable CLKOUT_DP
8022  * - Sequence to enable CLKOUT_DP without spread
8023  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
8024  */
8025 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
8026                                  bool with_spread, bool with_fdi)
8027 {
8028         uint32_t reg, tmp;
8029
8030         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
8031                 with_spread = true;
8032         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
8033             with_fdi, "LP PCH doesn't have FDI\n"))
8034                 with_fdi = false;
8035
8036         mutex_lock(&dev_priv->sb_lock);
8037
8038         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8039         tmp &= ~SBI_SSCCTL_DISABLE;
8040         tmp |= SBI_SSCCTL_PATHALT;
8041         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8042
8043         udelay(24);
8044
8045         if (with_spread) {
8046                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8047                 tmp &= ~SBI_SSCCTL_PATHALT;
8048                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8049
8050                 if (with_fdi) {
8051                         lpt_reset_fdi_mphy(dev_priv);
8052                         lpt_program_fdi_mphy(dev_priv);
8053                 }
8054         }
8055
8056         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8057         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8058         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8059         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8060
8061         mutex_unlock(&dev_priv->sb_lock);
8062 }
8063
8064 /* Sequence to disable CLKOUT_DP */
8065 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
8066 {
8067         uint32_t reg, tmp;
8068
8069         mutex_lock(&dev_priv->sb_lock);
8070
8071         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
8072         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
8073         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
8074         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
8075
8076         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
8077         if (!(tmp & SBI_SSCCTL_DISABLE)) {
8078                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
8079                         tmp |= SBI_SSCCTL_PATHALT;
8080                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8081                         udelay(32);
8082                 }
8083                 tmp |= SBI_SSCCTL_DISABLE;
8084                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
8085         }
8086
8087         mutex_unlock(&dev_priv->sb_lock);
8088 }
8089
8090 #define BEND_IDX(steps) ((50 + (steps)) / 5)
8091
8092 static const uint16_t sscdivintphase[] = {
8093         [BEND_IDX( 50)] = 0x3B23,
8094         [BEND_IDX( 45)] = 0x3B23,
8095         [BEND_IDX( 40)] = 0x3C23,
8096         [BEND_IDX( 35)] = 0x3C23,
8097         [BEND_IDX( 30)] = 0x3D23,
8098         [BEND_IDX( 25)] = 0x3D23,
8099         [BEND_IDX( 20)] = 0x3E23,
8100         [BEND_IDX( 15)] = 0x3E23,
8101         [BEND_IDX( 10)] = 0x3F23,
8102         [BEND_IDX(  5)] = 0x3F23,
8103         [BEND_IDX(  0)] = 0x0025,
8104         [BEND_IDX( -5)] = 0x0025,
8105         [BEND_IDX(-10)] = 0x0125,
8106         [BEND_IDX(-15)] = 0x0125,
8107         [BEND_IDX(-20)] = 0x0225,
8108         [BEND_IDX(-25)] = 0x0225,
8109         [BEND_IDX(-30)] = 0x0325,
8110         [BEND_IDX(-35)] = 0x0325,
8111         [BEND_IDX(-40)] = 0x0425,
8112         [BEND_IDX(-45)] = 0x0425,
8113         [BEND_IDX(-50)] = 0x0525,
8114 };
8115
8116 /*
8117  * Bend CLKOUT_DP
8118  * steps -50 to 50 inclusive, in steps of 5
8119  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8120  * change in clock period = -(steps / 10) * 5.787 ps
8121  */
8122 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8123 {
8124         uint32_t tmp;
8125         int idx = BEND_IDX(steps);
8126
8127         if (WARN_ON(steps % 5 != 0))
8128                 return;
8129
8130         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8131                 return;
8132
8133         mutex_lock(&dev_priv->sb_lock);
8134
8135         if (steps % 10 != 0)
8136                 tmp = 0xAAAAAAAB;
8137         else
8138                 tmp = 0x00000000;
8139         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8140
8141         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8142         tmp &= 0xffff0000;
8143         tmp |= sscdivintphase[idx];
8144         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8145
8146         mutex_unlock(&dev_priv->sb_lock);
8147 }
8148
8149 #undef BEND_IDX
8150
8151 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8152 {
8153         struct intel_encoder *encoder;
8154         bool has_vga = false;
8155
8156         for_each_intel_encoder(&dev_priv->drm, encoder) {
8157                 switch (encoder->type) {
8158                 case INTEL_OUTPUT_ANALOG:
8159                         has_vga = true;
8160                         break;
8161                 default:
8162                         break;
8163                 }
8164         }
8165
8166         if (has_vga) {
8167                 lpt_bend_clkout_dp(dev_priv, 0);
8168                 lpt_enable_clkout_dp(dev_priv, true, true);
8169         } else {
8170                 lpt_disable_clkout_dp(dev_priv);
8171         }
8172 }
8173
8174 /*
8175  * Initialize reference clocks when the driver loads
8176  */
8177 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8178 {
8179         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8180                 ironlake_init_pch_refclk(dev_priv);
8181         else if (HAS_PCH_LPT(dev_priv))
8182                 lpt_init_pch_refclk(dev_priv);
8183 }
8184
8185 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8186 {
8187         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8188         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8189         int pipe = intel_crtc->pipe;
8190         uint32_t val;
8191
8192         val = 0;
8193
8194         switch (intel_crtc->config->pipe_bpp) {
8195         case 18:
8196                 val |= PIPECONF_6BPC;
8197                 break;
8198         case 24:
8199                 val |= PIPECONF_8BPC;
8200                 break;
8201         case 30:
8202                 val |= PIPECONF_10BPC;
8203                 break;
8204         case 36:
8205                 val |= PIPECONF_12BPC;
8206                 break;
8207         default:
8208                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8209                 BUG();
8210         }
8211
8212         if (intel_crtc->config->dither)
8213                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8214
8215         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8216                 val |= PIPECONF_INTERLACED_ILK;
8217         else
8218                 val |= PIPECONF_PROGRESSIVE;
8219
8220         if (intel_crtc->config->limited_color_range)
8221                 val |= PIPECONF_COLOR_RANGE_SELECT;
8222
8223         I915_WRITE(PIPECONF(pipe), val);
8224         POSTING_READ(PIPECONF(pipe));
8225 }
8226
8227 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8228 {
8229         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8230         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8231         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8232         u32 val = 0;
8233
8234         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8235                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8236
8237         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8238                 val |= PIPECONF_INTERLACED_ILK;
8239         else
8240                 val |= PIPECONF_PROGRESSIVE;
8241
8242         I915_WRITE(PIPECONF(cpu_transcoder), val);
8243         POSTING_READ(PIPECONF(cpu_transcoder));
8244 }
8245
8246 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8247 {
8248         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8249         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8250         struct intel_crtc_state *config = intel_crtc->config;
8251
8252         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
8253                 u32 val = 0;
8254
8255                 switch (intel_crtc->config->pipe_bpp) {
8256                 case 18:
8257                         val |= PIPEMISC_DITHER_6_BPC;
8258                         break;
8259                 case 24:
8260                         val |= PIPEMISC_DITHER_8_BPC;
8261                         break;
8262                 case 30:
8263                         val |= PIPEMISC_DITHER_10_BPC;
8264                         break;
8265                 case 36:
8266                         val |= PIPEMISC_DITHER_12_BPC;
8267                         break;
8268                 default:
8269                         /* Case prevented by pipe_config_set_bpp. */
8270                         BUG();
8271                 }
8272
8273                 if (intel_crtc->config->dither)
8274                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8275
8276                 if (config->ycbcr420) {
8277                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8278                                 PIPEMISC_YUV420_ENABLE |
8279                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8280                 }
8281
8282                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8283         }
8284 }
8285
8286 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8287 {
8288         /*
8289          * Account for spread spectrum to avoid
8290          * oversubscribing the link. Max center spread
8291          * is 2.5%; use 5% for safety's sake.
8292          */
8293         u32 bps = target_clock * bpp * 21 / 20;
8294         return DIV_ROUND_UP(bps, link_bw * 8);
8295 }
8296
8297 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8298 {
8299         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8300 }
8301
8302 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8303                                   struct intel_crtc_state *crtc_state,
8304                                   struct dpll *reduced_clock)
8305 {
8306         struct drm_crtc *crtc = &intel_crtc->base;
8307         struct drm_device *dev = crtc->dev;
8308         struct drm_i915_private *dev_priv = to_i915(dev);
8309         u32 dpll, fp, fp2;
8310         int factor;
8311
8312         /* Enable autotuning of the PLL clock (if permissible) */
8313         factor = 21;
8314         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8315                 if ((intel_panel_use_ssc(dev_priv) &&
8316                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8317                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8318                         factor = 25;
8319         } else if (crtc_state->sdvo_tv_clock)
8320                 factor = 20;
8321
8322         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8323
8324         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8325                 fp |= FP_CB_TUNE;
8326
8327         if (reduced_clock) {
8328                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8329
8330                 if (reduced_clock->m < factor * reduced_clock->n)
8331                         fp2 |= FP_CB_TUNE;
8332         } else {
8333                 fp2 = fp;
8334         }
8335
8336         dpll = 0;
8337
8338         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8339                 dpll |= DPLLB_MODE_LVDS;
8340         else
8341                 dpll |= DPLLB_MODE_DAC_SERIAL;
8342
8343         dpll |= (crtc_state->pixel_multiplier - 1)
8344                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8345
8346         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8347             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8348                 dpll |= DPLL_SDVO_HIGH_SPEED;
8349
8350         if (intel_crtc_has_dp_encoder(crtc_state))
8351                 dpll |= DPLL_SDVO_HIGH_SPEED;
8352
8353         /*
8354          * The high speed IO clock is only really required for
8355          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8356          * possible to share the DPLL between CRT and HDMI. Enabling
8357          * the clock needlessly does no real harm, except use up a
8358          * bit of power potentially.
8359          *
8360          * We'll limit this to IVB with 3 pipes, since it has only two
8361          * DPLLs and so DPLL sharing is the only way to get three pipes
8362          * driving PCH ports at the same time. On SNB we could do this,
8363          * and potentially avoid enabling the second DPLL, but it's not
8364          * clear if it''s a win or loss power wise. No point in doing
8365          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8366          */
8367         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8368             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8369                 dpll |= DPLL_SDVO_HIGH_SPEED;
8370
8371         /* compute bitmask from p1 value */
8372         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8373         /* also FPA1 */
8374         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8375
8376         switch (crtc_state->dpll.p2) {
8377         case 5:
8378                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8379                 break;
8380         case 7:
8381                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8382                 break;
8383         case 10:
8384                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8385                 break;
8386         case 14:
8387                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8388                 break;
8389         }
8390
8391         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8392             intel_panel_use_ssc(dev_priv))
8393                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8394         else
8395                 dpll |= PLL_REF_INPUT_DREFCLK;
8396
8397         dpll |= DPLL_VCO_ENABLE;
8398
8399         crtc_state->dpll_hw_state.dpll = dpll;
8400         crtc_state->dpll_hw_state.fp0 = fp;
8401         crtc_state->dpll_hw_state.fp1 = fp2;
8402 }
8403
8404 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8405                                        struct intel_crtc_state *crtc_state)
8406 {
8407         struct drm_device *dev = crtc->base.dev;
8408         struct drm_i915_private *dev_priv = to_i915(dev);
8409         const struct intel_limit *limit;
8410         int refclk = 120000;
8411
8412         memset(&crtc_state->dpll_hw_state, 0,
8413                sizeof(crtc_state->dpll_hw_state));
8414
8415         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8416         if (!crtc_state->has_pch_encoder)
8417                 return 0;
8418
8419         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8420                 if (intel_panel_use_ssc(dev_priv)) {
8421                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8422                                       dev_priv->vbt.lvds_ssc_freq);
8423                         refclk = dev_priv->vbt.lvds_ssc_freq;
8424                 }
8425
8426                 if (intel_is_dual_link_lvds(dev)) {
8427                         if (refclk == 100000)
8428                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8429                         else
8430                                 limit = &intel_limits_ironlake_dual_lvds;
8431                 } else {
8432                         if (refclk == 100000)
8433                                 limit = &intel_limits_ironlake_single_lvds_100m;
8434                         else
8435                                 limit = &intel_limits_ironlake_single_lvds;
8436                 }
8437         } else {
8438                 limit = &intel_limits_ironlake_dac;
8439         }
8440
8441         if (!crtc_state->clock_set &&
8442             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8443                                 refclk, NULL, &crtc_state->dpll)) {
8444                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8445                 return -EINVAL;
8446         }
8447
8448         ironlake_compute_dpll(crtc, crtc_state, NULL);
8449
8450         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8451                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8452                                  pipe_name(crtc->pipe));
8453                 return -EINVAL;
8454         }
8455
8456         return 0;
8457 }
8458
8459 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8460                                          struct intel_link_m_n *m_n)
8461 {
8462         struct drm_device *dev = crtc->base.dev;
8463         struct drm_i915_private *dev_priv = to_i915(dev);
8464         enum pipe pipe = crtc->pipe;
8465
8466         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8467         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8468         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8469                 & ~TU_SIZE_MASK;
8470         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8471         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8472                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8473 }
8474
8475 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8476                                          enum transcoder transcoder,
8477                                          struct intel_link_m_n *m_n,
8478                                          struct intel_link_m_n *m2_n2)
8479 {
8480         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8481         enum pipe pipe = crtc->pipe;
8482
8483         if (INTEL_GEN(dev_priv) >= 5) {
8484                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8485                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8486                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8487                         & ~TU_SIZE_MASK;
8488                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8489                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8490                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8491                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8492                  * gen < 8) and if DRRS is supported (to make sure the
8493                  * registers are not unnecessarily read).
8494                  */
8495                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8496                         crtc->config->has_drrs) {
8497                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8498                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8499                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8500                                         & ~TU_SIZE_MASK;
8501                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8502                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8503                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8504                 }
8505         } else {
8506                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8507                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8508                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8509                         & ~TU_SIZE_MASK;
8510                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8511                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8512                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8513         }
8514 }
8515
8516 void intel_dp_get_m_n(struct intel_crtc *crtc,
8517                       struct intel_crtc_state *pipe_config)
8518 {
8519         if (pipe_config->has_pch_encoder)
8520                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8521         else
8522                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8523                                              &pipe_config->dp_m_n,
8524                                              &pipe_config->dp_m2_n2);
8525 }
8526
8527 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8528                                         struct intel_crtc_state *pipe_config)
8529 {
8530         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8531                                      &pipe_config->fdi_m_n, NULL);
8532 }
8533
8534 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8535                                     struct intel_crtc_state *pipe_config)
8536 {
8537         struct drm_device *dev = crtc->base.dev;
8538         struct drm_i915_private *dev_priv = to_i915(dev);
8539         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8540         uint32_t ps_ctrl = 0;
8541         int id = -1;
8542         int i;
8543
8544         /* find scaler attached to this pipe */
8545         for (i = 0; i < crtc->num_scalers; i++) {
8546                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8547                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8548                         id = i;
8549                         pipe_config->pch_pfit.enabled = true;
8550                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8551                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8552                         break;
8553                 }
8554         }
8555
8556         scaler_state->scaler_id = id;
8557         if (id >= 0) {
8558                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8559         } else {
8560                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8561         }
8562 }
8563
8564 static void
8565 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8566                                  struct intel_initial_plane_config *plane_config)
8567 {
8568         struct drm_device *dev = crtc->base.dev;
8569         struct drm_i915_private *dev_priv = to_i915(dev);
8570         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8571         enum plane_id plane_id = plane->id;
8572         enum pipe pipe = crtc->pipe;
8573         u32 val, base, offset, stride_mult, tiling, alpha;
8574         int fourcc, pixel_format;
8575         unsigned int aligned_height;
8576         struct drm_framebuffer *fb;
8577         struct intel_framebuffer *intel_fb;
8578
8579         if (!plane->get_hw_state(plane))
8580                 return;
8581
8582         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8583         if (!intel_fb) {
8584                 DRM_DEBUG_KMS("failed to alloc fb\n");
8585                 return;
8586         }
8587
8588         fb = &intel_fb->base;
8589
8590         fb->dev = dev;
8591
8592         val = I915_READ(PLANE_CTL(pipe, plane_id));
8593
8594         if (INTEL_GEN(dev_priv) >= 11)
8595                 pixel_format = val & ICL_PLANE_CTL_FORMAT_MASK;
8596         else
8597                 pixel_format = val & PLANE_CTL_FORMAT_MASK;
8598
8599         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8600                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8601                 alpha &= PLANE_COLOR_ALPHA_MASK;
8602         } else {
8603                 alpha = val & PLANE_CTL_ALPHA_MASK;
8604         }
8605
8606         fourcc = skl_format_to_fourcc(pixel_format,
8607                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8608         fb->format = drm_format_info(fourcc);
8609
8610         tiling = val & PLANE_CTL_TILED_MASK;
8611         switch (tiling) {
8612         case PLANE_CTL_TILED_LINEAR:
8613                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8614                 break;
8615         case PLANE_CTL_TILED_X:
8616                 plane_config->tiling = I915_TILING_X;
8617                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8618                 break;
8619         case PLANE_CTL_TILED_Y:
8620                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8621                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8622                 else
8623                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8624                 break;
8625         case PLANE_CTL_TILED_YF:
8626                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8627                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8628                 else
8629                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8630                 break;
8631         default:
8632                 MISSING_CASE(tiling);
8633                 goto error;
8634         }
8635
8636         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8637         plane_config->base = base;
8638
8639         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8640
8641         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8642         fb->height = ((val >> 16) & 0xfff) + 1;
8643         fb->width = ((val >> 0) & 0x1fff) + 1;
8644
8645         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8646         stride_mult = intel_fb_stride_alignment(fb, 0);
8647         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8648
8649         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8650
8651         plane_config->size = fb->pitches[0] * aligned_height;
8652
8653         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8654                       crtc->base.name, plane->base.name, fb->width, fb->height,
8655                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8656                       plane_config->size);
8657
8658         plane_config->fb = intel_fb;
8659         return;
8660
8661 error:
8662         kfree(intel_fb);
8663 }
8664
8665 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8666                                      struct intel_crtc_state *pipe_config)
8667 {
8668         struct drm_device *dev = crtc->base.dev;
8669         struct drm_i915_private *dev_priv = to_i915(dev);
8670         uint32_t tmp;
8671
8672         tmp = I915_READ(PF_CTL(crtc->pipe));
8673
8674         if (tmp & PF_ENABLE) {
8675                 pipe_config->pch_pfit.enabled = true;
8676                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8677                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8678
8679                 /* We currently do not free assignements of panel fitters on
8680                  * ivb/hsw (since we don't use the higher upscaling modes which
8681                  * differentiates them) so just WARN about this case for now. */
8682                 if (IS_GEN7(dev_priv)) {
8683                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8684                                 PF_PIPE_SEL_IVB(crtc->pipe));
8685                 }
8686         }
8687 }
8688
8689 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8690                                      struct intel_crtc_state *pipe_config)
8691 {
8692         struct drm_device *dev = crtc->base.dev;
8693         struct drm_i915_private *dev_priv = to_i915(dev);
8694         enum intel_display_power_domain power_domain;
8695         uint32_t tmp;
8696         bool ret;
8697
8698         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8699         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8700                 return false;
8701
8702         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8703         pipe_config->shared_dpll = NULL;
8704
8705         ret = false;
8706         tmp = I915_READ(PIPECONF(crtc->pipe));
8707         if (!(tmp & PIPECONF_ENABLE))
8708                 goto out;
8709
8710         switch (tmp & PIPECONF_BPC_MASK) {
8711         case PIPECONF_6BPC:
8712                 pipe_config->pipe_bpp = 18;
8713                 break;
8714         case PIPECONF_8BPC:
8715                 pipe_config->pipe_bpp = 24;
8716                 break;
8717         case PIPECONF_10BPC:
8718                 pipe_config->pipe_bpp = 30;
8719                 break;
8720         case PIPECONF_12BPC:
8721                 pipe_config->pipe_bpp = 36;
8722                 break;
8723         default:
8724                 break;
8725         }
8726
8727         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8728                 pipe_config->limited_color_range = true;
8729
8730         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8731                 struct intel_shared_dpll *pll;
8732                 enum intel_dpll_id pll_id;
8733
8734                 pipe_config->has_pch_encoder = true;
8735
8736                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8737                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8738                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8739
8740                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8741
8742                 if (HAS_PCH_IBX(dev_priv)) {
8743                         /*
8744                          * The pipe->pch transcoder and pch transcoder->pll
8745                          * mapping is fixed.
8746                          */
8747                         pll_id = (enum intel_dpll_id) crtc->pipe;
8748                 } else {
8749                         tmp = I915_READ(PCH_DPLL_SEL);
8750                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8751                                 pll_id = DPLL_ID_PCH_PLL_B;
8752                         else
8753                                 pll_id= DPLL_ID_PCH_PLL_A;
8754                 }
8755
8756                 pipe_config->shared_dpll =
8757                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8758                 pll = pipe_config->shared_dpll;
8759
8760                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
8761                                                  &pipe_config->dpll_hw_state));
8762
8763                 tmp = pipe_config->dpll_hw_state.dpll;
8764                 pipe_config->pixel_multiplier =
8765                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8766                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8767
8768                 ironlake_pch_clock_get(crtc, pipe_config);
8769         } else {
8770                 pipe_config->pixel_multiplier = 1;
8771         }
8772
8773         intel_get_pipe_timings(crtc, pipe_config);
8774         intel_get_pipe_src_size(crtc, pipe_config);
8775
8776         ironlake_get_pfit_config(crtc, pipe_config);
8777
8778         ret = true;
8779
8780 out:
8781         intel_display_power_put(dev_priv, power_domain);
8782
8783         return ret;
8784 }
8785
8786 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8787 {
8788         struct drm_device *dev = &dev_priv->drm;
8789         struct intel_crtc *crtc;
8790
8791         for_each_intel_crtc(dev, crtc)
8792                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8793                      pipe_name(crtc->pipe));
8794
8795         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL)),
8796                         "Display power well on\n");
8797         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8798         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8799         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8800         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8801         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8802              "CPU PWM1 enabled\n");
8803         if (IS_HASWELL(dev_priv))
8804                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8805                      "CPU PWM2 enabled\n");
8806         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8807              "PCH PWM1 enabled\n");
8808         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8809              "Utility pin enabled\n");
8810         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8811
8812         /*
8813          * In theory we can still leave IRQs enabled, as long as only the HPD
8814          * interrupts remain enabled. We used to check for that, but since it's
8815          * gen-specific and since we only disable LCPLL after we fully disable
8816          * the interrupts, the check below should be enough.
8817          */
8818         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8819 }
8820
8821 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8822 {
8823         if (IS_HASWELL(dev_priv))
8824                 return I915_READ(D_COMP_HSW);
8825         else
8826                 return I915_READ(D_COMP_BDW);
8827 }
8828
8829 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8830 {
8831         if (IS_HASWELL(dev_priv)) {
8832                 mutex_lock(&dev_priv->pcu_lock);
8833                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8834                                             val))
8835                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
8836                 mutex_unlock(&dev_priv->pcu_lock);
8837         } else {
8838                 I915_WRITE(D_COMP_BDW, val);
8839                 POSTING_READ(D_COMP_BDW);
8840         }
8841 }
8842
8843 /*
8844  * This function implements pieces of two sequences from BSpec:
8845  * - Sequence for display software to disable LCPLL
8846  * - Sequence for display software to allow package C8+
8847  * The steps implemented here are just the steps that actually touch the LCPLL
8848  * register. Callers should take care of disabling all the display engine
8849  * functions, doing the mode unset, fixing interrupts, etc.
8850  */
8851 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8852                               bool switch_to_fclk, bool allow_power_down)
8853 {
8854         uint32_t val;
8855
8856         assert_can_disable_lcpll(dev_priv);
8857
8858         val = I915_READ(LCPLL_CTL);
8859
8860         if (switch_to_fclk) {
8861                 val |= LCPLL_CD_SOURCE_FCLK;
8862                 I915_WRITE(LCPLL_CTL, val);
8863
8864                 if (wait_for_us(I915_READ(LCPLL_CTL) &
8865                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
8866                         DRM_ERROR("Switching to FCLK failed\n");
8867
8868                 val = I915_READ(LCPLL_CTL);
8869         }
8870
8871         val |= LCPLL_PLL_DISABLE;
8872         I915_WRITE(LCPLL_CTL, val);
8873         POSTING_READ(LCPLL_CTL);
8874
8875         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
8876                 DRM_ERROR("LCPLL still locked\n");
8877
8878         val = hsw_read_dcomp(dev_priv);
8879         val |= D_COMP_COMP_DISABLE;
8880         hsw_write_dcomp(dev_priv, val);
8881         ndelay(100);
8882
8883         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8884                      1))
8885                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8886
8887         if (allow_power_down) {
8888                 val = I915_READ(LCPLL_CTL);
8889                 val |= LCPLL_POWER_DOWN_ALLOW;
8890                 I915_WRITE(LCPLL_CTL, val);
8891                 POSTING_READ(LCPLL_CTL);
8892         }
8893 }
8894
8895 /*
8896  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8897  * source.
8898  */
8899 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8900 {
8901         uint32_t val;
8902
8903         val = I915_READ(LCPLL_CTL);
8904
8905         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8906                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8907                 return;
8908
8909         /*
8910          * Make sure we're not on PC8 state before disabling PC8, otherwise
8911          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8912          */
8913         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8914
8915         if (val & LCPLL_POWER_DOWN_ALLOW) {
8916                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8917                 I915_WRITE(LCPLL_CTL, val);
8918                 POSTING_READ(LCPLL_CTL);
8919         }
8920
8921         val = hsw_read_dcomp(dev_priv);
8922         val |= D_COMP_COMP_FORCE;
8923         val &= ~D_COMP_COMP_DISABLE;
8924         hsw_write_dcomp(dev_priv, val);
8925
8926         val = I915_READ(LCPLL_CTL);
8927         val &= ~LCPLL_PLL_DISABLE;
8928         I915_WRITE(LCPLL_CTL, val);
8929
8930         if (intel_wait_for_register(dev_priv,
8931                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
8932                                     5))
8933                 DRM_ERROR("LCPLL not locked yet\n");
8934
8935         if (val & LCPLL_CD_SOURCE_FCLK) {
8936                 val = I915_READ(LCPLL_CTL);
8937                 val &= ~LCPLL_CD_SOURCE_FCLK;
8938                 I915_WRITE(LCPLL_CTL, val);
8939
8940                 if (wait_for_us((I915_READ(LCPLL_CTL) &
8941                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8942                         DRM_ERROR("Switching back to LCPLL failed\n");
8943         }
8944
8945         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8946
8947         intel_update_cdclk(dev_priv);
8948         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
8949 }
8950
8951 /*
8952  * Package states C8 and deeper are really deep PC states that can only be
8953  * reached when all the devices on the system allow it, so even if the graphics
8954  * device allows PC8+, it doesn't mean the system will actually get to these
8955  * states. Our driver only allows PC8+ when going into runtime PM.
8956  *
8957  * The requirements for PC8+ are that all the outputs are disabled, the power
8958  * well is disabled and most interrupts are disabled, and these are also
8959  * requirements for runtime PM. When these conditions are met, we manually do
8960  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
8961  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
8962  * hang the machine.
8963  *
8964  * When we really reach PC8 or deeper states (not just when we allow it) we lose
8965  * the state of some registers, so when we come back from PC8+ we need to
8966  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
8967  * need to take care of the registers kept by RC6. Notice that this happens even
8968  * if we don't put the device in PCI D3 state (which is what currently happens
8969  * because of the runtime PM support).
8970  *
8971  * For more, read "Display Sequences for Package C8" on the hardware
8972  * documentation.
8973  */
8974 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
8975 {
8976         uint32_t val;
8977
8978         DRM_DEBUG_KMS("Enabling package C8+\n");
8979
8980         if (HAS_PCH_LPT_LP(dev_priv)) {
8981                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8982                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
8983                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8984         }
8985
8986         lpt_disable_clkout_dp(dev_priv);
8987         hsw_disable_lcpll(dev_priv, true, true);
8988 }
8989
8990 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
8991 {
8992         uint32_t val;
8993
8994         DRM_DEBUG_KMS("Disabling package C8+\n");
8995
8996         hsw_restore_lcpll(dev_priv);
8997         lpt_init_pch_refclk(dev_priv);
8998
8999         if (HAS_PCH_LPT_LP(dev_priv)) {
9000                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
9001                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
9002                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
9003         }
9004 }
9005
9006 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
9007                                       struct intel_crtc_state *crtc_state)
9008 {
9009         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
9010                 struct intel_encoder *encoder =
9011                         intel_ddi_get_crtc_new_encoder(crtc_state);
9012
9013                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
9014                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
9015                                          pipe_name(crtc->pipe));
9016                         return -EINVAL;
9017                 }
9018         }
9019
9020         return 0;
9021 }
9022
9023 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
9024                                    enum port port,
9025                                    struct intel_crtc_state *pipe_config)
9026 {
9027         enum intel_dpll_id id;
9028         u32 temp;
9029
9030         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
9031         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
9032
9033         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
9034                 return;
9035
9036         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9037 }
9038
9039 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
9040                                 enum port port,
9041                                 struct intel_crtc_state *pipe_config)
9042 {
9043         enum intel_dpll_id id;
9044
9045         switch (port) {
9046         case PORT_A:
9047                 id = DPLL_ID_SKL_DPLL0;
9048                 break;
9049         case PORT_B:
9050                 id = DPLL_ID_SKL_DPLL1;
9051                 break;
9052         case PORT_C:
9053                 id = DPLL_ID_SKL_DPLL2;
9054                 break;
9055         default:
9056                 DRM_ERROR("Incorrect port type\n");
9057                 return;
9058         }
9059
9060         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9061 }
9062
9063 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
9064                                 enum port port,
9065                                 struct intel_crtc_state *pipe_config)
9066 {
9067         enum intel_dpll_id id;
9068         u32 temp;
9069
9070         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
9071         id = temp >> (port * 3 + 1);
9072
9073         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
9074                 return;
9075
9076         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9077 }
9078
9079 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
9080                                 enum port port,
9081                                 struct intel_crtc_state *pipe_config)
9082 {
9083         enum intel_dpll_id id;
9084         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
9085
9086         switch (ddi_pll_sel) {
9087         case PORT_CLK_SEL_WRPLL1:
9088                 id = DPLL_ID_WRPLL1;
9089                 break;
9090         case PORT_CLK_SEL_WRPLL2:
9091                 id = DPLL_ID_WRPLL2;
9092                 break;
9093         case PORT_CLK_SEL_SPLL:
9094                 id = DPLL_ID_SPLL;
9095                 break;
9096         case PORT_CLK_SEL_LCPLL_810:
9097                 id = DPLL_ID_LCPLL_810;
9098                 break;
9099         case PORT_CLK_SEL_LCPLL_1350:
9100                 id = DPLL_ID_LCPLL_1350;
9101                 break;
9102         case PORT_CLK_SEL_LCPLL_2700:
9103                 id = DPLL_ID_LCPLL_2700;
9104                 break;
9105         default:
9106                 MISSING_CASE(ddi_pll_sel);
9107                 /* fall through */
9108         case PORT_CLK_SEL_NONE:
9109                 return;
9110         }
9111
9112         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9113 }
9114
9115 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9116                                      struct intel_crtc_state *pipe_config,
9117                                      u64 *power_domain_mask)
9118 {
9119         struct drm_device *dev = crtc->base.dev;
9120         struct drm_i915_private *dev_priv = to_i915(dev);
9121         enum intel_display_power_domain power_domain;
9122         u32 tmp;
9123
9124         /*
9125          * The pipe->transcoder mapping is fixed with the exception of the eDP
9126          * transcoder handled below.
9127          */
9128         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9129
9130         /*
9131          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9132          * consistency and less surprising code; it's in always on power).
9133          */
9134         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9135         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9136                 enum pipe trans_edp_pipe;
9137                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9138                 default:
9139                         WARN(1, "unknown pipe linked to edp transcoder\n");
9140                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9141                 case TRANS_DDI_EDP_INPUT_A_ON:
9142                         trans_edp_pipe = PIPE_A;
9143                         break;
9144                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9145                         trans_edp_pipe = PIPE_B;
9146                         break;
9147                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9148                         trans_edp_pipe = PIPE_C;
9149                         break;
9150                 }
9151
9152                 if (trans_edp_pipe == crtc->pipe)
9153                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9154         }
9155
9156         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9157         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9158                 return false;
9159         *power_domain_mask |= BIT_ULL(power_domain);
9160
9161         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9162
9163         return tmp & PIPECONF_ENABLE;
9164 }
9165
9166 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9167                                          struct intel_crtc_state *pipe_config,
9168                                          u64 *power_domain_mask)
9169 {
9170         struct drm_device *dev = crtc->base.dev;
9171         struct drm_i915_private *dev_priv = to_i915(dev);
9172         enum intel_display_power_domain power_domain;
9173         enum port port;
9174         enum transcoder cpu_transcoder;
9175         u32 tmp;
9176
9177         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9178                 if (port == PORT_A)
9179                         cpu_transcoder = TRANSCODER_DSI_A;
9180                 else
9181                         cpu_transcoder = TRANSCODER_DSI_C;
9182
9183                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9184                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9185                         continue;
9186                 *power_domain_mask |= BIT_ULL(power_domain);
9187
9188                 /*
9189                  * The PLL needs to be enabled with a valid divider
9190                  * configuration, otherwise accessing DSI registers will hang
9191                  * the machine. See BSpec North Display Engine
9192                  * registers/MIPI[BXT]. We can break out here early, since we
9193                  * need the same DSI PLL to be enabled for both DSI ports.
9194                  */
9195                 if (!intel_dsi_pll_is_enabled(dev_priv))
9196                         break;
9197
9198                 /* XXX: this works for video mode only */
9199                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9200                 if (!(tmp & DPI_ENABLE))
9201                         continue;
9202
9203                 tmp = I915_READ(MIPI_CTRL(port));
9204                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9205                         continue;
9206
9207                 pipe_config->cpu_transcoder = cpu_transcoder;
9208                 break;
9209         }
9210
9211         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9212 }
9213
9214 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9215                                        struct intel_crtc_state *pipe_config)
9216 {
9217         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9218         struct intel_shared_dpll *pll;
9219         enum port port;
9220         uint32_t tmp;
9221
9222         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9223
9224         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9225
9226         if (IS_CANNONLAKE(dev_priv))
9227                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9228         else if (IS_GEN9_BC(dev_priv))
9229                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9230         else if (IS_GEN9_LP(dev_priv))
9231                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9232         else
9233                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9234
9235         pll = pipe_config->shared_dpll;
9236         if (pll) {
9237                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9238                                                  &pipe_config->dpll_hw_state));
9239         }
9240
9241         /*
9242          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9243          * DDI E. So just check whether this pipe is wired to DDI E and whether
9244          * the PCH transcoder is on.
9245          */
9246         if (INTEL_GEN(dev_priv) < 9 &&
9247             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9248                 pipe_config->has_pch_encoder = true;
9249
9250                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9251                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9252                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9253
9254                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9255         }
9256 }
9257
9258 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9259                                     struct intel_crtc_state *pipe_config)
9260 {
9261         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9262         enum intel_display_power_domain power_domain;
9263         u64 power_domain_mask;
9264         bool active;
9265
9266         intel_crtc_init_scalers(crtc, pipe_config);
9267
9268         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9269         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9270                 return false;
9271         power_domain_mask = BIT_ULL(power_domain);
9272
9273         pipe_config->shared_dpll = NULL;
9274
9275         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9276
9277         if (IS_GEN9_LP(dev_priv) &&
9278             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9279                 WARN_ON(active);
9280                 active = true;
9281         }
9282
9283         if (!active)
9284                 goto out;
9285
9286         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9287                 haswell_get_ddi_port_state(crtc, pipe_config);
9288                 intel_get_pipe_timings(crtc, pipe_config);
9289         }
9290
9291         intel_get_pipe_src_size(crtc, pipe_config);
9292
9293         pipe_config->gamma_mode =
9294                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9295
9296         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
9297                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9298                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9299
9300                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10) {
9301                         bool blend_mode_420 = tmp &
9302                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9303
9304                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9305                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9306                             pipe_config->ycbcr420 != blend_mode_420)
9307                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9308                 } else if (clrspace_yuv) {
9309                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9310                 }
9311         }
9312
9313         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9314         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9315                 power_domain_mask |= BIT_ULL(power_domain);
9316                 if (INTEL_GEN(dev_priv) >= 9)
9317                         skylake_get_pfit_config(crtc, pipe_config);
9318                 else
9319                         ironlake_get_pfit_config(crtc, pipe_config);
9320         }
9321
9322         if (hsw_crtc_supports_ips(crtc)) {
9323                 if (IS_HASWELL(dev_priv))
9324                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9325                 else {
9326                         /*
9327                          * We cannot readout IPS state on broadwell, set to
9328                          * true so we can set it to a defined state on first
9329                          * commit.
9330                          */
9331                         pipe_config->ips_enabled = true;
9332                 }
9333         }
9334
9335         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9336             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9337                 pipe_config->pixel_multiplier =
9338                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9339         } else {
9340                 pipe_config->pixel_multiplier = 1;
9341         }
9342
9343 out:
9344         for_each_power_domain(power_domain, power_domain_mask)
9345                 intel_display_power_put(dev_priv, power_domain);
9346
9347         return active;
9348 }
9349
9350 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9351 {
9352         struct drm_i915_private *dev_priv =
9353                 to_i915(plane_state->base.plane->dev);
9354         const struct drm_framebuffer *fb = plane_state->base.fb;
9355         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9356         u32 base;
9357
9358         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9359                 base = obj->phys_handle->busaddr;
9360         else
9361                 base = intel_plane_ggtt_offset(plane_state);
9362
9363         base += plane_state->main.offset;
9364
9365         /* ILK+ do this automagically */
9366         if (HAS_GMCH_DISPLAY(dev_priv) &&
9367             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9368                 base += (plane_state->base.crtc_h *
9369                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9370
9371         return base;
9372 }
9373
9374 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9375 {
9376         int x = plane_state->base.crtc_x;
9377         int y = plane_state->base.crtc_y;
9378         u32 pos = 0;
9379
9380         if (x < 0) {
9381                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9382                 x = -x;
9383         }
9384         pos |= x << CURSOR_X_SHIFT;
9385
9386         if (y < 0) {
9387                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9388                 y = -y;
9389         }
9390         pos |= y << CURSOR_Y_SHIFT;
9391
9392         return pos;
9393 }
9394
9395 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9396 {
9397         const struct drm_mode_config *config =
9398                 &plane_state->base.plane->dev->mode_config;
9399         int width = plane_state->base.crtc_w;
9400         int height = plane_state->base.crtc_h;
9401
9402         return width > 0 && width <= config->cursor_width &&
9403                 height > 0 && height <= config->cursor_height;
9404 }
9405
9406 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9407                               struct intel_plane_state *plane_state)
9408 {
9409         const struct drm_framebuffer *fb = plane_state->base.fb;
9410         struct drm_rect clip = {};
9411         int src_x, src_y;
9412         u32 offset;
9413         int ret;
9414
9415         if (crtc_state->base.enable)
9416                 drm_mode_get_hv_timing(&crtc_state->base.mode,
9417                                        &clip.x2, &clip.y2);
9418
9419         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9420                                                   &crtc_state->base,
9421                                                   &clip,
9422                                                   DRM_PLANE_HELPER_NO_SCALING,
9423                                                   DRM_PLANE_HELPER_NO_SCALING,
9424                                                   true, true);
9425         if (ret)
9426                 return ret;
9427
9428         if (!fb)
9429                 return 0;
9430
9431         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9432                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9433                 return -EINVAL;
9434         }
9435
9436         src_x = plane_state->base.src_x >> 16;
9437         src_y = plane_state->base.src_y >> 16;
9438
9439         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9440         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9441
9442         if (src_x != 0 || src_y != 0) {
9443                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9444                 return -EINVAL;
9445         }
9446
9447         plane_state->main.offset = offset;
9448
9449         return 0;
9450 }
9451
9452 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9453                            const struct intel_plane_state *plane_state)
9454 {
9455         const struct drm_framebuffer *fb = plane_state->base.fb;
9456
9457         return CURSOR_ENABLE |
9458                 CURSOR_GAMMA_ENABLE |
9459                 CURSOR_FORMAT_ARGB |
9460                 CURSOR_STRIDE(fb->pitches[0]);
9461 }
9462
9463 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9464 {
9465         int width = plane_state->base.crtc_w;
9466
9467         /*
9468          * 845g/865g are only limited by the width of their cursors,
9469          * the height is arbitrary up to the precision of the register.
9470          */
9471         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9472 }
9473
9474 static int i845_check_cursor(struct intel_plane *plane,
9475                              struct intel_crtc_state *crtc_state,
9476                              struct intel_plane_state *plane_state)
9477 {
9478         const struct drm_framebuffer *fb = plane_state->base.fb;
9479         int ret;
9480
9481         ret = intel_check_cursor(crtc_state, plane_state);
9482         if (ret)
9483                 return ret;
9484
9485         /* if we want to turn off the cursor ignore width and height */
9486         if (!fb)
9487                 return 0;
9488
9489         /* Check for which cursor types we support */
9490         if (!i845_cursor_size_ok(plane_state)) {
9491                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9492                           plane_state->base.crtc_w,
9493                           plane_state->base.crtc_h);
9494                 return -EINVAL;
9495         }
9496
9497         switch (fb->pitches[0]) {
9498         case 256:
9499         case 512:
9500         case 1024:
9501         case 2048:
9502                 break;
9503         default:
9504                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9505                               fb->pitches[0]);
9506                 return -EINVAL;
9507         }
9508
9509         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9510
9511         return 0;
9512 }
9513
9514 static void i845_update_cursor(struct intel_plane *plane,
9515                                const struct intel_crtc_state *crtc_state,
9516                                const struct intel_plane_state *plane_state)
9517 {
9518         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9519         u32 cntl = 0, base = 0, pos = 0, size = 0;
9520         unsigned long irqflags;
9521
9522         if (plane_state && plane_state->base.visible) {
9523                 unsigned int width = plane_state->base.crtc_w;
9524                 unsigned int height = plane_state->base.crtc_h;
9525
9526                 cntl = plane_state->ctl;
9527                 size = (height << 12) | width;
9528
9529                 base = intel_cursor_base(plane_state);
9530                 pos = intel_cursor_position(plane_state);
9531         }
9532
9533         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9534
9535         /* On these chipsets we can only modify the base/size/stride
9536          * whilst the cursor is disabled.
9537          */
9538         if (plane->cursor.base != base ||
9539             plane->cursor.size != size ||
9540             plane->cursor.cntl != cntl) {
9541                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9542                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9543                 I915_WRITE_FW(CURSIZE, size);
9544                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9545                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9546
9547                 plane->cursor.base = base;
9548                 plane->cursor.size = size;
9549                 plane->cursor.cntl = cntl;
9550         } else {
9551                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9552         }
9553
9554         POSTING_READ_FW(CURCNTR(PIPE_A));
9555
9556         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9557 }
9558
9559 static void i845_disable_cursor(struct intel_plane *plane,
9560                                 struct intel_crtc *crtc)
9561 {
9562         i845_update_cursor(plane, NULL, NULL);
9563 }
9564
9565 static bool i845_cursor_get_hw_state(struct intel_plane *plane)
9566 {
9567         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9568         enum intel_display_power_domain power_domain;
9569         bool ret;
9570
9571         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9572         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9573                 return false;
9574
9575         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9576
9577         intel_display_power_put(dev_priv, power_domain);
9578
9579         return ret;
9580 }
9581
9582 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9583                            const struct intel_plane_state *plane_state)
9584 {
9585         struct drm_i915_private *dev_priv =
9586                 to_i915(plane_state->base.plane->dev);
9587         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9588         u32 cntl;
9589
9590         cntl = MCURSOR_GAMMA_ENABLE;
9591
9592         if (HAS_DDI(dev_priv))
9593                 cntl |= CURSOR_PIPE_CSC_ENABLE;
9594
9595         if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
9596                 cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9597
9598         switch (plane_state->base.crtc_w) {
9599         case 64:
9600                 cntl |= CURSOR_MODE_64_ARGB_AX;
9601                 break;
9602         case 128:
9603                 cntl |= CURSOR_MODE_128_ARGB_AX;
9604                 break;
9605         case 256:
9606                 cntl |= CURSOR_MODE_256_ARGB_AX;
9607                 break;
9608         default:
9609                 MISSING_CASE(plane_state->base.crtc_w);
9610                 return 0;
9611         }
9612
9613         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9614                 cntl |= CURSOR_ROTATE_180;
9615
9616         return cntl;
9617 }
9618
9619 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9620 {
9621         struct drm_i915_private *dev_priv =
9622                 to_i915(plane_state->base.plane->dev);
9623         int width = plane_state->base.crtc_w;
9624         int height = plane_state->base.crtc_h;
9625
9626         if (!intel_cursor_size_ok(plane_state))
9627                 return false;
9628
9629         /* Cursor width is limited to a few power-of-two sizes */
9630         switch (width) {
9631         case 256:
9632         case 128:
9633         case 64:
9634                 break;
9635         default:
9636                 return false;
9637         }
9638
9639         /*
9640          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9641          * height from 8 lines up to the cursor width, when the
9642          * cursor is not rotated. Everything else requires square
9643          * cursors.
9644          */
9645         if (HAS_CUR_FBC(dev_priv) &&
9646             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9647                 if (height < 8 || height > width)
9648                         return false;
9649         } else {
9650                 if (height != width)
9651                         return false;
9652         }
9653
9654         return true;
9655 }
9656
9657 static int i9xx_check_cursor(struct intel_plane *plane,
9658                              struct intel_crtc_state *crtc_state,
9659                              struct intel_plane_state *plane_state)
9660 {
9661         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9662         const struct drm_framebuffer *fb = plane_state->base.fb;
9663         enum pipe pipe = plane->pipe;
9664         int ret;
9665
9666         ret = intel_check_cursor(crtc_state, plane_state);
9667         if (ret)
9668                 return ret;
9669
9670         /* if we want to turn off the cursor ignore width and height */
9671         if (!fb)
9672                 return 0;
9673
9674         /* Check for which cursor types we support */
9675         if (!i9xx_cursor_size_ok(plane_state)) {
9676                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9677                           plane_state->base.crtc_w,
9678                           plane_state->base.crtc_h);
9679                 return -EINVAL;
9680         }
9681
9682         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9683                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9684                               fb->pitches[0], plane_state->base.crtc_w);
9685                 return -EINVAL;
9686         }
9687
9688         /*
9689          * There's something wrong with the cursor on CHV pipe C.
9690          * If it straddles the left edge of the screen then
9691          * moving it away from the edge or disabling it often
9692          * results in a pipe underrun, and often that can lead to
9693          * dead pipe (constant underrun reported, and it scans
9694          * out just a solid color). To recover from that, the
9695          * display power well must be turned off and on again.
9696          * Refuse the put the cursor into that compromised position.
9697          */
9698         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9699             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9700                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9701                 return -EINVAL;
9702         }
9703
9704         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9705
9706         return 0;
9707 }
9708
9709 static void i9xx_update_cursor(struct intel_plane *plane,
9710                                const struct intel_crtc_state *crtc_state,
9711                                const struct intel_plane_state *plane_state)
9712 {
9713         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9714         enum pipe pipe = plane->pipe;
9715         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9716         unsigned long irqflags;
9717
9718         if (plane_state && plane_state->base.visible) {
9719                 cntl = plane_state->ctl;
9720
9721                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9722                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9723
9724                 base = intel_cursor_base(plane_state);
9725                 pos = intel_cursor_position(plane_state);
9726         }
9727
9728         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9729
9730         /*
9731          * On some platforms writing CURCNTR first will also
9732          * cause CURPOS to be armed by the CURBASE write.
9733          * Without the CURCNTR write the CURPOS write would
9734          * arm itself. Thus we always start the full update
9735          * with a CURCNTR write.
9736          *
9737          * On other platforms CURPOS always requires the
9738          * CURBASE write to arm the update. Additonally
9739          * a write to any of the cursor register will cancel
9740          * an already armed cursor update. Thus leaving out
9741          * the CURBASE write after CURPOS could lead to a
9742          * cursor that doesn't appear to move, or even change
9743          * shape. Thus we always write CURBASE.
9744          *
9745          * CURCNTR and CUR_FBC_CTL are always
9746          * armed by the CURBASE write only.
9747          */
9748         if (plane->cursor.base != base ||
9749             plane->cursor.size != fbc_ctl ||
9750             plane->cursor.cntl != cntl) {
9751                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9752                 if (HAS_CUR_FBC(dev_priv))
9753                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9754                 I915_WRITE_FW(CURPOS(pipe), pos);
9755                 I915_WRITE_FW(CURBASE(pipe), base);
9756
9757                 plane->cursor.base = base;
9758                 plane->cursor.size = fbc_ctl;
9759                 plane->cursor.cntl = cntl;
9760         } else {
9761                 I915_WRITE_FW(CURPOS(pipe), pos);
9762                 I915_WRITE_FW(CURBASE(pipe), base);
9763         }
9764
9765         POSTING_READ_FW(CURBASE(pipe));
9766
9767         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9768 }
9769
9770 static void i9xx_disable_cursor(struct intel_plane *plane,
9771                                 struct intel_crtc *crtc)
9772 {
9773         i9xx_update_cursor(plane, NULL, NULL);
9774 }
9775
9776 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane)
9777 {
9778         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9779         enum intel_display_power_domain power_domain;
9780         enum pipe pipe = plane->pipe;
9781         bool ret;
9782
9783         /*
9784          * Not 100% correct for planes that can move between pipes,
9785          * but that's only the case for gen2-3 which don't have any
9786          * display power wells.
9787          */
9788         power_domain = POWER_DOMAIN_PIPE(pipe);
9789         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9790                 return false;
9791
9792         ret = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
9793
9794         intel_display_power_put(dev_priv, power_domain);
9795
9796         return ret;
9797 }
9798
9799 /* VESA 640x480x72Hz mode to set on the pipe */
9800 static const struct drm_display_mode load_detect_mode = {
9801         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9802                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9803 };
9804
9805 struct drm_framebuffer *
9806 intel_framebuffer_create(struct drm_i915_gem_object *obj,
9807                          struct drm_mode_fb_cmd2 *mode_cmd)
9808 {
9809         struct intel_framebuffer *intel_fb;
9810         int ret;
9811
9812         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9813         if (!intel_fb)
9814                 return ERR_PTR(-ENOMEM);
9815
9816         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
9817         if (ret)
9818                 goto err;
9819
9820         return &intel_fb->base;
9821
9822 err:
9823         kfree(intel_fb);
9824         return ERR_PTR(ret);
9825 }
9826
9827 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
9828                                         struct drm_crtc *crtc)
9829 {
9830         struct drm_plane *plane;
9831         struct drm_plane_state *plane_state;
9832         int ret, i;
9833
9834         ret = drm_atomic_add_affected_planes(state, crtc);
9835         if (ret)
9836                 return ret;
9837
9838         for_each_new_plane_in_state(state, plane, plane_state, i) {
9839                 if (plane_state->crtc != crtc)
9840                         continue;
9841
9842                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
9843                 if (ret)
9844                         return ret;
9845
9846                 drm_atomic_set_fb_for_plane(plane_state, NULL);
9847         }
9848
9849         return 0;
9850 }
9851
9852 int intel_get_load_detect_pipe(struct drm_connector *connector,
9853                                const struct drm_display_mode *mode,
9854                                struct intel_load_detect_pipe *old,
9855                                struct drm_modeset_acquire_ctx *ctx)
9856 {
9857         struct intel_crtc *intel_crtc;
9858         struct intel_encoder *intel_encoder =
9859                 intel_attached_encoder(connector);
9860         struct drm_crtc *possible_crtc;
9861         struct drm_encoder *encoder = &intel_encoder->base;
9862         struct drm_crtc *crtc = NULL;
9863         struct drm_device *dev = encoder->dev;
9864         struct drm_i915_private *dev_priv = to_i915(dev);
9865         struct drm_mode_config *config = &dev->mode_config;
9866         struct drm_atomic_state *state = NULL, *restore_state = NULL;
9867         struct drm_connector_state *connector_state;
9868         struct intel_crtc_state *crtc_state;
9869         int ret, i = -1;
9870
9871         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9872                       connector->base.id, connector->name,
9873                       encoder->base.id, encoder->name);
9874
9875         old->restore_state = NULL;
9876
9877         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
9878
9879         /*
9880          * Algorithm gets a little messy:
9881          *
9882          *   - if the connector already has an assigned crtc, use it (but make
9883          *     sure it's on first)
9884          *
9885          *   - try to find the first unused crtc that can drive this connector,
9886          *     and use that if we find one
9887          */
9888
9889         /* See if we already have a CRTC for this connector */
9890         if (connector->state->crtc) {
9891                 crtc = connector->state->crtc;
9892
9893                 ret = drm_modeset_lock(&crtc->mutex, ctx);
9894                 if (ret)
9895                         goto fail;
9896
9897                 /* Make sure the crtc and connector are running */
9898                 goto found;
9899         }
9900
9901         /* Find an unused one (if possible) */
9902         for_each_crtc(dev, possible_crtc) {
9903                 i++;
9904                 if (!(encoder->possible_crtcs & (1 << i)))
9905                         continue;
9906
9907                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
9908                 if (ret)
9909                         goto fail;
9910
9911                 if (possible_crtc->state->enable) {
9912                         drm_modeset_unlock(&possible_crtc->mutex);
9913                         continue;
9914                 }
9915
9916                 crtc = possible_crtc;
9917                 break;
9918         }
9919
9920         /*
9921          * If we didn't find an unused CRTC, don't use any.
9922          */
9923         if (!crtc) {
9924                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
9925                 ret = -ENODEV;
9926                 goto fail;
9927         }
9928
9929 found:
9930         intel_crtc = to_intel_crtc(crtc);
9931
9932         state = drm_atomic_state_alloc(dev);
9933         restore_state = drm_atomic_state_alloc(dev);
9934         if (!state || !restore_state) {
9935                 ret = -ENOMEM;
9936                 goto fail;
9937         }
9938
9939         state->acquire_ctx = ctx;
9940         restore_state->acquire_ctx = ctx;
9941
9942         connector_state = drm_atomic_get_connector_state(state, connector);
9943         if (IS_ERR(connector_state)) {
9944                 ret = PTR_ERR(connector_state);
9945                 goto fail;
9946         }
9947
9948         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
9949         if (ret)
9950                 goto fail;
9951
9952         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9953         if (IS_ERR(crtc_state)) {
9954                 ret = PTR_ERR(crtc_state);
9955                 goto fail;
9956         }
9957
9958         crtc_state->base.active = crtc_state->base.enable = true;
9959
9960         if (!mode)
9961                 mode = &load_detect_mode;
9962
9963         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
9964         if (ret)
9965                 goto fail;
9966
9967         ret = intel_modeset_disable_planes(state, crtc);
9968         if (ret)
9969                 goto fail;
9970
9971         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
9972         if (!ret)
9973                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
9974         if (ret) {
9975                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
9976                 goto fail;
9977         }
9978
9979         ret = drm_atomic_commit(state);
9980         if (ret) {
9981                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
9982                 goto fail;
9983         }
9984
9985         old->restore_state = restore_state;
9986         drm_atomic_state_put(state);
9987
9988         /* let the connector get through one full cycle before testing */
9989         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
9990         return true;
9991
9992 fail:
9993         if (state) {
9994                 drm_atomic_state_put(state);
9995                 state = NULL;
9996         }
9997         if (restore_state) {
9998                 drm_atomic_state_put(restore_state);
9999                 restore_state = NULL;
10000         }
10001
10002         if (ret == -EDEADLK)
10003                 return ret;
10004
10005         return false;
10006 }
10007
10008 void intel_release_load_detect_pipe(struct drm_connector *connector,
10009                                     struct intel_load_detect_pipe *old,
10010                                     struct drm_modeset_acquire_ctx *ctx)
10011 {
10012         struct intel_encoder *intel_encoder =
10013                 intel_attached_encoder(connector);
10014         struct drm_encoder *encoder = &intel_encoder->base;
10015         struct drm_atomic_state *state = old->restore_state;
10016         int ret;
10017
10018         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
10019                       connector->base.id, connector->name,
10020                       encoder->base.id, encoder->name);
10021
10022         if (!state)
10023                 return;
10024
10025         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
10026         if (ret)
10027                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
10028         drm_atomic_state_put(state);
10029 }
10030
10031 static int i9xx_pll_refclk(struct drm_device *dev,
10032                            const struct intel_crtc_state *pipe_config)
10033 {
10034         struct drm_i915_private *dev_priv = to_i915(dev);
10035         u32 dpll = pipe_config->dpll_hw_state.dpll;
10036
10037         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
10038                 return dev_priv->vbt.lvds_ssc_freq;
10039         else if (HAS_PCH_SPLIT(dev_priv))
10040                 return 120000;
10041         else if (!IS_GEN2(dev_priv))
10042                 return 96000;
10043         else
10044                 return 48000;
10045 }
10046
10047 /* Returns the clock of the currently programmed mode of the given pipe. */
10048 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
10049                                 struct intel_crtc_state *pipe_config)
10050 {
10051         struct drm_device *dev = crtc->base.dev;
10052         struct drm_i915_private *dev_priv = to_i915(dev);
10053         int pipe = pipe_config->cpu_transcoder;
10054         u32 dpll = pipe_config->dpll_hw_state.dpll;
10055         u32 fp;
10056         struct dpll clock;
10057         int port_clock;
10058         int refclk = i9xx_pll_refclk(dev, pipe_config);
10059
10060         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
10061                 fp = pipe_config->dpll_hw_state.fp0;
10062         else
10063                 fp = pipe_config->dpll_hw_state.fp1;
10064
10065         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
10066         if (IS_PINEVIEW(dev_priv)) {
10067                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
10068                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
10069         } else {
10070                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
10071                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
10072         }
10073
10074         if (!IS_GEN2(dev_priv)) {
10075                 if (IS_PINEVIEW(dev_priv))
10076                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
10077                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
10078                 else
10079                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
10080                                DPLL_FPA01_P1_POST_DIV_SHIFT);
10081
10082                 switch (dpll & DPLL_MODE_MASK) {
10083                 case DPLLB_MODE_DAC_SERIAL:
10084                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
10085                                 5 : 10;
10086                         break;
10087                 case DPLLB_MODE_LVDS:
10088                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
10089                                 7 : 14;
10090                         break;
10091                 default:
10092                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
10093                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
10094                         return;
10095                 }
10096
10097                 if (IS_PINEVIEW(dev_priv))
10098                         port_clock = pnv_calc_dpll_params(refclk, &clock);
10099                 else
10100                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
10101         } else {
10102                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
10103                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
10104
10105                 if (is_lvds) {
10106                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10107                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10108
10109                         if (lvds & LVDS_CLKB_POWER_UP)
10110                                 clock.p2 = 7;
10111                         else
10112                                 clock.p2 = 14;
10113                 } else {
10114                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10115                                 clock.p1 = 2;
10116                         else {
10117                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10118                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10119                         }
10120                         if (dpll & PLL_P2_DIVIDE_BY_4)
10121                                 clock.p2 = 4;
10122                         else
10123                                 clock.p2 = 2;
10124                 }
10125
10126                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10127         }
10128
10129         /*
10130          * This value includes pixel_multiplier. We will use
10131          * port_clock to compute adjusted_mode.crtc_clock in the
10132          * encoder's get_config() function.
10133          */
10134         pipe_config->port_clock = port_clock;
10135 }
10136
10137 int intel_dotclock_calculate(int link_freq,
10138                              const struct intel_link_m_n *m_n)
10139 {
10140         /*
10141          * The calculation for the data clock is:
10142          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10143          * But we want to avoid losing precison if possible, so:
10144          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10145          *
10146          * and the link clock is simpler:
10147          * link_clock = (m * link_clock) / n
10148          */
10149
10150         if (!m_n->link_n)
10151                 return 0;
10152
10153         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10154 }
10155
10156 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10157                                    struct intel_crtc_state *pipe_config)
10158 {
10159         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10160
10161         /* read out port_clock from the DPLL */
10162         i9xx_crtc_clock_get(crtc, pipe_config);
10163
10164         /*
10165          * In case there is an active pipe without active ports,
10166          * we may need some idea for the dotclock anyway.
10167          * Calculate one based on the FDI configuration.
10168          */
10169         pipe_config->base.adjusted_mode.crtc_clock =
10170                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10171                                          &pipe_config->fdi_m_n);
10172 }
10173
10174 /* Returns the currently programmed mode of the given encoder. */
10175 struct drm_display_mode *
10176 intel_encoder_current_mode(struct intel_encoder *encoder)
10177 {
10178         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10179         struct intel_crtc_state *crtc_state;
10180         struct drm_display_mode *mode;
10181         struct intel_crtc *crtc;
10182         enum pipe pipe;
10183
10184         if (!encoder->get_hw_state(encoder, &pipe))
10185                 return NULL;
10186
10187         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10188
10189         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10190         if (!mode)
10191                 return NULL;
10192
10193         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10194         if (!crtc_state) {
10195                 kfree(mode);
10196                 return NULL;
10197         }
10198
10199         crtc_state->base.crtc = &crtc->base;
10200
10201         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10202                 kfree(crtc_state);
10203                 kfree(mode);
10204                 return NULL;
10205         }
10206
10207         encoder->get_config(encoder, crtc_state);
10208
10209         intel_mode_from_pipe_config(mode, crtc_state);
10210
10211         kfree(crtc_state);
10212
10213         return mode;
10214 }
10215
10216 static void intel_crtc_destroy(struct drm_crtc *crtc)
10217 {
10218         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10219
10220         drm_crtc_cleanup(crtc);
10221         kfree(intel_crtc);
10222 }
10223
10224 /**
10225  * intel_wm_need_update - Check whether watermarks need updating
10226  * @plane: drm plane
10227  * @state: new plane state
10228  *
10229  * Check current plane state versus the new one to determine whether
10230  * watermarks need to be recalculated.
10231  *
10232  * Returns true or false.
10233  */
10234 static bool intel_wm_need_update(struct drm_plane *plane,
10235                                  struct drm_plane_state *state)
10236 {
10237         struct intel_plane_state *new = to_intel_plane_state(state);
10238         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10239
10240         /* Update watermarks on tiling or size changes. */
10241         if (new->base.visible != cur->base.visible)
10242                 return true;
10243
10244         if (!cur->base.fb || !new->base.fb)
10245                 return false;
10246
10247         if (cur->base.fb->modifier != new->base.fb->modifier ||
10248             cur->base.rotation != new->base.rotation ||
10249             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10250             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10251             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10252             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10253                 return true;
10254
10255         return false;
10256 }
10257
10258 static bool needs_scaling(const struct intel_plane_state *state)
10259 {
10260         int src_w = drm_rect_width(&state->base.src) >> 16;
10261         int src_h = drm_rect_height(&state->base.src) >> 16;
10262         int dst_w = drm_rect_width(&state->base.dst);
10263         int dst_h = drm_rect_height(&state->base.dst);
10264
10265         return (src_w != dst_w || src_h != dst_h);
10266 }
10267
10268 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10269                                     struct drm_crtc_state *crtc_state,
10270                                     const struct intel_plane_state *old_plane_state,
10271                                     struct drm_plane_state *plane_state)
10272 {
10273         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10274         struct drm_crtc *crtc = crtc_state->crtc;
10275         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10276         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10277         struct drm_device *dev = crtc->dev;
10278         struct drm_i915_private *dev_priv = to_i915(dev);
10279         bool mode_changed = needs_modeset(crtc_state);
10280         bool was_crtc_enabled = old_crtc_state->base.active;
10281         bool is_crtc_enabled = crtc_state->active;
10282         bool turn_off, turn_on, visible, was_visible;
10283         struct drm_framebuffer *fb = plane_state->fb;
10284         int ret;
10285
10286         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10287                 ret = skl_update_scaler_plane(
10288                         to_intel_crtc_state(crtc_state),
10289                         to_intel_plane_state(plane_state));
10290                 if (ret)
10291                         return ret;
10292         }
10293
10294         was_visible = old_plane_state->base.visible;
10295         visible = plane_state->visible;
10296
10297         if (!was_crtc_enabled && WARN_ON(was_visible))
10298                 was_visible = false;
10299
10300         /*
10301          * Visibility is calculated as if the crtc was on, but
10302          * after scaler setup everything depends on it being off
10303          * when the crtc isn't active.
10304          *
10305          * FIXME this is wrong for watermarks. Watermarks should also
10306          * be computed as if the pipe would be active. Perhaps move
10307          * per-plane wm computation to the .check_plane() hook, and
10308          * only combine the results from all planes in the current place?
10309          */
10310         if (!is_crtc_enabled) {
10311                 plane_state->visible = visible = false;
10312                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10313         }
10314
10315         if (!was_visible && !visible)
10316                 return 0;
10317
10318         if (fb != old_plane_state->base.fb)
10319                 pipe_config->fb_changed = true;
10320
10321         turn_off = was_visible && (!visible || mode_changed);
10322         turn_on = visible && (!was_visible || mode_changed);
10323
10324         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10325                          intel_crtc->base.base.id, intel_crtc->base.name,
10326                          plane->base.base.id, plane->base.name,
10327                          fb ? fb->base.id : -1);
10328
10329         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10330                          plane->base.base.id, plane->base.name,
10331                          was_visible, visible,
10332                          turn_off, turn_on, mode_changed);
10333
10334         if (turn_on) {
10335                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10336                         pipe_config->update_wm_pre = true;
10337
10338                 /* must disable cxsr around plane enable/disable */
10339                 if (plane->id != PLANE_CURSOR)
10340                         pipe_config->disable_cxsr = true;
10341         } else if (turn_off) {
10342                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10343                         pipe_config->update_wm_post = true;
10344
10345                 /* must disable cxsr around plane enable/disable */
10346                 if (plane->id != PLANE_CURSOR)
10347                         pipe_config->disable_cxsr = true;
10348         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10349                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10350                         /* FIXME bollocks */
10351                         pipe_config->update_wm_pre = true;
10352                         pipe_config->update_wm_post = true;
10353                 }
10354         }
10355
10356         if (visible || was_visible)
10357                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10358
10359         /*
10360          * WaCxSRDisabledForSpriteScaling:ivb
10361          *
10362          * cstate->update_wm was already set above, so this flag will
10363          * take effect when we commit and program watermarks.
10364          */
10365         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
10366             needs_scaling(to_intel_plane_state(plane_state)) &&
10367             !needs_scaling(old_plane_state))
10368                 pipe_config->disable_lp_wm = true;
10369
10370         return 0;
10371 }
10372
10373 static bool encoders_cloneable(const struct intel_encoder *a,
10374                                const struct intel_encoder *b)
10375 {
10376         /* masks could be asymmetric, so check both ways */
10377         return a == b || (a->cloneable & (1 << b->type) &&
10378                           b->cloneable & (1 << a->type));
10379 }
10380
10381 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10382                                          struct intel_crtc *crtc,
10383                                          struct intel_encoder *encoder)
10384 {
10385         struct intel_encoder *source_encoder;
10386         struct drm_connector *connector;
10387         struct drm_connector_state *connector_state;
10388         int i;
10389
10390         for_each_new_connector_in_state(state, connector, connector_state, i) {
10391                 if (connector_state->crtc != &crtc->base)
10392                         continue;
10393
10394                 source_encoder =
10395                         to_intel_encoder(connector_state->best_encoder);
10396                 if (!encoders_cloneable(encoder, source_encoder))
10397                         return false;
10398         }
10399
10400         return true;
10401 }
10402
10403 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10404                                    struct drm_crtc_state *crtc_state)
10405 {
10406         struct drm_device *dev = crtc->dev;
10407         struct drm_i915_private *dev_priv = to_i915(dev);
10408         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10409         struct intel_crtc_state *pipe_config =
10410                 to_intel_crtc_state(crtc_state);
10411         struct drm_atomic_state *state = crtc_state->state;
10412         int ret;
10413         bool mode_changed = needs_modeset(crtc_state);
10414
10415         if (mode_changed && !crtc_state->active)
10416                 pipe_config->update_wm_post = true;
10417
10418         if (mode_changed && crtc_state->enable &&
10419             dev_priv->display.crtc_compute_clock &&
10420             !WARN_ON(pipe_config->shared_dpll)) {
10421                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10422                                                            pipe_config);
10423                 if (ret)
10424                         return ret;
10425         }
10426
10427         if (crtc_state->color_mgmt_changed) {
10428                 ret = intel_color_check(crtc, crtc_state);
10429                 if (ret)
10430                         return ret;
10431
10432                 /*
10433                  * Changing color management on Intel hardware is
10434                  * handled as part of planes update.
10435                  */
10436                 crtc_state->planes_changed = true;
10437         }
10438
10439         ret = 0;
10440         if (dev_priv->display.compute_pipe_wm) {
10441                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10442                 if (ret) {
10443                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10444                         return ret;
10445                 }
10446         }
10447
10448         if (dev_priv->display.compute_intermediate_wm &&
10449             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10450                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10451                         return 0;
10452
10453                 /*
10454                  * Calculate 'intermediate' watermarks that satisfy both the
10455                  * old state and the new state.  We can program these
10456                  * immediately.
10457                  */
10458                 ret = dev_priv->display.compute_intermediate_wm(dev,
10459                                                                 intel_crtc,
10460                                                                 pipe_config);
10461                 if (ret) {
10462                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10463                         return ret;
10464                 }
10465         } else if (dev_priv->display.compute_intermediate_wm) {
10466                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10467                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10468         }
10469
10470         if (INTEL_GEN(dev_priv) >= 9) {
10471                 if (mode_changed)
10472                         ret = skl_update_scaler_crtc(pipe_config);
10473
10474                 if (!ret)
10475                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10476                                                             pipe_config);
10477                 if (!ret)
10478                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10479                                                          pipe_config);
10480         }
10481
10482         if (HAS_IPS(dev_priv))
10483                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10484
10485         return ret;
10486 }
10487
10488 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10489         .atomic_begin = intel_begin_crtc_commit,
10490         .atomic_flush = intel_finish_crtc_commit,
10491         .atomic_check = intel_crtc_atomic_check,
10492 };
10493
10494 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10495 {
10496         struct intel_connector *connector;
10497         struct drm_connector_list_iter conn_iter;
10498
10499         drm_connector_list_iter_begin(dev, &conn_iter);
10500         for_each_intel_connector_iter(connector, &conn_iter) {
10501                 if (connector->base.state->crtc)
10502                         drm_connector_unreference(&connector->base);
10503
10504                 if (connector->base.encoder) {
10505                         connector->base.state->best_encoder =
10506                                 connector->base.encoder;
10507                         connector->base.state->crtc =
10508                                 connector->base.encoder->crtc;
10509
10510                         drm_connector_reference(&connector->base);
10511                 } else {
10512                         connector->base.state->best_encoder = NULL;
10513                         connector->base.state->crtc = NULL;
10514                 }
10515         }
10516         drm_connector_list_iter_end(&conn_iter);
10517 }
10518
10519 static void
10520 connected_sink_compute_bpp(struct intel_connector *connector,
10521                            struct intel_crtc_state *pipe_config)
10522 {
10523         const struct drm_display_info *info = &connector->base.display_info;
10524         int bpp = pipe_config->pipe_bpp;
10525
10526         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10527                       connector->base.base.id,
10528                       connector->base.name);
10529
10530         /* Don't use an invalid EDID bpc value */
10531         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10532                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10533                               bpp, info->bpc * 3);
10534                 pipe_config->pipe_bpp = info->bpc * 3;
10535         }
10536
10537         /* Clamp bpp to 8 on screens without EDID 1.4 */
10538         if (info->bpc == 0 && bpp > 24) {
10539                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10540                               bpp);
10541                 pipe_config->pipe_bpp = 24;
10542         }
10543 }
10544
10545 static int
10546 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10547                           struct intel_crtc_state *pipe_config)
10548 {
10549         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10550         struct drm_atomic_state *state;
10551         struct drm_connector *connector;
10552         struct drm_connector_state *connector_state;
10553         int bpp, i;
10554
10555         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10556             IS_CHERRYVIEW(dev_priv)))
10557                 bpp = 10*3;
10558         else if (INTEL_GEN(dev_priv) >= 5)
10559                 bpp = 12*3;
10560         else
10561                 bpp = 8*3;
10562
10563
10564         pipe_config->pipe_bpp = bpp;
10565
10566         state = pipe_config->base.state;
10567
10568         /* Clamp display bpp to EDID value */
10569         for_each_new_connector_in_state(state, connector, connector_state, i) {
10570                 if (connector_state->crtc != &crtc->base)
10571                         continue;
10572
10573                 connected_sink_compute_bpp(to_intel_connector(connector),
10574                                            pipe_config);
10575         }
10576
10577         return bpp;
10578 }
10579
10580 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10581 {
10582         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10583                         "type: 0x%x flags: 0x%x\n",
10584                 mode->crtc_clock,
10585                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10586                 mode->crtc_hsync_end, mode->crtc_htotal,
10587                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10588                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10589 }
10590
10591 static inline void
10592 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10593                       unsigned int lane_count, struct intel_link_m_n *m_n)
10594 {
10595         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10596                       id, lane_count,
10597                       m_n->gmch_m, m_n->gmch_n,
10598                       m_n->link_m, m_n->link_n, m_n->tu);
10599 }
10600
10601 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10602
10603 static const char * const output_type_str[] = {
10604         OUTPUT_TYPE(UNUSED),
10605         OUTPUT_TYPE(ANALOG),
10606         OUTPUT_TYPE(DVO),
10607         OUTPUT_TYPE(SDVO),
10608         OUTPUT_TYPE(LVDS),
10609         OUTPUT_TYPE(TVOUT),
10610         OUTPUT_TYPE(HDMI),
10611         OUTPUT_TYPE(DP),
10612         OUTPUT_TYPE(EDP),
10613         OUTPUT_TYPE(DSI),
10614         OUTPUT_TYPE(DDI),
10615         OUTPUT_TYPE(DP_MST),
10616 };
10617
10618 #undef OUTPUT_TYPE
10619
10620 static void snprintf_output_types(char *buf, size_t len,
10621                                   unsigned int output_types)
10622 {
10623         char *str = buf;
10624         int i;
10625
10626         str[0] = '\0';
10627
10628         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
10629                 int r;
10630
10631                 if ((output_types & BIT(i)) == 0)
10632                         continue;
10633
10634                 r = snprintf(str, len, "%s%s",
10635                              str != buf ? "," : "", output_type_str[i]);
10636                 if (r >= len)
10637                         break;
10638                 str += r;
10639                 len -= r;
10640
10641                 output_types &= ~BIT(i);
10642         }
10643
10644         WARN_ON_ONCE(output_types != 0);
10645 }
10646
10647 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10648                                    struct intel_crtc_state *pipe_config,
10649                                    const char *context)
10650 {
10651         struct drm_device *dev = crtc->base.dev;
10652         struct drm_i915_private *dev_priv = to_i915(dev);
10653         struct drm_plane *plane;
10654         struct intel_plane *intel_plane;
10655         struct intel_plane_state *state;
10656         struct drm_framebuffer *fb;
10657         char buf[64];
10658
10659         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10660                       crtc->base.base.id, crtc->base.name, context);
10661
10662         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
10663         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
10664                       buf, pipe_config->output_types);
10665
10666         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
10667                       transcoder_name(pipe_config->cpu_transcoder),
10668                       pipe_config->pipe_bpp, pipe_config->dither);
10669
10670         if (pipe_config->has_pch_encoder)
10671                 intel_dump_m_n_config(pipe_config, "fdi",
10672                                       pipe_config->fdi_lanes,
10673                                       &pipe_config->fdi_m_n);
10674
10675         if (pipe_config->ycbcr420)
10676                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
10677
10678         if (intel_crtc_has_dp_encoder(pipe_config)) {
10679                 intel_dump_m_n_config(pipe_config, "dp m_n",
10680                                 pipe_config->lane_count, &pipe_config->dp_m_n);
10681                 if (pipe_config->has_drrs)
10682                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
10683                                               pipe_config->lane_count,
10684                                               &pipe_config->dp_m2_n2);
10685         }
10686
10687         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10688                       pipe_config->has_audio, pipe_config->has_infoframe);
10689
10690         DRM_DEBUG_KMS("requested mode:\n");
10691         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10692         DRM_DEBUG_KMS("adjusted mode:\n");
10693         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10694         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10695         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
10696                       pipe_config->port_clock,
10697                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
10698                       pipe_config->pixel_rate);
10699
10700         if (INTEL_GEN(dev_priv) >= 9)
10701                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
10702                               crtc->num_scalers,
10703                               pipe_config->scaler_state.scaler_users,
10704                               pipe_config->scaler_state.scaler_id);
10705
10706         if (HAS_GMCH_DISPLAY(dev_priv))
10707                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10708                               pipe_config->gmch_pfit.control,
10709                               pipe_config->gmch_pfit.pgm_ratios,
10710                               pipe_config->gmch_pfit.lvds_border_bits);
10711         else
10712                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10713                               pipe_config->pch_pfit.pos,
10714                               pipe_config->pch_pfit.size,
10715                               enableddisabled(pipe_config->pch_pfit.enabled));
10716
10717         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
10718                       pipe_config->ips_enabled, pipe_config->double_wide);
10719
10720         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
10721
10722         DRM_DEBUG_KMS("planes on this crtc\n");
10723         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
10724                 struct drm_format_name_buf format_name;
10725                 intel_plane = to_intel_plane(plane);
10726                 if (intel_plane->pipe != crtc->pipe)
10727                         continue;
10728
10729                 state = to_intel_plane_state(plane->state);
10730                 fb = state->base.fb;
10731                 if (!fb) {
10732                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
10733                                       plane->base.id, plane->name, state->scaler_id);
10734                         continue;
10735                 }
10736
10737                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
10738                               plane->base.id, plane->name,
10739                               fb->base.id, fb->width, fb->height,
10740                               drm_get_format_name(fb->format->format, &format_name));
10741                 if (INTEL_GEN(dev_priv) >= 9)
10742                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
10743                                       state->scaler_id,
10744                                       state->base.src.x1 >> 16,
10745                                       state->base.src.y1 >> 16,
10746                                       drm_rect_width(&state->base.src) >> 16,
10747                                       drm_rect_height(&state->base.src) >> 16,
10748                                       state->base.dst.x1, state->base.dst.y1,
10749                                       drm_rect_width(&state->base.dst),
10750                                       drm_rect_height(&state->base.dst));
10751         }
10752 }
10753
10754 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
10755 {
10756         struct drm_device *dev = state->dev;
10757         struct drm_connector *connector;
10758         struct drm_connector_list_iter conn_iter;
10759         unsigned int used_ports = 0;
10760         unsigned int used_mst_ports = 0;
10761         bool ret = true;
10762
10763         /*
10764          * Walk the connector list instead of the encoder
10765          * list to detect the problem on ddi platforms
10766          * where there's just one encoder per digital port.
10767          */
10768         drm_connector_list_iter_begin(dev, &conn_iter);
10769         drm_for_each_connector_iter(connector, &conn_iter) {
10770                 struct drm_connector_state *connector_state;
10771                 struct intel_encoder *encoder;
10772
10773                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
10774                 if (!connector_state)
10775                         connector_state = connector->state;
10776
10777                 if (!connector_state->best_encoder)
10778                         continue;
10779
10780                 encoder = to_intel_encoder(connector_state->best_encoder);
10781
10782                 WARN_ON(!connector_state->crtc);
10783
10784                 switch (encoder->type) {
10785                         unsigned int port_mask;
10786                 case INTEL_OUTPUT_DDI:
10787                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
10788                                 break;
10789                 case INTEL_OUTPUT_DP:
10790                 case INTEL_OUTPUT_HDMI:
10791                 case INTEL_OUTPUT_EDP:
10792                         port_mask = 1 << encoder->port;
10793
10794                         /* the same port mustn't appear more than once */
10795                         if (used_ports & port_mask)
10796                                 ret = false;
10797
10798                         used_ports |= port_mask;
10799                         break;
10800                 case INTEL_OUTPUT_DP_MST:
10801                         used_mst_ports |=
10802                                 1 << encoder->port;
10803                         break;
10804                 default:
10805                         break;
10806                 }
10807         }
10808         drm_connector_list_iter_end(&conn_iter);
10809
10810         /* can't mix MST and SST/HDMI on the same port */
10811         if (used_ports & used_mst_ports)
10812                 return false;
10813
10814         return ret;
10815 }
10816
10817 static void
10818 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
10819 {
10820         struct drm_i915_private *dev_priv =
10821                 to_i915(crtc_state->base.crtc->dev);
10822         struct intel_crtc_scaler_state scaler_state;
10823         struct intel_dpll_hw_state dpll_hw_state;
10824         struct intel_shared_dpll *shared_dpll;
10825         struct intel_crtc_wm_state wm_state;
10826         bool force_thru, ips_force_disable;
10827
10828         /* FIXME: before the switch to atomic started, a new pipe_config was
10829          * kzalloc'd. Code that depends on any field being zero should be
10830          * fixed, so that the crtc_state can be safely duplicated. For now,
10831          * only fields that are know to not cause problems are preserved. */
10832
10833         scaler_state = crtc_state->scaler_state;
10834         shared_dpll = crtc_state->shared_dpll;
10835         dpll_hw_state = crtc_state->dpll_hw_state;
10836         force_thru = crtc_state->pch_pfit.force_thru;
10837         ips_force_disable = crtc_state->ips_force_disable;
10838         if (IS_G4X(dev_priv) ||
10839             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10840                 wm_state = crtc_state->wm;
10841
10842         /* Keep base drm_crtc_state intact, only clear our extended struct */
10843         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
10844         memset(&crtc_state->base + 1, 0,
10845                sizeof(*crtc_state) - sizeof(crtc_state->base));
10846
10847         crtc_state->scaler_state = scaler_state;
10848         crtc_state->shared_dpll = shared_dpll;
10849         crtc_state->dpll_hw_state = dpll_hw_state;
10850         crtc_state->pch_pfit.force_thru = force_thru;
10851         crtc_state->ips_force_disable = ips_force_disable;
10852         if (IS_G4X(dev_priv) ||
10853             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10854                 crtc_state->wm = wm_state;
10855 }
10856
10857 static int
10858 intel_modeset_pipe_config(struct drm_crtc *crtc,
10859                           struct intel_crtc_state *pipe_config)
10860 {
10861         struct drm_atomic_state *state = pipe_config->base.state;
10862         struct intel_encoder *encoder;
10863         struct drm_connector *connector;
10864         struct drm_connector_state *connector_state;
10865         int base_bpp, ret = -EINVAL;
10866         int i;
10867         bool retry = true;
10868
10869         clear_intel_crtc_state(pipe_config);
10870
10871         pipe_config->cpu_transcoder =
10872                 (enum transcoder) to_intel_crtc(crtc)->pipe;
10873
10874         /*
10875          * Sanitize sync polarity flags based on requested ones. If neither
10876          * positive or negative polarity is requested, treat this as meaning
10877          * negative polarity.
10878          */
10879         if (!(pipe_config->base.adjusted_mode.flags &
10880               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
10881                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
10882
10883         if (!(pipe_config->base.adjusted_mode.flags &
10884               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
10885                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
10886
10887         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
10888                                              pipe_config);
10889         if (base_bpp < 0)
10890                 goto fail;
10891
10892         /*
10893          * Determine the real pipe dimensions. Note that stereo modes can
10894          * increase the actual pipe size due to the frame doubling and
10895          * insertion of additional space for blanks between the frame. This
10896          * is stored in the crtc timings. We use the requested mode to do this
10897          * computation to clearly distinguish it from the adjusted mode, which
10898          * can be changed by the connectors in the below retry loop.
10899          */
10900         drm_mode_get_hv_timing(&pipe_config->base.mode,
10901                                &pipe_config->pipe_src_w,
10902                                &pipe_config->pipe_src_h);
10903
10904         for_each_new_connector_in_state(state, connector, connector_state, i) {
10905                 if (connector_state->crtc != crtc)
10906                         continue;
10907
10908                 encoder = to_intel_encoder(connector_state->best_encoder);
10909
10910                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
10911                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
10912                         goto fail;
10913                 }
10914
10915                 /*
10916                  * Determine output_types before calling the .compute_config()
10917                  * hooks so that the hooks can use this information safely.
10918                  */
10919                 if (encoder->compute_output_type)
10920                         pipe_config->output_types |=
10921                                 BIT(encoder->compute_output_type(encoder, pipe_config,
10922                                                                  connector_state));
10923                 else
10924                         pipe_config->output_types |= BIT(encoder->type);
10925         }
10926
10927 encoder_retry:
10928         /* Ensure the port clock defaults are reset when retrying. */
10929         pipe_config->port_clock = 0;
10930         pipe_config->pixel_multiplier = 1;
10931
10932         /* Fill in default crtc timings, allow encoders to overwrite them. */
10933         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
10934                               CRTC_STEREO_DOUBLE);
10935
10936         /* Pass our mode to the connectors and the CRTC to give them a chance to
10937          * adjust it according to limitations or connector properties, and also
10938          * a chance to reject the mode entirely.
10939          */
10940         for_each_new_connector_in_state(state, connector, connector_state, i) {
10941                 if (connector_state->crtc != crtc)
10942                         continue;
10943
10944                 encoder = to_intel_encoder(connector_state->best_encoder);
10945
10946                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
10947                         DRM_DEBUG_KMS("Encoder config failure\n");
10948                         goto fail;
10949                 }
10950         }
10951
10952         /* Set default port clock if not overwritten by the encoder. Needs to be
10953          * done afterwards in case the encoder adjusts the mode. */
10954         if (!pipe_config->port_clock)
10955                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
10956                         * pipe_config->pixel_multiplier;
10957
10958         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
10959         if (ret < 0) {
10960                 DRM_DEBUG_KMS("CRTC fixup failed\n");
10961                 goto fail;
10962         }
10963
10964         if (ret == RETRY) {
10965                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
10966                         ret = -EINVAL;
10967                         goto fail;
10968                 }
10969
10970                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
10971                 retry = false;
10972                 goto encoder_retry;
10973         }
10974
10975         /* Dithering seems to not pass-through bits correctly when it should, so
10976          * only enable it on 6bpc panels and when its not a compliance
10977          * test requesting 6bpc video pattern.
10978          */
10979         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
10980                 !pipe_config->dither_force_disable;
10981         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
10982                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
10983
10984 fail:
10985         return ret;
10986 }
10987
10988 static bool intel_fuzzy_clock_check(int clock1, int clock2)
10989 {
10990         int diff;
10991
10992         if (clock1 == clock2)
10993                 return true;
10994
10995         if (!clock1 || !clock2)
10996                 return false;
10997
10998         diff = abs(clock1 - clock2);
10999
11000         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
11001                 return true;
11002
11003         return false;
11004 }
11005
11006 static bool
11007 intel_compare_m_n(unsigned int m, unsigned int n,
11008                   unsigned int m2, unsigned int n2,
11009                   bool exact)
11010 {
11011         if (m == m2 && n == n2)
11012                 return true;
11013
11014         if (exact || !m || !n || !m2 || !n2)
11015                 return false;
11016
11017         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
11018
11019         if (n > n2) {
11020                 while (n > n2) {
11021                         m2 <<= 1;
11022                         n2 <<= 1;
11023                 }
11024         } else if (n < n2) {
11025                 while (n < n2) {
11026                         m <<= 1;
11027                         n <<= 1;
11028                 }
11029         }
11030
11031         if (n != n2)
11032                 return false;
11033
11034         return intel_fuzzy_clock_check(m, m2);
11035 }
11036
11037 static bool
11038 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
11039                        struct intel_link_m_n *m2_n2,
11040                        bool adjust)
11041 {
11042         if (m_n->tu == m2_n2->tu &&
11043             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
11044                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
11045             intel_compare_m_n(m_n->link_m, m_n->link_n,
11046                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
11047                 if (adjust)
11048                         *m2_n2 = *m_n;
11049
11050                 return true;
11051         }
11052
11053         return false;
11054 }
11055
11056 static void __printf(3, 4)
11057 pipe_config_err(bool adjust, const char *name, const char *format, ...)
11058 {
11059         char *level;
11060         unsigned int category;
11061         struct va_format vaf;
11062         va_list args;
11063
11064         if (adjust) {
11065                 level = KERN_DEBUG;
11066                 category = DRM_UT_KMS;
11067         } else {
11068                 level = KERN_ERR;
11069                 category = DRM_UT_NONE;
11070         }
11071
11072         va_start(args, format);
11073         vaf.fmt = format;
11074         vaf.va = &args;
11075
11076         drm_printk(level, category, "mismatch in %s %pV", name, &vaf);
11077
11078         va_end(args);
11079 }
11080
11081 static bool
11082 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
11083                           struct intel_crtc_state *current_config,
11084                           struct intel_crtc_state *pipe_config,
11085                           bool adjust)
11086 {
11087         bool ret = true;
11088         bool fixup_inherited = adjust &&
11089                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
11090                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
11091
11092 #define PIPE_CONF_CHECK_X(name) \
11093         if (current_config->name != pipe_config->name) { \
11094                 pipe_config_err(adjust, __stringify(name), \
11095                           "(expected 0x%08x, found 0x%08x)\n", \
11096                           current_config->name, \
11097                           pipe_config->name); \
11098                 ret = false; \
11099         }
11100
11101 #define PIPE_CONF_CHECK_I(name) \
11102         if (current_config->name != pipe_config->name) { \
11103                 pipe_config_err(adjust, __stringify(name), \
11104                           "(expected %i, found %i)\n", \
11105                           current_config->name, \
11106                           pipe_config->name); \
11107                 ret = false; \
11108         }
11109
11110 #define PIPE_CONF_CHECK_BOOL(name)      \
11111         if (current_config->name != pipe_config->name) { \
11112                 pipe_config_err(adjust, __stringify(name), \
11113                           "(expected %s, found %s)\n", \
11114                           yesno(current_config->name), \
11115                           yesno(pipe_config->name)); \
11116                 ret = false; \
11117         }
11118
11119 /*
11120  * Checks state where we only read out the enabling, but not the entire
11121  * state itself (like full infoframes or ELD for audio). These states
11122  * require a full modeset on bootup to fix up.
11123  */
11124 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) \
11125         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11126                 PIPE_CONF_CHECK_BOOL(name); \
11127         } else { \
11128                 pipe_config_err(adjust, __stringify(name), \
11129                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11130                           yesno(current_config->name), \
11131                           yesno(pipe_config->name)); \
11132                 ret = false; \
11133         }
11134
11135 #define PIPE_CONF_CHECK_P(name) \
11136         if (current_config->name != pipe_config->name) { \
11137                 pipe_config_err(adjust, __stringify(name), \
11138                           "(expected %p, found %p)\n", \
11139                           current_config->name, \
11140                           pipe_config->name); \
11141                 ret = false; \
11142         }
11143
11144 #define PIPE_CONF_CHECK_M_N(name) \
11145         if (!intel_compare_link_m_n(&current_config->name, \
11146                                     &pipe_config->name,\
11147                                     adjust)) { \
11148                 pipe_config_err(adjust, __stringify(name), \
11149                           "(expected tu %i gmch %i/%i link %i/%i, " \
11150                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11151                           current_config->name.tu, \
11152                           current_config->name.gmch_m, \
11153                           current_config->name.gmch_n, \
11154                           current_config->name.link_m, \
11155                           current_config->name.link_n, \
11156                           pipe_config->name.tu, \
11157                           pipe_config->name.gmch_m, \
11158                           pipe_config->name.gmch_n, \
11159                           pipe_config->name.link_m, \
11160                           pipe_config->name.link_n); \
11161                 ret = false; \
11162         }
11163
11164 /* This is required for BDW+ where there is only one set of registers for
11165  * switching between high and low RR.
11166  * This macro can be used whenever a comparison has to be made between one
11167  * hw state and multiple sw state variables.
11168  */
11169 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
11170         if (!intel_compare_link_m_n(&current_config->name, \
11171                                     &pipe_config->name, adjust) && \
11172             !intel_compare_link_m_n(&current_config->alt_name, \
11173                                     &pipe_config->name, adjust)) { \
11174                 pipe_config_err(adjust, __stringify(name), \
11175                           "(expected tu %i gmch %i/%i link %i/%i, " \
11176                           "or tu %i gmch %i/%i link %i/%i, " \
11177                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11178                           current_config->name.tu, \
11179                           current_config->name.gmch_m, \
11180                           current_config->name.gmch_n, \
11181                           current_config->name.link_m, \
11182                           current_config->name.link_n, \
11183                           current_config->alt_name.tu, \
11184                           current_config->alt_name.gmch_m, \
11185                           current_config->alt_name.gmch_n, \
11186                           current_config->alt_name.link_m, \
11187                           current_config->alt_name.link_n, \
11188                           pipe_config->name.tu, \
11189                           pipe_config->name.gmch_m, \
11190                           pipe_config->name.gmch_n, \
11191                           pipe_config->name.link_m, \
11192                           pipe_config->name.link_n); \
11193                 ret = false; \
11194         }
11195
11196 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
11197         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11198                 pipe_config_err(adjust, __stringify(name), \
11199                           "(%x) (expected %i, found %i)\n", \
11200                           (mask), \
11201                           current_config->name & (mask), \
11202                           pipe_config->name & (mask)); \
11203                 ret = false; \
11204         }
11205
11206 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
11207         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11208                 pipe_config_err(adjust, __stringify(name), \
11209                           "(expected %i, found %i)\n", \
11210                           current_config->name, \
11211                           pipe_config->name); \
11212                 ret = false; \
11213         }
11214
11215 #define PIPE_CONF_QUIRK(quirk)  \
11216         ((current_config->quirks | pipe_config->quirks) & (quirk))
11217
11218         PIPE_CONF_CHECK_I(cpu_transcoder);
11219
11220         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11221         PIPE_CONF_CHECK_I(fdi_lanes);
11222         PIPE_CONF_CHECK_M_N(fdi_m_n);
11223
11224         PIPE_CONF_CHECK_I(lane_count);
11225         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11226
11227         if (INTEL_GEN(dev_priv) < 8) {
11228                 PIPE_CONF_CHECK_M_N(dp_m_n);
11229
11230                 if (current_config->has_drrs)
11231                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11232         } else
11233                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11234
11235         PIPE_CONF_CHECK_X(output_types);
11236
11237         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11238         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11239         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11240         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11241         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11242         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11243
11244         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11245         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11246         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11247         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11248         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11249         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11250
11251         PIPE_CONF_CHECK_I(pixel_multiplier);
11252         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11253         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11254             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11255                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11256
11257         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11258         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11259         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11260         PIPE_CONF_CHECK_BOOL(ycbcr420);
11261
11262         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11263
11264         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11265                               DRM_MODE_FLAG_INTERLACE);
11266
11267         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11268                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11269                                       DRM_MODE_FLAG_PHSYNC);
11270                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11271                                       DRM_MODE_FLAG_NHSYNC);
11272                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11273                                       DRM_MODE_FLAG_PVSYNC);
11274                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11275                                       DRM_MODE_FLAG_NVSYNC);
11276         }
11277
11278         PIPE_CONF_CHECK_X(gmch_pfit.control);
11279         /* pfit ratios are autocomputed by the hw on gen4+ */
11280         if (INTEL_GEN(dev_priv) < 4)
11281                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11282         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11283
11284         if (!adjust) {
11285                 PIPE_CONF_CHECK_I(pipe_src_w);
11286                 PIPE_CONF_CHECK_I(pipe_src_h);
11287
11288                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11289                 if (current_config->pch_pfit.enabled) {
11290                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11291                         PIPE_CONF_CHECK_X(pch_pfit.size);
11292                 }
11293
11294                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11295                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11296         }
11297
11298         PIPE_CONF_CHECK_BOOL(double_wide);
11299
11300         PIPE_CONF_CHECK_P(shared_dpll);
11301         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11302         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11303         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11304         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11305         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11306         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11307         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11308         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11309         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11310         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11311         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11312         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11313         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11314         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11315         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11316         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11317         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11318         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11319         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11320         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11321         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11322
11323         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11324         PIPE_CONF_CHECK_X(dsi_pll.div);
11325
11326         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11327                 PIPE_CONF_CHECK_I(pipe_bpp);
11328
11329         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11330         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11331
11332         PIPE_CONF_CHECK_I(min_voltage_level);
11333
11334 #undef PIPE_CONF_CHECK_X
11335 #undef PIPE_CONF_CHECK_I
11336 #undef PIPE_CONF_CHECK_BOOL
11337 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11338 #undef PIPE_CONF_CHECK_P
11339 #undef PIPE_CONF_CHECK_FLAGS
11340 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11341 #undef PIPE_CONF_QUIRK
11342
11343         return ret;
11344 }
11345
11346 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11347                                            const struct intel_crtc_state *pipe_config)
11348 {
11349         if (pipe_config->has_pch_encoder) {
11350                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11351                                                             &pipe_config->fdi_m_n);
11352                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11353
11354                 /*
11355                  * FDI already provided one idea for the dotclock.
11356                  * Yell if the encoder disagrees.
11357                  */
11358                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11359                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11360                      fdi_dotclock, dotclock);
11361         }
11362 }
11363
11364 static void verify_wm_state(struct drm_crtc *crtc,
11365                             struct drm_crtc_state *new_state)
11366 {
11367         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11368         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11369         struct skl_pipe_wm hw_wm, *sw_wm;
11370         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11371         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11372         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11373         const enum pipe pipe = intel_crtc->pipe;
11374         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11375
11376         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11377                 return;
11378
11379         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11380         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11381
11382         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11383         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11384
11385         /* planes */
11386         for_each_universal_plane(dev_priv, pipe, plane) {
11387                 hw_plane_wm = &hw_wm.planes[plane];
11388                 sw_plane_wm = &sw_wm->planes[plane];
11389
11390                 /* Watermarks */
11391                 for (level = 0; level <= max_level; level++) {
11392                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11393                                                 &sw_plane_wm->wm[level]))
11394                                 continue;
11395
11396                         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",
11397                                   pipe_name(pipe), plane + 1, level,
11398                                   sw_plane_wm->wm[level].plane_en,
11399                                   sw_plane_wm->wm[level].plane_res_b,
11400                                   sw_plane_wm->wm[level].plane_res_l,
11401                                   hw_plane_wm->wm[level].plane_en,
11402                                   hw_plane_wm->wm[level].plane_res_b,
11403                                   hw_plane_wm->wm[level].plane_res_l);
11404                 }
11405
11406                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11407                                          &sw_plane_wm->trans_wm)) {
11408                         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",
11409                                   pipe_name(pipe), plane + 1,
11410                                   sw_plane_wm->trans_wm.plane_en,
11411                                   sw_plane_wm->trans_wm.plane_res_b,
11412                                   sw_plane_wm->trans_wm.plane_res_l,
11413                                   hw_plane_wm->trans_wm.plane_en,
11414                                   hw_plane_wm->trans_wm.plane_res_b,
11415                                   hw_plane_wm->trans_wm.plane_res_l);
11416                 }
11417
11418                 /* DDB */
11419                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11420                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11421
11422                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11423                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11424                                   pipe_name(pipe), plane + 1,
11425                                   sw_ddb_entry->start, sw_ddb_entry->end,
11426                                   hw_ddb_entry->start, hw_ddb_entry->end);
11427                 }
11428         }
11429
11430         /*
11431          * cursor
11432          * If the cursor plane isn't active, we may not have updated it's ddb
11433          * allocation. In that case since the ddb allocation will be updated
11434          * once the plane becomes visible, we can skip this check
11435          */
11436         if (1) {
11437                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11438                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11439
11440                 /* Watermarks */
11441                 for (level = 0; level <= max_level; level++) {
11442                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11443                                                 &sw_plane_wm->wm[level]))
11444                                 continue;
11445
11446                         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",
11447                                   pipe_name(pipe), level,
11448                                   sw_plane_wm->wm[level].plane_en,
11449                                   sw_plane_wm->wm[level].plane_res_b,
11450                                   sw_plane_wm->wm[level].plane_res_l,
11451                                   hw_plane_wm->wm[level].plane_en,
11452                                   hw_plane_wm->wm[level].plane_res_b,
11453                                   hw_plane_wm->wm[level].plane_res_l);
11454                 }
11455
11456                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11457                                          &sw_plane_wm->trans_wm)) {
11458                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11459                                   pipe_name(pipe),
11460                                   sw_plane_wm->trans_wm.plane_en,
11461                                   sw_plane_wm->trans_wm.plane_res_b,
11462                                   sw_plane_wm->trans_wm.plane_res_l,
11463                                   hw_plane_wm->trans_wm.plane_en,
11464                                   hw_plane_wm->trans_wm.plane_res_b,
11465                                   hw_plane_wm->trans_wm.plane_res_l);
11466                 }
11467
11468                 /* DDB */
11469                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11470                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11471
11472                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11473                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11474                                   pipe_name(pipe),
11475                                   sw_ddb_entry->start, sw_ddb_entry->end,
11476                                   hw_ddb_entry->start, hw_ddb_entry->end);
11477                 }
11478         }
11479 }
11480
11481 static void
11482 verify_connector_state(struct drm_device *dev,
11483                        struct drm_atomic_state *state,
11484                        struct drm_crtc *crtc)
11485 {
11486         struct drm_connector *connector;
11487         struct drm_connector_state *new_conn_state;
11488         int i;
11489
11490         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11491                 struct drm_encoder *encoder = connector->encoder;
11492                 struct drm_crtc_state *crtc_state = NULL;
11493
11494                 if (new_conn_state->crtc != crtc)
11495                         continue;
11496
11497                 if (crtc)
11498                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11499
11500                 intel_connector_verify_state(crtc_state, new_conn_state);
11501
11502                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11503                      "connector's atomic encoder doesn't match legacy encoder\n");
11504         }
11505 }
11506
11507 static void
11508 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11509 {
11510         struct intel_encoder *encoder;
11511         struct drm_connector *connector;
11512         struct drm_connector_state *old_conn_state, *new_conn_state;
11513         int i;
11514
11515         for_each_intel_encoder(dev, encoder) {
11516                 bool enabled = false, found = false;
11517                 enum pipe pipe;
11518
11519                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11520                               encoder->base.base.id,
11521                               encoder->base.name);
11522
11523                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11524                                                    new_conn_state, i) {
11525                         if (old_conn_state->best_encoder == &encoder->base)
11526                                 found = true;
11527
11528                         if (new_conn_state->best_encoder != &encoder->base)
11529                                 continue;
11530                         found = enabled = true;
11531
11532                         I915_STATE_WARN(new_conn_state->crtc !=
11533                                         encoder->base.crtc,
11534                              "connector's crtc doesn't match encoder crtc\n");
11535                 }
11536
11537                 if (!found)
11538                         continue;
11539
11540                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11541                      "encoder's enabled state mismatch "
11542                      "(expected %i, found %i)\n",
11543                      !!encoder->base.crtc, enabled);
11544
11545                 if (!encoder->base.crtc) {
11546                         bool active;
11547
11548                         active = encoder->get_hw_state(encoder, &pipe);
11549                         I915_STATE_WARN(active,
11550                              "encoder detached but still enabled on pipe %c.\n",
11551                              pipe_name(pipe));
11552                 }
11553         }
11554 }
11555
11556 static void
11557 verify_crtc_state(struct drm_crtc *crtc,
11558                   struct drm_crtc_state *old_crtc_state,
11559                   struct drm_crtc_state *new_crtc_state)
11560 {
11561         struct drm_device *dev = crtc->dev;
11562         struct drm_i915_private *dev_priv = to_i915(dev);
11563         struct intel_encoder *encoder;
11564         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11565         struct intel_crtc_state *pipe_config, *sw_config;
11566         struct drm_atomic_state *old_state;
11567         bool active;
11568
11569         old_state = old_crtc_state->state;
11570         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11571         pipe_config = to_intel_crtc_state(old_crtc_state);
11572         memset(pipe_config, 0, sizeof(*pipe_config));
11573         pipe_config->base.crtc = crtc;
11574         pipe_config->base.state = old_state;
11575
11576         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11577
11578         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11579
11580         /* we keep both pipes enabled on 830 */
11581         if (IS_I830(dev_priv))
11582                 active = new_crtc_state->active;
11583
11584         I915_STATE_WARN(new_crtc_state->active != active,
11585              "crtc active state doesn't match with hw state "
11586              "(expected %i, found %i)\n", new_crtc_state->active, active);
11587
11588         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11589              "transitional active state does not match atomic hw state "
11590              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11591
11592         for_each_encoder_on_crtc(dev, crtc, encoder) {
11593                 enum pipe pipe;
11594
11595                 active = encoder->get_hw_state(encoder, &pipe);
11596                 I915_STATE_WARN(active != new_crtc_state->active,
11597                         "[ENCODER:%i] active %i with crtc active %i\n",
11598                         encoder->base.base.id, active, new_crtc_state->active);
11599
11600                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11601                                 "Encoder connected to wrong pipe %c\n",
11602                                 pipe_name(pipe));
11603
11604                 if (active)
11605                         encoder->get_config(encoder, pipe_config);
11606         }
11607
11608         intel_crtc_compute_pixel_rate(pipe_config);
11609
11610         if (!new_crtc_state->active)
11611                 return;
11612
11613         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11614
11615         sw_config = to_intel_crtc_state(new_crtc_state);
11616         if (!intel_pipe_config_compare(dev_priv, sw_config,
11617                                        pipe_config, false)) {
11618                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11619                 intel_dump_pipe_config(intel_crtc, pipe_config,
11620                                        "[hw state]");
11621                 intel_dump_pipe_config(intel_crtc, sw_config,
11622                                        "[sw state]");
11623         }
11624 }
11625
11626 static void
11627 intel_verify_planes(struct intel_atomic_state *state)
11628 {
11629         struct intel_plane *plane;
11630         const struct intel_plane_state *plane_state;
11631         int i;
11632
11633         for_each_new_intel_plane_in_state(state, plane,
11634                                           plane_state, i)
11635                 assert_plane(plane, plane_state->base.visible);
11636 }
11637
11638 static void
11639 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11640                          struct intel_shared_dpll *pll,
11641                          struct drm_crtc *crtc,
11642                          struct drm_crtc_state *new_state)
11643 {
11644         struct intel_dpll_hw_state dpll_hw_state;
11645         unsigned crtc_mask;
11646         bool active;
11647
11648         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11649
11650         DRM_DEBUG_KMS("%s\n", pll->name);
11651
11652         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
11653
11654         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
11655                 I915_STATE_WARN(!pll->on && pll->active_mask,
11656                      "pll in active use but not on in sw tracking\n");
11657                 I915_STATE_WARN(pll->on && !pll->active_mask,
11658                      "pll is on but not used by any active crtc\n");
11659                 I915_STATE_WARN(pll->on != active,
11660                      "pll on state mismatch (expected %i, found %i)\n",
11661                      pll->on, active);
11662         }
11663
11664         if (!crtc) {
11665                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
11666                                 "more active pll users than references: %x vs %x\n",
11667                                 pll->active_mask, pll->state.crtc_mask);
11668
11669                 return;
11670         }
11671
11672         crtc_mask = 1 << drm_crtc_index(crtc);
11673
11674         if (new_state->active)
11675                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
11676                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
11677                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11678         else
11679                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11680                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
11681                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11682
11683         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
11684                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
11685                         crtc_mask, pll->state.crtc_mask);
11686
11687         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
11688                                           &dpll_hw_state,
11689                                           sizeof(dpll_hw_state)),
11690                         "pll hw state mismatch\n");
11691 }
11692
11693 static void
11694 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
11695                          struct drm_crtc_state *old_crtc_state,
11696                          struct drm_crtc_state *new_crtc_state)
11697 {
11698         struct drm_i915_private *dev_priv = to_i915(dev);
11699         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
11700         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
11701
11702         if (new_state->shared_dpll)
11703                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
11704
11705         if (old_state->shared_dpll &&
11706             old_state->shared_dpll != new_state->shared_dpll) {
11707                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
11708                 struct intel_shared_dpll *pll = old_state->shared_dpll;
11709
11710                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11711                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
11712                                 pipe_name(drm_crtc_index(crtc)));
11713                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
11714                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
11715                                 pipe_name(drm_crtc_index(crtc)));
11716         }
11717 }
11718
11719 static void
11720 intel_modeset_verify_crtc(struct drm_crtc *crtc,
11721                           struct drm_atomic_state *state,
11722                           struct drm_crtc_state *old_state,
11723                           struct drm_crtc_state *new_state)
11724 {
11725         if (!needs_modeset(new_state) &&
11726             !to_intel_crtc_state(new_state)->update_pipe)
11727                 return;
11728
11729         verify_wm_state(crtc, new_state);
11730         verify_connector_state(crtc->dev, state, crtc);
11731         verify_crtc_state(crtc, old_state, new_state);
11732         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
11733 }
11734
11735 static void
11736 verify_disabled_dpll_state(struct drm_device *dev)
11737 {
11738         struct drm_i915_private *dev_priv = to_i915(dev);
11739         int i;
11740
11741         for (i = 0; i < dev_priv->num_shared_dpll; i++)
11742                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
11743 }
11744
11745 static void
11746 intel_modeset_verify_disabled(struct drm_device *dev,
11747                               struct drm_atomic_state *state)
11748 {
11749         verify_encoder_state(dev, state);
11750         verify_connector_state(dev, state, NULL);
11751         verify_disabled_dpll_state(dev);
11752 }
11753
11754 static void update_scanline_offset(struct intel_crtc *crtc)
11755 {
11756         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11757
11758         /*
11759          * The scanline counter increments at the leading edge of hsync.
11760          *
11761          * On most platforms it starts counting from vtotal-1 on the
11762          * first active line. That means the scanline counter value is
11763          * always one less than what we would expect. Ie. just after
11764          * start of vblank, which also occurs at start of hsync (on the
11765          * last active line), the scanline counter will read vblank_start-1.
11766          *
11767          * On gen2 the scanline counter starts counting from 1 instead
11768          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
11769          * to keep the value positive), instead of adding one.
11770          *
11771          * On HSW+ the behaviour of the scanline counter depends on the output
11772          * type. For DP ports it behaves like most other platforms, but on HDMI
11773          * there's an extra 1 line difference. So we need to add two instead of
11774          * one to the value.
11775          *
11776          * On VLV/CHV DSI the scanline counter would appear to increment
11777          * approx. 1/3 of a scanline before start of vblank. Unfortunately
11778          * that means we can't tell whether we're in vblank or not while
11779          * we're on that particular line. We must still set scanline_offset
11780          * to 1 so that the vblank timestamps come out correct when we query
11781          * the scanline counter from within the vblank interrupt handler.
11782          * However if queried just before the start of vblank we'll get an
11783          * answer that's slightly in the future.
11784          */
11785         if (IS_GEN2(dev_priv)) {
11786                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
11787                 int vtotal;
11788
11789                 vtotal = adjusted_mode->crtc_vtotal;
11790                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
11791                         vtotal /= 2;
11792
11793                 crtc->scanline_offset = vtotal - 1;
11794         } else if (HAS_DDI(dev_priv) &&
11795                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
11796                 crtc->scanline_offset = 2;
11797         } else
11798                 crtc->scanline_offset = 1;
11799 }
11800
11801 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
11802 {
11803         struct drm_device *dev = state->dev;
11804         struct drm_i915_private *dev_priv = to_i915(dev);
11805         struct drm_crtc *crtc;
11806         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11807         int i;
11808
11809         if (!dev_priv->display.crtc_compute_clock)
11810                 return;
11811
11812         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11813                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11814                 struct intel_shared_dpll *old_dpll =
11815                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
11816
11817                 if (!needs_modeset(new_crtc_state))
11818                         continue;
11819
11820                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
11821
11822                 if (!old_dpll)
11823                         continue;
11824
11825                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
11826         }
11827 }
11828
11829 /*
11830  * This implements the workaround described in the "notes" section of the mode
11831  * set sequence documentation. When going from no pipes or single pipe to
11832  * multiple pipes, and planes are enabled after the pipe, we need to wait at
11833  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
11834  */
11835 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
11836 {
11837         struct drm_crtc_state *crtc_state;
11838         struct intel_crtc *intel_crtc;
11839         struct drm_crtc *crtc;
11840         struct intel_crtc_state *first_crtc_state = NULL;
11841         struct intel_crtc_state *other_crtc_state = NULL;
11842         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
11843         int i;
11844
11845         /* look at all crtc's that are going to be enabled in during modeset */
11846         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
11847                 intel_crtc = to_intel_crtc(crtc);
11848
11849                 if (!crtc_state->active || !needs_modeset(crtc_state))
11850                         continue;
11851
11852                 if (first_crtc_state) {
11853                         other_crtc_state = to_intel_crtc_state(crtc_state);
11854                         break;
11855                 } else {
11856                         first_crtc_state = to_intel_crtc_state(crtc_state);
11857                         first_pipe = intel_crtc->pipe;
11858                 }
11859         }
11860
11861         /* No workaround needed? */
11862         if (!first_crtc_state)
11863                 return 0;
11864
11865         /* w/a possibly needed, check how many crtc's are already enabled. */
11866         for_each_intel_crtc(state->dev, intel_crtc) {
11867                 struct intel_crtc_state *pipe_config;
11868
11869                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
11870                 if (IS_ERR(pipe_config))
11871                         return PTR_ERR(pipe_config);
11872
11873                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
11874
11875                 if (!pipe_config->base.active ||
11876                     needs_modeset(&pipe_config->base))
11877                         continue;
11878
11879                 /* 2 or more enabled crtcs means no need for w/a */
11880                 if (enabled_pipe != INVALID_PIPE)
11881                         return 0;
11882
11883                 enabled_pipe = intel_crtc->pipe;
11884         }
11885
11886         if (enabled_pipe != INVALID_PIPE)
11887                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
11888         else if (other_crtc_state)
11889                 other_crtc_state->hsw_workaround_pipe = first_pipe;
11890
11891         return 0;
11892 }
11893
11894 static int intel_lock_all_pipes(struct drm_atomic_state *state)
11895 {
11896         struct drm_crtc *crtc;
11897
11898         /* Add all pipes to the state */
11899         for_each_crtc(state->dev, crtc) {
11900                 struct drm_crtc_state *crtc_state;
11901
11902                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11903                 if (IS_ERR(crtc_state))
11904                         return PTR_ERR(crtc_state);
11905         }
11906
11907         return 0;
11908 }
11909
11910 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
11911 {
11912         struct drm_crtc *crtc;
11913
11914         /*
11915          * Add all pipes to the state, and force
11916          * a modeset on all the active ones.
11917          */
11918         for_each_crtc(state->dev, crtc) {
11919                 struct drm_crtc_state *crtc_state;
11920                 int ret;
11921
11922                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11923                 if (IS_ERR(crtc_state))
11924                         return PTR_ERR(crtc_state);
11925
11926                 if (!crtc_state->active || needs_modeset(crtc_state))
11927                         continue;
11928
11929                 crtc_state->mode_changed = true;
11930
11931                 ret = drm_atomic_add_affected_connectors(state, crtc);
11932                 if (ret)
11933                         return ret;
11934
11935                 ret = drm_atomic_add_affected_planes(state, crtc);
11936                 if (ret)
11937                         return ret;
11938         }
11939
11940         return 0;
11941 }
11942
11943 static int intel_modeset_checks(struct drm_atomic_state *state)
11944 {
11945         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
11946         struct drm_i915_private *dev_priv = to_i915(state->dev);
11947         struct drm_crtc *crtc;
11948         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11949         int ret = 0, i;
11950
11951         if (!check_digital_port_conflicts(state)) {
11952                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
11953                 return -EINVAL;
11954         }
11955
11956         intel_state->modeset = true;
11957         intel_state->active_crtcs = dev_priv->active_crtcs;
11958         intel_state->cdclk.logical = dev_priv->cdclk.logical;
11959         intel_state->cdclk.actual = dev_priv->cdclk.actual;
11960
11961         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11962                 if (new_crtc_state->active)
11963                         intel_state->active_crtcs |= 1 << i;
11964                 else
11965                         intel_state->active_crtcs &= ~(1 << i);
11966
11967                 if (old_crtc_state->active != new_crtc_state->active)
11968                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
11969         }
11970
11971         /*
11972          * See if the config requires any additional preparation, e.g.
11973          * to adjust global state with pipes off.  We need to do this
11974          * here so we can get the modeset_pipe updated config for the new
11975          * mode set on this crtc.  For other crtcs we need to use the
11976          * adjusted_mode bits in the crtc directly.
11977          */
11978         if (dev_priv->display.modeset_calc_cdclk) {
11979                 ret = dev_priv->display.modeset_calc_cdclk(state);
11980                 if (ret < 0)
11981                         return ret;
11982
11983                 /*
11984                  * Writes to dev_priv->cdclk.logical must protected by
11985                  * holding all the crtc locks, even if we don't end up
11986                  * touching the hardware
11987                  */
11988                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
11989                                         &intel_state->cdclk.logical)) {
11990                         ret = intel_lock_all_pipes(state);
11991                         if (ret < 0)
11992                                 return ret;
11993                 }
11994
11995                 /* All pipes must be switched off while we change the cdclk. */
11996                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
11997                                               &intel_state->cdclk.actual)) {
11998                         ret = intel_modeset_all_pipes(state);
11999                         if (ret < 0)
12000                                 return ret;
12001                 }
12002
12003                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
12004                               intel_state->cdclk.logical.cdclk,
12005                               intel_state->cdclk.actual.cdclk);
12006                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
12007                               intel_state->cdclk.logical.voltage_level,
12008                               intel_state->cdclk.actual.voltage_level);
12009         } else {
12010                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
12011         }
12012
12013         intel_modeset_clear_plls(state);
12014
12015         if (IS_HASWELL(dev_priv))
12016                 return haswell_mode_set_planes_workaround(state);
12017
12018         return 0;
12019 }
12020
12021 /*
12022  * Handle calculation of various watermark data at the end of the atomic check
12023  * phase.  The code here should be run after the per-crtc and per-plane 'check'
12024  * handlers to ensure that all derived state has been updated.
12025  */
12026 static int calc_watermark_data(struct drm_atomic_state *state)
12027 {
12028         struct drm_device *dev = state->dev;
12029         struct drm_i915_private *dev_priv = to_i915(dev);
12030
12031         /* Is there platform-specific watermark information to calculate? */
12032         if (dev_priv->display.compute_global_watermarks)
12033                 return dev_priv->display.compute_global_watermarks(state);
12034
12035         return 0;
12036 }
12037
12038 /**
12039  * intel_atomic_check - validate state object
12040  * @dev: drm device
12041  * @state: state to validate
12042  */
12043 static int intel_atomic_check(struct drm_device *dev,
12044                               struct drm_atomic_state *state)
12045 {
12046         struct drm_i915_private *dev_priv = to_i915(dev);
12047         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12048         struct drm_crtc *crtc;
12049         struct drm_crtc_state *old_crtc_state, *crtc_state;
12050         int ret, i;
12051         bool any_ms = false;
12052
12053         ret = drm_atomic_helper_check_modeset(dev, state);
12054         if (ret)
12055                 return ret;
12056
12057         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
12058                 struct intel_crtc_state *pipe_config =
12059                         to_intel_crtc_state(crtc_state);
12060
12061                 /* Catch I915_MODE_FLAG_INHERITED */
12062                 if (crtc_state->mode.private_flags != old_crtc_state->mode.private_flags)
12063                         crtc_state->mode_changed = true;
12064
12065                 if (!needs_modeset(crtc_state))
12066                         continue;
12067
12068                 if (!crtc_state->enable) {
12069                         any_ms = true;
12070                         continue;
12071                 }
12072
12073                 /* FIXME: For only active_changed we shouldn't need to do any
12074                  * state recomputation at all. */
12075
12076                 ret = drm_atomic_add_affected_connectors(state, crtc);
12077                 if (ret)
12078                         return ret;
12079
12080                 ret = intel_modeset_pipe_config(crtc, pipe_config);
12081                 if (ret) {
12082                         intel_dump_pipe_config(to_intel_crtc(crtc),
12083                                                pipe_config, "[failed]");
12084                         return ret;
12085                 }
12086
12087                 if (i915_modparams.fastboot &&
12088                     intel_pipe_config_compare(dev_priv,
12089                                         to_intel_crtc_state(old_crtc_state),
12090                                         pipe_config, true)) {
12091                         crtc_state->mode_changed = false;
12092                         pipe_config->update_pipe = true;
12093                 }
12094
12095                 if (needs_modeset(crtc_state))
12096                         any_ms = true;
12097
12098                 ret = drm_atomic_add_affected_planes(state, crtc);
12099                 if (ret)
12100                         return ret;
12101
12102                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
12103                                        needs_modeset(crtc_state) ?
12104                                        "[modeset]" : "[fastset]");
12105         }
12106
12107         if (any_ms) {
12108                 ret = intel_modeset_checks(state);
12109
12110                 if (ret)
12111                         return ret;
12112         } else {
12113                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12114         }
12115
12116         ret = drm_atomic_helper_check_planes(dev, state);
12117         if (ret)
12118                 return ret;
12119
12120         intel_fbc_choose_crtc(dev_priv, intel_state);
12121         return calc_watermark_data(state);
12122 }
12123
12124 static int intel_atomic_prepare_commit(struct drm_device *dev,
12125                                        struct drm_atomic_state *state)
12126 {
12127         return drm_atomic_helper_prepare_planes(dev, state);
12128 }
12129
12130 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12131 {
12132         struct drm_device *dev = crtc->base.dev;
12133
12134         if (!dev->max_vblank_count)
12135                 return (u32)drm_crtc_accurate_vblank_count(&crtc->base);
12136
12137         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12138 }
12139
12140 static void intel_update_crtc(struct drm_crtc *crtc,
12141                               struct drm_atomic_state *state,
12142                               struct drm_crtc_state *old_crtc_state,
12143                               struct drm_crtc_state *new_crtc_state)
12144 {
12145         struct drm_device *dev = crtc->dev;
12146         struct drm_i915_private *dev_priv = to_i915(dev);
12147         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12148         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12149         bool modeset = needs_modeset(new_crtc_state);
12150
12151         if (modeset) {
12152                 update_scanline_offset(intel_crtc);
12153                 dev_priv->display.crtc_enable(pipe_config, state);
12154         } else {
12155                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12156                                        pipe_config);
12157         }
12158
12159         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12160                 intel_fbc_enable(
12161                     intel_crtc, pipe_config,
12162                     to_intel_plane_state(crtc->primary->state));
12163         }
12164
12165         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12166 }
12167
12168 static void intel_update_crtcs(struct drm_atomic_state *state)
12169 {
12170         struct drm_crtc *crtc;
12171         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12172         int i;
12173
12174         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12175                 if (!new_crtc_state->active)
12176                         continue;
12177
12178                 intel_update_crtc(crtc, state, old_crtc_state,
12179                                   new_crtc_state);
12180         }
12181 }
12182
12183 static void skl_update_crtcs(struct drm_atomic_state *state)
12184 {
12185         struct drm_i915_private *dev_priv = to_i915(state->dev);
12186         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12187         struct drm_crtc *crtc;
12188         struct intel_crtc *intel_crtc;
12189         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12190         struct intel_crtc_state *cstate;
12191         unsigned int updated = 0;
12192         bool progress;
12193         enum pipe pipe;
12194         int i;
12195
12196         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12197
12198         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12199                 /* ignore allocations for crtc's that have been turned off. */
12200                 if (new_crtc_state->active)
12201                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12202
12203         /*
12204          * Whenever the number of active pipes changes, we need to make sure we
12205          * update the pipes in the right order so that their ddb allocations
12206          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12207          * cause pipe underruns and other bad stuff.
12208          */
12209         do {
12210                 progress = false;
12211
12212                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12213                         bool vbl_wait = false;
12214                         unsigned int cmask = drm_crtc_mask(crtc);
12215
12216                         intel_crtc = to_intel_crtc(crtc);
12217                         cstate = to_intel_crtc_state(new_crtc_state);
12218                         pipe = intel_crtc->pipe;
12219
12220                         if (updated & cmask || !cstate->base.active)
12221                                 continue;
12222
12223                         if (skl_ddb_allocation_overlaps(dev_priv,
12224                                                         entries,
12225                                                         &cstate->wm.skl.ddb,
12226                                                         i))
12227                                 continue;
12228
12229                         updated |= cmask;
12230                         entries[i] = &cstate->wm.skl.ddb;
12231
12232                         /*
12233                          * If this is an already active pipe, it's DDB changed,
12234                          * and this isn't the last pipe that needs updating
12235                          * then we need to wait for a vblank to pass for the
12236                          * new ddb allocation to take effect.
12237                          */
12238                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12239                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12240                             !new_crtc_state->active_changed &&
12241                             intel_state->wm_results.dirty_pipes != updated)
12242                                 vbl_wait = true;
12243
12244                         intel_update_crtc(crtc, state, old_crtc_state,
12245                                           new_crtc_state);
12246
12247                         if (vbl_wait)
12248                                 intel_wait_for_vblank(dev_priv, pipe);
12249
12250                         progress = true;
12251                 }
12252         } while (progress);
12253 }
12254
12255 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12256 {
12257         struct intel_atomic_state *state, *next;
12258         struct llist_node *freed;
12259
12260         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12261         llist_for_each_entry_safe(state, next, freed, freed)
12262                 drm_atomic_state_put(&state->base);
12263 }
12264
12265 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12266 {
12267         struct drm_i915_private *dev_priv =
12268                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12269
12270         intel_atomic_helper_free_state(dev_priv);
12271 }
12272
12273 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12274 {
12275         struct wait_queue_entry wait_fence, wait_reset;
12276         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12277
12278         init_wait_entry(&wait_fence, 0);
12279         init_wait_entry(&wait_reset, 0);
12280         for (;;) {
12281                 prepare_to_wait(&intel_state->commit_ready.wait,
12282                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12283                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12284                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12285
12286
12287                 if (i915_sw_fence_done(&intel_state->commit_ready)
12288                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12289                         break;
12290
12291                 schedule();
12292         }
12293         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12294         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12295 }
12296
12297 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12298 {
12299         struct drm_device *dev = state->dev;
12300         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12301         struct drm_i915_private *dev_priv = to_i915(dev);
12302         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12303         struct drm_crtc *crtc;
12304         struct intel_crtc_state *intel_cstate;
12305         u64 put_domains[I915_MAX_PIPES] = {};
12306         int i;
12307
12308         intel_atomic_commit_fence_wait(intel_state);
12309
12310         drm_atomic_helper_wait_for_dependencies(state);
12311
12312         if (intel_state->modeset)
12313                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12314
12315         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12316                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12317
12318                 if (needs_modeset(new_crtc_state) ||
12319                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12320
12321                         put_domains[to_intel_crtc(crtc)->pipe] =
12322                                 modeset_get_crtc_power_domains(crtc,
12323                                         to_intel_crtc_state(new_crtc_state));
12324                 }
12325
12326                 if (!needs_modeset(new_crtc_state))
12327                         continue;
12328
12329                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12330                                        to_intel_crtc_state(new_crtc_state));
12331
12332                 if (old_crtc_state->active) {
12333                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
12334                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
12335                         intel_crtc->active = false;
12336                         intel_fbc_disable(intel_crtc);
12337                         intel_disable_shared_dpll(intel_crtc);
12338
12339                         /*
12340                          * Underruns don't always raise
12341                          * interrupts, so check manually.
12342                          */
12343                         intel_check_cpu_fifo_underruns(dev_priv);
12344                         intel_check_pch_fifo_underruns(dev_priv);
12345
12346                         if (!new_crtc_state->active) {
12347                                 /*
12348                                  * Make sure we don't call initial_watermarks
12349                                  * for ILK-style watermark updates.
12350                                  *
12351                                  * No clue what this is supposed to achieve.
12352                                  */
12353                                 if (INTEL_GEN(dev_priv) >= 9)
12354                                         dev_priv->display.initial_watermarks(intel_state,
12355                                                                              to_intel_crtc_state(new_crtc_state));
12356                         }
12357                 }
12358         }
12359
12360         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12361         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12362                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12363
12364         if (intel_state->modeset) {
12365                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12366
12367                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12368
12369                 /*
12370                  * SKL workaround: bspec recommends we disable the SAGV when we
12371                  * have more then one pipe enabled
12372                  */
12373                 if (!intel_can_enable_sagv(state))
12374                         intel_disable_sagv(dev_priv);
12375
12376                 intel_modeset_verify_disabled(dev, state);
12377         }
12378
12379         /* Complete the events for pipes that have now been disabled */
12380         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12381                 bool modeset = needs_modeset(new_crtc_state);
12382
12383                 /* Complete events for now disable pipes here. */
12384                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12385                         spin_lock_irq(&dev->event_lock);
12386                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12387                         spin_unlock_irq(&dev->event_lock);
12388
12389                         new_crtc_state->event = NULL;
12390                 }
12391         }
12392
12393         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12394         dev_priv->display.update_crtcs(state);
12395
12396         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12397          * already, but still need the state for the delayed optimization. To
12398          * fix this:
12399          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12400          * - schedule that vblank worker _before_ calling hw_done
12401          * - at the start of commit_tail, cancel it _synchrously
12402          * - switch over to the vblank wait helper in the core after that since
12403          *   we don't need out special handling any more.
12404          */
12405         drm_atomic_helper_wait_for_flip_done(dev, state);
12406
12407         /*
12408          * Now that the vblank has passed, we can go ahead and program the
12409          * optimal watermarks on platforms that need two-step watermark
12410          * programming.
12411          *
12412          * TODO: Move this (and other cleanup) to an async worker eventually.
12413          */
12414         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12415                 intel_cstate = to_intel_crtc_state(new_crtc_state);
12416
12417                 if (dev_priv->display.optimize_watermarks)
12418                         dev_priv->display.optimize_watermarks(intel_state,
12419                                                               intel_cstate);
12420         }
12421
12422         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12423                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12424
12425                 if (put_domains[i])
12426                         modeset_put_power_domains(dev_priv, put_domains[i]);
12427
12428                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12429         }
12430
12431         if (intel_state->modeset)
12432                 intel_verify_planes(intel_state);
12433
12434         if (intel_state->modeset && intel_can_enable_sagv(state))
12435                 intel_enable_sagv(dev_priv);
12436
12437         drm_atomic_helper_commit_hw_done(state);
12438
12439         if (intel_state->modeset) {
12440                 /* As one of the primary mmio accessors, KMS has a high
12441                  * likelihood of triggering bugs in unclaimed access. After we
12442                  * finish modesetting, see if an error has been flagged, and if
12443                  * so enable debugging for the next modeset - and hope we catch
12444                  * the culprit.
12445                  */
12446                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12447                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12448         }
12449
12450         drm_atomic_helper_cleanup_planes(dev, state);
12451
12452         drm_atomic_helper_commit_cleanup_done(state);
12453
12454         drm_atomic_state_put(state);
12455
12456         intel_atomic_helper_free_state(dev_priv);
12457 }
12458
12459 static void intel_atomic_commit_work(struct work_struct *work)
12460 {
12461         struct drm_atomic_state *state =
12462                 container_of(work, struct drm_atomic_state, commit_work);
12463
12464         intel_atomic_commit_tail(state);
12465 }
12466
12467 static int __i915_sw_fence_call
12468 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12469                           enum i915_sw_fence_notify notify)
12470 {
12471         struct intel_atomic_state *state =
12472                 container_of(fence, struct intel_atomic_state, commit_ready);
12473
12474         switch (notify) {
12475         case FENCE_COMPLETE:
12476                 /* we do blocking waits in the worker, nothing to do here */
12477                 break;
12478         case FENCE_FREE:
12479                 {
12480                         struct intel_atomic_helper *helper =
12481                                 &to_i915(state->base.dev)->atomic_helper;
12482
12483                         if (llist_add(&state->freed, &helper->free_list))
12484                                 schedule_work(&helper->free_work);
12485                         break;
12486                 }
12487         }
12488
12489         return NOTIFY_DONE;
12490 }
12491
12492 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12493 {
12494         struct drm_plane_state *old_plane_state, *new_plane_state;
12495         struct drm_plane *plane;
12496         int i;
12497
12498         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12499                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12500                                   intel_fb_obj(new_plane_state->fb),
12501                                   to_intel_plane(plane)->frontbuffer_bit);
12502 }
12503
12504 /**
12505  * intel_atomic_commit - commit validated state object
12506  * @dev: DRM device
12507  * @state: the top-level driver state object
12508  * @nonblock: nonblocking commit
12509  *
12510  * This function commits a top-level state object that has been validated
12511  * with drm_atomic_helper_check().
12512  *
12513  * RETURNS
12514  * Zero for success or -errno.
12515  */
12516 static int intel_atomic_commit(struct drm_device *dev,
12517                                struct drm_atomic_state *state,
12518                                bool nonblock)
12519 {
12520         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12521         struct drm_i915_private *dev_priv = to_i915(dev);
12522         int ret = 0;
12523
12524         drm_atomic_state_get(state);
12525         i915_sw_fence_init(&intel_state->commit_ready,
12526                            intel_atomic_commit_ready);
12527
12528         /*
12529          * The intel_legacy_cursor_update() fast path takes care
12530          * of avoiding the vblank waits for simple cursor
12531          * movement and flips. For cursor on/off and size changes,
12532          * we want to perform the vblank waits so that watermark
12533          * updates happen during the correct frames. Gen9+ have
12534          * double buffered watermarks and so shouldn't need this.
12535          *
12536          * Unset state->legacy_cursor_update before the call to
12537          * drm_atomic_helper_setup_commit() because otherwise
12538          * drm_atomic_helper_wait_for_flip_done() is a noop and
12539          * we get FIFO underruns because we didn't wait
12540          * for vblank.
12541          *
12542          * FIXME doing watermarks and fb cleanup from a vblank worker
12543          * (assuming we had any) would solve these problems.
12544          */
12545         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12546                 struct intel_crtc_state *new_crtc_state;
12547                 struct intel_crtc *crtc;
12548                 int i;
12549
12550                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12551                         if (new_crtc_state->wm.need_postvbl_update ||
12552                             new_crtc_state->update_wm_post)
12553                                 state->legacy_cursor_update = false;
12554         }
12555
12556         ret = intel_atomic_prepare_commit(dev, state);
12557         if (ret) {
12558                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12559                 i915_sw_fence_commit(&intel_state->commit_ready);
12560                 return ret;
12561         }
12562
12563         ret = drm_atomic_helper_setup_commit(state, nonblock);
12564         if (!ret)
12565                 ret = drm_atomic_helper_swap_state(state, true);
12566
12567         if (ret) {
12568                 i915_sw_fence_commit(&intel_state->commit_ready);
12569
12570                 drm_atomic_helper_cleanup_planes(dev, state);
12571                 return ret;
12572         }
12573         dev_priv->wm.distrust_bios_wm = false;
12574         intel_shared_dpll_swap_state(state);
12575         intel_atomic_track_fbs(state);
12576
12577         if (intel_state->modeset) {
12578                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12579                        sizeof(intel_state->min_cdclk));
12580                 memcpy(dev_priv->min_voltage_level,
12581                        intel_state->min_voltage_level,
12582                        sizeof(intel_state->min_voltage_level));
12583                 dev_priv->active_crtcs = intel_state->active_crtcs;
12584                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12585                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12586         }
12587
12588         drm_atomic_state_get(state);
12589         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12590
12591         i915_sw_fence_commit(&intel_state->commit_ready);
12592         if (nonblock && intel_state->modeset) {
12593                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12594         } else if (nonblock) {
12595                 queue_work(system_unbound_wq, &state->commit_work);
12596         } else {
12597                 if (intel_state->modeset)
12598                         flush_workqueue(dev_priv->modeset_wq);
12599                 intel_atomic_commit_tail(state);
12600         }
12601
12602         return 0;
12603 }
12604
12605 static const struct drm_crtc_funcs intel_crtc_funcs = {
12606         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12607         .set_config = drm_atomic_helper_set_config,
12608         .destroy = intel_crtc_destroy,
12609         .page_flip = drm_atomic_helper_page_flip,
12610         .atomic_duplicate_state = intel_crtc_duplicate_state,
12611         .atomic_destroy_state = intel_crtc_destroy_state,
12612         .set_crc_source = intel_crtc_set_crc_source,
12613 };
12614
12615 struct wait_rps_boost {
12616         struct wait_queue_entry wait;
12617
12618         struct drm_crtc *crtc;
12619         struct i915_request *request;
12620 };
12621
12622 static int do_rps_boost(struct wait_queue_entry *_wait,
12623                         unsigned mode, int sync, void *key)
12624 {
12625         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
12626         struct i915_request *rq = wait->request;
12627
12628         /*
12629          * If we missed the vblank, but the request is already running it
12630          * is reasonable to assume that it will complete before the next
12631          * vblank without our intervention, so leave RPS alone.
12632          */
12633         if (!i915_request_started(rq))
12634                 gen6_rps_boost(rq, NULL);
12635         i915_request_put(rq);
12636
12637         drm_crtc_vblank_put(wait->crtc);
12638
12639         list_del(&wait->wait.entry);
12640         kfree(wait);
12641         return 1;
12642 }
12643
12644 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
12645                                        struct dma_fence *fence)
12646 {
12647         struct wait_rps_boost *wait;
12648
12649         if (!dma_fence_is_i915(fence))
12650                 return;
12651
12652         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
12653                 return;
12654
12655         if (drm_crtc_vblank_get(crtc))
12656                 return;
12657
12658         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
12659         if (!wait) {
12660                 drm_crtc_vblank_put(crtc);
12661                 return;
12662         }
12663
12664         wait->request = to_request(dma_fence_get(fence));
12665         wait->crtc = crtc;
12666
12667         wait->wait.func = do_rps_boost;
12668         wait->wait.flags = 0;
12669
12670         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
12671 }
12672
12673 static int intel_plane_pin_fb(struct intel_plane_state *plane_state)
12674 {
12675         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
12676         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12677         struct drm_framebuffer *fb = plane_state->base.fb;
12678         struct i915_vma *vma;
12679
12680         if (plane->id == PLANE_CURSOR &&
12681             INTEL_INFO(dev_priv)->cursor_needs_physical) {
12682                 struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12683                 const int align = intel_cursor_alignment(dev_priv);
12684
12685                 return i915_gem_object_attach_phys(obj, align);
12686         }
12687
12688         vma = intel_pin_and_fence_fb_obj(fb,
12689                                          plane_state->base.rotation,
12690                                          intel_plane_uses_fence(plane_state),
12691                                          &plane_state->flags);
12692         if (IS_ERR(vma))
12693                 return PTR_ERR(vma);
12694
12695         plane_state->vma = vma;
12696
12697         return 0;
12698 }
12699
12700 static void intel_plane_unpin_fb(struct intel_plane_state *old_plane_state)
12701 {
12702         struct i915_vma *vma;
12703
12704         vma = fetch_and_zero(&old_plane_state->vma);
12705         if (vma)
12706                 intel_unpin_fb_vma(vma, old_plane_state->flags);
12707 }
12708
12709 /**
12710  * intel_prepare_plane_fb - Prepare fb for usage on plane
12711  * @plane: drm plane to prepare for
12712  * @new_state: the plane state being prepared
12713  *
12714  * Prepares a framebuffer for usage on a display plane.  Generally this
12715  * involves pinning the underlying object and updating the frontbuffer tracking
12716  * bits.  Some older platforms need special physical address handling for
12717  * cursor planes.
12718  *
12719  * Must be called with struct_mutex held.
12720  *
12721  * Returns 0 on success, negative error code on failure.
12722  */
12723 int
12724 intel_prepare_plane_fb(struct drm_plane *plane,
12725                        struct drm_plane_state *new_state)
12726 {
12727         struct intel_atomic_state *intel_state =
12728                 to_intel_atomic_state(new_state->state);
12729         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12730         struct drm_framebuffer *fb = new_state->fb;
12731         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12732         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
12733         int ret;
12734
12735         if (old_obj) {
12736                 struct drm_crtc_state *crtc_state =
12737                         drm_atomic_get_existing_crtc_state(new_state->state,
12738                                                            plane->state->crtc);
12739
12740                 /* Big Hammer, we also need to ensure that any pending
12741                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
12742                  * current scanout is retired before unpinning the old
12743                  * framebuffer. Note that we rely on userspace rendering
12744                  * into the buffer attached to the pipe they are waiting
12745                  * on. If not, userspace generates a GPU hang with IPEHR
12746                  * point to the MI_WAIT_FOR_EVENT.
12747                  *
12748                  * This should only fail upon a hung GPU, in which case we
12749                  * can safely continue.
12750                  */
12751                 if (needs_modeset(crtc_state)) {
12752                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12753                                                               old_obj->resv, NULL,
12754                                                               false, 0,
12755                                                               GFP_KERNEL);
12756                         if (ret < 0)
12757                                 return ret;
12758                 }
12759         }
12760
12761         if (new_state->fence) { /* explicit fencing */
12762                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
12763                                                     new_state->fence,
12764                                                     I915_FENCE_TIMEOUT,
12765                                                     GFP_KERNEL);
12766                 if (ret < 0)
12767                         return ret;
12768         }
12769
12770         if (!obj)
12771                 return 0;
12772
12773         ret = i915_gem_object_pin_pages(obj);
12774         if (ret)
12775                 return ret;
12776
12777         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
12778         if (ret) {
12779                 i915_gem_object_unpin_pages(obj);
12780                 return ret;
12781         }
12782
12783         ret = intel_plane_pin_fb(to_intel_plane_state(new_state));
12784
12785         i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
12786
12787         mutex_unlock(&dev_priv->drm.struct_mutex);
12788         i915_gem_object_unpin_pages(obj);
12789         if (ret)
12790                 return ret;
12791
12792         if (!new_state->fence) { /* implicit fencing */
12793                 struct dma_fence *fence;
12794
12795                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12796                                                       obj->resv, NULL,
12797                                                       false, I915_FENCE_TIMEOUT,
12798                                                       GFP_KERNEL);
12799                 if (ret < 0)
12800                         return ret;
12801
12802                 fence = reservation_object_get_excl_rcu(obj->resv);
12803                 if (fence) {
12804                         add_rps_boost_after_vblank(new_state->crtc, fence);
12805                         dma_fence_put(fence);
12806                 }
12807         } else {
12808                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
12809         }
12810
12811         return 0;
12812 }
12813
12814 /**
12815  * intel_cleanup_plane_fb - Cleans up an fb after plane use
12816  * @plane: drm plane to clean up for
12817  * @old_state: the state from the previous modeset
12818  *
12819  * Cleans up a framebuffer that has just been removed from a plane.
12820  *
12821  * Must be called with struct_mutex held.
12822  */
12823 void
12824 intel_cleanup_plane_fb(struct drm_plane *plane,
12825                        struct drm_plane_state *old_state)
12826 {
12827         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12828
12829         /* Should only be called after a successful intel_prepare_plane_fb()! */
12830         mutex_lock(&dev_priv->drm.struct_mutex);
12831         intel_plane_unpin_fb(to_intel_plane_state(old_state));
12832         mutex_unlock(&dev_priv->drm.struct_mutex);
12833 }
12834
12835 int
12836 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
12837 {
12838         struct drm_i915_private *dev_priv;
12839         int max_scale;
12840         int crtc_clock, max_dotclk;
12841
12842         if (!intel_crtc || !crtc_state->base.enable)
12843                 return DRM_PLANE_HELPER_NO_SCALING;
12844
12845         dev_priv = to_i915(intel_crtc->base.dev);
12846
12847         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
12848         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
12849
12850         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
12851                 max_dotclk *= 2;
12852
12853         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
12854                 return DRM_PLANE_HELPER_NO_SCALING;
12855
12856         /*
12857          * skl max scale is lower of:
12858          *    close to 3 but not 3, -1 is for that purpose
12859          *            or
12860          *    cdclk/crtc_clock
12861          */
12862         max_scale = min((1 << 16) * 3 - 1,
12863                         (1 << 8) * ((max_dotclk << 8) / crtc_clock));
12864
12865         return max_scale;
12866 }
12867
12868 static int
12869 intel_check_primary_plane(struct intel_plane *plane,
12870                           struct intel_crtc_state *crtc_state,
12871                           struct intel_plane_state *state)
12872 {
12873         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12874         struct drm_crtc *crtc = state->base.crtc;
12875         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
12876         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
12877         bool can_position = false;
12878         struct drm_rect clip = {};
12879         int ret;
12880
12881         if (INTEL_GEN(dev_priv) >= 9) {
12882                 /* use scaler when colorkey is not required */
12883                 if (!state->ckey.flags) {
12884                         min_scale = 1;
12885                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
12886                 }
12887                 can_position = true;
12888         }
12889
12890         if (crtc_state->base.enable)
12891                 drm_mode_get_hv_timing(&crtc_state->base.mode,
12892                                        &clip.x2, &clip.y2);
12893
12894         ret = drm_atomic_helper_check_plane_state(&state->base,
12895                                                   &crtc_state->base,
12896                                                   &clip,
12897                                                   min_scale, max_scale,
12898                                                   can_position, true);
12899         if (ret)
12900                 return ret;
12901
12902         if (!state->base.fb)
12903                 return 0;
12904
12905         if (INTEL_GEN(dev_priv) >= 9) {
12906                 ret = skl_check_plane_surface(crtc_state, state);
12907                 if (ret)
12908                         return ret;
12909
12910                 state->ctl = skl_plane_ctl(crtc_state, state);
12911         } else {
12912                 ret = i9xx_check_plane_surface(state);
12913                 if (ret)
12914                         return ret;
12915
12916                 state->ctl = i9xx_plane_ctl(crtc_state, state);
12917         }
12918
12919         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
12920                 state->color_ctl = glk_plane_color_ctl(crtc_state, state);
12921
12922         return 0;
12923 }
12924
12925 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
12926                                     struct drm_crtc_state *old_crtc_state)
12927 {
12928         struct drm_device *dev = crtc->dev;
12929         struct drm_i915_private *dev_priv = to_i915(dev);
12930         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12931         struct intel_crtc_state *old_intel_cstate =
12932                 to_intel_crtc_state(old_crtc_state);
12933         struct intel_atomic_state *old_intel_state =
12934                 to_intel_atomic_state(old_crtc_state->state);
12935         struct intel_crtc_state *intel_cstate =
12936                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
12937         bool modeset = needs_modeset(&intel_cstate->base);
12938
12939         if (!modeset &&
12940             (intel_cstate->base.color_mgmt_changed ||
12941              intel_cstate->update_pipe)) {
12942                 intel_color_set_csc(&intel_cstate->base);
12943                 intel_color_load_luts(&intel_cstate->base);
12944         }
12945
12946         /* Perform vblank evasion around commit operation */
12947         intel_pipe_update_start(intel_cstate);
12948
12949         if (modeset)
12950                 goto out;
12951
12952         if (intel_cstate->update_pipe)
12953                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
12954         else if (INTEL_GEN(dev_priv) >= 9)
12955                 skl_detach_scalers(intel_crtc);
12956
12957 out:
12958         if (dev_priv->display.atomic_update_watermarks)
12959                 dev_priv->display.atomic_update_watermarks(old_intel_state,
12960                                                            intel_cstate);
12961 }
12962
12963 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
12964                                      struct drm_crtc_state *old_crtc_state)
12965 {
12966         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12967         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12968         struct intel_atomic_state *old_intel_state =
12969                 to_intel_atomic_state(old_crtc_state->state);
12970         struct intel_crtc_state *new_crtc_state =
12971                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
12972
12973         intel_pipe_update_end(new_crtc_state);
12974
12975         if (new_crtc_state->update_pipe &&
12976             !needs_modeset(&new_crtc_state->base) &&
12977             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED) {
12978                 if (!IS_GEN2(dev_priv))
12979                         intel_set_cpu_fifo_underrun_reporting(dev_priv, intel_crtc->pipe, true);
12980
12981                 if (new_crtc_state->has_pch_encoder) {
12982                         enum pipe pch_transcoder =
12983                                 intel_crtc_pch_transcoder(intel_crtc);
12984
12985                         intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
12986                 }
12987         }
12988 }
12989
12990 /**
12991  * intel_plane_destroy - destroy a plane
12992  * @plane: plane to destroy
12993  *
12994  * Common destruction function for all types of planes (primary, cursor,
12995  * sprite).
12996  */
12997 void intel_plane_destroy(struct drm_plane *plane)
12998 {
12999         drm_plane_cleanup(plane);
13000         kfree(to_intel_plane(plane));
13001 }
13002
13003 static bool i8xx_mod_supported(uint32_t format, uint64_t modifier)
13004 {
13005         switch (format) {
13006         case DRM_FORMAT_C8:
13007         case DRM_FORMAT_RGB565:
13008         case DRM_FORMAT_XRGB1555:
13009         case DRM_FORMAT_XRGB8888:
13010                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13011                         modifier == I915_FORMAT_MOD_X_TILED;
13012         default:
13013                 return false;
13014         }
13015 }
13016
13017 static bool i965_mod_supported(uint32_t format, uint64_t modifier)
13018 {
13019         switch (format) {
13020         case DRM_FORMAT_C8:
13021         case DRM_FORMAT_RGB565:
13022         case DRM_FORMAT_XRGB8888:
13023         case DRM_FORMAT_XBGR8888:
13024         case DRM_FORMAT_XRGB2101010:
13025         case DRM_FORMAT_XBGR2101010:
13026                 return modifier == DRM_FORMAT_MOD_LINEAR ||
13027                         modifier == I915_FORMAT_MOD_X_TILED;
13028         default:
13029                 return false;
13030         }
13031 }
13032
13033 static bool skl_mod_supported(uint32_t format, uint64_t modifier)
13034 {
13035         switch (format) {
13036         case DRM_FORMAT_XRGB8888:
13037         case DRM_FORMAT_XBGR8888:
13038         case DRM_FORMAT_ARGB8888:
13039         case DRM_FORMAT_ABGR8888:
13040                 if (modifier == I915_FORMAT_MOD_Yf_TILED_CCS ||
13041                     modifier == I915_FORMAT_MOD_Y_TILED_CCS)
13042                         return true;
13043                 /* fall through */
13044         case DRM_FORMAT_RGB565:
13045         case DRM_FORMAT_XRGB2101010:
13046         case DRM_FORMAT_XBGR2101010:
13047         case DRM_FORMAT_YUYV:
13048         case DRM_FORMAT_YVYU:
13049         case DRM_FORMAT_UYVY:
13050         case DRM_FORMAT_VYUY:
13051                 if (modifier == I915_FORMAT_MOD_Yf_TILED)
13052                         return true;
13053                 /* fall through */
13054         case DRM_FORMAT_C8:
13055                 if (modifier == DRM_FORMAT_MOD_LINEAR ||
13056                     modifier == I915_FORMAT_MOD_X_TILED ||
13057                     modifier == I915_FORMAT_MOD_Y_TILED)
13058                         return true;
13059                 /* fall through */
13060         default:
13061                 return false;
13062         }
13063 }
13064
13065 static bool intel_primary_plane_format_mod_supported(struct drm_plane *plane,
13066                                                      uint32_t format,
13067                                                      uint64_t modifier)
13068 {
13069         struct drm_i915_private *dev_priv = to_i915(plane->dev);
13070
13071         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13072                 return false;
13073
13074         if ((modifier >> 56) != DRM_FORMAT_MOD_VENDOR_INTEL &&
13075             modifier != DRM_FORMAT_MOD_LINEAR)
13076                 return false;
13077
13078         if (INTEL_GEN(dev_priv) >= 9)
13079                 return skl_mod_supported(format, modifier);
13080         else if (INTEL_GEN(dev_priv) >= 4)
13081                 return i965_mod_supported(format, modifier);
13082         else
13083                 return i8xx_mod_supported(format, modifier);
13084 }
13085
13086 static bool intel_cursor_plane_format_mod_supported(struct drm_plane *plane,
13087                                                     uint32_t format,
13088                                                     uint64_t modifier)
13089 {
13090         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
13091                 return false;
13092
13093         return modifier == DRM_FORMAT_MOD_LINEAR && format == DRM_FORMAT_ARGB8888;
13094 }
13095
13096 static struct drm_plane_funcs intel_plane_funcs = {
13097         .update_plane = drm_atomic_helper_update_plane,
13098         .disable_plane = drm_atomic_helper_disable_plane,
13099         .destroy = intel_plane_destroy,
13100         .atomic_get_property = intel_plane_atomic_get_property,
13101         .atomic_set_property = intel_plane_atomic_set_property,
13102         .atomic_duplicate_state = intel_plane_duplicate_state,
13103         .atomic_destroy_state = intel_plane_destroy_state,
13104         .format_mod_supported = intel_primary_plane_format_mod_supported,
13105 };
13106
13107 static int
13108 intel_legacy_cursor_update(struct drm_plane *plane,
13109                            struct drm_crtc *crtc,
13110                            struct drm_framebuffer *fb,
13111                            int crtc_x, int crtc_y,
13112                            unsigned int crtc_w, unsigned int crtc_h,
13113                            uint32_t src_x, uint32_t src_y,
13114                            uint32_t src_w, uint32_t src_h,
13115                            struct drm_modeset_acquire_ctx *ctx)
13116 {
13117         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
13118         int ret;
13119         struct drm_plane_state *old_plane_state, *new_plane_state;
13120         struct intel_plane *intel_plane = to_intel_plane(plane);
13121         struct drm_framebuffer *old_fb;
13122         struct drm_crtc_state *crtc_state = crtc->state;
13123
13124         /*
13125          * When crtc is inactive or there is a modeset pending,
13126          * wait for it to complete in the slowpath
13127          */
13128         if (!crtc_state->active || needs_modeset(crtc_state) ||
13129             to_intel_crtc_state(crtc_state)->update_pipe)
13130                 goto slow;
13131
13132         old_plane_state = plane->state;
13133         /*
13134          * Don't do an async update if there is an outstanding commit modifying
13135          * the plane.  This prevents our async update's changes from getting
13136          * overridden by a previous synchronous update's state.
13137          */
13138         if (old_plane_state->commit &&
13139             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13140                 goto slow;
13141
13142         /*
13143          * If any parameters change that may affect watermarks,
13144          * take the slowpath. Only changing fb or position should be
13145          * in the fastpath.
13146          */
13147         if (old_plane_state->crtc != crtc ||
13148             old_plane_state->src_w != src_w ||
13149             old_plane_state->src_h != src_h ||
13150             old_plane_state->crtc_w != crtc_w ||
13151             old_plane_state->crtc_h != crtc_h ||
13152             !old_plane_state->fb != !fb)
13153                 goto slow;
13154
13155         new_plane_state = intel_plane_duplicate_state(plane);
13156         if (!new_plane_state)
13157                 return -ENOMEM;
13158
13159         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13160
13161         new_plane_state->src_x = src_x;
13162         new_plane_state->src_y = src_y;
13163         new_plane_state->src_w = src_w;
13164         new_plane_state->src_h = src_h;
13165         new_plane_state->crtc_x = crtc_x;
13166         new_plane_state->crtc_y = crtc_y;
13167         new_plane_state->crtc_w = crtc_w;
13168         new_plane_state->crtc_h = crtc_h;
13169
13170         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13171                                                   to_intel_crtc_state(crtc->state), /* FIXME need a new crtc state? */
13172                                                   to_intel_plane_state(plane->state),
13173                                                   to_intel_plane_state(new_plane_state));
13174         if (ret)
13175                 goto out_free;
13176
13177         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13178         if (ret)
13179                 goto out_free;
13180
13181         ret = intel_plane_pin_fb(to_intel_plane_state(new_plane_state));
13182         if (ret)
13183                 goto out_unlock;
13184
13185         old_fb = old_plane_state->fb;
13186
13187         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13188                           intel_plane->frontbuffer_bit);
13189
13190         /* Swap plane state */
13191         plane->state = new_plane_state;
13192
13193         if (plane->state->visible) {
13194                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13195                 intel_plane->update_plane(intel_plane,
13196                                           to_intel_crtc_state(crtc->state),
13197                                           to_intel_plane_state(plane->state));
13198         } else {
13199                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13200                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13201         }
13202
13203         intel_plane_unpin_fb(to_intel_plane_state(old_plane_state));
13204
13205 out_unlock:
13206         mutex_unlock(&dev_priv->drm.struct_mutex);
13207 out_free:
13208         if (ret)
13209                 intel_plane_destroy_state(plane, new_plane_state);
13210         else
13211                 intel_plane_destroy_state(plane, old_plane_state);
13212         return ret;
13213
13214 slow:
13215         return drm_atomic_helper_update_plane(plane, crtc, fb,
13216                                               crtc_x, crtc_y, crtc_w, crtc_h,
13217                                               src_x, src_y, src_w, src_h, ctx);
13218 }
13219
13220 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13221         .update_plane = intel_legacy_cursor_update,
13222         .disable_plane = drm_atomic_helper_disable_plane,
13223         .destroy = intel_plane_destroy,
13224         .atomic_get_property = intel_plane_atomic_get_property,
13225         .atomic_set_property = intel_plane_atomic_set_property,
13226         .atomic_duplicate_state = intel_plane_duplicate_state,
13227         .atomic_destroy_state = intel_plane_destroy_state,
13228         .format_mod_supported = intel_cursor_plane_format_mod_supported,
13229 };
13230
13231 static bool i9xx_plane_has_fbc(struct drm_i915_private *dev_priv,
13232                                enum i9xx_plane_id i9xx_plane)
13233 {
13234         if (!HAS_FBC(dev_priv))
13235                 return false;
13236
13237         if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
13238                 return i9xx_plane == PLANE_A; /* tied to pipe A */
13239         else if (IS_IVYBRIDGE(dev_priv))
13240                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B ||
13241                         i9xx_plane == PLANE_C;
13242         else if (INTEL_GEN(dev_priv) >= 4)
13243                 return i9xx_plane == PLANE_A || i9xx_plane == PLANE_B;
13244         else
13245                 return i9xx_plane == PLANE_A;
13246 }
13247
13248 static bool skl_plane_has_fbc(struct drm_i915_private *dev_priv,
13249                               enum pipe pipe, enum plane_id plane_id)
13250 {
13251         if (!HAS_FBC(dev_priv))
13252                 return false;
13253
13254         return pipe == PIPE_A && plane_id == PLANE_PRIMARY;
13255 }
13256
13257 static struct intel_plane *
13258 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13259 {
13260         struct intel_plane *primary = NULL;
13261         struct intel_plane_state *state = NULL;
13262         const uint32_t *intel_primary_formats;
13263         unsigned int supported_rotations;
13264         unsigned int num_formats;
13265         const uint64_t *modifiers;
13266         int ret;
13267
13268         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13269         if (!primary) {
13270                 ret = -ENOMEM;
13271                 goto fail;
13272         }
13273
13274         state = intel_create_plane_state(&primary->base);
13275         if (!state) {
13276                 ret = -ENOMEM;
13277                 goto fail;
13278         }
13279
13280         primary->base.state = &state->base;
13281
13282         primary->can_scale = false;
13283         primary->max_downscale = 1;
13284         if (INTEL_GEN(dev_priv) >= 9) {
13285                 primary->can_scale = true;
13286                 state->scaler_id = -1;
13287         }
13288         primary->pipe = pipe;
13289         /*
13290          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13291          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13292          */
13293         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13294                 primary->i9xx_plane = (enum i9xx_plane_id) !pipe;
13295         else
13296                 primary->i9xx_plane = (enum i9xx_plane_id) pipe;
13297         primary->id = PLANE_PRIMARY;
13298         primary->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, primary->id);
13299
13300         if (INTEL_GEN(dev_priv) >= 9)
13301                 primary->has_fbc = skl_plane_has_fbc(dev_priv,
13302                                                      primary->pipe,
13303                                                      primary->id);
13304         else
13305                 primary->has_fbc = i9xx_plane_has_fbc(dev_priv,
13306                                                       primary->i9xx_plane);
13307
13308         if (primary->has_fbc) {
13309                 struct intel_fbc *fbc = &dev_priv->fbc;
13310
13311                 fbc->possible_framebuffer_bits |= primary->frontbuffer_bit;
13312         }
13313
13314         primary->check_plane = intel_check_primary_plane;
13315
13316         if (INTEL_GEN(dev_priv) >= 9) {
13317                 intel_primary_formats = skl_primary_formats;
13318                 num_formats = ARRAY_SIZE(skl_primary_formats);
13319
13320                 if (skl_plane_has_ccs(dev_priv, pipe, PLANE_PRIMARY))
13321                         modifiers = skl_format_modifiers_ccs;
13322                 else
13323                         modifiers = skl_format_modifiers_noccs;
13324
13325                 primary->update_plane = skl_update_plane;
13326                 primary->disable_plane = skl_disable_plane;
13327                 primary->get_hw_state = skl_plane_get_hw_state;
13328         } else if (INTEL_GEN(dev_priv) >= 4) {
13329                 intel_primary_formats = i965_primary_formats;
13330                 num_formats = ARRAY_SIZE(i965_primary_formats);
13331                 modifiers = i9xx_format_modifiers;
13332
13333                 primary->update_plane = i9xx_update_plane;
13334                 primary->disable_plane = i9xx_disable_plane;
13335                 primary->get_hw_state = i9xx_plane_get_hw_state;
13336         } else {
13337                 intel_primary_formats = i8xx_primary_formats;
13338                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13339                 modifiers = i9xx_format_modifiers;
13340
13341                 primary->update_plane = i9xx_update_plane;
13342                 primary->disable_plane = i9xx_disable_plane;
13343                 primary->get_hw_state = i9xx_plane_get_hw_state;
13344         }
13345
13346         if (INTEL_GEN(dev_priv) >= 9)
13347                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13348                                                0, &intel_plane_funcs,
13349                                                intel_primary_formats, num_formats,
13350                                                modifiers,
13351                                                DRM_PLANE_TYPE_PRIMARY,
13352                                                "plane 1%c", pipe_name(pipe));
13353         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13354                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13355                                                0, &intel_plane_funcs,
13356                                                intel_primary_formats, num_formats,
13357                                                modifiers,
13358                                                DRM_PLANE_TYPE_PRIMARY,
13359                                                "primary %c", pipe_name(pipe));
13360         else
13361                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13362                                                0, &intel_plane_funcs,
13363                                                intel_primary_formats, num_formats,
13364                                                modifiers,
13365                                                DRM_PLANE_TYPE_PRIMARY,
13366                                                "plane %c",
13367                                                plane_name(primary->i9xx_plane));
13368         if (ret)
13369                 goto fail;
13370
13371         if (INTEL_GEN(dev_priv) >= 10) {
13372                 supported_rotations =
13373                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13374                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270 |
13375                         DRM_MODE_REFLECT_X;
13376         } else if (INTEL_GEN(dev_priv) >= 9) {
13377                 supported_rotations =
13378                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13379                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13380         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13381                 supported_rotations =
13382                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13383                         DRM_MODE_REFLECT_X;
13384         } else if (INTEL_GEN(dev_priv) >= 4) {
13385                 supported_rotations =
13386                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13387         } else {
13388                 supported_rotations = DRM_MODE_ROTATE_0;
13389         }
13390
13391         if (INTEL_GEN(dev_priv) >= 4)
13392                 drm_plane_create_rotation_property(&primary->base,
13393                                                    DRM_MODE_ROTATE_0,
13394                                                    supported_rotations);
13395
13396         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13397
13398         return primary;
13399
13400 fail:
13401         kfree(state);
13402         kfree(primary);
13403
13404         return ERR_PTR(ret);
13405 }
13406
13407 static struct intel_plane *
13408 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13409                           enum pipe pipe)
13410 {
13411         struct intel_plane *cursor = NULL;
13412         struct intel_plane_state *state = NULL;
13413         int ret;
13414
13415         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13416         if (!cursor) {
13417                 ret = -ENOMEM;
13418                 goto fail;
13419         }
13420
13421         state = intel_create_plane_state(&cursor->base);
13422         if (!state) {
13423                 ret = -ENOMEM;
13424                 goto fail;
13425         }
13426
13427         cursor->base.state = &state->base;
13428
13429         cursor->can_scale = false;
13430         cursor->max_downscale = 1;
13431         cursor->pipe = pipe;
13432         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13433         cursor->id = PLANE_CURSOR;
13434         cursor->frontbuffer_bit = INTEL_FRONTBUFFER(pipe, cursor->id);
13435
13436         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13437                 cursor->update_plane = i845_update_cursor;
13438                 cursor->disable_plane = i845_disable_cursor;
13439                 cursor->get_hw_state = i845_cursor_get_hw_state;
13440                 cursor->check_plane = i845_check_cursor;
13441         } else {
13442                 cursor->update_plane = i9xx_update_cursor;
13443                 cursor->disable_plane = i9xx_disable_cursor;
13444                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13445                 cursor->check_plane = i9xx_check_cursor;
13446         }
13447
13448         cursor->cursor.base = ~0;
13449         cursor->cursor.cntl = ~0;
13450
13451         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13452                 cursor->cursor.size = ~0;
13453
13454         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13455                                        0, &intel_cursor_plane_funcs,
13456                                        intel_cursor_formats,
13457                                        ARRAY_SIZE(intel_cursor_formats),
13458                                        cursor_format_modifiers,
13459                                        DRM_PLANE_TYPE_CURSOR,
13460                                        "cursor %c", pipe_name(pipe));
13461         if (ret)
13462                 goto fail;
13463
13464         if (INTEL_GEN(dev_priv) >= 4)
13465                 drm_plane_create_rotation_property(&cursor->base,
13466                                                    DRM_MODE_ROTATE_0,
13467                                                    DRM_MODE_ROTATE_0 |
13468                                                    DRM_MODE_ROTATE_180);
13469
13470         if (INTEL_GEN(dev_priv) >= 9)
13471                 state->scaler_id = -1;
13472
13473         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13474
13475         return cursor;
13476
13477 fail:
13478         kfree(state);
13479         kfree(cursor);
13480
13481         return ERR_PTR(ret);
13482 }
13483
13484 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13485                                     struct intel_crtc_state *crtc_state)
13486 {
13487         struct intel_crtc_scaler_state *scaler_state =
13488                 &crtc_state->scaler_state;
13489         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13490         int i;
13491
13492         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13493         if (!crtc->num_scalers)
13494                 return;
13495
13496         for (i = 0; i < crtc->num_scalers; i++) {
13497                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13498
13499                 scaler->in_use = 0;
13500                 scaler->mode = PS_SCALER_MODE_DYN;
13501         }
13502
13503         scaler_state->scaler_id = -1;
13504 }
13505
13506 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13507 {
13508         struct intel_crtc *intel_crtc;
13509         struct intel_crtc_state *crtc_state = NULL;
13510         struct intel_plane *primary = NULL;
13511         struct intel_plane *cursor = NULL;
13512         int sprite, ret;
13513
13514         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13515         if (!intel_crtc)
13516                 return -ENOMEM;
13517
13518         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13519         if (!crtc_state) {
13520                 ret = -ENOMEM;
13521                 goto fail;
13522         }
13523         intel_crtc->config = crtc_state;
13524         intel_crtc->base.state = &crtc_state->base;
13525         crtc_state->base.crtc = &intel_crtc->base;
13526
13527         primary = intel_primary_plane_create(dev_priv, pipe);
13528         if (IS_ERR(primary)) {
13529                 ret = PTR_ERR(primary);
13530                 goto fail;
13531         }
13532         intel_crtc->plane_ids_mask |= BIT(primary->id);
13533
13534         for_each_sprite(dev_priv, pipe, sprite) {
13535                 struct intel_plane *plane;
13536
13537                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13538                 if (IS_ERR(plane)) {
13539                         ret = PTR_ERR(plane);
13540                         goto fail;
13541                 }
13542                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13543         }
13544
13545         cursor = intel_cursor_plane_create(dev_priv, pipe);
13546         if (IS_ERR(cursor)) {
13547                 ret = PTR_ERR(cursor);
13548                 goto fail;
13549         }
13550         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13551
13552         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13553                                         &primary->base, &cursor->base,
13554                                         &intel_crtc_funcs,
13555                                         "pipe %c", pipe_name(pipe));
13556         if (ret)
13557                 goto fail;
13558
13559         intel_crtc->pipe = pipe;
13560
13561         /* initialize shared scalers */
13562         intel_crtc_init_scalers(intel_crtc, crtc_state);
13563
13564         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13565                dev_priv->plane_to_crtc_mapping[primary->i9xx_plane] != NULL);
13566         dev_priv->plane_to_crtc_mapping[primary->i9xx_plane] = intel_crtc;
13567         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = intel_crtc;
13568
13569         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13570
13571         intel_color_init(&intel_crtc->base);
13572
13573         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13574
13575         return 0;
13576
13577 fail:
13578         /*
13579          * drm_mode_config_cleanup() will free up any
13580          * crtcs/planes already initialized.
13581          */
13582         kfree(crtc_state);
13583         kfree(intel_crtc);
13584
13585         return ret;
13586 }
13587
13588 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13589 {
13590         struct drm_device *dev = connector->base.dev;
13591
13592         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13593
13594         if (!connector->base.state->crtc)
13595                 return INVALID_PIPE;
13596
13597         return to_intel_crtc(connector->base.state->crtc)->pipe;
13598 }
13599
13600 int intel_get_pipe_from_crtc_id_ioctl(struct drm_device *dev, void *data,
13601                                       struct drm_file *file)
13602 {
13603         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13604         struct drm_crtc *drmmode_crtc;
13605         struct intel_crtc *crtc;
13606
13607         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
13608         if (!drmmode_crtc)
13609                 return -ENOENT;
13610
13611         crtc = to_intel_crtc(drmmode_crtc);
13612         pipe_from_crtc_id->pipe = crtc->pipe;
13613
13614         return 0;
13615 }
13616
13617 static int intel_encoder_clones(struct intel_encoder *encoder)
13618 {
13619         struct drm_device *dev = encoder->base.dev;
13620         struct intel_encoder *source_encoder;
13621         int index_mask = 0;
13622         int entry = 0;
13623
13624         for_each_intel_encoder(dev, source_encoder) {
13625                 if (encoders_cloneable(encoder, source_encoder))
13626                         index_mask |= (1 << entry);
13627
13628                 entry++;
13629         }
13630
13631         return index_mask;
13632 }
13633
13634 static bool has_edp_a(struct drm_i915_private *dev_priv)
13635 {
13636         if (!IS_MOBILE(dev_priv))
13637                 return false;
13638
13639         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13640                 return false;
13641
13642         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13643                 return false;
13644
13645         return true;
13646 }
13647
13648 static bool intel_crt_present(struct drm_i915_private *dev_priv)
13649 {
13650         if (INTEL_GEN(dev_priv) >= 9)
13651                 return false;
13652
13653         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
13654                 return false;
13655
13656         if (IS_CHERRYVIEW(dev_priv))
13657                 return false;
13658
13659         if (HAS_PCH_LPT_H(dev_priv) &&
13660             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
13661                 return false;
13662
13663         /* DDI E can't be used if DDI A requires 4 lanes */
13664         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
13665                 return false;
13666
13667         if (!dev_priv->vbt.int_crt_support)
13668                 return false;
13669
13670         return true;
13671 }
13672
13673 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
13674 {
13675         int pps_num;
13676         int pps_idx;
13677
13678         if (HAS_DDI(dev_priv))
13679                 return;
13680         /*
13681          * This w/a is needed at least on CPT/PPT, but to be sure apply it
13682          * everywhere where registers can be write protected.
13683          */
13684         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13685                 pps_num = 2;
13686         else
13687                 pps_num = 1;
13688
13689         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
13690                 u32 val = I915_READ(PP_CONTROL(pps_idx));
13691
13692                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
13693                 I915_WRITE(PP_CONTROL(pps_idx), val);
13694         }
13695 }
13696
13697 static void intel_pps_init(struct drm_i915_private *dev_priv)
13698 {
13699         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
13700                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
13701         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13702                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
13703         else
13704                 dev_priv->pps_mmio_base = PPS_BASE;
13705
13706         intel_pps_unlock_regs_wa(dev_priv);
13707 }
13708
13709 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
13710 {
13711         struct intel_encoder *encoder;
13712         bool dpd_is_edp = false;
13713
13714         intel_pps_init(dev_priv);
13715
13716         /*
13717          * intel_edp_init_connector() depends on this completing first, to
13718          * prevent the registeration of both eDP and LVDS and the incorrect
13719          * sharing of the PPS.
13720          */
13721         intel_lvds_init(dev_priv);
13722
13723         if (intel_crt_present(dev_priv))
13724                 intel_crt_init(dev_priv);
13725
13726         if (IS_GEN9_LP(dev_priv)) {
13727                 /*
13728                  * FIXME: Broxton doesn't support port detection via the
13729                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13730                  * detect the ports.
13731                  */
13732                 intel_ddi_init(dev_priv, PORT_A);
13733                 intel_ddi_init(dev_priv, PORT_B);
13734                 intel_ddi_init(dev_priv, PORT_C);
13735
13736                 intel_dsi_init(dev_priv);
13737         } else if (HAS_DDI(dev_priv)) {
13738                 int found;
13739
13740                 /*
13741                  * Haswell uses DDI functions to detect digital outputs.
13742                  * On SKL pre-D0 the strap isn't connected, so we assume
13743                  * it's there.
13744                  */
13745                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
13746                 /* WaIgnoreDDIAStrap: skl */
13747                 if (found || IS_GEN9_BC(dev_priv))
13748                         intel_ddi_init(dev_priv, PORT_A);
13749
13750                 /* DDI B, C, D, and F detection is indicated by the SFUSE_STRAP
13751                  * register */
13752                 found = I915_READ(SFUSE_STRAP);
13753
13754                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13755                         intel_ddi_init(dev_priv, PORT_B);
13756                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13757                         intel_ddi_init(dev_priv, PORT_C);
13758                 if (found & SFUSE_STRAP_DDID_DETECTED)
13759                         intel_ddi_init(dev_priv, PORT_D);
13760                 if (found & SFUSE_STRAP_DDIF_DETECTED)
13761                         intel_ddi_init(dev_priv, PORT_F);
13762                 /*
13763                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
13764                  */
13765                 if (IS_GEN9_BC(dev_priv) &&
13766                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
13767                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
13768                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
13769                         intel_ddi_init(dev_priv, PORT_E);
13770
13771         } else if (HAS_PCH_SPLIT(dev_priv)) {
13772                 int found;
13773                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
13774
13775                 if (has_edp_a(dev_priv))
13776                         intel_dp_init(dev_priv, DP_A, PORT_A);
13777
13778                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13779                         /* PCH SDVOB multiplex with HDMIB */
13780                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
13781                         if (!found)
13782                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
13783                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13784                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
13785                 }
13786
13787                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13788                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
13789
13790                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13791                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
13792
13793                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13794                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
13795
13796                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13797                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
13798         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
13799                 bool has_edp, has_port;
13800
13801                 /*
13802                  * The DP_DETECTED bit is the latched state of the DDC
13803                  * SDA pin at boot. However since eDP doesn't require DDC
13804                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13805                  * eDP ports may have been muxed to an alternate function.
13806                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13807                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13808                  * detect eDP ports.
13809                  *
13810                  * Sadly the straps seem to be missing sometimes even for HDMI
13811                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
13812                  * and VBT for the presence of the port. Additionally we can't
13813                  * trust the port type the VBT declares as we've seen at least
13814                  * HDMI ports that the VBT claim are DP or eDP.
13815                  */
13816                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
13817                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
13818                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
13819                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
13820                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
13821                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
13822
13823                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
13824                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
13825                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
13826                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
13827                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
13828                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
13829
13830                 if (IS_CHERRYVIEW(dev_priv)) {
13831                         /*
13832                          * eDP not supported on port D,
13833                          * so no need to worry about it
13834                          */
13835                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
13836                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
13837                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
13838                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
13839                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
13840                 }
13841
13842                 intel_dsi_init(dev_priv);
13843         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
13844                 bool found = false;
13845
13846                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13847                         DRM_DEBUG_KMS("probing SDVOB\n");
13848                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
13849                         if (!found && IS_G4X(dev_priv)) {
13850                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
13851                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
13852                         }
13853
13854                         if (!found && IS_G4X(dev_priv))
13855                                 intel_dp_init(dev_priv, DP_B, PORT_B);
13856                 }
13857
13858                 /* Before G4X SDVOC doesn't have its own detect register */
13859
13860                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13861                         DRM_DEBUG_KMS("probing SDVOC\n");
13862                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
13863                 }
13864
13865                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
13866
13867                         if (IS_G4X(dev_priv)) {
13868                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
13869                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
13870                         }
13871                         if (IS_G4X(dev_priv))
13872                                 intel_dp_init(dev_priv, DP_C, PORT_C);
13873                 }
13874
13875                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
13876                         intel_dp_init(dev_priv, DP_D, PORT_D);
13877         } else if (IS_GEN2(dev_priv))
13878                 intel_dvo_init(dev_priv);
13879
13880         if (SUPPORTS_TV(dev_priv))
13881                 intel_tv_init(dev_priv);
13882
13883         intel_psr_init(dev_priv);
13884
13885         for_each_intel_encoder(&dev_priv->drm, encoder) {
13886                 encoder->base.possible_crtcs = encoder->crtc_mask;
13887                 encoder->base.possible_clones =
13888                         intel_encoder_clones(encoder);
13889         }
13890
13891         intel_init_pch_refclk(dev_priv);
13892
13893         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
13894 }
13895
13896 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
13897 {
13898         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13899
13900         drm_framebuffer_cleanup(fb);
13901
13902         i915_gem_object_lock(intel_fb->obj);
13903         WARN_ON(!intel_fb->obj->framebuffer_references--);
13904         i915_gem_object_unlock(intel_fb->obj);
13905
13906         i915_gem_object_put(intel_fb->obj);
13907
13908         kfree(intel_fb);
13909 }
13910
13911 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
13912                                                 struct drm_file *file,
13913                                                 unsigned int *handle)
13914 {
13915         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13916         struct drm_i915_gem_object *obj = intel_fb->obj;
13917
13918         if (obj->userptr.mm) {
13919                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
13920                 return -EINVAL;
13921         }
13922
13923         return drm_gem_handle_create(file, &obj->base, handle);
13924 }
13925
13926 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
13927                                         struct drm_file *file,
13928                                         unsigned flags, unsigned color,
13929                                         struct drm_clip_rect *clips,
13930                                         unsigned num_clips)
13931 {
13932         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13933
13934         i915_gem_object_flush_if_display(obj);
13935         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13936
13937         return 0;
13938 }
13939
13940 static const struct drm_framebuffer_funcs intel_fb_funcs = {
13941         .destroy = intel_user_framebuffer_destroy,
13942         .create_handle = intel_user_framebuffer_create_handle,
13943         .dirty = intel_user_framebuffer_dirty,
13944 };
13945
13946 static
13947 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
13948                          uint64_t fb_modifier, uint32_t pixel_format)
13949 {
13950         u32 gen = INTEL_GEN(dev_priv);
13951
13952         if (gen >= 9) {
13953                 int cpp = drm_format_plane_cpp(pixel_format, 0);
13954
13955                 /* "The stride in bytes must not exceed the of the size of 8K
13956                  *  pixels and 32K bytes."
13957                  */
13958                 return min(8192 * cpp, 32768);
13959         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
13960                 return 32*1024;
13961         } else if (gen >= 4) {
13962                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13963                         return 16*1024;
13964                 else
13965                         return 32*1024;
13966         } else if (gen >= 3) {
13967                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13968                         return 8*1024;
13969                 else
13970                         return 16*1024;
13971         } else {
13972                 /* XXX DSPC is limited to 4k tiled */
13973                 return 8*1024;
13974         }
13975 }
13976
13977 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
13978                                   struct drm_i915_gem_object *obj,
13979                                   struct drm_mode_fb_cmd2 *mode_cmd)
13980 {
13981         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
13982         struct drm_framebuffer *fb = &intel_fb->base;
13983         struct drm_format_name_buf format_name;
13984         u32 pitch_limit;
13985         unsigned int tiling, stride;
13986         int ret = -EINVAL;
13987         int i;
13988
13989         i915_gem_object_lock(obj);
13990         obj->framebuffer_references++;
13991         tiling = i915_gem_object_get_tiling(obj);
13992         stride = i915_gem_object_get_stride(obj);
13993         i915_gem_object_unlock(obj);
13994
13995         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
13996                 /*
13997                  * If there's a fence, enforce that
13998                  * the fb modifier and tiling mode match.
13999                  */
14000                 if (tiling != I915_TILING_NONE &&
14001                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14002                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
14003                         goto err;
14004                 }
14005         } else {
14006                 if (tiling == I915_TILING_X) {
14007                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
14008                 } else if (tiling == I915_TILING_Y) {
14009                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
14010                         goto err;
14011                 }
14012         }
14013
14014         /* Passed in modifier sanity checking. */
14015         switch (mode_cmd->modifier[0]) {
14016         case I915_FORMAT_MOD_Y_TILED_CCS:
14017         case I915_FORMAT_MOD_Yf_TILED_CCS:
14018                 switch (mode_cmd->pixel_format) {
14019                 case DRM_FORMAT_XBGR8888:
14020                 case DRM_FORMAT_ABGR8888:
14021                 case DRM_FORMAT_XRGB8888:
14022                 case DRM_FORMAT_ARGB8888:
14023                         break;
14024                 default:
14025                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
14026                         goto err;
14027                 }
14028                 /* fall through */
14029         case I915_FORMAT_MOD_Y_TILED:
14030         case I915_FORMAT_MOD_Yf_TILED:
14031                 if (INTEL_GEN(dev_priv) < 9) {
14032                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
14033                                       mode_cmd->modifier[0]);
14034                         goto err;
14035                 }
14036         case DRM_FORMAT_MOD_LINEAR:
14037         case I915_FORMAT_MOD_X_TILED:
14038                 break;
14039         default:
14040                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
14041                               mode_cmd->modifier[0]);
14042                 goto err;
14043         }
14044
14045         /*
14046          * gen2/3 display engine uses the fence if present,
14047          * so the tiling mode must match the fb modifier exactly.
14048          */
14049         if (INTEL_GEN(dev_priv) < 4 &&
14050             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
14051                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
14052                 goto err;
14053         }
14054
14055         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
14056                                            mode_cmd->pixel_format);
14057         if (mode_cmd->pitches[0] > pitch_limit) {
14058                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
14059                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
14060                               "tiled" : "linear",
14061                               mode_cmd->pitches[0], pitch_limit);
14062                 goto err;
14063         }
14064
14065         /*
14066          * If there's a fence, enforce that
14067          * the fb pitch and fence stride match.
14068          */
14069         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
14070                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
14071                               mode_cmd->pitches[0], stride);
14072                 goto err;
14073         }
14074
14075         /* Reject formats not supported by any plane early. */
14076         switch (mode_cmd->pixel_format) {
14077         case DRM_FORMAT_C8:
14078         case DRM_FORMAT_RGB565:
14079         case DRM_FORMAT_XRGB8888:
14080         case DRM_FORMAT_ARGB8888:
14081                 break;
14082         case DRM_FORMAT_XRGB1555:
14083                 if (INTEL_GEN(dev_priv) > 3) {
14084                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14085                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14086                         goto err;
14087                 }
14088                 break;
14089         case DRM_FORMAT_ABGR8888:
14090                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
14091                     INTEL_GEN(dev_priv) < 9) {
14092                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14093                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14094                         goto err;
14095                 }
14096                 break;
14097         case DRM_FORMAT_XBGR8888:
14098         case DRM_FORMAT_XRGB2101010:
14099         case DRM_FORMAT_XBGR2101010:
14100                 if (INTEL_GEN(dev_priv) < 4) {
14101                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14102                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14103                         goto err;
14104                 }
14105                 break;
14106         case DRM_FORMAT_ABGR2101010:
14107                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
14108                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14109                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14110                         goto err;
14111                 }
14112                 break;
14113         case DRM_FORMAT_YUYV:
14114         case DRM_FORMAT_UYVY:
14115         case DRM_FORMAT_YVYU:
14116         case DRM_FORMAT_VYUY:
14117                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
14118                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14119                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
14120                         goto err;
14121                 }
14122                 break;
14123         default:
14124                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
14125                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
14126                 goto err;
14127         }
14128
14129         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
14130         if (mode_cmd->offsets[0] != 0)
14131                 goto err;
14132
14133         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
14134
14135         for (i = 0; i < fb->format->num_planes; i++) {
14136                 u32 stride_alignment;
14137
14138                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
14139                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
14140                         goto err;
14141                 }
14142
14143                 stride_alignment = intel_fb_stride_alignment(fb, i);
14144
14145                 /*
14146                  * Display WA #0531: skl,bxt,kbl,glk
14147                  *
14148                  * Render decompression and plane width > 3840
14149                  * combined with horizontal panning requires the
14150                  * plane stride to be a multiple of 4. We'll just
14151                  * require the entire fb to accommodate that to avoid
14152                  * potential runtime errors at plane configuration time.
14153                  */
14154                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14155                     (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
14156                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS))
14157                         stride_alignment *= 4;
14158
14159                 if (fb->pitches[i] & (stride_alignment - 1)) {
14160                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14161                                       i, fb->pitches[i], stride_alignment);
14162                         goto err;
14163                 }
14164         }
14165
14166         intel_fb->obj = obj;
14167
14168         ret = intel_fill_fb_info(dev_priv, fb);
14169         if (ret)
14170                 goto err;
14171
14172         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14173         if (ret) {
14174                 DRM_ERROR("framebuffer init failed %d\n", ret);
14175                 goto err;
14176         }
14177
14178         return 0;
14179
14180 err:
14181         i915_gem_object_lock(obj);
14182         obj->framebuffer_references--;
14183         i915_gem_object_unlock(obj);
14184         return ret;
14185 }
14186
14187 static struct drm_framebuffer *
14188 intel_user_framebuffer_create(struct drm_device *dev,
14189                               struct drm_file *filp,
14190                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14191 {
14192         struct drm_framebuffer *fb;
14193         struct drm_i915_gem_object *obj;
14194         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14195
14196         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14197         if (!obj)
14198                 return ERR_PTR(-ENOENT);
14199
14200         fb = intel_framebuffer_create(obj, &mode_cmd);
14201         if (IS_ERR(fb))
14202                 i915_gem_object_put(obj);
14203
14204         return fb;
14205 }
14206
14207 static void intel_atomic_state_free(struct drm_atomic_state *state)
14208 {
14209         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14210
14211         drm_atomic_state_default_release(state);
14212
14213         i915_sw_fence_fini(&intel_state->commit_ready);
14214
14215         kfree(state);
14216 }
14217
14218 static enum drm_mode_status
14219 intel_mode_valid(struct drm_device *dev,
14220                  const struct drm_display_mode *mode)
14221 {
14222         if (mode->vscan > 1)
14223                 return MODE_NO_VSCAN;
14224
14225         if (mode->flags & DRM_MODE_FLAG_DBLSCAN)
14226                 return MODE_NO_DBLESCAN;
14227
14228         if (mode->flags & DRM_MODE_FLAG_HSKEW)
14229                 return MODE_H_ILLEGAL;
14230
14231         if (mode->flags & (DRM_MODE_FLAG_CSYNC |
14232                            DRM_MODE_FLAG_NCSYNC |
14233                            DRM_MODE_FLAG_PCSYNC))
14234                 return MODE_HSYNC;
14235
14236         if (mode->flags & (DRM_MODE_FLAG_BCAST |
14237                            DRM_MODE_FLAG_PIXMUX |
14238                            DRM_MODE_FLAG_CLKDIV2))
14239                 return MODE_BAD;
14240
14241         return MODE_OK;
14242 }
14243
14244 static const struct drm_mode_config_funcs intel_mode_funcs = {
14245         .fb_create = intel_user_framebuffer_create,
14246         .get_format_info = intel_get_format_info,
14247         .output_poll_changed = intel_fbdev_output_poll_changed,
14248         .mode_valid = intel_mode_valid,
14249         .atomic_check = intel_atomic_check,
14250         .atomic_commit = intel_atomic_commit,
14251         .atomic_state_alloc = intel_atomic_state_alloc,
14252         .atomic_state_clear = intel_atomic_state_clear,
14253         .atomic_state_free = intel_atomic_state_free,
14254 };
14255
14256 /**
14257  * intel_init_display_hooks - initialize the display modesetting hooks
14258  * @dev_priv: device private
14259  */
14260 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14261 {
14262         intel_init_cdclk_hooks(dev_priv);
14263
14264         if (INTEL_GEN(dev_priv) >= 9) {
14265                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14266                 dev_priv->display.get_initial_plane_config =
14267                         skylake_get_initial_plane_config;
14268                 dev_priv->display.crtc_compute_clock =
14269                         haswell_crtc_compute_clock;
14270                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14271                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14272         } else if (HAS_DDI(dev_priv)) {
14273                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14274                 dev_priv->display.get_initial_plane_config =
14275                         i9xx_get_initial_plane_config;
14276                 dev_priv->display.crtc_compute_clock =
14277                         haswell_crtc_compute_clock;
14278                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14279                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14280         } else if (HAS_PCH_SPLIT(dev_priv)) {
14281                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14282                 dev_priv->display.get_initial_plane_config =
14283                         i9xx_get_initial_plane_config;
14284                 dev_priv->display.crtc_compute_clock =
14285                         ironlake_crtc_compute_clock;
14286                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14287                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14288         } else if (IS_CHERRYVIEW(dev_priv)) {
14289                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14290                 dev_priv->display.get_initial_plane_config =
14291                         i9xx_get_initial_plane_config;
14292                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14293                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14294                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14295         } else if (IS_VALLEYVIEW(dev_priv)) {
14296                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14297                 dev_priv->display.get_initial_plane_config =
14298                         i9xx_get_initial_plane_config;
14299                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14300                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14301                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14302         } else if (IS_G4X(dev_priv)) {
14303                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14304                 dev_priv->display.get_initial_plane_config =
14305                         i9xx_get_initial_plane_config;
14306                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14307                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14308                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14309         } else if (IS_PINEVIEW(dev_priv)) {
14310                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14311                 dev_priv->display.get_initial_plane_config =
14312                         i9xx_get_initial_plane_config;
14313                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14314                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14315                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14316         } else if (!IS_GEN2(dev_priv)) {
14317                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14318                 dev_priv->display.get_initial_plane_config =
14319                         i9xx_get_initial_plane_config;
14320                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14321                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14322                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14323         } else {
14324                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14325                 dev_priv->display.get_initial_plane_config =
14326                         i9xx_get_initial_plane_config;
14327                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14328                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14329                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14330         }
14331
14332         if (IS_GEN5(dev_priv)) {
14333                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14334         } else if (IS_GEN6(dev_priv)) {
14335                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14336         } else if (IS_IVYBRIDGE(dev_priv)) {
14337                 /* FIXME: detect B0+ stepping and use auto training */
14338                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14339         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14340                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14341         }
14342
14343         if (INTEL_GEN(dev_priv) >= 9)
14344                 dev_priv->display.update_crtcs = skl_update_crtcs;
14345         else
14346                 dev_priv->display.update_crtcs = intel_update_crtcs;
14347 }
14348
14349 /*
14350  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14351  */
14352 static void quirk_ssc_force_disable(struct drm_device *dev)
14353 {
14354         struct drm_i915_private *dev_priv = to_i915(dev);
14355         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14356         DRM_INFO("applying lvds SSC disable quirk\n");
14357 }
14358
14359 /*
14360  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14361  * brightness value
14362  */
14363 static void quirk_invert_brightness(struct drm_device *dev)
14364 {
14365         struct drm_i915_private *dev_priv = to_i915(dev);
14366         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14367         DRM_INFO("applying inverted panel brightness quirk\n");
14368 }
14369
14370 /* Some VBT's incorrectly indicate no backlight is present */
14371 static void quirk_backlight_present(struct drm_device *dev)
14372 {
14373         struct drm_i915_private *dev_priv = to_i915(dev);
14374         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14375         DRM_INFO("applying backlight present quirk\n");
14376 }
14377
14378 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14379  * which is 300 ms greater than eDP spec T12 min.
14380  */
14381 static void quirk_increase_t12_delay(struct drm_device *dev)
14382 {
14383         struct drm_i915_private *dev_priv = to_i915(dev);
14384
14385         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14386         DRM_INFO("Applying T12 delay quirk\n");
14387 }
14388
14389 struct intel_quirk {
14390         int device;
14391         int subsystem_vendor;
14392         int subsystem_device;
14393         void (*hook)(struct drm_device *dev);
14394 };
14395
14396 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14397 struct intel_dmi_quirk {
14398         void (*hook)(struct drm_device *dev);
14399         const struct dmi_system_id (*dmi_id_list)[];
14400 };
14401
14402 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14403 {
14404         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14405         return 1;
14406 }
14407
14408 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14409         {
14410                 .dmi_id_list = &(const struct dmi_system_id[]) {
14411                         {
14412                                 .callback = intel_dmi_reverse_brightness,
14413                                 .ident = "NCR Corporation",
14414                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14415                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14416                                 },
14417                         },
14418                         { }  /* terminating entry */
14419                 },
14420                 .hook = quirk_invert_brightness,
14421         },
14422 };
14423
14424 static struct intel_quirk intel_quirks[] = {
14425         /* Lenovo U160 cannot use SSC on LVDS */
14426         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14427
14428         /* Sony Vaio Y cannot use SSC on LVDS */
14429         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14430
14431         /* Acer Aspire 5734Z must invert backlight brightness */
14432         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14433
14434         /* Acer/eMachines G725 */
14435         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14436
14437         /* Acer/eMachines e725 */
14438         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14439
14440         /* Acer/Packard Bell NCL20 */
14441         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14442
14443         /* Acer Aspire 4736Z */
14444         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14445
14446         /* Acer Aspire 5336 */
14447         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14448
14449         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14450         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14451
14452         /* Acer C720 Chromebook (Core i3 4005U) */
14453         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14454
14455         /* Apple Macbook 2,1 (Core 2 T7400) */
14456         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14457
14458         /* Apple Macbook 4,1 */
14459         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14460
14461         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14462         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14463
14464         /* HP Chromebook 14 (Celeron 2955U) */
14465         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14466
14467         /* Dell Chromebook 11 */
14468         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14469
14470         /* Dell Chromebook 11 (2015 version) */
14471         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14472
14473         /* Toshiba Satellite P50-C-18C */
14474         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14475 };
14476
14477 static void intel_init_quirks(struct drm_device *dev)
14478 {
14479         struct pci_dev *d = dev->pdev;
14480         int i;
14481
14482         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14483                 struct intel_quirk *q = &intel_quirks[i];
14484
14485                 if (d->device == q->device &&
14486                     (d->subsystem_vendor == q->subsystem_vendor ||
14487                      q->subsystem_vendor == PCI_ANY_ID) &&
14488                     (d->subsystem_device == q->subsystem_device ||
14489                      q->subsystem_device == PCI_ANY_ID))
14490                         q->hook(dev);
14491         }
14492         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14493                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14494                         intel_dmi_quirks[i].hook(dev);
14495         }
14496 }
14497
14498 /* Disable the VGA plane that we never use */
14499 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14500 {
14501         struct pci_dev *pdev = dev_priv->drm.pdev;
14502         u8 sr1;
14503         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14504
14505         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14506         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14507         outb(SR01, VGA_SR_INDEX);
14508         sr1 = inb(VGA_SR_DATA);
14509         outb(sr1 | 1<<5, VGA_SR_DATA);
14510         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14511         udelay(300);
14512
14513         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14514         POSTING_READ(vga_reg);
14515 }
14516
14517 void intel_modeset_init_hw(struct drm_device *dev)
14518 {
14519         struct drm_i915_private *dev_priv = to_i915(dev);
14520
14521         intel_update_cdclk(dev_priv);
14522         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
14523         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14524 }
14525
14526 /*
14527  * Calculate what we think the watermarks should be for the state we've read
14528  * out of the hardware and then immediately program those watermarks so that
14529  * we ensure the hardware settings match our internal state.
14530  *
14531  * We can calculate what we think WM's should be by creating a duplicate of the
14532  * current state (which was constructed during hardware readout) and running it
14533  * through the atomic check code to calculate new watermark values in the
14534  * state object.
14535  */
14536 static void sanitize_watermarks(struct drm_device *dev)
14537 {
14538         struct drm_i915_private *dev_priv = to_i915(dev);
14539         struct drm_atomic_state *state;
14540         struct intel_atomic_state *intel_state;
14541         struct drm_crtc *crtc;
14542         struct drm_crtc_state *cstate;
14543         struct drm_modeset_acquire_ctx ctx;
14544         int ret;
14545         int i;
14546
14547         /* Only supported on platforms that use atomic watermark design */
14548         if (!dev_priv->display.optimize_watermarks)
14549                 return;
14550
14551         /*
14552          * We need to hold connection_mutex before calling duplicate_state so
14553          * that the connector loop is protected.
14554          */
14555         drm_modeset_acquire_init(&ctx, 0);
14556 retry:
14557         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14558         if (ret == -EDEADLK) {
14559                 drm_modeset_backoff(&ctx);
14560                 goto retry;
14561         } else if (WARN_ON(ret)) {
14562                 goto fail;
14563         }
14564
14565         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14566         if (WARN_ON(IS_ERR(state)))
14567                 goto fail;
14568
14569         intel_state = to_intel_atomic_state(state);
14570
14571         /*
14572          * Hardware readout is the only time we don't want to calculate
14573          * intermediate watermarks (since we don't trust the current
14574          * watermarks).
14575          */
14576         if (!HAS_GMCH_DISPLAY(dev_priv))
14577                 intel_state->skip_intermediate_wm = true;
14578
14579         ret = intel_atomic_check(dev, state);
14580         if (ret) {
14581                 /*
14582                  * If we fail here, it means that the hardware appears to be
14583                  * programmed in a way that shouldn't be possible, given our
14584                  * understanding of watermark requirements.  This might mean a
14585                  * mistake in the hardware readout code or a mistake in the
14586                  * watermark calculations for a given platform.  Raise a WARN
14587                  * so that this is noticeable.
14588                  *
14589                  * If this actually happens, we'll have to just leave the
14590                  * BIOS-programmed watermarks untouched and hope for the best.
14591                  */
14592                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14593                 goto put_state;
14594         }
14595
14596         /* Write calculated watermark values back */
14597         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14598                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14599
14600                 cs->wm.need_postvbl_update = true;
14601                 dev_priv->display.optimize_watermarks(intel_state, cs);
14602
14603                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
14604         }
14605
14606 put_state:
14607         drm_atomic_state_put(state);
14608 fail:
14609         drm_modeset_drop_locks(&ctx);
14610         drm_modeset_acquire_fini(&ctx);
14611 }
14612
14613 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
14614 {
14615         if (IS_GEN5(dev_priv)) {
14616                 u32 fdi_pll_clk =
14617                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
14618
14619                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
14620         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
14621                 dev_priv->fdi_pll_freq = 270000;
14622         } else {
14623                 return;
14624         }
14625
14626         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
14627 }
14628
14629 int intel_modeset_init(struct drm_device *dev)
14630 {
14631         struct drm_i915_private *dev_priv = to_i915(dev);
14632         struct i915_ggtt *ggtt = &dev_priv->ggtt;
14633         enum pipe pipe;
14634         struct intel_crtc *crtc;
14635
14636         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
14637
14638         drm_mode_config_init(dev);
14639
14640         dev->mode_config.min_width = 0;
14641         dev->mode_config.min_height = 0;
14642
14643         dev->mode_config.preferred_depth = 24;
14644         dev->mode_config.prefer_shadow = 1;
14645
14646         dev->mode_config.allow_fb_modifiers = true;
14647
14648         dev->mode_config.funcs = &intel_mode_funcs;
14649
14650         init_llist_head(&dev_priv->atomic_helper.free_list);
14651         INIT_WORK(&dev_priv->atomic_helper.free_work,
14652                   intel_atomic_helper_free_state_worker);
14653
14654         intel_init_quirks(dev);
14655
14656         intel_init_pm(dev_priv);
14657
14658         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14659                 return 0;
14660
14661         /*
14662          * There may be no VBT; and if the BIOS enabled SSC we can
14663          * just keep using it to avoid unnecessary flicker.  Whereas if the
14664          * BIOS isn't using it, don't assume it will work even if the VBT
14665          * indicates as much.
14666          */
14667         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
14668                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14669                                             DREF_SSC1_ENABLE);
14670
14671                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
14672                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
14673                                      bios_lvds_use_ssc ? "en" : "dis",
14674                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
14675                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
14676                 }
14677         }
14678
14679         if (IS_GEN2(dev_priv)) {
14680                 dev->mode_config.max_width = 2048;
14681                 dev->mode_config.max_height = 2048;
14682         } else if (IS_GEN3(dev_priv)) {
14683                 dev->mode_config.max_width = 4096;
14684                 dev->mode_config.max_height = 4096;
14685         } else {
14686                 dev->mode_config.max_width = 8192;
14687                 dev->mode_config.max_height = 8192;
14688         }
14689
14690         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14691                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
14692                 dev->mode_config.cursor_height = 1023;
14693         } else if (IS_GEN2(dev_priv)) {
14694                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14695                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14696         } else {
14697                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14698                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14699         }
14700
14701         dev->mode_config.fb_base = ggtt->gmadr.start;
14702
14703         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14704                       INTEL_INFO(dev_priv)->num_pipes,
14705                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
14706
14707         for_each_pipe(dev_priv, pipe) {
14708                 int ret;
14709
14710                 ret = intel_crtc_init(dev_priv, pipe);
14711                 if (ret) {
14712                         drm_mode_config_cleanup(dev);
14713                         return ret;
14714                 }
14715         }
14716
14717         intel_shared_dpll_init(dev);
14718         intel_update_fdi_pll_freq(dev_priv);
14719
14720         intel_update_czclk(dev_priv);
14721         intel_modeset_init_hw(dev);
14722
14723         if (dev_priv->max_cdclk_freq == 0)
14724                 intel_update_max_cdclk(dev_priv);
14725
14726         /* Just disable it once at startup */
14727         i915_disable_vga(dev_priv);
14728         intel_setup_outputs(dev_priv);
14729
14730         drm_modeset_lock_all(dev);
14731         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
14732         drm_modeset_unlock_all(dev);
14733
14734         for_each_intel_crtc(dev, crtc) {
14735                 struct intel_initial_plane_config plane_config = {};
14736
14737                 if (!crtc->active)
14738                         continue;
14739
14740                 /*
14741                  * Note that reserving the BIOS fb up front prevents us
14742                  * from stuffing other stolen allocations like the ring
14743                  * on top.  This prevents some ugliness at boot time, and
14744                  * can even allow for smooth boot transitions if the BIOS
14745                  * fb is large enough for the active pipe configuration.
14746                  */
14747                 dev_priv->display.get_initial_plane_config(crtc,
14748                                                            &plane_config);
14749
14750                 /*
14751                  * If the fb is shared between multiple heads, we'll
14752                  * just get the first one.
14753                  */
14754                 intel_find_initial_plane_obj(crtc, &plane_config);
14755         }
14756
14757         /*
14758          * Make sure hardware watermarks really match the state we read out.
14759          * Note that we need to do this after reconstructing the BIOS fb's
14760          * since the watermark calculation done here will use pstate->fb.
14761          */
14762         if (!HAS_GMCH_DISPLAY(dev_priv))
14763                 sanitize_watermarks(dev);
14764
14765         return 0;
14766 }
14767
14768 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14769 {
14770         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14771         /* 640x480@60Hz, ~25175 kHz */
14772         struct dpll clock = {
14773                 .m1 = 18,
14774                 .m2 = 7,
14775                 .p1 = 13,
14776                 .p2 = 4,
14777                 .n = 2,
14778         };
14779         u32 dpll, fp;
14780         int i;
14781
14782         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
14783
14784         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
14785                       pipe_name(pipe), clock.vco, clock.dot);
14786
14787         fp = i9xx_dpll_compute_fp(&clock);
14788         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
14789                 DPLL_VGA_MODE_DIS |
14790                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
14791                 PLL_P2_DIVIDE_BY_4 |
14792                 PLL_REF_INPUT_DREFCLK |
14793                 DPLL_VCO_ENABLE;
14794
14795         I915_WRITE(FP0(pipe), fp);
14796         I915_WRITE(FP1(pipe), fp);
14797
14798         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
14799         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
14800         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
14801         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
14802         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
14803         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
14804         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
14805
14806         /*
14807          * Apparently we need to have VGA mode enabled prior to changing
14808          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
14809          * dividers, even though the register value does change.
14810          */
14811         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
14812         I915_WRITE(DPLL(pipe), dpll);
14813
14814         /* Wait for the clocks to stabilize. */
14815         POSTING_READ(DPLL(pipe));
14816         udelay(150);
14817
14818         /* The pixel multiplier can only be updated once the
14819          * DPLL is enabled and the clocks are stable.
14820          *
14821          * So write it again.
14822          */
14823         I915_WRITE(DPLL(pipe), dpll);
14824
14825         /* We do this three times for luck */
14826         for (i = 0; i < 3 ; i++) {
14827                 I915_WRITE(DPLL(pipe), dpll);
14828                 POSTING_READ(DPLL(pipe));
14829                 udelay(150); /* wait for warmup */
14830         }
14831
14832         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
14833         POSTING_READ(PIPECONF(pipe));
14834
14835         intel_wait_for_pipe_scanline_moving(crtc);
14836 }
14837
14838 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14839 {
14840         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14841
14842         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
14843                       pipe_name(pipe));
14844
14845         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
14846         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
14847         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
14848         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & CURSOR_MODE);
14849         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & CURSOR_MODE);
14850
14851         I915_WRITE(PIPECONF(pipe), 0);
14852         POSTING_READ(PIPECONF(pipe));
14853
14854         intel_wait_for_pipe_scanline_stopped(crtc);
14855
14856         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
14857         POSTING_READ(DPLL(pipe));
14858 }
14859
14860 static bool intel_plane_mapping_ok(struct intel_crtc *crtc,
14861                                    struct intel_plane *plane)
14862 {
14863         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14864         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
14865         u32 val = I915_READ(DSPCNTR(i9xx_plane));
14866
14867         return (val & DISPLAY_PLANE_ENABLE) == 0 ||
14868                 (val & DISPPLANE_SEL_PIPE_MASK) == DISPPLANE_SEL_PIPE(crtc->pipe);
14869 }
14870
14871 static void
14872 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
14873 {
14874         struct intel_crtc *crtc;
14875
14876         if (INTEL_GEN(dev_priv) >= 4)
14877                 return;
14878
14879         for_each_intel_crtc(&dev_priv->drm, crtc) {
14880                 struct intel_plane *plane =
14881                         to_intel_plane(crtc->base.primary);
14882
14883                 if (intel_plane_mapping_ok(crtc, plane))
14884                         continue;
14885
14886                 DRM_DEBUG_KMS("%s attached to the wrong pipe, disabling plane\n",
14887                               plane->base.name);
14888                 intel_plane_disable_noatomic(crtc, plane);
14889         }
14890 }
14891
14892 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
14893 {
14894         struct drm_device *dev = crtc->base.dev;
14895         struct intel_encoder *encoder;
14896
14897         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14898                 return true;
14899
14900         return false;
14901 }
14902
14903 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
14904 {
14905         struct drm_device *dev = encoder->base.dev;
14906         struct intel_connector *connector;
14907
14908         for_each_connector_on_encoder(dev, &encoder->base, connector)
14909                 return connector;
14910
14911         return NULL;
14912 }
14913
14914 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
14915                               enum pipe pch_transcoder)
14916 {
14917         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
14918                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
14919 }
14920
14921 static void intel_sanitize_crtc(struct intel_crtc *crtc,
14922                                 struct drm_modeset_acquire_ctx *ctx)
14923 {
14924         struct drm_device *dev = crtc->base.dev;
14925         struct drm_i915_private *dev_priv = to_i915(dev);
14926         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
14927
14928         /* Clear any frame start delays used for debugging left by the BIOS */
14929         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
14930                 i915_reg_t reg = PIPECONF(cpu_transcoder);
14931
14932                 I915_WRITE(reg,
14933                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14934         }
14935
14936         /* restore vblank interrupts to correct state */
14937         drm_crtc_vblank_reset(&crtc->base);
14938         if (crtc->active) {
14939                 struct intel_plane *plane;
14940
14941                 drm_crtc_vblank_on(&crtc->base);
14942
14943                 /* Disable everything but the primary plane */
14944                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
14945                         const struct intel_plane_state *plane_state =
14946                                 to_intel_plane_state(plane->base.state);
14947
14948                         if (plane_state->base.visible &&
14949                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
14950                                 intel_plane_disable_noatomic(crtc, plane);
14951                 }
14952         }
14953
14954         /* Adjust the state of the output pipe according to whether we
14955          * have active connectors/encoders. */
14956         if (crtc->active && !intel_crtc_has_encoders(crtc))
14957                 intel_crtc_disable_noatomic(&crtc->base, ctx);
14958
14959         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
14960                 /*
14961                  * We start out with underrun reporting disabled to avoid races.
14962                  * For correct bookkeeping mark this on active crtcs.
14963                  *
14964                  * Also on gmch platforms we dont have any hardware bits to
14965                  * disable the underrun reporting. Which means we need to start
14966                  * out with underrun reporting disabled also on inactive pipes,
14967                  * since otherwise we'll complain about the garbage we read when
14968                  * e.g. coming up after runtime pm.
14969                  *
14970                  * No protection against concurrent access is required - at
14971                  * worst a fifo underrun happens which also sets this to false.
14972                  */
14973                 crtc->cpu_fifo_underrun_disabled = true;
14974                 /*
14975                  * We track the PCH trancoder underrun reporting state
14976                  * within the crtc. With crtc for pipe A housing the underrun
14977                  * reporting state for PCH transcoder A, crtc for pipe B housing
14978                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
14979                  * and marking underrun reporting as disabled for the non-existing
14980                  * PCH transcoders B and C would prevent enabling the south
14981                  * error interrupt (see cpt_can_enable_serr_int()).
14982                  */
14983                 if (has_pch_trancoder(dev_priv, crtc->pipe))
14984                         crtc->pch_fifo_underrun_disabled = true;
14985         }
14986 }
14987
14988 static void intel_sanitize_encoder(struct intel_encoder *encoder)
14989 {
14990         struct intel_connector *connector;
14991
14992         /* We need to check both for a crtc link (meaning that the
14993          * encoder is active and trying to read from a pipe) and the
14994          * pipe itself being active. */
14995         bool has_active_crtc = encoder->base.crtc &&
14996                 to_intel_crtc(encoder->base.crtc)->active;
14997
14998         connector = intel_encoder_find_connector(encoder);
14999         if (connector && !has_active_crtc) {
15000                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
15001                               encoder->base.base.id,
15002                               encoder->base.name);
15003
15004                 /* Connector is active, but has no active pipe. This is
15005                  * fallout from our resume register restoring. Disable
15006                  * the encoder manually again. */
15007                 if (encoder->base.crtc) {
15008                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
15009
15010                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
15011                                       encoder->base.base.id,
15012                                       encoder->base.name);
15013                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15014                         if (encoder->post_disable)
15015                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
15016                 }
15017                 encoder->base.crtc = NULL;
15018
15019                 /* Inconsistent output/port/pipe state happens presumably due to
15020                  * a bug in one of the get_hw_state functions. Or someplace else
15021                  * in our code, like the register restore mess on resume. Clamp
15022                  * things to off as a safer default. */
15023
15024                 connector->base.dpms = DRM_MODE_DPMS_OFF;
15025                 connector->base.encoder = NULL;
15026         }
15027 }
15028
15029 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
15030 {
15031         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
15032
15033         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
15034                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
15035                 i915_disable_vga(dev_priv);
15036         }
15037 }
15038
15039 void i915_redisable_vga(struct drm_i915_private *dev_priv)
15040 {
15041         /* This function can be called both from intel_modeset_setup_hw_state or
15042          * at a very early point in our resume sequence, where the power well
15043          * structures are not yet restored. Since this function is at a very
15044          * paranoid "someone might have enabled VGA while we were not looking"
15045          * level, just check if the power well is enabled instead of trying to
15046          * follow the "don't touch the power well if we don't need it" policy
15047          * the rest of the driver uses. */
15048         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
15049                 return;
15050
15051         i915_redisable_vga_power_on(dev_priv);
15052
15053         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
15054 }
15055
15056 /* FIXME read out full plane state for all planes */
15057 static void readout_plane_state(struct intel_crtc *crtc)
15058 {
15059         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
15060         struct intel_crtc_state *crtc_state =
15061                 to_intel_crtc_state(crtc->base.state);
15062         struct intel_plane *plane;
15063
15064         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
15065                 struct intel_plane_state *plane_state =
15066                         to_intel_plane_state(plane->base.state);
15067                 bool visible = plane->get_hw_state(plane);
15068
15069                 intel_set_plane_visible(crtc_state, plane_state, visible);
15070         }
15071 }
15072
15073 static void intel_modeset_readout_hw_state(struct drm_device *dev)
15074 {
15075         struct drm_i915_private *dev_priv = to_i915(dev);
15076         enum pipe pipe;
15077         struct intel_crtc *crtc;
15078         struct intel_encoder *encoder;
15079         struct intel_connector *connector;
15080         struct drm_connector_list_iter conn_iter;
15081         int i;
15082
15083         dev_priv->active_crtcs = 0;
15084
15085         for_each_intel_crtc(dev, crtc) {
15086                 struct intel_crtc_state *crtc_state =
15087                         to_intel_crtc_state(crtc->base.state);
15088
15089                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
15090                 memset(crtc_state, 0, sizeof(*crtc_state));
15091                 crtc_state->base.crtc = &crtc->base;
15092
15093                 crtc_state->base.active = crtc_state->base.enable =
15094                         dev_priv->display.get_pipe_config(crtc, crtc_state);
15095
15096                 crtc->base.enabled = crtc_state->base.enable;
15097                 crtc->active = crtc_state->base.active;
15098
15099                 if (crtc_state->base.active)
15100                         dev_priv->active_crtcs |= 1 << crtc->pipe;
15101
15102                 readout_plane_state(crtc);
15103
15104                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
15105                               crtc->base.base.id, crtc->base.name,
15106                               enableddisabled(crtc_state->base.active));
15107         }
15108
15109         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15110                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15111
15112                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
15113                                                   &pll->state.hw_state);
15114                 pll->state.crtc_mask = 0;
15115                 for_each_intel_crtc(dev, crtc) {
15116                         struct intel_crtc_state *crtc_state =
15117                                 to_intel_crtc_state(crtc->base.state);
15118
15119                         if (crtc_state->base.active &&
15120                             crtc_state->shared_dpll == pll)
15121                                 pll->state.crtc_mask |= 1 << crtc->pipe;
15122                 }
15123                 pll->active_mask = pll->state.crtc_mask;
15124
15125                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
15126                               pll->name, pll->state.crtc_mask, pll->on);
15127         }
15128
15129         for_each_intel_encoder(dev, encoder) {
15130                 pipe = 0;
15131
15132                 if (encoder->get_hw_state(encoder, &pipe)) {
15133                         struct intel_crtc_state *crtc_state;
15134
15135                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15136                         crtc_state = to_intel_crtc_state(crtc->base.state);
15137
15138                         encoder->base.crtc = &crtc->base;
15139                         encoder->get_config(encoder, crtc_state);
15140                 } else {
15141                         encoder->base.crtc = NULL;
15142                 }
15143
15144                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
15145                               encoder->base.base.id, encoder->base.name,
15146                               enableddisabled(encoder->base.crtc),
15147                               pipe_name(pipe));
15148         }
15149
15150         drm_connector_list_iter_begin(dev, &conn_iter);
15151         for_each_intel_connector_iter(connector, &conn_iter) {
15152                 if (connector->get_hw_state(connector)) {
15153                         connector->base.dpms = DRM_MODE_DPMS_ON;
15154
15155                         encoder = connector->encoder;
15156                         connector->base.encoder = &encoder->base;
15157
15158                         if (encoder->base.crtc &&
15159                             encoder->base.crtc->state->active) {
15160                                 /*
15161                                  * This has to be done during hardware readout
15162                                  * because anything calling .crtc_disable may
15163                                  * rely on the connector_mask being accurate.
15164                                  */
15165                                 encoder->base.crtc->state->connector_mask |=
15166                                         1 << drm_connector_index(&connector->base);
15167                                 encoder->base.crtc->state->encoder_mask |=
15168                                         1 << drm_encoder_index(&encoder->base);
15169                         }
15170
15171                 } else {
15172                         connector->base.dpms = DRM_MODE_DPMS_OFF;
15173                         connector->base.encoder = NULL;
15174                 }
15175                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
15176                               connector->base.base.id, connector->base.name,
15177                               enableddisabled(connector->base.encoder));
15178         }
15179         drm_connector_list_iter_end(&conn_iter);
15180
15181         for_each_intel_crtc(dev, crtc) {
15182                 struct intel_crtc_state *crtc_state =
15183                         to_intel_crtc_state(crtc->base.state);
15184                 int min_cdclk = 0;
15185
15186                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15187                 if (crtc_state->base.active) {
15188                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15189                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15190                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15191
15192                         /*
15193                          * The initial mode needs to be set in order to keep
15194                          * the atomic core happy. It wants a valid mode if the
15195                          * crtc's enabled, so we do the above call.
15196                          *
15197                          * But we don't set all the derived state fully, hence
15198                          * set a flag to indicate that a full recalculation is
15199                          * needed on the next commit.
15200                          */
15201                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15202
15203                         intel_crtc_compute_pixel_rate(crtc_state);
15204
15205                         if (dev_priv->display.modeset_calc_cdclk) {
15206                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15207                                 if (WARN_ON(min_cdclk < 0))
15208                                         min_cdclk = 0;
15209                         }
15210
15211                         drm_calc_timestamping_constants(&crtc->base,
15212                                                         &crtc_state->base.adjusted_mode);
15213                         update_scanline_offset(crtc);
15214                 }
15215
15216                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15217                 dev_priv->min_voltage_level[crtc->pipe] =
15218                         crtc_state->min_voltage_level;
15219
15220                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15221         }
15222 }
15223
15224 static void
15225 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15226 {
15227         struct intel_encoder *encoder;
15228
15229         for_each_intel_encoder(&dev_priv->drm, encoder) {
15230                 u64 get_domains;
15231                 enum intel_display_power_domain domain;
15232
15233                 if (!encoder->get_power_domains)
15234                         continue;
15235
15236                 get_domains = encoder->get_power_domains(encoder);
15237                 for_each_power_domain(domain, get_domains)
15238                         intel_display_power_get(dev_priv, domain);
15239         }
15240 }
15241
15242 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15243 {
15244         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15245         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15246                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15247                            DARBF_GATING_DIS);
15248
15249         if (IS_HASWELL(dev_priv)) {
15250                 /*
15251                  * WaRsPkgCStateDisplayPMReq:hsw
15252                  * System hang if this isn't done before disabling all planes!
15253                  */
15254                 I915_WRITE(CHICKEN_PAR1_1,
15255                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15256         }
15257 }
15258
15259 /* Scan out the current hw modeset state,
15260  * and sanitizes it to the current state
15261  */
15262 static void
15263 intel_modeset_setup_hw_state(struct drm_device *dev,
15264                              struct drm_modeset_acquire_ctx *ctx)
15265 {
15266         struct drm_i915_private *dev_priv = to_i915(dev);
15267         enum pipe pipe;
15268         struct intel_crtc *crtc;
15269         struct intel_encoder *encoder;
15270         int i;
15271
15272         intel_early_display_was(dev_priv);
15273         intel_modeset_readout_hw_state(dev);
15274
15275         /* HW state is read out, now we need to sanitize this mess. */
15276         get_encoder_power_domains(dev_priv);
15277
15278         intel_sanitize_plane_mapping(dev_priv);
15279
15280         for_each_intel_encoder(dev, encoder) {
15281                 intel_sanitize_encoder(encoder);
15282         }
15283
15284         for_each_pipe(dev_priv, pipe) {
15285                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15286
15287                 intel_sanitize_crtc(crtc, ctx);
15288                 intel_dump_pipe_config(crtc, crtc->config,
15289                                        "[setup_hw_state]");
15290         }
15291
15292         intel_modeset_update_connector_atomic_state(dev);
15293
15294         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15295                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15296
15297                 if (!pll->on || pll->active_mask)
15298                         continue;
15299
15300                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15301
15302                 pll->funcs.disable(dev_priv, pll);
15303                 pll->on = false;
15304         }
15305
15306         if (IS_G4X(dev_priv)) {
15307                 g4x_wm_get_hw_state(dev);
15308                 g4x_wm_sanitize(dev_priv);
15309         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15310                 vlv_wm_get_hw_state(dev);
15311                 vlv_wm_sanitize(dev_priv);
15312         } else if (INTEL_GEN(dev_priv) >= 9) {
15313                 skl_wm_get_hw_state(dev);
15314         } else if (HAS_PCH_SPLIT(dev_priv)) {
15315                 ilk_wm_get_hw_state(dev);
15316         }
15317
15318         for_each_intel_crtc(dev, crtc) {
15319                 u64 put_domains;
15320
15321                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15322                 if (WARN_ON(put_domains))
15323                         modeset_put_power_domains(dev_priv, put_domains);
15324         }
15325         intel_display_set_init_power(dev_priv, false);
15326
15327         intel_power_domains_verify_state(dev_priv);
15328
15329         intel_fbc_init_pipe_state(dev_priv);
15330 }
15331
15332 void intel_display_resume(struct drm_device *dev)
15333 {
15334         struct drm_i915_private *dev_priv = to_i915(dev);
15335         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15336         struct drm_modeset_acquire_ctx ctx;
15337         int ret;
15338
15339         dev_priv->modeset_restore_state = NULL;
15340         if (state)
15341                 state->acquire_ctx = &ctx;
15342
15343         drm_modeset_acquire_init(&ctx, 0);
15344
15345         while (1) {
15346                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15347                 if (ret != -EDEADLK)
15348                         break;
15349
15350                 drm_modeset_backoff(&ctx);
15351         }
15352
15353         if (!ret)
15354                 ret = __intel_display_resume(dev, state, &ctx);
15355
15356         intel_enable_ipc(dev_priv);
15357         drm_modeset_drop_locks(&ctx);
15358         drm_modeset_acquire_fini(&ctx);
15359
15360         if (ret)
15361                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15362         if (state)
15363                 drm_atomic_state_put(state);
15364 }
15365
15366 int intel_connector_register(struct drm_connector *connector)
15367 {
15368         struct intel_connector *intel_connector = to_intel_connector(connector);
15369         int ret;
15370
15371         ret = intel_backlight_device_register(intel_connector);
15372         if (ret)
15373                 goto err;
15374
15375         return 0;
15376
15377 err:
15378         return ret;
15379 }
15380
15381 void intel_connector_unregister(struct drm_connector *connector)
15382 {
15383         struct intel_connector *intel_connector = to_intel_connector(connector);
15384
15385         intel_backlight_device_unregister(intel_connector);
15386         intel_panel_destroy_backlight(connector);
15387 }
15388
15389 static void intel_hpd_poll_fini(struct drm_device *dev)
15390 {
15391         struct intel_connector *connector;
15392         struct drm_connector_list_iter conn_iter;
15393
15394         /* Kill all the work that may have been queued by hpd. */
15395         drm_connector_list_iter_begin(dev, &conn_iter);
15396         for_each_intel_connector_iter(connector, &conn_iter) {
15397                 if (connector->modeset_retry_work.func)
15398                         cancel_work_sync(&connector->modeset_retry_work);
15399                 if (connector->hdcp_shim) {
15400                         cancel_delayed_work_sync(&connector->hdcp_check_work);
15401                         cancel_work_sync(&connector->hdcp_prop_work);
15402                 }
15403         }
15404         drm_connector_list_iter_end(&conn_iter);
15405 }
15406
15407 void intel_modeset_cleanup(struct drm_device *dev)
15408 {
15409         struct drm_i915_private *dev_priv = to_i915(dev);
15410
15411         flush_work(&dev_priv->atomic_helper.free_work);
15412         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15413
15414         intel_disable_gt_powersave(dev_priv);
15415
15416         /*
15417          * Interrupts and polling as the first thing to avoid creating havoc.
15418          * Too much stuff here (turning of connectors, ...) would
15419          * experience fancy races otherwise.
15420          */
15421         intel_irq_uninstall(dev_priv);
15422
15423         /*
15424          * Due to the hpd irq storm handling the hotplug work can re-arm the
15425          * poll handlers. Hence disable polling after hpd handling is shut down.
15426          */
15427         intel_hpd_poll_fini(dev);
15428
15429         /* poll work can call into fbdev, hence clean that up afterwards */
15430         intel_fbdev_fini(dev_priv);
15431
15432         intel_unregister_dsm_handler();
15433
15434         intel_fbc_global_disable(dev_priv);
15435
15436         /* flush any delayed tasks or pending work */
15437         flush_scheduled_work();
15438
15439         drm_mode_config_cleanup(dev);
15440
15441         intel_cleanup_overlay(dev_priv);
15442
15443         intel_cleanup_gt_powersave(dev_priv);
15444
15445         intel_teardown_gmbus(dev_priv);
15446
15447         destroy_workqueue(dev_priv->modeset_wq);
15448 }
15449
15450 void intel_connector_attach_encoder(struct intel_connector *connector,
15451                                     struct intel_encoder *encoder)
15452 {
15453         connector->encoder = encoder;
15454         drm_mode_connector_attach_encoder(&connector->base,
15455                                           &encoder->base);
15456 }
15457
15458 /*
15459  * set vga decode state - true == enable VGA decode
15460  */
15461 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15462 {
15463         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15464         u16 gmch_ctrl;
15465
15466         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15467                 DRM_ERROR("failed to read control word\n");
15468                 return -EIO;
15469         }
15470
15471         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15472                 return 0;
15473
15474         if (state)
15475                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15476         else
15477                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15478
15479         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15480                 DRM_ERROR("failed to write control word\n");
15481                 return -EIO;
15482         }
15483
15484         return 0;
15485 }
15486
15487 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15488
15489 struct intel_display_error_state {
15490
15491         u32 power_well_driver;
15492
15493         int num_transcoders;
15494
15495         struct intel_cursor_error_state {
15496                 u32 control;
15497                 u32 position;
15498                 u32 base;
15499                 u32 size;
15500         } cursor[I915_MAX_PIPES];
15501
15502         struct intel_pipe_error_state {
15503                 bool power_domain_on;
15504                 u32 source;
15505                 u32 stat;
15506         } pipe[I915_MAX_PIPES];
15507
15508         struct intel_plane_error_state {
15509                 u32 control;
15510                 u32 stride;
15511                 u32 size;
15512                 u32 pos;
15513                 u32 addr;
15514                 u32 surface;
15515                 u32 tile_offset;
15516         } plane[I915_MAX_PIPES];
15517
15518         struct intel_transcoder_error_state {
15519                 bool power_domain_on;
15520                 enum transcoder cpu_transcoder;
15521
15522                 u32 conf;
15523
15524                 u32 htotal;
15525                 u32 hblank;
15526                 u32 hsync;
15527                 u32 vtotal;
15528                 u32 vblank;
15529                 u32 vsync;
15530         } transcoder[4];
15531 };
15532
15533 struct intel_display_error_state *
15534 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15535 {
15536         struct intel_display_error_state *error;
15537         int transcoders[] = {
15538                 TRANSCODER_A,
15539                 TRANSCODER_B,
15540                 TRANSCODER_C,
15541                 TRANSCODER_EDP,
15542         };
15543         int i;
15544
15545         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15546                 return NULL;
15547
15548         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15549         if (error == NULL)
15550                 return NULL;
15551
15552         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15553                 error->power_well_driver =
15554                         I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL));
15555
15556         for_each_pipe(dev_priv, i) {
15557                 error->pipe[i].power_domain_on =
15558                         __intel_display_power_is_enabled(dev_priv,
15559                                                          POWER_DOMAIN_PIPE(i));
15560                 if (!error->pipe[i].power_domain_on)
15561                         continue;
15562
15563                 error->cursor[i].control = I915_READ(CURCNTR(i));
15564                 error->cursor[i].position = I915_READ(CURPOS(i));
15565                 error->cursor[i].base = I915_READ(CURBASE(i));
15566
15567                 error->plane[i].control = I915_READ(DSPCNTR(i));
15568                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15569                 if (INTEL_GEN(dev_priv) <= 3) {
15570                         error->plane[i].size = I915_READ(DSPSIZE(i));
15571                         error->plane[i].pos = I915_READ(DSPPOS(i));
15572                 }
15573                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15574                         error->plane[i].addr = I915_READ(DSPADDR(i));
15575                 if (INTEL_GEN(dev_priv) >= 4) {
15576                         error->plane[i].surface = I915_READ(DSPSURF(i));
15577                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15578                 }
15579
15580                 error->pipe[i].source = I915_READ(PIPESRC(i));
15581
15582                 if (HAS_GMCH_DISPLAY(dev_priv))
15583                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15584         }
15585
15586         /* Note: this does not include DSI transcoders. */
15587         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15588         if (HAS_DDI(dev_priv))
15589                 error->num_transcoders++; /* Account for eDP. */
15590
15591         for (i = 0; i < error->num_transcoders; i++) {
15592                 enum transcoder cpu_transcoder = transcoders[i];
15593
15594                 error->transcoder[i].power_domain_on =
15595                         __intel_display_power_is_enabled(dev_priv,
15596                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15597                 if (!error->transcoder[i].power_domain_on)
15598                         continue;
15599
15600                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15601
15602                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15603                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15604                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15605                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15606                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15607                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15608                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15609         }
15610
15611         return error;
15612 }
15613
15614 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15615
15616 void
15617 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15618                                 struct intel_display_error_state *error)
15619 {
15620         struct drm_i915_private *dev_priv = m->i915;
15621         int i;
15622
15623         if (!error)
15624                 return;
15625
15626         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
15627         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15628                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15629                            error->power_well_driver);
15630         for_each_pipe(dev_priv, i) {
15631                 err_printf(m, "Pipe [%d]:\n", i);
15632                 err_printf(m, "  Power: %s\n",
15633                            onoff(error->pipe[i].power_domain_on));
15634                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15635                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15636
15637                 err_printf(m, "Plane [%d]:\n", i);
15638                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15639                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15640                 if (INTEL_GEN(dev_priv) <= 3) {
15641                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15642                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15643                 }
15644                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15645                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15646                 if (INTEL_GEN(dev_priv) >= 4) {
15647                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15648                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15649                 }
15650
15651                 err_printf(m, "Cursor [%d]:\n", i);
15652                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15653                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15654                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15655         }
15656
15657         for (i = 0; i < error->num_transcoders; i++) {
15658                 err_printf(m, "CPU transcoder: %s\n",
15659                            transcoder_name(error->transcoder[i].cpu_transcoder));
15660                 err_printf(m, "  Power: %s\n",
15661                            onoff(error->transcoder[i].power_domain_on));
15662                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15663                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15664                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15665                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15666                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15667                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15668                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15669         }
15670 }
15671
15672 #endif