Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/net
[sfrench/cifs-2.6.git] / drivers / gpu / drm / i915 / intel_display.c
1 /*
2  * Copyright © 2006-2007 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Eric Anholt <eric@anholt.net>
25  */
26
27 #include <linux/dmi.h>
28 #include <linux/module.h>
29 #include <linux/input.h>
30 #include <linux/i2c.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <linux/vgaarb.h>
34 #include <drm/drm_edid.h>
35 #include <drm/drmP.h>
36 #include "intel_drv.h"
37 #include "intel_frontbuffer.h"
38 #include <drm/i915_drm.h>
39 #include "i915_drv.h"
40 #include "i915_gem_clflush.h"
41 #include "intel_dsi.h"
42 #include "i915_trace.h"
43 #include <drm/drm_atomic.h>
44 #include <drm/drm_atomic_helper.h>
45 #include <drm/drm_dp_helper.h>
46 #include <drm/drm_crtc_helper.h>
47 #include <drm/drm_plane_helper.h>
48 #include <drm/drm_rect.h>
49 #include <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  * Returns whether the given set of divisors are valid for a given refclk with
563  * the given connectors.
564  */
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_INFO(dev_priv)->gen >= 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_INFO(dev_priv)->gen >= 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 struct i915_vma *
2071 intel_pin_and_fence_fb_obj(struct drm_framebuffer *fb, unsigned int rotation)
2072 {
2073         struct drm_device *dev = fb->dev;
2074         struct drm_i915_private *dev_priv = to_i915(dev);
2075         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
2076         struct i915_ggtt_view view;
2077         struct i915_vma *vma;
2078         u32 alignment;
2079
2080         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
2081
2082         alignment = intel_surf_alignment(fb, 0);
2083
2084         intel_fill_fb_ggtt_view(&view, fb, rotation);
2085
2086         /* Note that the w/a also requires 64 PTE of padding following the
2087          * bo. We currently fill all unused PTE with the shadow page and so
2088          * we should always have valid PTE following the scanout preventing
2089          * the VT-d warning.
2090          */
2091         if (intel_scanout_needs_vtd_wa(dev_priv) && alignment < 256 * 1024)
2092                 alignment = 256 * 1024;
2093
2094         /*
2095          * Global gtt pte registers are special registers which actually forward
2096          * writes to a chunk of system memory. Which means that there is no risk
2097          * that the register values disappear as soon as we call
2098          * intel_runtime_pm_put(), so it is correct to wrap only the
2099          * pin/unpin/fence and not more.
2100          */
2101         intel_runtime_pm_get(dev_priv);
2102
2103         atomic_inc(&dev_priv->gpu_error.pending_fb_pin);
2104
2105         vma = i915_gem_object_pin_to_display_plane(obj, alignment, &view);
2106         if (IS_ERR(vma))
2107                 goto err;
2108
2109         if (i915_vma_is_map_and_fenceable(vma)) {
2110                 /* Install a fence for tiled scan-out. Pre-i965 always needs a
2111                  * fence, whereas 965+ only requires a fence if using
2112                  * framebuffer compression.  For simplicity, we always, when
2113                  * possible, install a fence as the cost is not that onerous.
2114                  *
2115                  * If we fail to fence the tiled scanout, then either the
2116                  * modeset will reject the change (which is highly unlikely as
2117                  * the affected systems, all but one, do not have unmappable
2118                  * space) or we will not be able to enable full powersaving
2119                  * techniques (also likely not to apply due to various limits
2120                  * FBC and the like impose on the size of the buffer, which
2121                  * presumably we violated anyway with this unmappable buffer).
2122                  * Anyway, it is presumably better to stumble onwards with
2123                  * something and try to run the system in a "less than optimal"
2124                  * mode that matches the user configuration.
2125                  */
2126                 i915_vma_pin_fence(vma);
2127         }
2128
2129         i915_vma_get(vma);
2130 err:
2131         atomic_dec(&dev_priv->gpu_error.pending_fb_pin);
2132
2133         intel_runtime_pm_put(dev_priv);
2134         return vma;
2135 }
2136
2137 void intel_unpin_fb_vma(struct i915_vma *vma)
2138 {
2139         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
2140
2141         i915_vma_unpin_fence(vma);
2142         i915_gem_object_unpin_from_display_plane(vma);
2143         i915_vma_put(vma);
2144 }
2145
2146 static int intel_fb_pitch(const struct drm_framebuffer *fb, int plane,
2147                           unsigned int rotation)
2148 {
2149         if (drm_rotation_90_or_270(rotation))
2150                 return to_intel_framebuffer(fb)->rotated[plane].pitch;
2151         else
2152                 return fb->pitches[plane];
2153 }
2154
2155 /*
2156  * Convert the x/y offsets into a linear offset.
2157  * Only valid with 0/180 degree rotation, which is fine since linear
2158  * offset is only used with linear buffers on pre-hsw and tiled buffers
2159  * with gen2/3, and 90/270 degree rotations isn't supported on any of them.
2160  */
2161 u32 intel_fb_xy_to_linear(int x, int y,
2162                           const struct intel_plane_state *state,
2163                           int plane)
2164 {
2165         const struct drm_framebuffer *fb = state->base.fb;
2166         unsigned int cpp = fb->format->cpp[plane];
2167         unsigned int pitch = fb->pitches[plane];
2168
2169         return y * pitch + x * cpp;
2170 }
2171
2172 /*
2173  * Add the x/y offsets derived from fb->offsets[] to the user
2174  * specified plane src x/y offsets. The resulting x/y offsets
2175  * specify the start of scanout from the beginning of the gtt mapping.
2176  */
2177 void intel_add_fb_offsets(int *x, int *y,
2178                           const struct intel_plane_state *state,
2179                           int plane)
2180
2181 {
2182         const struct intel_framebuffer *intel_fb = to_intel_framebuffer(state->base.fb);
2183         unsigned int rotation = state->base.rotation;
2184
2185         if (drm_rotation_90_or_270(rotation)) {
2186                 *x += intel_fb->rotated[plane].x;
2187                 *y += intel_fb->rotated[plane].y;
2188         } else {
2189                 *x += intel_fb->normal[plane].x;
2190                 *y += intel_fb->normal[plane].y;
2191         }
2192 }
2193
2194 static u32 __intel_adjust_tile_offset(int *x, int *y,
2195                                       unsigned int tile_width,
2196                                       unsigned int tile_height,
2197                                       unsigned int tile_size,
2198                                       unsigned int pitch_tiles,
2199                                       u32 old_offset,
2200                                       u32 new_offset)
2201 {
2202         unsigned int pitch_pixels = pitch_tiles * tile_width;
2203         unsigned int tiles;
2204
2205         WARN_ON(old_offset & (tile_size - 1));
2206         WARN_ON(new_offset & (tile_size - 1));
2207         WARN_ON(new_offset > old_offset);
2208
2209         tiles = (old_offset - new_offset) / tile_size;
2210
2211         *y += tiles / pitch_tiles * tile_height;
2212         *x += tiles % pitch_tiles * tile_width;
2213
2214         /* minimize x in case it got needlessly big */
2215         *y += *x / pitch_pixels * tile_height;
2216         *x %= pitch_pixels;
2217
2218         return new_offset;
2219 }
2220
2221 static u32 _intel_adjust_tile_offset(int *x, int *y,
2222                                      const struct drm_framebuffer *fb, int plane,
2223                                      unsigned int rotation,
2224                                      u32 old_offset, u32 new_offset)
2225 {
2226         const struct drm_i915_private *dev_priv = to_i915(fb->dev);
2227         unsigned int cpp = fb->format->cpp[plane];
2228         unsigned int pitch = intel_fb_pitch(fb, plane, rotation);
2229
2230         WARN_ON(new_offset > old_offset);
2231
2232         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2233                 unsigned int tile_size, tile_width, tile_height;
2234                 unsigned int pitch_tiles;
2235
2236                 tile_size = intel_tile_size(dev_priv);
2237                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2238
2239                 if (drm_rotation_90_or_270(rotation)) {
2240                         pitch_tiles = pitch / tile_height;
2241                         swap(tile_width, tile_height);
2242                 } else {
2243                         pitch_tiles = pitch / (tile_width * cpp);
2244                 }
2245
2246                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2247                                            tile_size, pitch_tiles,
2248                                            old_offset, new_offset);
2249         } else {
2250                 old_offset += *y * pitch + *x * cpp;
2251
2252                 *y = (old_offset - new_offset) / pitch;
2253                 *x = ((old_offset - new_offset) - *y * pitch) / cpp;
2254         }
2255
2256         return new_offset;
2257 }
2258
2259 /*
2260  * Adjust the tile offset by moving the difference into
2261  * the x/y offsets.
2262  */
2263 static u32 intel_adjust_tile_offset(int *x, int *y,
2264                                     const struct intel_plane_state *state, int plane,
2265                                     u32 old_offset, u32 new_offset)
2266 {
2267         return _intel_adjust_tile_offset(x, y, state->base.fb, plane,
2268                                          state->base.rotation,
2269                                          old_offset, new_offset);
2270 }
2271
2272 /*
2273  * Computes the linear offset to the base tile and adjusts
2274  * x, y. bytes per pixel is assumed to be a power-of-two.
2275  *
2276  * In the 90/270 rotated case, x and y are assumed
2277  * to be already rotated to match the rotated GTT view, and
2278  * pitch is the tile_height aligned framebuffer height.
2279  *
2280  * This function is used when computing the derived information
2281  * under intel_framebuffer, so using any of that information
2282  * here is not allowed. Anything under drm_framebuffer can be
2283  * used. This is why the user has to pass in the pitch since it
2284  * is specified in the rotated orientation.
2285  */
2286 static u32 _intel_compute_tile_offset(const struct drm_i915_private *dev_priv,
2287                                       int *x, int *y,
2288                                       const struct drm_framebuffer *fb, int plane,
2289                                       unsigned int pitch,
2290                                       unsigned int rotation,
2291                                       u32 alignment)
2292 {
2293         uint64_t fb_modifier = fb->modifier;
2294         unsigned int cpp = fb->format->cpp[plane];
2295         u32 offset, offset_aligned;
2296
2297         if (alignment)
2298                 alignment--;
2299
2300         if (fb_modifier != DRM_FORMAT_MOD_LINEAR) {
2301                 unsigned int tile_size, tile_width, tile_height;
2302                 unsigned int tile_rows, tiles, pitch_tiles;
2303
2304                 tile_size = intel_tile_size(dev_priv);
2305                 intel_tile_dims(fb, plane, &tile_width, &tile_height);
2306
2307                 if (drm_rotation_90_or_270(rotation)) {
2308                         pitch_tiles = pitch / tile_height;
2309                         swap(tile_width, tile_height);
2310                 } else {
2311                         pitch_tiles = pitch / (tile_width * cpp);
2312                 }
2313
2314                 tile_rows = *y / tile_height;
2315                 *y %= tile_height;
2316
2317                 tiles = *x / tile_width;
2318                 *x %= tile_width;
2319
2320                 offset = (tile_rows * pitch_tiles + tiles) * tile_size;
2321                 offset_aligned = offset & ~alignment;
2322
2323                 __intel_adjust_tile_offset(x, y, tile_width, tile_height,
2324                                            tile_size, pitch_tiles,
2325                                            offset, offset_aligned);
2326         } else {
2327                 offset = *y * pitch + *x * cpp;
2328                 offset_aligned = offset & ~alignment;
2329
2330                 *y = (offset & alignment) / pitch;
2331                 *x = ((offset & alignment) - *y * pitch) / cpp;
2332         }
2333
2334         return offset_aligned;
2335 }
2336
2337 u32 intel_compute_tile_offset(int *x, int *y,
2338                               const struct intel_plane_state *state,
2339                               int plane)
2340 {
2341         struct intel_plane *intel_plane = to_intel_plane(state->base.plane);
2342         struct drm_i915_private *dev_priv = to_i915(intel_plane->base.dev);
2343         const struct drm_framebuffer *fb = state->base.fb;
2344         unsigned int rotation = state->base.rotation;
2345         int pitch = intel_fb_pitch(fb, plane, rotation);
2346         u32 alignment;
2347
2348         if (intel_plane->id == PLANE_CURSOR)
2349                 alignment = intel_cursor_alignment(dev_priv);
2350         else
2351                 alignment = intel_surf_alignment(fb, plane);
2352
2353         return _intel_compute_tile_offset(dev_priv, x, y, fb, plane, pitch,
2354                                           rotation, alignment);
2355 }
2356
2357 /* Convert the fb->offset[] into x/y offsets */
2358 static int intel_fb_offset_to_xy(int *x, int *y,
2359                                  const struct drm_framebuffer *fb, int plane)
2360 {
2361         struct drm_i915_private *dev_priv = to_i915(fb->dev);
2362
2363         if (fb->modifier != DRM_FORMAT_MOD_LINEAR &&
2364             fb->offsets[plane] % intel_tile_size(dev_priv))
2365                 return -EINVAL;
2366
2367         *x = 0;
2368         *y = 0;
2369
2370         _intel_adjust_tile_offset(x, y,
2371                                   fb, plane, DRM_MODE_ROTATE_0,
2372                                   fb->offsets[plane], 0);
2373
2374         return 0;
2375 }
2376
2377 static unsigned int intel_fb_modifier_to_tiling(uint64_t fb_modifier)
2378 {
2379         switch (fb_modifier) {
2380         case I915_FORMAT_MOD_X_TILED:
2381                 return I915_TILING_X;
2382         case I915_FORMAT_MOD_Y_TILED:
2383         case I915_FORMAT_MOD_Y_TILED_CCS:
2384                 return I915_TILING_Y;
2385         default:
2386                 return I915_TILING_NONE;
2387         }
2388 }
2389
2390 static const struct drm_format_info ccs_formats[] = {
2391         { .format = DRM_FORMAT_XRGB8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2392         { .format = DRM_FORMAT_XBGR8888, .depth = 24, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2393         { .format = DRM_FORMAT_ARGB8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2394         { .format = DRM_FORMAT_ABGR8888, .depth = 32, .num_planes = 2, .cpp = { 4, 1, }, .hsub = 8, .vsub = 16, },
2395 };
2396
2397 static const struct drm_format_info *
2398 lookup_format_info(const struct drm_format_info formats[],
2399                    int num_formats, u32 format)
2400 {
2401         int i;
2402
2403         for (i = 0; i < num_formats; i++) {
2404                 if (formats[i].format == format)
2405                         return &formats[i];
2406         }
2407
2408         return NULL;
2409 }
2410
2411 static const struct drm_format_info *
2412 intel_get_format_info(const struct drm_mode_fb_cmd2 *cmd)
2413 {
2414         switch (cmd->modifier[0]) {
2415         case I915_FORMAT_MOD_Y_TILED_CCS:
2416         case I915_FORMAT_MOD_Yf_TILED_CCS:
2417                 return lookup_format_info(ccs_formats,
2418                                           ARRAY_SIZE(ccs_formats),
2419                                           cmd->pixel_format);
2420         default:
2421                 return NULL;
2422         }
2423 }
2424
2425 static int
2426 intel_fill_fb_info(struct drm_i915_private *dev_priv,
2427                    struct drm_framebuffer *fb)
2428 {
2429         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
2430         struct intel_rotation_info *rot_info = &intel_fb->rot_info;
2431         u32 gtt_offset_rotated = 0;
2432         unsigned int max_size = 0;
2433         int i, num_planes = fb->format->num_planes;
2434         unsigned int tile_size = intel_tile_size(dev_priv);
2435
2436         for (i = 0; i < num_planes; i++) {
2437                 unsigned int width, height;
2438                 unsigned int cpp, size;
2439                 u32 offset;
2440                 int x, y;
2441                 int ret;
2442
2443                 cpp = fb->format->cpp[i];
2444                 width = drm_framebuffer_plane_width(fb->width, fb, i);
2445                 height = drm_framebuffer_plane_height(fb->height, fb, i);
2446
2447                 ret = intel_fb_offset_to_xy(&x, &y, fb, i);
2448                 if (ret) {
2449                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2450                                       i, fb->offsets[i]);
2451                         return ret;
2452                 }
2453
2454                 if ((fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2455                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) && i == 1) {
2456                         int hsub = fb->format->hsub;
2457                         int vsub = fb->format->vsub;
2458                         int tile_width, tile_height;
2459                         int main_x, main_y;
2460                         int ccs_x, ccs_y;
2461
2462                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2463                         tile_width *= hsub;
2464                         tile_height *= vsub;
2465
2466                         ccs_x = (x * hsub) % tile_width;
2467                         ccs_y = (y * vsub) % tile_height;
2468                         main_x = intel_fb->normal[0].x % tile_width;
2469                         main_y = intel_fb->normal[0].y % tile_height;
2470
2471                         /*
2472                          * CCS doesn't have its own x/y offset register, so the intra CCS tile
2473                          * x/y offsets must match between CCS and the main surface.
2474                          */
2475                         if (main_x != ccs_x || main_y != ccs_y) {
2476                                 DRM_DEBUG_KMS("Bad CCS x/y (main %d,%d ccs %d,%d) full (main %d,%d ccs %d,%d)\n",
2477                                               main_x, main_y,
2478                                               ccs_x, ccs_y,
2479                                               intel_fb->normal[0].x,
2480                                               intel_fb->normal[0].y,
2481                                               x, y);
2482                                 return -EINVAL;
2483                         }
2484                 }
2485
2486                 /*
2487                  * The fence (if used) is aligned to the start of the object
2488                  * so having the framebuffer wrap around across the edge of the
2489                  * fenced region doesn't really work. We have no API to configure
2490                  * the fence start offset within the object (nor could we probably
2491                  * on gen2/3). So it's just easier if we just require that the
2492                  * fb layout agrees with the fence layout. We already check that the
2493                  * fb stride matches the fence stride elsewhere.
2494                  */
2495                 if (i == 0 && i915_gem_object_is_tiled(intel_fb->obj) &&
2496                     (x + width) * cpp > fb->pitches[i]) {
2497                         DRM_DEBUG_KMS("bad fb plane %d offset: 0x%x\n",
2498                                       i, fb->offsets[i]);
2499                         return -EINVAL;
2500                 }
2501
2502                 /*
2503                  * First pixel of the framebuffer from
2504                  * the start of the normal gtt mapping.
2505                  */
2506                 intel_fb->normal[i].x = x;
2507                 intel_fb->normal[i].y = y;
2508
2509                 offset = _intel_compute_tile_offset(dev_priv, &x, &y,
2510                                                     fb, i, fb->pitches[i],
2511                                                     DRM_MODE_ROTATE_0, tile_size);
2512                 offset /= tile_size;
2513
2514                 if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
2515                         unsigned int tile_width, tile_height;
2516                         unsigned int pitch_tiles;
2517                         struct drm_rect r;
2518
2519                         intel_tile_dims(fb, i, &tile_width, &tile_height);
2520
2521                         rot_info->plane[i].offset = offset;
2522                         rot_info->plane[i].stride = DIV_ROUND_UP(fb->pitches[i], tile_width * cpp);
2523                         rot_info->plane[i].width = DIV_ROUND_UP(x + width, tile_width);
2524                         rot_info->plane[i].height = DIV_ROUND_UP(y + height, tile_height);
2525
2526                         intel_fb->rotated[i].pitch =
2527                                 rot_info->plane[i].height * tile_height;
2528
2529                         /* how many tiles does this plane need */
2530                         size = rot_info->plane[i].stride * rot_info->plane[i].height;
2531                         /*
2532                          * If the plane isn't horizontally tile aligned,
2533                          * we need one more tile.
2534                          */
2535                         if (x != 0)
2536                                 size++;
2537
2538                         /* rotate the x/y offsets to match the GTT view */
2539                         r.x1 = x;
2540                         r.y1 = y;
2541                         r.x2 = x + width;
2542                         r.y2 = y + height;
2543                         drm_rect_rotate(&r,
2544                                         rot_info->plane[i].width * tile_width,
2545                                         rot_info->plane[i].height * tile_height,
2546                                         DRM_MODE_ROTATE_270);
2547                         x = r.x1;
2548                         y = r.y1;
2549
2550                         /* rotate the tile dimensions to match the GTT view */
2551                         pitch_tiles = intel_fb->rotated[i].pitch / tile_height;
2552                         swap(tile_width, tile_height);
2553
2554                         /*
2555                          * We only keep the x/y offsets, so push all of the
2556                          * gtt offset into the x/y offsets.
2557                          */
2558                         __intel_adjust_tile_offset(&x, &y,
2559                                                    tile_width, tile_height,
2560                                                    tile_size, pitch_tiles,
2561                                                    gtt_offset_rotated * tile_size, 0);
2562
2563                         gtt_offset_rotated += rot_info->plane[i].width * rot_info->plane[i].height;
2564
2565                         /*
2566                          * First pixel of the framebuffer from
2567                          * the start of the rotated gtt mapping.
2568                          */
2569                         intel_fb->rotated[i].x = x;
2570                         intel_fb->rotated[i].y = y;
2571                 } else {
2572                         size = DIV_ROUND_UP((y + height) * fb->pitches[i] +
2573                                             x * cpp, tile_size);
2574                 }
2575
2576                 /* how many tiles in total needed in the bo */
2577                 max_size = max(max_size, offset + size);
2578         }
2579
2580         if (max_size * tile_size > intel_fb->obj->base.size) {
2581                 DRM_DEBUG_KMS("fb too big for bo (need %u bytes, have %zu bytes)\n",
2582                               max_size * tile_size, intel_fb->obj->base.size);
2583                 return -EINVAL;
2584         }
2585
2586         return 0;
2587 }
2588
2589 static int i9xx_format_to_fourcc(int format)
2590 {
2591         switch (format) {
2592         case DISPPLANE_8BPP:
2593                 return DRM_FORMAT_C8;
2594         case DISPPLANE_BGRX555:
2595                 return DRM_FORMAT_XRGB1555;
2596         case DISPPLANE_BGRX565:
2597                 return DRM_FORMAT_RGB565;
2598         default:
2599         case DISPPLANE_BGRX888:
2600                 return DRM_FORMAT_XRGB8888;
2601         case DISPPLANE_RGBX888:
2602                 return DRM_FORMAT_XBGR8888;
2603         case DISPPLANE_BGRX101010:
2604                 return DRM_FORMAT_XRGB2101010;
2605         case DISPPLANE_RGBX101010:
2606                 return DRM_FORMAT_XBGR2101010;
2607         }
2608 }
2609
2610 static int skl_format_to_fourcc(int format, bool rgb_order, bool alpha)
2611 {
2612         switch (format) {
2613         case PLANE_CTL_FORMAT_RGB_565:
2614                 return DRM_FORMAT_RGB565;
2615         default:
2616         case PLANE_CTL_FORMAT_XRGB_8888:
2617                 if (rgb_order) {
2618                         if (alpha)
2619                                 return DRM_FORMAT_ABGR8888;
2620                         else
2621                                 return DRM_FORMAT_XBGR8888;
2622                 } else {
2623                         if (alpha)
2624                                 return DRM_FORMAT_ARGB8888;
2625                         else
2626                                 return DRM_FORMAT_XRGB8888;
2627                 }
2628         case PLANE_CTL_FORMAT_XRGB_2101010:
2629                 if (rgb_order)
2630                         return DRM_FORMAT_XBGR2101010;
2631                 else
2632                         return DRM_FORMAT_XRGB2101010;
2633         }
2634 }
2635
2636 static bool
2637 intel_alloc_initial_plane_obj(struct intel_crtc *crtc,
2638                               struct intel_initial_plane_config *plane_config)
2639 {
2640         struct drm_device *dev = crtc->base.dev;
2641         struct drm_i915_private *dev_priv = to_i915(dev);
2642         struct drm_i915_gem_object *obj = NULL;
2643         struct drm_mode_fb_cmd2 mode_cmd = { 0 };
2644         struct drm_framebuffer *fb = &plane_config->fb->base;
2645         u32 base_aligned = round_down(plane_config->base, PAGE_SIZE);
2646         u32 size_aligned = round_up(plane_config->base + plane_config->size,
2647                                     PAGE_SIZE);
2648
2649         size_aligned -= base_aligned;
2650
2651         if (plane_config->size == 0)
2652                 return false;
2653
2654         /* If the FB is too big, just don't use it since fbdev is not very
2655          * important and we should probably use that space with FBC or other
2656          * features. */
2657         if (size_aligned * 2 > dev_priv->stolen_usable_size)
2658                 return false;
2659
2660         mutex_lock(&dev->struct_mutex);
2661         obj = i915_gem_object_create_stolen_for_preallocated(dev_priv,
2662                                                              base_aligned,
2663                                                              base_aligned,
2664                                                              size_aligned);
2665         mutex_unlock(&dev->struct_mutex);
2666         if (!obj)
2667                 return false;
2668
2669         if (plane_config->tiling == I915_TILING_X)
2670                 obj->tiling_and_stride = fb->pitches[0] | I915_TILING_X;
2671
2672         mode_cmd.pixel_format = fb->format->format;
2673         mode_cmd.width = fb->width;
2674         mode_cmd.height = fb->height;
2675         mode_cmd.pitches[0] = fb->pitches[0];
2676         mode_cmd.modifier[0] = fb->modifier;
2677         mode_cmd.flags = DRM_MODE_FB_MODIFIERS;
2678
2679         if (intel_framebuffer_init(to_intel_framebuffer(fb), obj, &mode_cmd)) {
2680                 DRM_DEBUG_KMS("intel fb init failed\n");
2681                 goto out_unref_obj;
2682         }
2683
2684
2685         DRM_DEBUG_KMS("initial plane fb obj %p\n", obj);
2686         return true;
2687
2688 out_unref_obj:
2689         i915_gem_object_put(obj);
2690         return false;
2691 }
2692
2693 static void
2694 intel_set_plane_visible(struct intel_crtc_state *crtc_state,
2695                         struct intel_plane_state *plane_state,
2696                         bool visible)
2697 {
2698         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
2699
2700         plane_state->base.visible = visible;
2701
2702         /* FIXME pre-g4x don't work like this */
2703         if (visible) {
2704                 crtc_state->base.plane_mask |= BIT(drm_plane_index(&plane->base));
2705                 crtc_state->active_planes |= BIT(plane->id);
2706         } else {
2707                 crtc_state->base.plane_mask &= ~BIT(drm_plane_index(&plane->base));
2708                 crtc_state->active_planes &= ~BIT(plane->id);
2709         }
2710
2711         DRM_DEBUG_KMS("%s active planes 0x%x\n",
2712                       crtc_state->base.crtc->name,
2713                       crtc_state->active_planes);
2714 }
2715
2716 static void intel_plane_disable_noatomic(struct intel_crtc *crtc,
2717                                          struct intel_plane *plane)
2718 {
2719         struct intel_crtc_state *crtc_state =
2720                 to_intel_crtc_state(crtc->base.state);
2721         struct intel_plane_state *plane_state =
2722                 to_intel_plane_state(plane->base.state);
2723
2724         intel_set_plane_visible(crtc_state, plane_state, false);
2725
2726         if (plane->id == PLANE_PRIMARY)
2727                 intel_pre_disable_primary_noatomic(&crtc->base);
2728
2729         trace_intel_disable_plane(&plane->base, crtc);
2730         plane->disable_plane(plane, crtc);
2731 }
2732
2733 static void
2734 intel_find_initial_plane_obj(struct intel_crtc *intel_crtc,
2735                              struct intel_initial_plane_config *plane_config)
2736 {
2737         struct drm_device *dev = intel_crtc->base.dev;
2738         struct drm_i915_private *dev_priv = to_i915(dev);
2739         struct drm_crtc *c;
2740         struct drm_i915_gem_object *obj;
2741         struct drm_plane *primary = intel_crtc->base.primary;
2742         struct drm_plane_state *plane_state = primary->state;
2743         struct drm_crtc_state *crtc_state = intel_crtc->base.state;
2744         struct intel_plane *intel_plane = to_intel_plane(primary);
2745         struct intel_plane_state *intel_state =
2746                 to_intel_plane_state(plane_state);
2747         struct drm_framebuffer *fb;
2748
2749         if (!plane_config->fb)
2750                 return;
2751
2752         if (intel_alloc_initial_plane_obj(intel_crtc, plane_config)) {
2753                 fb = &plane_config->fb->base;
2754                 goto valid_fb;
2755         }
2756
2757         kfree(plane_config->fb);
2758
2759         /*
2760          * Failed to alloc the obj, check to see if we should share
2761          * an fb with another CRTC instead
2762          */
2763         for_each_crtc(dev, c) {
2764                 struct intel_plane_state *state;
2765
2766                 if (c == &intel_crtc->base)
2767                         continue;
2768
2769                 if (!to_intel_crtc(c)->active)
2770                         continue;
2771
2772                 state = to_intel_plane_state(c->primary->state);
2773                 if (!state->vma)
2774                         continue;
2775
2776                 if (intel_plane_ggtt_offset(state) == plane_config->base) {
2777                         fb = c->primary->fb;
2778                         drm_framebuffer_get(fb);
2779                         goto valid_fb;
2780                 }
2781         }
2782
2783         /*
2784          * We've failed to reconstruct the BIOS FB.  Current display state
2785          * indicates that the primary plane is visible, but has a NULL FB,
2786          * which will lead to problems later if we don't fix it up.  The
2787          * simplest solution is to just disable the primary plane now and
2788          * pretend the BIOS never had it enabled.
2789          */
2790         intel_plane_disable_noatomic(intel_crtc, intel_plane);
2791
2792         return;
2793
2794 valid_fb:
2795         mutex_lock(&dev->struct_mutex);
2796         intel_state->vma =
2797                 intel_pin_and_fence_fb_obj(fb, primary->state->rotation);
2798         mutex_unlock(&dev->struct_mutex);
2799         if (IS_ERR(intel_state->vma)) {
2800                 DRM_ERROR("failed to pin boot fb on pipe %d: %li\n",
2801                           intel_crtc->pipe, PTR_ERR(intel_state->vma));
2802
2803                 intel_state->vma = NULL;
2804                 drm_framebuffer_put(fb);
2805                 return;
2806         }
2807
2808         plane_state->src_x = 0;
2809         plane_state->src_y = 0;
2810         plane_state->src_w = fb->width << 16;
2811         plane_state->src_h = fb->height << 16;
2812
2813         plane_state->crtc_x = 0;
2814         plane_state->crtc_y = 0;
2815         plane_state->crtc_w = fb->width;
2816         plane_state->crtc_h = fb->height;
2817
2818         intel_state->base.src = drm_plane_state_src(plane_state);
2819         intel_state->base.dst = drm_plane_state_dest(plane_state);
2820
2821         obj = intel_fb_obj(fb);
2822         if (i915_gem_object_is_tiled(obj))
2823                 dev_priv->preserve_bios_swizzle = true;
2824
2825         drm_framebuffer_get(fb);
2826         primary->fb = primary->state->fb = fb;
2827         primary->crtc = primary->state->crtc = &intel_crtc->base;
2828
2829         intel_set_plane_visible(to_intel_crtc_state(crtc_state),
2830                                 to_intel_plane_state(plane_state),
2831                                 true);
2832
2833         atomic_or(to_intel_plane(primary)->frontbuffer_bit,
2834                   &obj->frontbuffer_bits);
2835 }
2836
2837 static int skl_max_plane_width(const struct drm_framebuffer *fb, int plane,
2838                                unsigned int rotation)
2839 {
2840         int cpp = fb->format->cpp[plane];
2841
2842         switch (fb->modifier) {
2843         case DRM_FORMAT_MOD_LINEAR:
2844         case I915_FORMAT_MOD_X_TILED:
2845                 switch (cpp) {
2846                 case 8:
2847                         return 4096;
2848                 case 4:
2849                 case 2:
2850                 case 1:
2851                         return 8192;
2852                 default:
2853                         MISSING_CASE(cpp);
2854                         break;
2855                 }
2856                 break;
2857         case I915_FORMAT_MOD_Y_TILED_CCS:
2858         case I915_FORMAT_MOD_Yf_TILED_CCS:
2859                 /* FIXME AUX plane? */
2860         case I915_FORMAT_MOD_Y_TILED:
2861         case I915_FORMAT_MOD_Yf_TILED:
2862                 switch (cpp) {
2863                 case 8:
2864                         return 2048;
2865                 case 4:
2866                         return 4096;
2867                 case 2:
2868                 case 1:
2869                         return 8192;
2870                 default:
2871                         MISSING_CASE(cpp);
2872                         break;
2873                 }
2874                 break;
2875         default:
2876                 MISSING_CASE(fb->modifier);
2877         }
2878
2879         return 2048;
2880 }
2881
2882 static bool skl_check_main_ccs_coordinates(struct intel_plane_state *plane_state,
2883                                            int main_x, int main_y, u32 main_offset)
2884 {
2885         const struct drm_framebuffer *fb = plane_state->base.fb;
2886         int hsub = fb->format->hsub;
2887         int vsub = fb->format->vsub;
2888         int aux_x = plane_state->aux.x;
2889         int aux_y = plane_state->aux.y;
2890         u32 aux_offset = plane_state->aux.offset;
2891         u32 alignment = intel_surf_alignment(fb, 1);
2892
2893         while (aux_offset >= main_offset && aux_y <= main_y) {
2894                 int x, y;
2895
2896                 if (aux_x == main_x && aux_y == main_y)
2897                         break;
2898
2899                 if (aux_offset == 0)
2900                         break;
2901
2902                 x = aux_x / hsub;
2903                 y = aux_y / vsub;
2904                 aux_offset = intel_adjust_tile_offset(&x, &y, plane_state, 1,
2905                                                       aux_offset, aux_offset - alignment);
2906                 aux_x = x * hsub + aux_x % hsub;
2907                 aux_y = y * vsub + aux_y % vsub;
2908         }
2909
2910         if (aux_x != main_x || aux_y != main_y)
2911                 return false;
2912
2913         plane_state->aux.offset = aux_offset;
2914         plane_state->aux.x = aux_x;
2915         plane_state->aux.y = aux_y;
2916
2917         return true;
2918 }
2919
2920 static int skl_check_main_surface(struct intel_plane_state *plane_state)
2921 {
2922         const struct drm_framebuffer *fb = plane_state->base.fb;
2923         unsigned int rotation = plane_state->base.rotation;
2924         int x = plane_state->base.src.x1 >> 16;
2925         int y = plane_state->base.src.y1 >> 16;
2926         int w = drm_rect_width(&plane_state->base.src) >> 16;
2927         int h = drm_rect_height(&plane_state->base.src) >> 16;
2928         int max_width = skl_max_plane_width(fb, 0, rotation);
2929         int max_height = 4096;
2930         u32 alignment, offset, aux_offset = plane_state->aux.offset;
2931
2932         if (w > max_width || h > max_height) {
2933                 DRM_DEBUG_KMS("requested Y/RGB source size %dx%d too big (limit %dx%d)\n",
2934                               w, h, max_width, max_height);
2935                 return -EINVAL;
2936         }
2937
2938         intel_add_fb_offsets(&x, &y, plane_state, 0);
2939         offset = intel_compute_tile_offset(&x, &y, plane_state, 0);
2940         alignment = intel_surf_alignment(fb, 0);
2941
2942         /*
2943          * AUX surface offset is specified as the distance from the
2944          * main surface offset, and it must be non-negative. Make
2945          * sure that is what we will get.
2946          */
2947         if (offset > aux_offset)
2948                 offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2949                                                   offset, aux_offset & ~(alignment - 1));
2950
2951         /*
2952          * When using an X-tiled surface, the plane blows up
2953          * if the x offset + width exceed the stride.
2954          *
2955          * TODO: linear and Y-tiled seem fine, Yf untested,
2956          */
2957         if (fb->modifier == I915_FORMAT_MOD_X_TILED) {
2958                 int cpp = fb->format->cpp[0];
2959
2960                 while ((x + w) * cpp > fb->pitches[0]) {
2961                         if (offset == 0) {
2962                                 DRM_DEBUG_KMS("Unable to find suitable display surface offset due to X-tiling\n");
2963                                 return -EINVAL;
2964                         }
2965
2966                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2967                                                           offset, offset - alignment);
2968                 }
2969         }
2970
2971         /*
2972          * CCS AUX surface doesn't have its own x/y offsets, we must make sure
2973          * they match with the main surface x/y offsets.
2974          */
2975         if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
2976             fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
2977                 while (!skl_check_main_ccs_coordinates(plane_state, x, y, offset)) {
2978                         if (offset == 0)
2979                                 break;
2980
2981                         offset = intel_adjust_tile_offset(&x, &y, plane_state, 0,
2982                                                           offset, offset - alignment);
2983                 }
2984
2985                 if (x != plane_state->aux.x || y != plane_state->aux.y) {
2986                         DRM_DEBUG_KMS("Unable to find suitable display surface offset due to CCS\n");
2987                         return -EINVAL;
2988                 }
2989         }
2990
2991         plane_state->main.offset = offset;
2992         plane_state->main.x = x;
2993         plane_state->main.y = y;
2994
2995         return 0;
2996 }
2997
2998 static int skl_check_nv12_aux_surface(struct intel_plane_state *plane_state)
2999 {
3000         const struct drm_framebuffer *fb = plane_state->base.fb;
3001         unsigned int rotation = plane_state->base.rotation;
3002         int max_width = skl_max_plane_width(fb, 1, rotation);
3003         int max_height = 4096;
3004         int x = plane_state->base.src.x1 >> 17;
3005         int y = plane_state->base.src.y1 >> 17;
3006         int w = drm_rect_width(&plane_state->base.src) >> 17;
3007         int h = drm_rect_height(&plane_state->base.src) >> 17;
3008         u32 offset;
3009
3010         intel_add_fb_offsets(&x, &y, plane_state, 1);
3011         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3012
3013         /* FIXME not quite sure how/if these apply to the chroma plane */
3014         if (w > max_width || h > max_height) {
3015                 DRM_DEBUG_KMS("CbCr source size %dx%d too big (limit %dx%d)\n",
3016                               w, h, max_width, max_height);
3017                 return -EINVAL;
3018         }
3019
3020         plane_state->aux.offset = offset;
3021         plane_state->aux.x = x;
3022         plane_state->aux.y = y;
3023
3024         return 0;
3025 }
3026
3027 static int skl_check_ccs_aux_surface(struct intel_plane_state *plane_state)
3028 {
3029         struct intel_plane *plane = to_intel_plane(plane_state->base.plane);
3030         struct intel_crtc *crtc = to_intel_crtc(plane_state->base.crtc);
3031         const struct drm_framebuffer *fb = plane_state->base.fb;
3032         int src_x = plane_state->base.src.x1 >> 16;
3033         int src_y = plane_state->base.src.y1 >> 16;
3034         int hsub = fb->format->hsub;
3035         int vsub = fb->format->vsub;
3036         int x = src_x / hsub;
3037         int y = src_y / vsub;
3038         u32 offset;
3039
3040         switch (plane->id) {
3041         case PLANE_PRIMARY:
3042         case PLANE_SPRITE0:
3043                 break;
3044         default:
3045                 DRM_DEBUG_KMS("RC support only on plane 1 and 2\n");
3046                 return -EINVAL;
3047         }
3048
3049         if (crtc->pipe == PIPE_C) {
3050                 DRM_DEBUG_KMS("No RC support on pipe C\n");
3051                 return -EINVAL;
3052         }
3053
3054         if (plane_state->base.rotation & ~(DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180)) {
3055                 DRM_DEBUG_KMS("RC support only with 0/180 degree rotation %x\n",
3056                               plane_state->base.rotation);
3057                 return -EINVAL;
3058         }
3059
3060         intel_add_fb_offsets(&x, &y, plane_state, 1);
3061         offset = intel_compute_tile_offset(&x, &y, plane_state, 1);
3062
3063         plane_state->aux.offset = offset;
3064         plane_state->aux.x = x * hsub + src_x % hsub;
3065         plane_state->aux.y = y * vsub + src_y % vsub;
3066
3067         return 0;
3068 }
3069
3070 int skl_check_plane_surface(struct intel_plane_state *plane_state)
3071 {
3072         const struct drm_framebuffer *fb = plane_state->base.fb;
3073         unsigned int rotation = plane_state->base.rotation;
3074         int ret;
3075
3076         if (rotation & DRM_MODE_REFLECT_X &&
3077             fb->modifier == DRM_FORMAT_MOD_LINEAR) {
3078                 DRM_DEBUG_KMS("horizontal flip is not supported with linear surface formats\n");
3079                 return -EINVAL;
3080         }
3081
3082         if (!plane_state->base.visible)
3083                 return 0;
3084
3085         /* Rotate src coordinates to match rotated GTT view */
3086         if (drm_rotation_90_or_270(rotation))
3087                 drm_rect_rotate(&plane_state->base.src,
3088                                 fb->width << 16, fb->height << 16,
3089                                 DRM_MODE_ROTATE_270);
3090
3091         /*
3092          * Handle the AUX surface first since
3093          * the main surface setup depends on it.
3094          */
3095         if (fb->format->format == DRM_FORMAT_NV12) {
3096                 ret = skl_check_nv12_aux_surface(plane_state);
3097                 if (ret)
3098                         return ret;
3099         } else if (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
3100                    fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS) {
3101                 ret = skl_check_ccs_aux_surface(plane_state);
3102                 if (ret)
3103                         return ret;
3104         } else {
3105                 plane_state->aux.offset = ~0xfff;
3106                 plane_state->aux.x = 0;
3107                 plane_state->aux.y = 0;
3108         }
3109
3110         ret = skl_check_main_surface(plane_state);
3111         if (ret)
3112                 return ret;
3113
3114         return 0;
3115 }
3116
3117 static u32 i9xx_plane_ctl(const struct intel_crtc_state *crtc_state,
3118                           const struct intel_plane_state *plane_state)
3119 {
3120         struct drm_i915_private *dev_priv =
3121                 to_i915(plane_state->base.plane->dev);
3122         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
3123         const struct drm_framebuffer *fb = plane_state->base.fb;
3124         unsigned int rotation = plane_state->base.rotation;
3125         u32 dspcntr;
3126
3127         dspcntr = DISPLAY_PLANE_ENABLE | DISPPLANE_GAMMA_ENABLE;
3128
3129         if (IS_G4X(dev_priv) || IS_GEN5(dev_priv) ||
3130             IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv))
3131                 dspcntr |= DISPPLANE_TRICKLE_FEED_DISABLE;
3132
3133         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
3134                 dspcntr |= DISPPLANE_PIPE_CSC_ENABLE;
3135
3136         if (INTEL_GEN(dev_priv) < 4)
3137                 dspcntr |= DISPPLANE_SEL_PIPE(crtc->pipe);
3138
3139         switch (fb->format->format) {
3140         case DRM_FORMAT_C8:
3141                 dspcntr |= DISPPLANE_8BPP;
3142                 break;
3143         case DRM_FORMAT_XRGB1555:
3144                 dspcntr |= DISPPLANE_BGRX555;
3145                 break;
3146         case DRM_FORMAT_RGB565:
3147                 dspcntr |= DISPPLANE_BGRX565;
3148                 break;
3149         case DRM_FORMAT_XRGB8888:
3150                 dspcntr |= DISPPLANE_BGRX888;
3151                 break;
3152         case DRM_FORMAT_XBGR8888:
3153                 dspcntr |= DISPPLANE_RGBX888;
3154                 break;
3155         case DRM_FORMAT_XRGB2101010:
3156                 dspcntr |= DISPPLANE_BGRX101010;
3157                 break;
3158         case DRM_FORMAT_XBGR2101010:
3159                 dspcntr |= DISPPLANE_RGBX101010;
3160                 break;
3161         default:
3162                 MISSING_CASE(fb->format->format);
3163                 return 0;
3164         }
3165
3166         if (INTEL_GEN(dev_priv) >= 4 &&
3167             fb->modifier == I915_FORMAT_MOD_X_TILED)
3168                 dspcntr |= DISPPLANE_TILED;
3169
3170         if (rotation & DRM_MODE_ROTATE_180)
3171                 dspcntr |= DISPPLANE_ROTATE_180;
3172
3173         if (rotation & DRM_MODE_REFLECT_X)
3174                 dspcntr |= DISPPLANE_MIRROR;
3175
3176         return dspcntr;
3177 }
3178
3179 int i9xx_check_plane_surface(struct intel_plane_state *plane_state)
3180 {
3181         struct drm_i915_private *dev_priv =
3182                 to_i915(plane_state->base.plane->dev);
3183         int src_x = plane_state->base.src.x1 >> 16;
3184         int src_y = plane_state->base.src.y1 >> 16;
3185         u32 offset;
3186
3187         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
3188
3189         if (INTEL_GEN(dev_priv) >= 4)
3190                 offset = intel_compute_tile_offset(&src_x, &src_y,
3191                                                    plane_state, 0);
3192         else
3193                 offset = 0;
3194
3195         /* HSW/BDW do this automagically in hardware */
3196         if (!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv)) {
3197                 unsigned int rotation = plane_state->base.rotation;
3198                 int src_w = drm_rect_width(&plane_state->base.src) >> 16;
3199                 int src_h = drm_rect_height(&plane_state->base.src) >> 16;
3200
3201                 if (rotation & DRM_MODE_ROTATE_180) {
3202                         src_x += src_w - 1;
3203                         src_y += src_h - 1;
3204                 } else if (rotation & DRM_MODE_REFLECT_X) {
3205                         src_x += src_w - 1;
3206                 }
3207         }
3208
3209         plane_state->main.offset = offset;
3210         plane_state->main.x = src_x;
3211         plane_state->main.y = src_y;
3212
3213         return 0;
3214 }
3215
3216 static void i9xx_update_plane(struct intel_plane *plane,
3217                               const struct intel_crtc_state *crtc_state,
3218                               const struct intel_plane_state *plane_state)
3219 {
3220         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3221         const struct drm_framebuffer *fb = plane_state->base.fb;
3222         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3223         u32 linear_offset;
3224         u32 dspcntr = plane_state->ctl;
3225         i915_reg_t reg = DSPCNTR(i9xx_plane);
3226         int x = plane_state->main.x;
3227         int y = plane_state->main.y;
3228         unsigned long irqflags;
3229         u32 dspaddr_offset;
3230
3231         linear_offset = intel_fb_xy_to_linear(x, y, plane_state, 0);
3232
3233         if (INTEL_GEN(dev_priv) >= 4)
3234                 dspaddr_offset = plane_state->main.offset;
3235         else
3236                 dspaddr_offset = linear_offset;
3237
3238         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3239
3240         if (INTEL_GEN(dev_priv) < 4) {
3241                 /* pipesrc and dspsize control the size that is scaled from,
3242                  * which should always be the user's requested size.
3243                  */
3244                 I915_WRITE_FW(DSPSIZE(i9xx_plane),
3245                               ((crtc_state->pipe_src_h - 1) << 16) |
3246                               (crtc_state->pipe_src_w - 1));
3247                 I915_WRITE_FW(DSPPOS(i9xx_plane), 0);
3248         } else if (IS_CHERRYVIEW(dev_priv) && i9xx_plane == PLANE_B) {
3249                 I915_WRITE_FW(PRIMSIZE(i9xx_plane),
3250                               ((crtc_state->pipe_src_h - 1) << 16) |
3251                               (crtc_state->pipe_src_w - 1));
3252                 I915_WRITE_FW(PRIMPOS(i9xx_plane), 0);
3253                 I915_WRITE_FW(PRIMCNSTALPHA(i9xx_plane), 0);
3254         }
3255
3256         I915_WRITE_FW(reg, dspcntr);
3257
3258         I915_WRITE_FW(DSPSTRIDE(i9xx_plane), fb->pitches[0]);
3259         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3260                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3261                               intel_plane_ggtt_offset(plane_state) +
3262                               dspaddr_offset);
3263                 I915_WRITE_FW(DSPOFFSET(i9xx_plane), (y << 16) | x);
3264         } else if (INTEL_GEN(dev_priv) >= 4) {
3265                 I915_WRITE_FW(DSPSURF(i9xx_plane),
3266                               intel_plane_ggtt_offset(plane_state) +
3267                               dspaddr_offset);
3268                 I915_WRITE_FW(DSPTILEOFF(i9xx_plane), (y << 16) | x);
3269                 I915_WRITE_FW(DSPLINOFF(i9xx_plane), linear_offset);
3270         } else {
3271                 I915_WRITE_FW(DSPADDR(i9xx_plane),
3272                               intel_plane_ggtt_offset(plane_state) +
3273                               dspaddr_offset);
3274         }
3275         POSTING_READ_FW(reg);
3276
3277         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3278 }
3279
3280 static void i9xx_disable_plane(struct intel_plane *plane,
3281                                struct intel_crtc *crtc)
3282 {
3283         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3284         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3285         unsigned long irqflags;
3286
3287         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
3288
3289         I915_WRITE_FW(DSPCNTR(i9xx_plane), 0);
3290         if (INTEL_GEN(dev_priv) >= 4)
3291                 I915_WRITE_FW(DSPSURF(i9xx_plane), 0);
3292         else
3293                 I915_WRITE_FW(DSPADDR(i9xx_plane), 0);
3294         POSTING_READ_FW(DSPCNTR(i9xx_plane));
3295
3296         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
3297 }
3298
3299 static bool i9xx_plane_get_hw_state(struct intel_plane *plane)
3300 {
3301         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
3302         enum intel_display_power_domain power_domain;
3303         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
3304         enum pipe pipe = plane->pipe;
3305         bool ret;
3306
3307         /*
3308          * Not 100% correct for planes that can move between pipes,
3309          * but that's only the case for gen2-4 which don't have any
3310          * display power wells.
3311          */
3312         power_domain = POWER_DOMAIN_PIPE(pipe);
3313         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
3314                 return false;
3315
3316         ret = I915_READ(DSPCNTR(i9xx_plane)) & DISPLAY_PLANE_ENABLE;
3317
3318         intel_display_power_put(dev_priv, power_domain);
3319
3320         return ret;
3321 }
3322
3323 static u32
3324 intel_fb_stride_alignment(const struct drm_framebuffer *fb, int plane)
3325 {
3326         if (fb->modifier == DRM_FORMAT_MOD_LINEAR)
3327                 return 64;
3328         else
3329                 return intel_tile_width_bytes(fb, plane);
3330 }
3331
3332 static void skl_detach_scaler(struct intel_crtc *intel_crtc, int id)
3333 {
3334         struct drm_device *dev = intel_crtc->base.dev;
3335         struct drm_i915_private *dev_priv = to_i915(dev);
3336
3337         I915_WRITE(SKL_PS_CTRL(intel_crtc->pipe, id), 0);
3338         I915_WRITE(SKL_PS_WIN_POS(intel_crtc->pipe, id), 0);
3339         I915_WRITE(SKL_PS_WIN_SZ(intel_crtc->pipe, id), 0);
3340 }
3341
3342 /*
3343  * This function detaches (aka. unbinds) unused scalers in hardware
3344  */
3345 static void skl_detach_scalers(struct intel_crtc *intel_crtc)
3346 {
3347         struct intel_crtc_scaler_state *scaler_state;
3348         int i;
3349
3350         scaler_state = &intel_crtc->config->scaler_state;
3351
3352         /* loop through and disable scalers that aren't in use */
3353         for (i = 0; i < intel_crtc->num_scalers; i++) {
3354                 if (!scaler_state->scalers[i].in_use)
3355                         skl_detach_scaler(intel_crtc, i);
3356         }
3357 }
3358
3359 u32 skl_plane_stride(const struct drm_framebuffer *fb, int plane,
3360                      unsigned int rotation)
3361 {
3362         u32 stride;
3363
3364         if (plane >= fb->format->num_planes)
3365                 return 0;
3366
3367         stride = intel_fb_pitch(fb, plane, rotation);
3368
3369         /*
3370          * The stride is either expressed as a multiple of 64 bytes chunks for
3371          * linear buffers or in number of tiles for tiled buffers.
3372          */
3373         if (drm_rotation_90_or_270(rotation))
3374                 stride /= intel_tile_height(fb, plane);
3375         else
3376                 stride /= intel_fb_stride_alignment(fb, plane);
3377
3378         return stride;
3379 }
3380
3381 static u32 skl_plane_ctl_format(uint32_t pixel_format)
3382 {
3383         switch (pixel_format) {
3384         case DRM_FORMAT_C8:
3385                 return PLANE_CTL_FORMAT_INDEXED;
3386         case DRM_FORMAT_RGB565:
3387                 return PLANE_CTL_FORMAT_RGB_565;
3388         case DRM_FORMAT_XBGR8888:
3389         case DRM_FORMAT_ABGR8888:
3390                 return PLANE_CTL_FORMAT_XRGB_8888 | PLANE_CTL_ORDER_RGBX;
3391         case DRM_FORMAT_XRGB8888:
3392         case DRM_FORMAT_ARGB8888:
3393                 return PLANE_CTL_FORMAT_XRGB_8888;
3394         case DRM_FORMAT_XRGB2101010:
3395                 return PLANE_CTL_FORMAT_XRGB_2101010;
3396         case DRM_FORMAT_XBGR2101010:
3397                 return PLANE_CTL_ORDER_RGBX | PLANE_CTL_FORMAT_XRGB_2101010;
3398         case DRM_FORMAT_YUYV:
3399                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YUYV;
3400         case DRM_FORMAT_YVYU:
3401                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_YVYU;
3402         case DRM_FORMAT_UYVY:
3403                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_UYVY;
3404         case DRM_FORMAT_VYUY:
3405                 return PLANE_CTL_FORMAT_YUV422 | PLANE_CTL_YUV422_VYUY;
3406         default:
3407                 MISSING_CASE(pixel_format);
3408         }
3409
3410         return 0;
3411 }
3412
3413 /*
3414  * XXX: For ARBG/ABGR formats we default to expecting scanout buffers
3415  * to be already pre-multiplied. We need to add a knob (or a different
3416  * DRM_FORMAT) for user-space to configure that.
3417  */
3418 static u32 skl_plane_ctl_alpha(uint32_t pixel_format)
3419 {
3420         switch (pixel_format) {
3421         case DRM_FORMAT_ABGR8888:
3422         case DRM_FORMAT_ARGB8888:
3423                 return PLANE_CTL_ALPHA_SW_PREMULTIPLY;
3424         default:
3425                 return PLANE_CTL_ALPHA_DISABLE;
3426         }
3427 }
3428
3429 static u32 glk_plane_color_ctl_alpha(uint32_t pixel_format)
3430 {
3431         switch (pixel_format) {
3432         case DRM_FORMAT_ABGR8888:
3433         case DRM_FORMAT_ARGB8888:
3434                 return PLANE_COLOR_ALPHA_SW_PREMULTIPLY;
3435         default:
3436                 return PLANE_COLOR_ALPHA_DISABLE;
3437         }
3438 }
3439
3440 static u32 skl_plane_ctl_tiling(uint64_t fb_modifier)
3441 {
3442         switch (fb_modifier) {
3443         case DRM_FORMAT_MOD_LINEAR:
3444                 break;
3445         case I915_FORMAT_MOD_X_TILED:
3446                 return PLANE_CTL_TILED_X;
3447         case I915_FORMAT_MOD_Y_TILED:
3448                 return PLANE_CTL_TILED_Y;
3449         case I915_FORMAT_MOD_Y_TILED_CCS:
3450                 return PLANE_CTL_TILED_Y | PLANE_CTL_DECOMPRESSION_ENABLE;
3451         case I915_FORMAT_MOD_Yf_TILED:
3452                 return PLANE_CTL_TILED_YF;
3453         case I915_FORMAT_MOD_Yf_TILED_CCS:
3454                 return PLANE_CTL_TILED_YF | PLANE_CTL_DECOMPRESSION_ENABLE;
3455         default:
3456                 MISSING_CASE(fb_modifier);
3457         }
3458
3459         return 0;
3460 }
3461
3462 static u32 skl_plane_ctl_rotate(unsigned int rotate)
3463 {
3464         switch (rotate) {
3465         case DRM_MODE_ROTATE_0:
3466                 break;
3467         /*
3468          * DRM_MODE_ROTATE_ is counter clockwise to stay compatible with Xrandr
3469          * while i915 HW rotation is clockwise, thats why this swapping.
3470          */
3471         case DRM_MODE_ROTATE_90:
3472                 return PLANE_CTL_ROTATE_270;
3473         case DRM_MODE_ROTATE_180:
3474                 return PLANE_CTL_ROTATE_180;
3475         case DRM_MODE_ROTATE_270:
3476                 return PLANE_CTL_ROTATE_90;
3477         default:
3478                 MISSING_CASE(rotate);
3479         }
3480
3481         return 0;
3482 }
3483
3484 static u32 cnl_plane_ctl_flip(unsigned int reflect)
3485 {
3486         switch (reflect) {
3487         case 0:
3488                 break;
3489         case DRM_MODE_REFLECT_X:
3490                 return PLANE_CTL_FLIP_HORIZONTAL;
3491         case DRM_MODE_REFLECT_Y:
3492         default:
3493                 MISSING_CASE(reflect);
3494         }
3495
3496         return 0;
3497 }
3498
3499 u32 skl_plane_ctl(const struct intel_crtc_state *crtc_state,
3500                   const struct intel_plane_state *plane_state)
3501 {
3502         struct drm_i915_private *dev_priv =
3503                 to_i915(plane_state->base.plane->dev);
3504         const struct drm_framebuffer *fb = plane_state->base.fb;
3505         unsigned int rotation = plane_state->base.rotation;
3506         const struct drm_intel_sprite_colorkey *key = &plane_state->ckey;
3507         u32 plane_ctl;
3508
3509         plane_ctl = PLANE_CTL_ENABLE;
3510
3511         if (INTEL_GEN(dev_priv) < 10 && !IS_GEMINILAKE(dev_priv)) {
3512                 plane_ctl |= skl_plane_ctl_alpha(fb->format->format);
3513                 plane_ctl |=
3514                         PLANE_CTL_PIPE_GAMMA_ENABLE |
3515                         PLANE_CTL_PIPE_CSC_ENABLE |
3516                         PLANE_CTL_PLANE_GAMMA_DISABLE;
3517         }
3518
3519         plane_ctl |= skl_plane_ctl_format(fb->format->format);
3520         plane_ctl |= skl_plane_ctl_tiling(fb->modifier);
3521         plane_ctl |= skl_plane_ctl_rotate(rotation & DRM_MODE_ROTATE_MASK);
3522
3523         if (INTEL_GEN(dev_priv) >= 10)
3524                 plane_ctl |= cnl_plane_ctl_flip(rotation &
3525                                                 DRM_MODE_REFLECT_MASK);
3526
3527         if (key->flags & I915_SET_COLORKEY_DESTINATION)
3528                 plane_ctl |= PLANE_CTL_KEY_ENABLE_DESTINATION;
3529         else if (key->flags & I915_SET_COLORKEY_SOURCE)
3530                 plane_ctl |= PLANE_CTL_KEY_ENABLE_SOURCE;
3531
3532         return plane_ctl;
3533 }
3534
3535 u32 glk_plane_color_ctl(const struct intel_crtc_state *crtc_state,
3536                         const struct intel_plane_state *plane_state)
3537 {
3538         const struct drm_framebuffer *fb = plane_state->base.fb;
3539         u32 plane_color_ctl = 0;
3540
3541         plane_color_ctl |= PLANE_COLOR_PIPE_GAMMA_ENABLE;
3542         plane_color_ctl |= PLANE_COLOR_PIPE_CSC_ENABLE;
3543         plane_color_ctl |= PLANE_COLOR_PLANE_GAMMA_DISABLE;
3544         plane_color_ctl |= glk_plane_color_ctl_alpha(fb->format->format);
3545
3546         return plane_color_ctl;
3547 }
3548
3549 static int
3550 __intel_display_resume(struct drm_device *dev,
3551                        struct drm_atomic_state *state,
3552                        struct drm_modeset_acquire_ctx *ctx)
3553 {
3554         struct drm_crtc_state *crtc_state;
3555         struct drm_crtc *crtc;
3556         int i, ret;
3557
3558         intel_modeset_setup_hw_state(dev, ctx);
3559         i915_redisable_vga(to_i915(dev));
3560
3561         if (!state)
3562                 return 0;
3563
3564         /*
3565          * We've duplicated the state, pointers to the old state are invalid.
3566          *
3567          * Don't attempt to use the old state until we commit the duplicated state.
3568          */
3569         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
3570                 /*
3571                  * Force recalculation even if we restore
3572                  * current state. With fast modeset this may not result
3573                  * in a modeset when the state is compatible.
3574                  */
3575                 crtc_state->mode_changed = true;
3576         }
3577
3578         /* ignore any reset values/BIOS leftovers in the WM registers */
3579         if (!HAS_GMCH_DISPLAY(to_i915(dev)))
3580                 to_intel_atomic_state(state)->skip_intermediate_wm = true;
3581
3582         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
3583
3584         WARN_ON(ret == -EDEADLK);
3585         return ret;
3586 }
3587
3588 static bool gpu_reset_clobbers_display(struct drm_i915_private *dev_priv)
3589 {
3590         return intel_has_gpu_reset(dev_priv) &&
3591                 INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv);
3592 }
3593
3594 void intel_prepare_reset(struct drm_i915_private *dev_priv)
3595 {
3596         struct drm_device *dev = &dev_priv->drm;
3597         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3598         struct drm_atomic_state *state;
3599         int ret;
3600
3601
3602         /* reset doesn't touch the display */
3603         if (!i915_modparams.force_reset_modeset_test &&
3604             !gpu_reset_clobbers_display(dev_priv))
3605                 return;
3606
3607         /* We have a modeset vs reset deadlock, defensively unbreak it. */
3608         set_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3609         wake_up_all(&dev_priv->gpu_error.wait_queue);
3610
3611         if (atomic_read(&dev_priv->gpu_error.pending_fb_pin)) {
3612                 DRM_DEBUG_KMS("Modeset potentially stuck, unbreaking through wedging\n");
3613                 i915_gem_set_wedged(dev_priv);
3614         }
3615
3616         /*
3617          * Need mode_config.mutex so that we don't
3618          * trample ongoing ->detect() and whatnot.
3619          */
3620         mutex_lock(&dev->mode_config.mutex);
3621         drm_modeset_acquire_init(ctx, 0);
3622         while (1) {
3623                 ret = drm_modeset_lock_all_ctx(dev, ctx);
3624                 if (ret != -EDEADLK)
3625                         break;
3626
3627                 drm_modeset_backoff(ctx);
3628         }
3629         /*
3630          * Disabling the crtcs gracefully seems nicer. Also the
3631          * g33 docs say we should at least disable all the planes.
3632          */
3633         state = drm_atomic_helper_duplicate_state(dev, ctx);
3634         if (IS_ERR(state)) {
3635                 ret = PTR_ERR(state);
3636                 DRM_ERROR("Duplicating state failed with %i\n", ret);
3637                 return;
3638         }
3639
3640         ret = drm_atomic_helper_disable_all(dev, ctx);
3641         if (ret) {
3642                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
3643                 drm_atomic_state_put(state);
3644                 return;
3645         }
3646
3647         dev_priv->modeset_restore_state = state;
3648         state->acquire_ctx = ctx;
3649 }
3650
3651 void intel_finish_reset(struct drm_i915_private *dev_priv)
3652 {
3653         struct drm_device *dev = &dev_priv->drm;
3654         struct drm_modeset_acquire_ctx *ctx = &dev_priv->reset_ctx;
3655         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
3656         int ret;
3657
3658         /* reset doesn't touch the display */
3659         if (!i915_modparams.force_reset_modeset_test &&
3660             !gpu_reset_clobbers_display(dev_priv))
3661                 return;
3662
3663         if (!state)
3664                 goto unlock;
3665
3666         dev_priv->modeset_restore_state = NULL;
3667
3668         /* reset doesn't touch the display */
3669         if (!gpu_reset_clobbers_display(dev_priv)) {
3670                 /* for testing only restore the display */
3671                 ret = __intel_display_resume(dev, state, ctx);
3672                 if (ret)
3673                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3674         } else {
3675                 /*
3676                  * The display has been reset as well,
3677                  * so need a full re-initialization.
3678                  */
3679                 intel_runtime_pm_disable_interrupts(dev_priv);
3680                 intel_runtime_pm_enable_interrupts(dev_priv);
3681
3682                 intel_pps_unlock_regs_wa(dev_priv);
3683                 intel_modeset_init_hw(dev);
3684                 intel_init_clock_gating(dev_priv);
3685
3686                 spin_lock_irq(&dev_priv->irq_lock);
3687                 if (dev_priv->display.hpd_irq_setup)
3688                         dev_priv->display.hpd_irq_setup(dev_priv);
3689                 spin_unlock_irq(&dev_priv->irq_lock);
3690
3691                 ret = __intel_display_resume(dev, state, ctx);
3692                 if (ret)
3693                         DRM_ERROR("Restoring old state failed with %i\n", ret);
3694
3695                 intel_hpd_init(dev_priv);
3696         }
3697
3698         drm_atomic_state_put(state);
3699 unlock:
3700         drm_modeset_drop_locks(ctx);
3701         drm_modeset_acquire_fini(ctx);
3702         mutex_unlock(&dev->mode_config.mutex);
3703
3704         clear_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags);
3705 }
3706
3707 static void intel_update_pipe_config(const struct intel_crtc_state *old_crtc_state,
3708                                      const struct intel_crtc_state *new_crtc_state)
3709 {
3710         struct intel_crtc *crtc = to_intel_crtc(new_crtc_state->base.crtc);
3711         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3712
3713         /* drm_atomic_helper_update_legacy_modeset_state might not be called. */
3714         crtc->base.mode = new_crtc_state->base.mode;
3715
3716         /*
3717          * Update pipe size and adjust fitter if needed: the reason for this is
3718          * that in compute_mode_changes we check the native mode (not the pfit
3719          * mode) to see if we can flip rather than do a full mode set. In the
3720          * fastboot case, we'll flip, but if we don't update the pipesrc and
3721          * pfit state, we'll end up with a big fb scanned out into the wrong
3722          * sized surface.
3723          */
3724
3725         I915_WRITE(PIPESRC(crtc->pipe),
3726                    ((new_crtc_state->pipe_src_w - 1) << 16) |
3727                    (new_crtc_state->pipe_src_h - 1));
3728
3729         /* on skylake this is done by detaching scalers */
3730         if (INTEL_GEN(dev_priv) >= 9) {
3731                 skl_detach_scalers(crtc);
3732
3733                 if (new_crtc_state->pch_pfit.enabled)
3734                         skylake_pfit_enable(crtc);
3735         } else if (HAS_PCH_SPLIT(dev_priv)) {
3736                 if (new_crtc_state->pch_pfit.enabled)
3737                         ironlake_pfit_enable(crtc);
3738                 else if (old_crtc_state->pch_pfit.enabled)
3739                         ironlake_pfit_disable(crtc, true);
3740         }
3741 }
3742
3743 static void intel_fdi_normal_train(struct intel_crtc *crtc)
3744 {
3745         struct drm_device *dev = crtc->base.dev;
3746         struct drm_i915_private *dev_priv = to_i915(dev);
3747         int pipe = crtc->pipe;
3748         i915_reg_t reg;
3749         u32 temp;
3750
3751         /* enable normal train */
3752         reg = FDI_TX_CTL(pipe);
3753         temp = I915_READ(reg);
3754         if (IS_IVYBRIDGE(dev_priv)) {
3755                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
3756                 temp |= FDI_LINK_TRAIN_NONE_IVB | FDI_TX_ENHANCE_FRAME_ENABLE;
3757         } else {
3758                 temp &= ~FDI_LINK_TRAIN_NONE;
3759                 temp |= FDI_LINK_TRAIN_NONE | FDI_TX_ENHANCE_FRAME_ENABLE;
3760         }
3761         I915_WRITE(reg, temp);
3762
3763         reg = FDI_RX_CTL(pipe);
3764         temp = I915_READ(reg);
3765         if (HAS_PCH_CPT(dev_priv)) {
3766                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3767                 temp |= FDI_LINK_TRAIN_NORMAL_CPT;
3768         } else {
3769                 temp &= ~FDI_LINK_TRAIN_NONE;
3770                 temp |= FDI_LINK_TRAIN_NONE;
3771         }
3772         I915_WRITE(reg, temp | FDI_RX_ENHANCE_FRAME_ENABLE);
3773
3774         /* wait one idle pattern time */
3775         POSTING_READ(reg);
3776         udelay(1000);
3777
3778         /* IVB wants error correction enabled */
3779         if (IS_IVYBRIDGE(dev_priv))
3780                 I915_WRITE(reg, I915_READ(reg) | FDI_FS_ERRC_ENABLE |
3781                            FDI_FE_ERRC_ENABLE);
3782 }
3783
3784 /* The FDI link training functions for ILK/Ibexpeak. */
3785 static void ironlake_fdi_link_train(struct intel_crtc *crtc,
3786                                     const struct intel_crtc_state *crtc_state)
3787 {
3788         struct drm_device *dev = crtc->base.dev;
3789         struct drm_i915_private *dev_priv = to_i915(dev);
3790         int pipe = crtc->pipe;
3791         i915_reg_t reg;
3792         u32 temp, tries;
3793
3794         /* FDI needs bits from pipe first */
3795         assert_pipe_enabled(dev_priv, pipe);
3796
3797         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3798            for train result */
3799         reg = FDI_RX_IMR(pipe);
3800         temp = I915_READ(reg);
3801         temp &= ~FDI_RX_SYMBOL_LOCK;
3802         temp &= ~FDI_RX_BIT_LOCK;
3803         I915_WRITE(reg, temp);
3804         I915_READ(reg);
3805         udelay(150);
3806
3807         /* enable CPU FDI TX and PCH FDI RX */
3808         reg = FDI_TX_CTL(pipe);
3809         temp = I915_READ(reg);
3810         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3811         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3812         temp &= ~FDI_LINK_TRAIN_NONE;
3813         temp |= FDI_LINK_TRAIN_PATTERN_1;
3814         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3815
3816         reg = FDI_RX_CTL(pipe);
3817         temp = I915_READ(reg);
3818         temp &= ~FDI_LINK_TRAIN_NONE;
3819         temp |= FDI_LINK_TRAIN_PATTERN_1;
3820         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3821
3822         POSTING_READ(reg);
3823         udelay(150);
3824
3825         /* Ironlake workaround, enable clock pointer after FDI enable*/
3826         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
3827         I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR |
3828                    FDI_RX_PHASE_SYNC_POINTER_EN);
3829
3830         reg = FDI_RX_IIR(pipe);
3831         for (tries = 0; tries < 5; tries++) {
3832                 temp = I915_READ(reg);
3833                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3834
3835                 if ((temp & FDI_RX_BIT_LOCK)) {
3836                         DRM_DEBUG_KMS("FDI train 1 done.\n");
3837                         I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3838                         break;
3839                 }
3840         }
3841         if (tries == 5)
3842                 DRM_ERROR("FDI train 1 fail!\n");
3843
3844         /* Train 2 */
3845         reg = FDI_TX_CTL(pipe);
3846         temp = I915_READ(reg);
3847         temp &= ~FDI_LINK_TRAIN_NONE;
3848         temp |= FDI_LINK_TRAIN_PATTERN_2;
3849         I915_WRITE(reg, temp);
3850
3851         reg = FDI_RX_CTL(pipe);
3852         temp = I915_READ(reg);
3853         temp &= ~FDI_LINK_TRAIN_NONE;
3854         temp |= FDI_LINK_TRAIN_PATTERN_2;
3855         I915_WRITE(reg, temp);
3856
3857         POSTING_READ(reg);
3858         udelay(150);
3859
3860         reg = FDI_RX_IIR(pipe);
3861         for (tries = 0; tries < 5; tries++) {
3862                 temp = I915_READ(reg);
3863                 DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3864
3865                 if (temp & FDI_RX_SYMBOL_LOCK) {
3866                         I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
3867                         DRM_DEBUG_KMS("FDI train 2 done.\n");
3868                         break;
3869                 }
3870         }
3871         if (tries == 5)
3872                 DRM_ERROR("FDI train 2 fail!\n");
3873
3874         DRM_DEBUG_KMS("FDI train done\n");
3875
3876 }
3877
3878 static const int snb_b_fdi_train_param[] = {
3879         FDI_LINK_TRAIN_400MV_0DB_SNB_B,
3880         FDI_LINK_TRAIN_400MV_6DB_SNB_B,
3881         FDI_LINK_TRAIN_600MV_3_5DB_SNB_B,
3882         FDI_LINK_TRAIN_800MV_0DB_SNB_B,
3883 };
3884
3885 /* The FDI link training functions for SNB/Cougarpoint. */
3886 static void gen6_fdi_link_train(struct intel_crtc *crtc,
3887                                 const struct intel_crtc_state *crtc_state)
3888 {
3889         struct drm_device *dev = crtc->base.dev;
3890         struct drm_i915_private *dev_priv = to_i915(dev);
3891         int pipe = crtc->pipe;
3892         i915_reg_t reg;
3893         u32 temp, i, retry;
3894
3895         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
3896            for train result */
3897         reg = FDI_RX_IMR(pipe);
3898         temp = I915_READ(reg);
3899         temp &= ~FDI_RX_SYMBOL_LOCK;
3900         temp &= ~FDI_RX_BIT_LOCK;
3901         I915_WRITE(reg, temp);
3902
3903         POSTING_READ(reg);
3904         udelay(150);
3905
3906         /* enable CPU FDI TX and PCH FDI RX */
3907         reg = FDI_TX_CTL(pipe);
3908         temp = I915_READ(reg);
3909         temp &= ~FDI_DP_PORT_WIDTH_MASK;
3910         temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
3911         temp &= ~FDI_LINK_TRAIN_NONE;
3912         temp |= FDI_LINK_TRAIN_PATTERN_1;
3913         temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3914         /* SNB-B */
3915         temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3916         I915_WRITE(reg, temp | FDI_TX_ENABLE);
3917
3918         I915_WRITE(FDI_RX_MISC(pipe),
3919                    FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
3920
3921         reg = FDI_RX_CTL(pipe);
3922         temp = I915_READ(reg);
3923         if (HAS_PCH_CPT(dev_priv)) {
3924                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3925                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
3926         } else {
3927                 temp &= ~FDI_LINK_TRAIN_NONE;
3928                 temp |= FDI_LINK_TRAIN_PATTERN_1;
3929         }
3930         I915_WRITE(reg, temp | FDI_RX_ENABLE);
3931
3932         POSTING_READ(reg);
3933         udelay(150);
3934
3935         for (i = 0; i < 4; i++) {
3936                 reg = FDI_TX_CTL(pipe);
3937                 temp = I915_READ(reg);
3938                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3939                 temp |= snb_b_fdi_train_param[i];
3940                 I915_WRITE(reg, temp);
3941
3942                 POSTING_READ(reg);
3943                 udelay(500);
3944
3945                 for (retry = 0; retry < 5; retry++) {
3946                         reg = FDI_RX_IIR(pipe);
3947                         temp = I915_READ(reg);
3948                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
3949                         if (temp & FDI_RX_BIT_LOCK) {
3950                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
3951                                 DRM_DEBUG_KMS("FDI train 1 done.\n");
3952                                 break;
3953                         }
3954                         udelay(50);
3955                 }
3956                 if (retry < 5)
3957                         break;
3958         }
3959         if (i == 4)
3960                 DRM_ERROR("FDI train 1 fail!\n");
3961
3962         /* Train 2 */
3963         reg = FDI_TX_CTL(pipe);
3964         temp = I915_READ(reg);
3965         temp &= ~FDI_LINK_TRAIN_NONE;
3966         temp |= FDI_LINK_TRAIN_PATTERN_2;
3967         if (IS_GEN6(dev_priv)) {
3968                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3969                 /* SNB-B */
3970                 temp |= FDI_LINK_TRAIN_400MV_0DB_SNB_B;
3971         }
3972         I915_WRITE(reg, temp);
3973
3974         reg = FDI_RX_CTL(pipe);
3975         temp = I915_READ(reg);
3976         if (HAS_PCH_CPT(dev_priv)) {
3977                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
3978                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
3979         } else {
3980                 temp &= ~FDI_LINK_TRAIN_NONE;
3981                 temp |= FDI_LINK_TRAIN_PATTERN_2;
3982         }
3983         I915_WRITE(reg, temp);
3984
3985         POSTING_READ(reg);
3986         udelay(150);
3987
3988         for (i = 0; i < 4; i++) {
3989                 reg = FDI_TX_CTL(pipe);
3990                 temp = I915_READ(reg);
3991                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
3992                 temp |= snb_b_fdi_train_param[i];
3993                 I915_WRITE(reg, temp);
3994
3995                 POSTING_READ(reg);
3996                 udelay(500);
3997
3998                 for (retry = 0; retry < 5; retry++) {
3999                         reg = FDI_RX_IIR(pipe);
4000                         temp = I915_READ(reg);
4001                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4002                         if (temp & FDI_RX_SYMBOL_LOCK) {
4003                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4004                                 DRM_DEBUG_KMS("FDI train 2 done.\n");
4005                                 break;
4006                         }
4007                         udelay(50);
4008                 }
4009                 if (retry < 5)
4010                         break;
4011         }
4012         if (i == 4)
4013                 DRM_ERROR("FDI train 2 fail!\n");
4014
4015         DRM_DEBUG_KMS("FDI train done.\n");
4016 }
4017
4018 /* Manual link training for Ivy Bridge A0 parts */
4019 static void ivb_manual_fdi_link_train(struct intel_crtc *crtc,
4020                                       const struct intel_crtc_state *crtc_state)
4021 {
4022         struct drm_device *dev = crtc->base.dev;
4023         struct drm_i915_private *dev_priv = to_i915(dev);
4024         int pipe = crtc->pipe;
4025         i915_reg_t reg;
4026         u32 temp, i, j;
4027
4028         /* Train 1: umask FDI RX Interrupt symbol_lock and bit_lock bit
4029            for train result */
4030         reg = FDI_RX_IMR(pipe);
4031         temp = I915_READ(reg);
4032         temp &= ~FDI_RX_SYMBOL_LOCK;
4033         temp &= ~FDI_RX_BIT_LOCK;
4034         I915_WRITE(reg, temp);
4035
4036         POSTING_READ(reg);
4037         udelay(150);
4038
4039         DRM_DEBUG_KMS("FDI_RX_IIR before link train 0x%x\n",
4040                       I915_READ(FDI_RX_IIR(pipe)));
4041
4042         /* Try each vswing and preemphasis setting twice before moving on */
4043         for (j = 0; j < ARRAY_SIZE(snb_b_fdi_train_param) * 2; j++) {
4044                 /* disable first in case we need to retry */
4045                 reg = FDI_TX_CTL(pipe);
4046                 temp = I915_READ(reg);
4047                 temp &= ~(FDI_LINK_TRAIN_AUTO | FDI_LINK_TRAIN_NONE_IVB);
4048                 temp &= ~FDI_TX_ENABLE;
4049                 I915_WRITE(reg, temp);
4050
4051                 reg = FDI_RX_CTL(pipe);
4052                 temp = I915_READ(reg);
4053                 temp &= ~FDI_LINK_TRAIN_AUTO;
4054                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4055                 temp &= ~FDI_RX_ENABLE;
4056                 I915_WRITE(reg, temp);
4057
4058                 /* enable CPU FDI TX and PCH FDI RX */
4059                 reg = FDI_TX_CTL(pipe);
4060                 temp = I915_READ(reg);
4061                 temp &= ~FDI_DP_PORT_WIDTH_MASK;
4062                 temp |= FDI_DP_PORT_WIDTH(crtc_state->fdi_lanes);
4063                 temp |= FDI_LINK_TRAIN_PATTERN_1_IVB;
4064                 temp &= ~FDI_LINK_TRAIN_VOL_EMP_MASK;
4065                 temp |= snb_b_fdi_train_param[j/2];
4066                 temp |= FDI_COMPOSITE_SYNC;
4067                 I915_WRITE(reg, temp | FDI_TX_ENABLE);
4068
4069                 I915_WRITE(FDI_RX_MISC(pipe),
4070                            FDI_RX_TP1_TO_TP2_48 | FDI_RX_FDI_DELAY_90);
4071
4072                 reg = FDI_RX_CTL(pipe);
4073                 temp = I915_READ(reg);
4074                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4075                 temp |= FDI_COMPOSITE_SYNC;
4076                 I915_WRITE(reg, temp | FDI_RX_ENABLE);
4077
4078                 POSTING_READ(reg);
4079                 udelay(1); /* should be 0.5us */
4080
4081                 for (i = 0; i < 4; i++) {
4082                         reg = FDI_RX_IIR(pipe);
4083                         temp = I915_READ(reg);
4084                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4085
4086                         if (temp & FDI_RX_BIT_LOCK ||
4087                             (I915_READ(reg) & FDI_RX_BIT_LOCK)) {
4088                                 I915_WRITE(reg, temp | FDI_RX_BIT_LOCK);
4089                                 DRM_DEBUG_KMS("FDI train 1 done, level %i.\n",
4090                                               i);
4091                                 break;
4092                         }
4093                         udelay(1); /* should be 0.5us */
4094                 }
4095                 if (i == 4) {
4096                         DRM_DEBUG_KMS("FDI train 1 fail on vswing %d\n", j / 2);
4097                         continue;
4098                 }
4099
4100                 /* Train 2 */
4101                 reg = FDI_TX_CTL(pipe);
4102                 temp = I915_READ(reg);
4103                 temp &= ~FDI_LINK_TRAIN_NONE_IVB;
4104                 temp |= FDI_LINK_TRAIN_PATTERN_2_IVB;
4105                 I915_WRITE(reg, temp);
4106
4107                 reg = FDI_RX_CTL(pipe);
4108                 temp = I915_READ(reg);
4109                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4110                 temp |= FDI_LINK_TRAIN_PATTERN_2_CPT;
4111                 I915_WRITE(reg, temp);
4112
4113                 POSTING_READ(reg);
4114                 udelay(2); /* should be 1.5us */
4115
4116                 for (i = 0; i < 4; i++) {
4117                         reg = FDI_RX_IIR(pipe);
4118                         temp = I915_READ(reg);
4119                         DRM_DEBUG_KMS("FDI_RX_IIR 0x%x\n", temp);
4120
4121                         if (temp & FDI_RX_SYMBOL_LOCK ||
4122                             (I915_READ(reg) & FDI_RX_SYMBOL_LOCK)) {
4123                                 I915_WRITE(reg, temp | FDI_RX_SYMBOL_LOCK);
4124                                 DRM_DEBUG_KMS("FDI train 2 done, level %i.\n",
4125                                               i);
4126                                 goto train_done;
4127                         }
4128                         udelay(2); /* should be 1.5us */
4129                 }
4130                 if (i == 4)
4131                         DRM_DEBUG_KMS("FDI train 2 fail on vswing %d\n", j / 2);
4132         }
4133
4134 train_done:
4135         DRM_DEBUG_KMS("FDI train done.\n");
4136 }
4137
4138 static void ironlake_fdi_pll_enable(struct intel_crtc *intel_crtc)
4139 {
4140         struct drm_device *dev = intel_crtc->base.dev;
4141         struct drm_i915_private *dev_priv = to_i915(dev);
4142         int pipe = intel_crtc->pipe;
4143         i915_reg_t reg;
4144         u32 temp;
4145
4146         /* enable PCH FDI RX PLL, wait warmup plus DMI latency */
4147         reg = FDI_RX_CTL(pipe);
4148         temp = I915_READ(reg);
4149         temp &= ~(FDI_DP_PORT_WIDTH_MASK | (0x7 << 16));
4150         temp |= FDI_DP_PORT_WIDTH(intel_crtc->config->fdi_lanes);
4151         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4152         I915_WRITE(reg, temp | FDI_RX_PLL_ENABLE);
4153
4154         POSTING_READ(reg);
4155         udelay(200);
4156
4157         /* Switch from Rawclk to PCDclk */
4158         temp = I915_READ(reg);
4159         I915_WRITE(reg, temp | FDI_PCDCLK);
4160
4161         POSTING_READ(reg);
4162         udelay(200);
4163
4164         /* Enable CPU FDI TX PLL, always on for Ironlake */
4165         reg = FDI_TX_CTL(pipe);
4166         temp = I915_READ(reg);
4167         if ((temp & FDI_TX_PLL_ENABLE) == 0) {
4168                 I915_WRITE(reg, temp | FDI_TX_PLL_ENABLE);
4169
4170                 POSTING_READ(reg);
4171                 udelay(100);
4172         }
4173 }
4174
4175 static void ironlake_fdi_pll_disable(struct intel_crtc *intel_crtc)
4176 {
4177         struct drm_device *dev = intel_crtc->base.dev;
4178         struct drm_i915_private *dev_priv = to_i915(dev);
4179         int pipe = intel_crtc->pipe;
4180         i915_reg_t reg;
4181         u32 temp;
4182
4183         /* Switch from PCDclk to Rawclk */
4184         reg = FDI_RX_CTL(pipe);
4185         temp = I915_READ(reg);
4186         I915_WRITE(reg, temp & ~FDI_PCDCLK);
4187
4188         /* Disable CPU FDI TX PLL */
4189         reg = FDI_TX_CTL(pipe);
4190         temp = I915_READ(reg);
4191         I915_WRITE(reg, temp & ~FDI_TX_PLL_ENABLE);
4192
4193         POSTING_READ(reg);
4194         udelay(100);
4195
4196         reg = FDI_RX_CTL(pipe);
4197         temp = I915_READ(reg);
4198         I915_WRITE(reg, temp & ~FDI_RX_PLL_ENABLE);
4199
4200         /* Wait for the clocks to turn off. */
4201         POSTING_READ(reg);
4202         udelay(100);
4203 }
4204
4205 static void ironlake_fdi_disable(struct drm_crtc *crtc)
4206 {
4207         struct drm_device *dev = crtc->dev;
4208         struct drm_i915_private *dev_priv = to_i915(dev);
4209         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4210         int pipe = intel_crtc->pipe;
4211         i915_reg_t reg;
4212         u32 temp;
4213
4214         /* disable CPU FDI tx and PCH FDI rx */
4215         reg = FDI_TX_CTL(pipe);
4216         temp = I915_READ(reg);
4217         I915_WRITE(reg, temp & ~FDI_TX_ENABLE);
4218         POSTING_READ(reg);
4219
4220         reg = FDI_RX_CTL(pipe);
4221         temp = I915_READ(reg);
4222         temp &= ~(0x7 << 16);
4223         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4224         I915_WRITE(reg, temp & ~FDI_RX_ENABLE);
4225
4226         POSTING_READ(reg);
4227         udelay(100);
4228
4229         /* Ironlake workaround, disable clock pointer after downing FDI */
4230         if (HAS_PCH_IBX(dev_priv))
4231                 I915_WRITE(FDI_RX_CHICKEN(pipe), FDI_RX_PHASE_SYNC_POINTER_OVR);
4232
4233         /* still set train pattern 1 */
4234         reg = FDI_TX_CTL(pipe);
4235         temp = I915_READ(reg);
4236         temp &= ~FDI_LINK_TRAIN_NONE;
4237         temp |= FDI_LINK_TRAIN_PATTERN_1;
4238         I915_WRITE(reg, temp);
4239
4240         reg = FDI_RX_CTL(pipe);
4241         temp = I915_READ(reg);
4242         if (HAS_PCH_CPT(dev_priv)) {
4243                 temp &= ~FDI_LINK_TRAIN_PATTERN_MASK_CPT;
4244                 temp |= FDI_LINK_TRAIN_PATTERN_1_CPT;
4245         } else {
4246                 temp &= ~FDI_LINK_TRAIN_NONE;
4247                 temp |= FDI_LINK_TRAIN_PATTERN_1;
4248         }
4249         /* BPC in FDI rx is consistent with that in PIPECONF */
4250         temp &= ~(0x07 << 16);
4251         temp |= (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) << 11;
4252         I915_WRITE(reg, temp);
4253
4254         POSTING_READ(reg);
4255         udelay(100);
4256 }
4257
4258 bool intel_has_pending_fb_unpin(struct drm_i915_private *dev_priv)
4259 {
4260         struct drm_crtc *crtc;
4261         bool cleanup_done;
4262
4263         drm_for_each_crtc(crtc, &dev_priv->drm) {
4264                 struct drm_crtc_commit *commit;
4265                 spin_lock(&crtc->commit_lock);
4266                 commit = list_first_entry_or_null(&crtc->commit_list,
4267                                                   struct drm_crtc_commit, commit_entry);
4268                 cleanup_done = commit ?
4269                         try_wait_for_completion(&commit->cleanup_done) : true;
4270                 spin_unlock(&crtc->commit_lock);
4271
4272                 if (cleanup_done)
4273                         continue;
4274
4275                 drm_crtc_wait_one_vblank(crtc);
4276
4277                 return true;
4278         }
4279
4280         return false;
4281 }
4282
4283 void lpt_disable_iclkip(struct drm_i915_private *dev_priv)
4284 {
4285         u32 temp;
4286
4287         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_GATE);
4288
4289         mutex_lock(&dev_priv->sb_lock);
4290
4291         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4292         temp |= SBI_SSCCTL_DISABLE;
4293         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4294
4295         mutex_unlock(&dev_priv->sb_lock);
4296 }
4297
4298 /* Program iCLKIP clock to the desired frequency */
4299 static void lpt_program_iclkip(struct intel_crtc *crtc)
4300 {
4301         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4302         int clock = crtc->config->base.adjusted_mode.crtc_clock;
4303         u32 divsel, phaseinc, auxdiv, phasedir = 0;
4304         u32 temp;
4305
4306         lpt_disable_iclkip(dev_priv);
4307
4308         /* The iCLK virtual clock root frequency is in MHz,
4309          * but the adjusted_mode->crtc_clock in in KHz. To get the
4310          * divisors, it is necessary to divide one by another, so we
4311          * convert the virtual clock precision to KHz here for higher
4312          * precision.
4313          */
4314         for (auxdiv = 0; auxdiv < 2; auxdiv++) {
4315                 u32 iclk_virtual_root_freq = 172800 * 1000;
4316                 u32 iclk_pi_range = 64;
4317                 u32 desired_divisor;
4318
4319                 desired_divisor = DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4320                                                     clock << auxdiv);
4321                 divsel = (desired_divisor / iclk_pi_range) - 2;
4322                 phaseinc = desired_divisor % iclk_pi_range;
4323
4324                 /*
4325                  * Near 20MHz is a corner case which is
4326                  * out of range for the 7-bit divisor
4327                  */
4328                 if (divsel <= 0x7f)
4329                         break;
4330         }
4331
4332         /* This should not happen with any sane values */
4333         WARN_ON(SBI_SSCDIVINTPHASE_DIVSEL(divsel) &
4334                 ~SBI_SSCDIVINTPHASE_DIVSEL_MASK);
4335         WARN_ON(SBI_SSCDIVINTPHASE_DIR(phasedir) &
4336                 ~SBI_SSCDIVINTPHASE_INCVAL_MASK);
4337
4338         DRM_DEBUG_KMS("iCLKIP clock: found settings for %dKHz refresh rate: auxdiv=%x, divsel=%x, phasedir=%x, phaseinc=%x\n",
4339                         clock,
4340                         auxdiv,
4341                         divsel,
4342                         phasedir,
4343                         phaseinc);
4344
4345         mutex_lock(&dev_priv->sb_lock);
4346
4347         /* Program SSCDIVINTPHASE6 */
4348         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4349         temp &= ~SBI_SSCDIVINTPHASE_DIVSEL_MASK;
4350         temp |= SBI_SSCDIVINTPHASE_DIVSEL(divsel);
4351         temp &= ~SBI_SSCDIVINTPHASE_INCVAL_MASK;
4352         temp |= SBI_SSCDIVINTPHASE_INCVAL(phaseinc);
4353         temp |= SBI_SSCDIVINTPHASE_DIR(phasedir);
4354         temp |= SBI_SSCDIVINTPHASE_PROPAGATE;
4355         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE6, temp, SBI_ICLK);
4356
4357         /* Program SSCAUXDIV */
4358         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4359         temp &= ~SBI_SSCAUXDIV_FINALDIV2SEL(1);
4360         temp |= SBI_SSCAUXDIV_FINALDIV2SEL(auxdiv);
4361         intel_sbi_write(dev_priv, SBI_SSCAUXDIV6, temp, SBI_ICLK);
4362
4363         /* Enable modulator and associated divider */
4364         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4365         temp &= ~SBI_SSCCTL_DISABLE;
4366         intel_sbi_write(dev_priv, SBI_SSCCTL6, temp, SBI_ICLK);
4367
4368         mutex_unlock(&dev_priv->sb_lock);
4369
4370         /* Wait for initialization time */
4371         udelay(24);
4372
4373         I915_WRITE(PIXCLK_GATE, PIXCLK_GATE_UNGATE);
4374 }
4375
4376 int lpt_get_iclkip(struct drm_i915_private *dev_priv)
4377 {
4378         u32 divsel, phaseinc, auxdiv;
4379         u32 iclk_virtual_root_freq = 172800 * 1000;
4380         u32 iclk_pi_range = 64;
4381         u32 desired_divisor;
4382         u32 temp;
4383
4384         if ((I915_READ(PIXCLK_GATE) & PIXCLK_GATE_UNGATE) == 0)
4385                 return 0;
4386
4387         mutex_lock(&dev_priv->sb_lock);
4388
4389         temp = intel_sbi_read(dev_priv, SBI_SSCCTL6, SBI_ICLK);
4390         if (temp & SBI_SSCCTL_DISABLE) {
4391                 mutex_unlock(&dev_priv->sb_lock);
4392                 return 0;
4393         }
4394
4395         temp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE6, SBI_ICLK);
4396         divsel = (temp & SBI_SSCDIVINTPHASE_DIVSEL_MASK) >>
4397                 SBI_SSCDIVINTPHASE_DIVSEL_SHIFT;
4398         phaseinc = (temp & SBI_SSCDIVINTPHASE_INCVAL_MASK) >>
4399                 SBI_SSCDIVINTPHASE_INCVAL_SHIFT;
4400
4401         temp = intel_sbi_read(dev_priv, SBI_SSCAUXDIV6, SBI_ICLK);
4402         auxdiv = (temp & SBI_SSCAUXDIV_FINALDIV2SEL_MASK) >>
4403                 SBI_SSCAUXDIV_FINALDIV2SEL_SHIFT;
4404
4405         mutex_unlock(&dev_priv->sb_lock);
4406
4407         desired_divisor = (divsel + 2) * iclk_pi_range + phaseinc;
4408
4409         return DIV_ROUND_CLOSEST(iclk_virtual_root_freq,
4410                                  desired_divisor << auxdiv);
4411 }
4412
4413 static void ironlake_pch_transcoder_set_timings(struct intel_crtc *crtc,
4414                                                 enum pipe pch_transcoder)
4415 {
4416         struct drm_device *dev = crtc->base.dev;
4417         struct drm_i915_private *dev_priv = to_i915(dev);
4418         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
4419
4420         I915_WRITE(PCH_TRANS_HTOTAL(pch_transcoder),
4421                    I915_READ(HTOTAL(cpu_transcoder)));
4422         I915_WRITE(PCH_TRANS_HBLANK(pch_transcoder),
4423                    I915_READ(HBLANK(cpu_transcoder)));
4424         I915_WRITE(PCH_TRANS_HSYNC(pch_transcoder),
4425                    I915_READ(HSYNC(cpu_transcoder)));
4426
4427         I915_WRITE(PCH_TRANS_VTOTAL(pch_transcoder),
4428                    I915_READ(VTOTAL(cpu_transcoder)));
4429         I915_WRITE(PCH_TRANS_VBLANK(pch_transcoder),
4430                    I915_READ(VBLANK(cpu_transcoder)));
4431         I915_WRITE(PCH_TRANS_VSYNC(pch_transcoder),
4432                    I915_READ(VSYNC(cpu_transcoder)));
4433         I915_WRITE(PCH_TRANS_VSYNCSHIFT(pch_transcoder),
4434                    I915_READ(VSYNCSHIFT(cpu_transcoder)));
4435 }
4436
4437 static void cpt_set_fdi_bc_bifurcation(struct drm_device *dev, bool enable)
4438 {
4439         struct drm_i915_private *dev_priv = to_i915(dev);
4440         uint32_t temp;
4441
4442         temp = I915_READ(SOUTH_CHICKEN1);
4443         if (!!(temp & FDI_BC_BIFURCATION_SELECT) == enable)
4444                 return;
4445
4446         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_B)) & FDI_RX_ENABLE);
4447         WARN_ON(I915_READ(FDI_RX_CTL(PIPE_C)) & FDI_RX_ENABLE);
4448
4449         temp &= ~FDI_BC_BIFURCATION_SELECT;
4450         if (enable)
4451                 temp |= FDI_BC_BIFURCATION_SELECT;
4452
4453         DRM_DEBUG_KMS("%sabling fdi C rx\n", enable ? "en" : "dis");
4454         I915_WRITE(SOUTH_CHICKEN1, temp);
4455         POSTING_READ(SOUTH_CHICKEN1);
4456 }
4457
4458 static void ivybridge_update_fdi_bc_bifurcation(struct intel_crtc *intel_crtc)
4459 {
4460         struct drm_device *dev = intel_crtc->base.dev;
4461
4462         switch (intel_crtc->pipe) {
4463         case PIPE_A:
4464                 break;
4465         case PIPE_B:
4466                 if (intel_crtc->config->fdi_lanes > 2)
4467                         cpt_set_fdi_bc_bifurcation(dev, false);
4468                 else
4469                         cpt_set_fdi_bc_bifurcation(dev, true);
4470
4471                 break;
4472         case PIPE_C:
4473                 cpt_set_fdi_bc_bifurcation(dev, true);
4474
4475                 break;
4476         default:
4477                 BUG();
4478         }
4479 }
4480
4481 /* Return which DP Port should be selected for Transcoder DP control */
4482 static enum port
4483 intel_trans_dp_port_sel(struct intel_crtc *crtc)
4484 {
4485         struct drm_device *dev = crtc->base.dev;
4486         struct intel_encoder *encoder;
4487
4488         for_each_encoder_on_crtc(dev, &crtc->base, encoder) {
4489                 if (encoder->type == INTEL_OUTPUT_DP ||
4490                     encoder->type == INTEL_OUTPUT_EDP)
4491                         return encoder->port;
4492         }
4493
4494         return -1;
4495 }
4496
4497 /*
4498  * Enable PCH resources required for PCH ports:
4499  *   - PCH PLLs
4500  *   - FDI training & RX/TX
4501  *   - update transcoder timings
4502  *   - DP transcoding bits
4503  *   - transcoder
4504  */
4505 static void ironlake_pch_enable(const struct intel_crtc_state *crtc_state)
4506 {
4507         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4508         struct drm_device *dev = crtc->base.dev;
4509         struct drm_i915_private *dev_priv = to_i915(dev);
4510         int pipe = crtc->pipe;
4511         u32 temp;
4512
4513         assert_pch_transcoder_disabled(dev_priv, pipe);
4514
4515         if (IS_IVYBRIDGE(dev_priv))
4516                 ivybridge_update_fdi_bc_bifurcation(crtc);
4517
4518         /* Write the TU size bits before fdi link training, so that error
4519          * detection works. */
4520         I915_WRITE(FDI_RX_TUSIZE1(pipe),
4521                    I915_READ(PIPE_DATA_M1(pipe)) & TU_SIZE_MASK);
4522
4523         /* For PCH output, training FDI link */
4524         dev_priv->display.fdi_link_train(crtc, crtc_state);
4525
4526         /* We need to program the right clock selection before writing the pixel
4527          * mutliplier into the DPLL. */
4528         if (HAS_PCH_CPT(dev_priv)) {
4529                 u32 sel;
4530
4531                 temp = I915_READ(PCH_DPLL_SEL);
4532                 temp |= TRANS_DPLL_ENABLE(pipe);
4533                 sel = TRANS_DPLLB_SEL(pipe);
4534                 if (crtc_state->shared_dpll ==
4535                     intel_get_shared_dpll_by_id(dev_priv, DPLL_ID_PCH_PLL_B))
4536                         temp |= sel;
4537                 else
4538                         temp &= ~sel;
4539                 I915_WRITE(PCH_DPLL_SEL, temp);
4540         }
4541
4542         /* XXX: pch pll's can be enabled any time before we enable the PCH
4543          * transcoder, and we actually should do this to not upset any PCH
4544          * transcoder that already use the clock when we share it.
4545          *
4546          * Note that enable_shared_dpll tries to do the right thing, but
4547          * get_shared_dpll unconditionally resets the pll - we need that to have
4548          * the right LVDS enable sequence. */
4549         intel_enable_shared_dpll(crtc);
4550
4551         /* set transcoder timing, panel must allow it */
4552         assert_panel_unlocked(dev_priv, pipe);
4553         ironlake_pch_transcoder_set_timings(crtc, pipe);
4554
4555         intel_fdi_normal_train(crtc);
4556
4557         /* For PCH DP, enable TRANS_DP_CTL */
4558         if (HAS_PCH_CPT(dev_priv) &&
4559             intel_crtc_has_dp_encoder(crtc_state)) {
4560                 const struct drm_display_mode *adjusted_mode =
4561                         &crtc_state->base.adjusted_mode;
4562                 u32 bpc = (I915_READ(PIPECONF(pipe)) & PIPECONF_BPC_MASK) >> 5;
4563                 i915_reg_t reg = TRANS_DP_CTL(pipe);
4564                 temp = I915_READ(reg);
4565                 temp &= ~(TRANS_DP_PORT_SEL_MASK |
4566                           TRANS_DP_SYNC_MASK |
4567                           TRANS_DP_BPC_MASK);
4568                 temp |= TRANS_DP_OUTPUT_ENABLE;
4569                 temp |= bpc << 9; /* same format but at 11:9 */
4570
4571                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
4572                         temp |= TRANS_DP_HSYNC_ACTIVE_HIGH;
4573                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
4574                         temp |= TRANS_DP_VSYNC_ACTIVE_HIGH;
4575
4576                 switch (intel_trans_dp_port_sel(crtc)) {
4577                 case PORT_B:
4578                         temp |= TRANS_DP_PORT_SEL_B;
4579                         break;
4580                 case PORT_C:
4581                         temp |= TRANS_DP_PORT_SEL_C;
4582                         break;
4583                 case PORT_D:
4584                         temp |= TRANS_DP_PORT_SEL_D;
4585                         break;
4586                 default:
4587                         BUG();
4588                 }
4589
4590                 I915_WRITE(reg, temp);
4591         }
4592
4593         ironlake_enable_pch_transcoder(dev_priv, pipe);
4594 }
4595
4596 static void lpt_pch_enable(const struct intel_crtc_state *crtc_state)
4597 {
4598         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4599         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
4600         enum transcoder cpu_transcoder = crtc_state->cpu_transcoder;
4601
4602         assert_pch_transcoder_disabled(dev_priv, PIPE_A);
4603
4604         lpt_program_iclkip(crtc);
4605
4606         /* Set transcoder timing. */
4607         ironlake_pch_transcoder_set_timings(crtc, PIPE_A);
4608
4609         lpt_enable_pch_transcoder(dev_priv, cpu_transcoder);
4610 }
4611
4612 static void cpt_verify_modeset(struct drm_device *dev, int pipe)
4613 {
4614         struct drm_i915_private *dev_priv = to_i915(dev);
4615         i915_reg_t dslreg = PIPEDSL(pipe);
4616         u32 temp;
4617
4618         temp = I915_READ(dslreg);
4619         udelay(500);
4620         if (wait_for(I915_READ(dslreg) != temp, 5)) {
4621                 if (wait_for(I915_READ(dslreg) != temp, 5))
4622                         DRM_ERROR("mode set failed: pipe %c stuck\n", pipe_name(pipe));
4623         }
4624 }
4625
4626 static int
4627 skl_update_scaler(struct intel_crtc_state *crtc_state, bool force_detach,
4628                   unsigned int scaler_user, int *scaler_id,
4629                   int src_w, int src_h, int dst_w, int dst_h)
4630 {
4631         struct intel_crtc_scaler_state *scaler_state =
4632                 &crtc_state->scaler_state;
4633         struct intel_crtc *intel_crtc =
4634                 to_intel_crtc(crtc_state->base.crtc);
4635         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
4636         const struct drm_display_mode *adjusted_mode =
4637                 &crtc_state->base.adjusted_mode;
4638         int need_scaling;
4639
4640         /*
4641          * Src coordinates are already rotated by 270 degrees for
4642          * the 90/270 degree plane rotation cases (to match the
4643          * GTT mapping), hence no need to account for rotation here.
4644          */
4645         need_scaling = src_w != dst_w || src_h != dst_h;
4646
4647         if (crtc_state->ycbcr420 && scaler_user == SKL_CRTC_INDEX)
4648                 need_scaling = true;
4649
4650         /*
4651          * Scaling/fitting not supported in IF-ID mode in GEN9+
4652          * TODO: Interlace fetch mode doesn't support YUV420 planar formats.
4653          * Once NV12 is enabled, handle it here while allocating scaler
4654          * for NV12.
4655          */
4656         if (INTEL_GEN(dev_priv) >= 9 && crtc_state->base.enable &&
4657             need_scaling && adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
4658                 DRM_DEBUG_KMS("Pipe/Plane scaling not supported with IF-ID mode\n");
4659                 return -EINVAL;
4660         }
4661
4662         /*
4663          * if plane is being disabled or scaler is no more required or force detach
4664          *  - free scaler binded to this plane/crtc
4665          *  - in order to do this, update crtc->scaler_usage
4666          *
4667          * Here scaler state in crtc_state is set free so that
4668          * scaler can be assigned to other user. Actual register
4669          * update to free the scaler is done in plane/panel-fit programming.
4670          * For this purpose crtc/plane_state->scaler_id isn't reset here.
4671          */
4672         if (force_detach || !need_scaling) {
4673                 if (*scaler_id >= 0) {
4674                         scaler_state->scaler_users &= ~(1 << scaler_user);
4675                         scaler_state->scalers[*scaler_id].in_use = 0;
4676
4677                         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4678                                 "Staged freeing scaler id %d scaler_users = 0x%x\n",
4679                                 intel_crtc->pipe, scaler_user, *scaler_id,
4680                                 scaler_state->scaler_users);
4681                         *scaler_id = -1;
4682                 }
4683                 return 0;
4684         }
4685
4686         /* range checks */
4687         if (src_w < SKL_MIN_SRC_W || src_h < SKL_MIN_SRC_H ||
4688                 dst_w < SKL_MIN_DST_W || dst_h < SKL_MIN_DST_H ||
4689
4690                 src_w > SKL_MAX_SRC_W || src_h > SKL_MAX_SRC_H ||
4691                 dst_w > SKL_MAX_DST_W || dst_h > SKL_MAX_DST_H) {
4692                 DRM_DEBUG_KMS("scaler_user index %u.%u: src %ux%u dst %ux%u "
4693                         "size is out of scaler range\n",
4694                         intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h);
4695                 return -EINVAL;
4696         }
4697
4698         /* mark this plane as a scaler user in crtc_state */
4699         scaler_state->scaler_users |= (1 << scaler_user);
4700         DRM_DEBUG_KMS("scaler_user index %u.%u: "
4701                 "staged scaling request for %ux%u->%ux%u scaler_users = 0x%x\n",
4702                 intel_crtc->pipe, scaler_user, src_w, src_h, dst_w, dst_h,
4703                 scaler_state->scaler_users);
4704
4705         return 0;
4706 }
4707
4708 /**
4709  * skl_update_scaler_crtc - Stages update to scaler state for a given crtc.
4710  *
4711  * @state: crtc's scaler state
4712  *
4713  * Return
4714  *     0 - scaler_usage updated successfully
4715  *    error - requested scaling cannot be supported or other error condition
4716  */
4717 int skl_update_scaler_crtc(struct intel_crtc_state *state)
4718 {
4719         const struct drm_display_mode *adjusted_mode = &state->base.adjusted_mode;
4720
4721         return skl_update_scaler(state, !state->base.active, SKL_CRTC_INDEX,
4722                 &state->scaler_state.scaler_id,
4723                 state->pipe_src_w, state->pipe_src_h,
4724                 adjusted_mode->crtc_hdisplay, adjusted_mode->crtc_vdisplay);
4725 }
4726
4727 /**
4728  * skl_update_scaler_plane - Stages update to scaler state for a given plane.
4729  *
4730  * @state: crtc's scaler state
4731  * @plane_state: atomic plane state to update
4732  *
4733  * Return
4734  *     0 - scaler_usage updated successfully
4735  *    error - requested scaling cannot be supported or other error condition
4736  */
4737 static int skl_update_scaler_plane(struct intel_crtc_state *crtc_state,
4738                                    struct intel_plane_state *plane_state)
4739 {
4740
4741         struct intel_plane *intel_plane =
4742                 to_intel_plane(plane_state->base.plane);
4743         struct drm_framebuffer *fb = plane_state->base.fb;
4744         int ret;
4745
4746         bool force_detach = !fb || !plane_state->base.visible;
4747
4748         ret = skl_update_scaler(crtc_state, force_detach,
4749                                 drm_plane_index(&intel_plane->base),
4750                                 &plane_state->scaler_id,
4751                                 drm_rect_width(&plane_state->base.src) >> 16,
4752                                 drm_rect_height(&plane_state->base.src) >> 16,
4753                                 drm_rect_width(&plane_state->base.dst),
4754                                 drm_rect_height(&plane_state->base.dst));
4755
4756         if (ret || plane_state->scaler_id < 0)
4757                 return ret;
4758
4759         /* check colorkey */
4760         if (plane_state->ckey.flags != I915_SET_COLORKEY_NONE) {
4761                 DRM_DEBUG_KMS("[PLANE:%d:%s] scaling with color key not allowed",
4762                               intel_plane->base.base.id,
4763                               intel_plane->base.name);
4764                 return -EINVAL;
4765         }
4766
4767         /* Check src format */
4768         switch (fb->format->format) {
4769         case DRM_FORMAT_RGB565:
4770         case DRM_FORMAT_XBGR8888:
4771         case DRM_FORMAT_XRGB8888:
4772         case DRM_FORMAT_ABGR8888:
4773         case DRM_FORMAT_ARGB8888:
4774         case DRM_FORMAT_XRGB2101010:
4775         case DRM_FORMAT_XBGR2101010:
4776         case DRM_FORMAT_YUYV:
4777         case DRM_FORMAT_YVYU:
4778         case DRM_FORMAT_UYVY:
4779         case DRM_FORMAT_VYUY:
4780                 break;
4781         default:
4782                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d unsupported scaling format 0x%x\n",
4783                               intel_plane->base.base.id, intel_plane->base.name,
4784                               fb->base.id, fb->format->format);
4785                 return -EINVAL;
4786         }
4787
4788         return 0;
4789 }
4790
4791 static void skylake_scaler_disable(struct intel_crtc *crtc)
4792 {
4793         int i;
4794
4795         for (i = 0; i < crtc->num_scalers; i++)
4796                 skl_detach_scaler(crtc, i);
4797 }
4798
4799 static void skylake_pfit_enable(struct intel_crtc *crtc)
4800 {
4801         struct drm_device *dev = crtc->base.dev;
4802         struct drm_i915_private *dev_priv = to_i915(dev);
4803         int pipe = crtc->pipe;
4804         struct intel_crtc_scaler_state *scaler_state =
4805                 &crtc->config->scaler_state;
4806
4807         if (crtc->config->pch_pfit.enabled) {
4808                 int id;
4809
4810                 if (WARN_ON(crtc->config->scaler_state.scaler_id < 0))
4811                         return;
4812
4813                 id = scaler_state->scaler_id;
4814                 I915_WRITE(SKL_PS_CTRL(pipe, id), PS_SCALER_EN |
4815                         PS_FILTER_MEDIUM | scaler_state->scalers[id].mode);
4816                 I915_WRITE(SKL_PS_WIN_POS(pipe, id), crtc->config->pch_pfit.pos);
4817                 I915_WRITE(SKL_PS_WIN_SZ(pipe, id), crtc->config->pch_pfit.size);
4818         }
4819 }
4820
4821 static void ironlake_pfit_enable(struct intel_crtc *crtc)
4822 {
4823         struct drm_device *dev = crtc->base.dev;
4824         struct drm_i915_private *dev_priv = to_i915(dev);
4825         int pipe = crtc->pipe;
4826
4827         if (crtc->config->pch_pfit.enabled) {
4828                 /* Force use of hard-coded filter coefficients
4829                  * as some pre-programmed values are broken,
4830                  * e.g. x201.
4831                  */
4832                 if (IS_IVYBRIDGE(dev_priv) || IS_HASWELL(dev_priv))
4833                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3 |
4834                                                  PF_PIPE_SEL_IVB(pipe));
4835                 else
4836                         I915_WRITE(PF_CTL(pipe), PF_ENABLE | PF_FILTER_MED_3x3);
4837                 I915_WRITE(PF_WIN_POS(pipe), crtc->config->pch_pfit.pos);
4838                 I915_WRITE(PF_WIN_SZ(pipe), crtc->config->pch_pfit.size);
4839         }
4840 }
4841
4842 void hsw_enable_ips(const struct intel_crtc_state *crtc_state)
4843 {
4844         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4845         struct drm_device *dev = crtc->base.dev;
4846         struct drm_i915_private *dev_priv = to_i915(dev);
4847
4848         if (!crtc_state->ips_enabled)
4849                 return;
4850
4851         /*
4852          * We can only enable IPS after we enable a plane and wait for a vblank
4853          * This function is called from post_plane_update, which is run after
4854          * a vblank wait.
4855          */
4856         WARN_ON(!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)));
4857
4858         if (IS_BROADWELL(dev_priv)) {
4859                 mutex_lock(&dev_priv->pcu_lock);
4860                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL,
4861                                                 IPS_ENABLE | IPS_PCODE_CONTROL));
4862                 mutex_unlock(&dev_priv->pcu_lock);
4863                 /* Quoting Art Runyan: "its not safe to expect any particular
4864                  * value in IPS_CTL bit 31 after enabling IPS through the
4865                  * mailbox." Moreover, the mailbox may return a bogus state,
4866                  * so we need to just enable it and continue on.
4867                  */
4868         } else {
4869                 I915_WRITE(IPS_CTL, IPS_ENABLE);
4870                 /* The bit only becomes 1 in the next vblank, so this wait here
4871                  * is essentially intel_wait_for_vblank. If we don't have this
4872                  * and don't wait for vblanks until the end of crtc_enable, then
4873                  * the HW state readout code will complain that the expected
4874                  * IPS_CTL value is not the one we read. */
4875                 if (intel_wait_for_register(dev_priv,
4876                                             IPS_CTL, IPS_ENABLE, IPS_ENABLE,
4877                                             50))
4878                         DRM_ERROR("Timed out waiting for IPS enable\n");
4879         }
4880 }
4881
4882 void hsw_disable_ips(const struct intel_crtc_state *crtc_state)
4883 {
4884         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
4885         struct drm_device *dev = crtc->base.dev;
4886         struct drm_i915_private *dev_priv = to_i915(dev);
4887
4888         if (!crtc_state->ips_enabled)
4889                 return;
4890
4891         if (IS_BROADWELL(dev_priv)) {
4892                 mutex_lock(&dev_priv->pcu_lock);
4893                 WARN_ON(sandybridge_pcode_write(dev_priv, DISPLAY_IPS_CONTROL, 0));
4894                 mutex_unlock(&dev_priv->pcu_lock);
4895                 /* wait for pcode to finish disabling IPS, which may take up to 42ms */
4896                 if (intel_wait_for_register(dev_priv,
4897                                             IPS_CTL, IPS_ENABLE, 0,
4898                                             42))
4899                         DRM_ERROR("Timed out waiting for IPS disable\n");
4900         } else {
4901                 I915_WRITE(IPS_CTL, 0);
4902                 POSTING_READ(IPS_CTL);
4903         }
4904
4905         /* We need to wait for a vblank before we can disable the plane. */
4906         intel_wait_for_vblank(dev_priv, crtc->pipe);
4907 }
4908
4909 static void intel_crtc_dpms_overlay_disable(struct intel_crtc *intel_crtc)
4910 {
4911         if (intel_crtc->overlay) {
4912                 struct drm_device *dev = intel_crtc->base.dev;
4913
4914                 mutex_lock(&dev->struct_mutex);
4915                 (void) intel_overlay_switch_off(intel_crtc->overlay);
4916                 mutex_unlock(&dev->struct_mutex);
4917         }
4918
4919         /* Let userspace switch the overlay on again. In most cases userspace
4920          * has to recompute where to put it anyway.
4921          */
4922 }
4923
4924 /**
4925  * intel_post_enable_primary - Perform operations after enabling primary plane
4926  * @crtc: the CRTC whose primary plane was just enabled
4927  *
4928  * Performs potentially sleeping operations that must be done after the primary
4929  * plane is enabled, such as updating FBC and IPS.  Note that this may be
4930  * called due to an explicit primary plane update, or due to an implicit
4931  * re-enable that is caused when a sprite plane is updated to no longer
4932  * completely hide the primary plane.
4933  */
4934 static void
4935 intel_post_enable_primary(struct drm_crtc *crtc,
4936                           const struct intel_crtc_state *new_crtc_state)
4937 {
4938         struct drm_device *dev = crtc->dev;
4939         struct drm_i915_private *dev_priv = to_i915(dev);
4940         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4941         int pipe = intel_crtc->pipe;
4942
4943         /*
4944          * Gen2 reports pipe underruns whenever all planes are disabled.
4945          * So don't enable underrun reporting before at least some planes
4946          * are enabled.
4947          * FIXME: Need to fix the logic to work when we turn off all planes
4948          * but leave the pipe running.
4949          */
4950         if (IS_GEN2(dev_priv))
4951                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
4952
4953         /* Underruns don't always raise interrupts, so check manually. */
4954         intel_check_cpu_fifo_underruns(dev_priv);
4955         intel_check_pch_fifo_underruns(dev_priv);
4956 }
4957
4958 /* FIXME get rid of this and use pre_plane_update */
4959 static void
4960 intel_pre_disable_primary_noatomic(struct drm_crtc *crtc)
4961 {
4962         struct drm_device *dev = crtc->dev;
4963         struct drm_i915_private *dev_priv = to_i915(dev);
4964         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
4965         int pipe = intel_crtc->pipe;
4966
4967         /*
4968          * Gen2 reports pipe underruns whenever all planes are disabled.
4969          * So disable underrun reporting before all the planes get disabled.
4970          */
4971         if (IS_GEN2(dev_priv))
4972                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
4973
4974         hsw_disable_ips(to_intel_crtc_state(crtc->state));
4975
4976         /*
4977          * Vblank time updates from the shadow to live plane control register
4978          * are blocked if the memory self-refresh mode is active at that
4979          * moment. So to make sure the plane gets truly disabled, disable
4980          * first the self-refresh mode. The self-refresh enable bit in turn
4981          * will be checked/applied by the HW only at the next frame start
4982          * event which is after the vblank start event, so we need to have a
4983          * wait-for-vblank between disabling the plane and the pipe.
4984          */
4985         if (HAS_GMCH_DISPLAY(dev_priv) &&
4986             intel_set_memory_cxsr(dev_priv, false))
4987                 intel_wait_for_vblank(dev_priv, pipe);
4988 }
4989
4990 static bool hsw_pre_update_disable_ips(const struct intel_crtc_state *old_crtc_state,
4991                                        const struct intel_crtc_state *new_crtc_state)
4992 {
4993         if (!old_crtc_state->ips_enabled)
4994                 return false;
4995
4996         if (needs_modeset(&new_crtc_state->base))
4997                 return true;
4998
4999         return !new_crtc_state->ips_enabled;
5000 }
5001
5002 static bool hsw_post_update_enable_ips(const struct intel_crtc_state *old_crtc_state,
5003                                        const struct intel_crtc_state *new_crtc_state)
5004 {
5005         if (!new_crtc_state->ips_enabled)
5006                 return false;
5007
5008         if (needs_modeset(&new_crtc_state->base))
5009                 return true;
5010
5011         /*
5012          * We can't read out IPS on broadwell, assume the worst and
5013          * forcibly enable IPS on the first fastset.
5014          */
5015         if (new_crtc_state->update_pipe &&
5016             old_crtc_state->base.adjusted_mode.private_flags & I915_MODE_FLAG_INHERITED)
5017                 return true;
5018
5019         return !old_crtc_state->ips_enabled;
5020 }
5021
5022 static void intel_post_plane_update(struct intel_crtc_state *old_crtc_state)
5023 {
5024         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5025         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5026         struct intel_crtc_state *pipe_config =
5027                 intel_atomic_get_new_crtc_state(to_intel_atomic_state(old_state),
5028                                                 crtc);
5029         struct drm_plane *primary = crtc->base.primary;
5030         struct drm_plane_state *old_pri_state =
5031                 drm_atomic_get_existing_plane_state(old_state, primary);
5032
5033         intel_frontbuffer_flip(to_i915(crtc->base.dev), pipe_config->fb_bits);
5034
5035         if (pipe_config->update_wm_post && pipe_config->base.active)
5036                 intel_update_watermarks(crtc);
5037
5038         if (hsw_post_update_enable_ips(old_crtc_state, pipe_config))
5039                 hsw_enable_ips(pipe_config);
5040
5041         if (old_pri_state) {
5042                 struct intel_plane_state *primary_state =
5043                         intel_atomic_get_new_plane_state(to_intel_atomic_state(old_state),
5044                                                          to_intel_plane(primary));
5045                 struct intel_plane_state *old_primary_state =
5046                         to_intel_plane_state(old_pri_state);
5047
5048                 intel_fbc_post_update(crtc);
5049
5050                 if (primary_state->base.visible &&
5051                     (needs_modeset(&pipe_config->base) ||
5052                      !old_primary_state->base.visible))
5053                         intel_post_enable_primary(&crtc->base, pipe_config);
5054         }
5055 }
5056
5057 static void intel_pre_plane_update(struct intel_crtc_state *old_crtc_state,
5058                                    struct intel_crtc_state *pipe_config)
5059 {
5060         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->base.crtc);
5061         struct drm_device *dev = crtc->base.dev;
5062         struct drm_i915_private *dev_priv = to_i915(dev);
5063         struct drm_atomic_state *old_state = old_crtc_state->base.state;
5064         struct drm_plane *primary = crtc->base.primary;
5065         struct drm_plane_state *old_pri_state =
5066                 drm_atomic_get_existing_plane_state(old_state, primary);
5067         bool modeset = needs_modeset(&pipe_config->base);
5068         struct intel_atomic_state *old_intel_state =
5069                 to_intel_atomic_state(old_state);
5070
5071         if (hsw_pre_update_disable_ips(old_crtc_state, pipe_config))
5072                 hsw_disable_ips(old_crtc_state);
5073
5074         if (old_pri_state) {
5075                 struct intel_plane_state *primary_state =
5076                         intel_atomic_get_new_plane_state(old_intel_state,
5077                                                          to_intel_plane(primary));
5078                 struct intel_plane_state *old_primary_state =
5079                         to_intel_plane_state(old_pri_state);
5080
5081                 intel_fbc_pre_update(crtc, pipe_config, primary_state);
5082                 /*
5083                  * Gen2 reports pipe underruns whenever all planes are disabled.
5084                  * So disable underrun reporting before all the planes get disabled.
5085                  */
5086                 if (IS_GEN2(dev_priv) && old_primary_state->base.visible &&
5087                     (modeset || !primary_state->base.visible))
5088                         intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5089         }
5090
5091         /*
5092          * Vblank time updates from the shadow to live plane control register
5093          * are blocked if the memory self-refresh mode is active at that
5094          * moment. So to make sure the plane gets truly disabled, disable
5095          * first the self-refresh mode. The self-refresh enable bit in turn
5096          * will be checked/applied by the HW only at the next frame start
5097          * event which is after the vblank start event, so we need to have a
5098          * wait-for-vblank between disabling the plane and the pipe.
5099          */
5100         if (HAS_GMCH_DISPLAY(dev_priv) && old_crtc_state->base.active &&
5101             pipe_config->disable_cxsr && intel_set_memory_cxsr(dev_priv, false))
5102                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5103
5104         /*
5105          * IVB workaround: must disable low power watermarks for at least
5106          * one frame before enabling scaling.  LP watermarks can be re-enabled
5107          * when scaling is disabled.
5108          *
5109          * WaCxSRDisabledForSpriteScaling:ivb
5110          */
5111         if (pipe_config->disable_lp_wm && ilk_disable_lp_wm(dev))
5112                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5113
5114         /*
5115          * If we're doing a modeset, we're done.  No need to do any pre-vblank
5116          * watermark programming here.
5117          */
5118         if (needs_modeset(&pipe_config->base))
5119                 return;
5120
5121         /*
5122          * For platforms that support atomic watermarks, program the
5123          * 'intermediate' watermarks immediately.  On pre-gen9 platforms, these
5124          * will be the intermediate values that are safe for both pre- and
5125          * post- vblank; when vblank happens, the 'active' values will be set
5126          * to the final 'target' values and we'll do this again to get the
5127          * optimal watermarks.  For gen9+ platforms, the values we program here
5128          * will be the final target values which will get automatically latched
5129          * at vblank time; no further programming will be necessary.
5130          *
5131          * If a platform hasn't been transitioned to atomic watermarks yet,
5132          * we'll continue to update watermarks the old way, if flags tell
5133          * us to.
5134          */
5135         if (dev_priv->display.initial_watermarks != NULL)
5136                 dev_priv->display.initial_watermarks(old_intel_state,
5137                                                      pipe_config);
5138         else if (pipe_config->update_wm_pre)
5139                 intel_update_watermarks(crtc);
5140 }
5141
5142 static void intel_crtc_disable_planes(struct drm_crtc *crtc, unsigned plane_mask)
5143 {
5144         struct drm_device *dev = crtc->dev;
5145         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5146         struct drm_plane *p;
5147         int pipe = intel_crtc->pipe;
5148
5149         intel_crtc_dpms_overlay_disable(intel_crtc);
5150
5151         drm_for_each_plane_mask(p, dev, plane_mask)
5152                 to_intel_plane(p)->disable_plane(to_intel_plane(p), intel_crtc);
5153
5154         /*
5155          * FIXME: Once we grow proper nuclear flip support out of this we need
5156          * to compute the mask of flip planes precisely. For the time being
5157          * consider this a flip to a NULL plane.
5158          */
5159         intel_frontbuffer_flip(to_i915(dev), INTEL_FRONTBUFFER_ALL_MASK(pipe));
5160 }
5161
5162 static void intel_encoders_pre_pll_enable(struct drm_crtc *crtc,
5163                                           struct intel_crtc_state *crtc_state,
5164                                           struct drm_atomic_state *old_state)
5165 {
5166         struct drm_connector_state *conn_state;
5167         struct drm_connector *conn;
5168         int i;
5169
5170         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5171                 struct intel_encoder *encoder =
5172                         to_intel_encoder(conn_state->best_encoder);
5173
5174                 if (conn_state->crtc != crtc)
5175                         continue;
5176
5177                 if (encoder->pre_pll_enable)
5178                         encoder->pre_pll_enable(encoder, crtc_state, conn_state);
5179         }
5180 }
5181
5182 static void intel_encoders_pre_enable(struct drm_crtc *crtc,
5183                                       struct intel_crtc_state *crtc_state,
5184                                       struct drm_atomic_state *old_state)
5185 {
5186         struct drm_connector_state *conn_state;
5187         struct drm_connector *conn;
5188         int i;
5189
5190         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5191                 struct intel_encoder *encoder =
5192                         to_intel_encoder(conn_state->best_encoder);
5193
5194                 if (conn_state->crtc != crtc)
5195                         continue;
5196
5197                 if (encoder->pre_enable)
5198                         encoder->pre_enable(encoder, crtc_state, conn_state);
5199         }
5200 }
5201
5202 static void intel_encoders_enable(struct drm_crtc *crtc,
5203                                   struct intel_crtc_state *crtc_state,
5204                                   struct drm_atomic_state *old_state)
5205 {
5206         struct drm_connector_state *conn_state;
5207         struct drm_connector *conn;
5208         int i;
5209
5210         for_each_new_connector_in_state(old_state, conn, conn_state, i) {
5211                 struct intel_encoder *encoder =
5212                         to_intel_encoder(conn_state->best_encoder);
5213
5214                 if (conn_state->crtc != crtc)
5215                         continue;
5216
5217                 encoder->enable(encoder, crtc_state, conn_state);
5218                 intel_opregion_notify_encoder(encoder, true);
5219         }
5220 }
5221
5222 static void intel_encoders_disable(struct drm_crtc *crtc,
5223                                    struct intel_crtc_state *old_crtc_state,
5224                                    struct drm_atomic_state *old_state)
5225 {
5226         struct drm_connector_state *old_conn_state;
5227         struct drm_connector *conn;
5228         int i;
5229
5230         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5231                 struct intel_encoder *encoder =
5232                         to_intel_encoder(old_conn_state->best_encoder);
5233
5234                 if (old_conn_state->crtc != crtc)
5235                         continue;
5236
5237                 intel_opregion_notify_encoder(encoder, false);
5238                 encoder->disable(encoder, old_crtc_state, old_conn_state);
5239         }
5240 }
5241
5242 static void intel_encoders_post_disable(struct drm_crtc *crtc,
5243                                         struct intel_crtc_state *old_crtc_state,
5244                                         struct drm_atomic_state *old_state)
5245 {
5246         struct drm_connector_state *old_conn_state;
5247         struct drm_connector *conn;
5248         int i;
5249
5250         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5251                 struct intel_encoder *encoder =
5252                         to_intel_encoder(old_conn_state->best_encoder);
5253
5254                 if (old_conn_state->crtc != crtc)
5255                         continue;
5256
5257                 if (encoder->post_disable)
5258                         encoder->post_disable(encoder, old_crtc_state, old_conn_state);
5259         }
5260 }
5261
5262 static void intel_encoders_post_pll_disable(struct drm_crtc *crtc,
5263                                             struct intel_crtc_state *old_crtc_state,
5264                                             struct drm_atomic_state *old_state)
5265 {
5266         struct drm_connector_state *old_conn_state;
5267         struct drm_connector *conn;
5268         int i;
5269
5270         for_each_old_connector_in_state(old_state, conn, old_conn_state, i) {
5271                 struct intel_encoder *encoder =
5272                         to_intel_encoder(old_conn_state->best_encoder);
5273
5274                 if (old_conn_state->crtc != crtc)
5275                         continue;
5276
5277                 if (encoder->post_pll_disable)
5278                         encoder->post_pll_disable(encoder, old_crtc_state, old_conn_state);
5279         }
5280 }
5281
5282 static void ironlake_crtc_enable(struct intel_crtc_state *pipe_config,
5283                                  struct drm_atomic_state *old_state)
5284 {
5285         struct drm_crtc *crtc = pipe_config->base.crtc;
5286         struct drm_device *dev = crtc->dev;
5287         struct drm_i915_private *dev_priv = to_i915(dev);
5288         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5289         int pipe = intel_crtc->pipe;
5290         struct intel_atomic_state *old_intel_state =
5291                 to_intel_atomic_state(old_state);
5292
5293         if (WARN_ON(intel_crtc->active))
5294                 return;
5295
5296         /*
5297          * Sometimes spurious CPU pipe underruns happen during FDI
5298          * training, at least with VGA+HDMI cloning. Suppress them.
5299          *
5300          * On ILK we get an occasional spurious CPU pipe underruns
5301          * between eDP port A enable and vdd enable. Also PCH port
5302          * enable seems to result in the occasional CPU pipe underrun.
5303          *
5304          * Spurious PCH underruns also occur during PCH enabling.
5305          */
5306         if (intel_crtc->config->has_pch_encoder || IS_GEN5(dev_priv))
5307                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5308         if (intel_crtc->config->has_pch_encoder)
5309                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5310
5311         if (intel_crtc->config->has_pch_encoder)
5312                 intel_prepare_shared_dpll(intel_crtc);
5313
5314         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5315                 intel_dp_set_m_n(intel_crtc, M1_N1);
5316
5317         intel_set_pipe_timings(intel_crtc);
5318         intel_set_pipe_src_size(intel_crtc);
5319
5320         if (intel_crtc->config->has_pch_encoder) {
5321                 intel_cpu_transcoder_set_m_n(intel_crtc,
5322                                      &intel_crtc->config->fdi_m_n, NULL);
5323         }
5324
5325         ironlake_set_pipeconf(crtc);
5326
5327         intel_crtc->active = true;
5328
5329         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5330
5331         if (intel_crtc->config->has_pch_encoder) {
5332                 /* Note: FDI PLL enabling _must_ be done before we enable the
5333                  * cpu pipes, hence this is separate from all the other fdi/pch
5334                  * enabling. */
5335                 ironlake_fdi_pll_enable(intel_crtc);
5336         } else {
5337                 assert_fdi_tx_disabled(dev_priv, pipe);
5338                 assert_fdi_rx_disabled(dev_priv, pipe);
5339         }
5340
5341         ironlake_pfit_enable(intel_crtc);
5342
5343         /*
5344          * On ILK+ LUT must be loaded before the pipe is running but with
5345          * clocks enabled
5346          */
5347         intel_color_load_luts(&pipe_config->base);
5348
5349         if (dev_priv->display.initial_watermarks != NULL)
5350                 dev_priv->display.initial_watermarks(old_intel_state, intel_crtc->config);
5351         intel_enable_pipe(pipe_config);
5352
5353         if (intel_crtc->config->has_pch_encoder)
5354                 ironlake_pch_enable(pipe_config);
5355
5356         assert_vblank_disabled(crtc);
5357         drm_crtc_vblank_on(crtc);
5358
5359         intel_encoders_enable(crtc, pipe_config, old_state);
5360
5361         if (HAS_PCH_CPT(dev_priv))
5362                 cpt_verify_modeset(dev, intel_crtc->pipe);
5363
5364         /* Must wait for vblank to avoid spurious PCH FIFO underruns */
5365         if (intel_crtc->config->has_pch_encoder)
5366                 intel_wait_for_vblank(dev_priv, pipe);
5367         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5368         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5369 }
5370
5371 /* IPS only exists on ULT machines and is tied to pipe A. */
5372 static bool hsw_crtc_supports_ips(struct intel_crtc *crtc)
5373 {
5374         return HAS_IPS(to_i915(crtc->base.dev)) && crtc->pipe == PIPE_A;
5375 }
5376
5377 static void glk_pipe_scaler_clock_gating_wa(struct drm_i915_private *dev_priv,
5378                                             enum pipe pipe, bool apply)
5379 {
5380         u32 val = I915_READ(CLKGATE_DIS_PSL(pipe));
5381         u32 mask = DPF_GATING_DIS | DPF_RAM_GATING_DIS | DPFR_GATING_DIS;
5382
5383         if (apply)
5384                 val |= mask;
5385         else
5386                 val &= ~mask;
5387
5388         I915_WRITE(CLKGATE_DIS_PSL(pipe), val);
5389 }
5390
5391 static void haswell_crtc_enable(struct intel_crtc_state *pipe_config,
5392                                 struct drm_atomic_state *old_state)
5393 {
5394         struct drm_crtc *crtc = pipe_config->base.crtc;
5395         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5396         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5397         int pipe = intel_crtc->pipe, hsw_workaround_pipe;
5398         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5399         struct intel_atomic_state *old_intel_state =
5400                 to_intel_atomic_state(old_state);
5401         bool psl_clkgate_wa;
5402
5403         if (WARN_ON(intel_crtc->active))
5404                 return;
5405
5406         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5407
5408         if (intel_crtc->config->shared_dpll)
5409                 intel_enable_shared_dpll(intel_crtc);
5410
5411         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5412                 intel_dp_set_m_n(intel_crtc, M1_N1);
5413
5414         if (!transcoder_is_dsi(cpu_transcoder))
5415                 intel_set_pipe_timings(intel_crtc);
5416
5417         intel_set_pipe_src_size(intel_crtc);
5418
5419         if (cpu_transcoder != TRANSCODER_EDP &&
5420             !transcoder_is_dsi(cpu_transcoder)) {
5421                 I915_WRITE(PIPE_MULT(cpu_transcoder),
5422                            intel_crtc->config->pixel_multiplier - 1);
5423         }
5424
5425         if (intel_crtc->config->has_pch_encoder) {
5426                 intel_cpu_transcoder_set_m_n(intel_crtc,
5427                                      &intel_crtc->config->fdi_m_n, NULL);
5428         }
5429
5430         if (!transcoder_is_dsi(cpu_transcoder))
5431                 haswell_set_pipeconf(crtc);
5432
5433         haswell_set_pipemisc(crtc);
5434
5435         intel_color_set_csc(&pipe_config->base);
5436
5437         intel_crtc->active = true;
5438
5439         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5440
5441         if (!transcoder_is_dsi(cpu_transcoder))
5442                 intel_ddi_enable_pipe_clock(pipe_config);
5443
5444         /* Display WA #1180: WaDisableScalarClockGating: glk, cnl */
5445         psl_clkgate_wa = (IS_GEMINILAKE(dev_priv) || IS_CANNONLAKE(dev_priv)) &&
5446                          intel_crtc->config->pch_pfit.enabled;
5447         if (psl_clkgate_wa)
5448                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, true);
5449
5450         if (INTEL_GEN(dev_priv) >= 9)
5451                 skylake_pfit_enable(intel_crtc);
5452         else
5453                 ironlake_pfit_enable(intel_crtc);
5454
5455         /*
5456          * On ILK+ LUT must be loaded before the pipe is running but with
5457          * clocks enabled
5458          */
5459         intel_color_load_luts(&pipe_config->base);
5460
5461         intel_ddi_set_pipe_settings(pipe_config);
5462         if (!transcoder_is_dsi(cpu_transcoder))
5463                 intel_ddi_enable_transcoder_func(pipe_config);
5464
5465         if (dev_priv->display.initial_watermarks != NULL)
5466                 dev_priv->display.initial_watermarks(old_intel_state, pipe_config);
5467
5468         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5469         if (!transcoder_is_dsi(cpu_transcoder))
5470                 intel_enable_pipe(pipe_config);
5471
5472         if (intel_crtc->config->has_pch_encoder)
5473                 lpt_pch_enable(pipe_config);
5474
5475         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5476                 intel_ddi_set_vc_payload_alloc(pipe_config, true);
5477
5478         assert_vblank_disabled(crtc);
5479         drm_crtc_vblank_on(crtc);
5480
5481         intel_encoders_enable(crtc, pipe_config, old_state);
5482
5483         if (psl_clkgate_wa) {
5484                 intel_wait_for_vblank(dev_priv, pipe);
5485                 glk_pipe_scaler_clock_gating_wa(dev_priv, pipe, false);
5486         }
5487
5488         /* If we change the relative order between pipe/planes enabling, we need
5489          * to change the workaround. */
5490         hsw_workaround_pipe = pipe_config->hsw_workaround_pipe;
5491         if (IS_HASWELL(dev_priv) && hsw_workaround_pipe != INVALID_PIPE) {
5492                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5493                 intel_wait_for_vblank(dev_priv, hsw_workaround_pipe);
5494         }
5495 }
5496
5497 static void ironlake_pfit_disable(struct intel_crtc *crtc, bool force)
5498 {
5499         struct drm_device *dev = crtc->base.dev;
5500         struct drm_i915_private *dev_priv = to_i915(dev);
5501         int pipe = crtc->pipe;
5502
5503         /* To avoid upsetting the power well on haswell only disable the pfit if
5504          * it's in use. The hw state code will make sure we get this right. */
5505         if (force || crtc->config->pch_pfit.enabled) {
5506                 I915_WRITE(PF_CTL(pipe), 0);
5507                 I915_WRITE(PF_WIN_POS(pipe), 0);
5508                 I915_WRITE(PF_WIN_SZ(pipe), 0);
5509         }
5510 }
5511
5512 static void ironlake_crtc_disable(struct intel_crtc_state *old_crtc_state,
5513                                   struct drm_atomic_state *old_state)
5514 {
5515         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5516         struct drm_device *dev = crtc->dev;
5517         struct drm_i915_private *dev_priv = to_i915(dev);
5518         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5519         int pipe = intel_crtc->pipe;
5520
5521         /*
5522          * Sometimes spurious CPU pipe underruns happen when the
5523          * pipe is already disabled, but FDI RX/TX is still enabled.
5524          * Happens at least with VGA+HDMI cloning. Suppress them.
5525          */
5526         if (intel_crtc->config->has_pch_encoder) {
5527                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5528                 intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, false);
5529         }
5530
5531         intel_encoders_disable(crtc, old_crtc_state, old_state);
5532
5533         drm_crtc_vblank_off(crtc);
5534         assert_vblank_disabled(crtc);
5535
5536         intel_disable_pipe(old_crtc_state);
5537
5538         ironlake_pfit_disable(intel_crtc, false);
5539
5540         if (intel_crtc->config->has_pch_encoder)
5541                 ironlake_fdi_disable(crtc);
5542
5543         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5544
5545         if (intel_crtc->config->has_pch_encoder) {
5546                 ironlake_disable_pch_transcoder(dev_priv, pipe);
5547
5548                 if (HAS_PCH_CPT(dev_priv)) {
5549                         i915_reg_t reg;
5550                         u32 temp;
5551
5552                         /* disable TRANS_DP_CTL */
5553                         reg = TRANS_DP_CTL(pipe);
5554                         temp = I915_READ(reg);
5555                         temp &= ~(TRANS_DP_OUTPUT_ENABLE |
5556                                   TRANS_DP_PORT_SEL_MASK);
5557                         temp |= TRANS_DP_PORT_SEL_NONE;
5558                         I915_WRITE(reg, temp);
5559
5560                         /* disable DPLL_SEL */
5561                         temp = I915_READ(PCH_DPLL_SEL);
5562                         temp &= ~(TRANS_DPLL_ENABLE(pipe) | TRANS_DPLLB_SEL(pipe));
5563                         I915_WRITE(PCH_DPLL_SEL, temp);
5564                 }
5565
5566                 ironlake_fdi_pll_disable(intel_crtc);
5567         }
5568
5569         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5570         intel_set_pch_fifo_underrun_reporting(dev_priv, pipe, true);
5571 }
5572
5573 static void haswell_crtc_disable(struct intel_crtc_state *old_crtc_state,
5574                                  struct drm_atomic_state *old_state)
5575 {
5576         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5577         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5578         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5579         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
5580
5581         intel_encoders_disable(crtc, old_crtc_state, old_state);
5582
5583         drm_crtc_vblank_off(crtc);
5584         assert_vblank_disabled(crtc);
5585
5586         /* XXX: Do the pipe assertions at the right place for BXT DSI. */
5587         if (!transcoder_is_dsi(cpu_transcoder))
5588                 intel_disable_pipe(old_crtc_state);
5589
5590         if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DP_MST))
5591                 intel_ddi_set_vc_payload_alloc(intel_crtc->config, false);
5592
5593         if (!transcoder_is_dsi(cpu_transcoder))
5594                 intel_ddi_disable_transcoder_func(dev_priv, cpu_transcoder);
5595
5596         if (INTEL_GEN(dev_priv) >= 9)
5597                 skylake_scaler_disable(intel_crtc);
5598         else
5599                 ironlake_pfit_disable(intel_crtc, false);
5600
5601         if (!transcoder_is_dsi(cpu_transcoder))
5602                 intel_ddi_disable_pipe_clock(intel_crtc->config);
5603
5604         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5605 }
5606
5607 static void i9xx_pfit_enable(struct intel_crtc *crtc)
5608 {
5609         struct drm_device *dev = crtc->base.dev;
5610         struct drm_i915_private *dev_priv = to_i915(dev);
5611         struct intel_crtc_state *pipe_config = crtc->config;
5612
5613         if (!pipe_config->gmch_pfit.control)
5614                 return;
5615
5616         /*
5617          * The panel fitter should only be adjusted whilst the pipe is disabled,
5618          * according to register description and PRM.
5619          */
5620         WARN_ON(I915_READ(PFIT_CONTROL) & PFIT_ENABLE);
5621         assert_pipe_disabled(dev_priv, crtc->pipe);
5622
5623         I915_WRITE(PFIT_PGM_RATIOS, pipe_config->gmch_pfit.pgm_ratios);
5624         I915_WRITE(PFIT_CONTROL, pipe_config->gmch_pfit.control);
5625
5626         /* Border color in case we don't scale up to the full screen. Black by
5627          * default, change to something else for debugging. */
5628         I915_WRITE(BCLRPAT(crtc->pipe), 0);
5629 }
5630
5631 enum intel_display_power_domain intel_port_to_power_domain(enum port port)
5632 {
5633         switch (port) {
5634         case PORT_A:
5635                 return POWER_DOMAIN_PORT_DDI_A_LANES;
5636         case PORT_B:
5637                 return POWER_DOMAIN_PORT_DDI_B_LANES;
5638         case PORT_C:
5639                 return POWER_DOMAIN_PORT_DDI_C_LANES;
5640         case PORT_D:
5641                 return POWER_DOMAIN_PORT_DDI_D_LANES;
5642         case PORT_E:
5643                 return POWER_DOMAIN_PORT_DDI_E_LANES;
5644         default:
5645                 MISSING_CASE(port);
5646                 return POWER_DOMAIN_PORT_OTHER;
5647         }
5648 }
5649
5650 static u64 get_crtc_power_domains(struct drm_crtc *crtc,
5651                                   struct intel_crtc_state *crtc_state)
5652 {
5653         struct drm_device *dev = crtc->dev;
5654         struct drm_i915_private *dev_priv = to_i915(dev);
5655         struct drm_encoder *encoder;
5656         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5657         enum pipe pipe = intel_crtc->pipe;
5658         u64 mask;
5659         enum transcoder transcoder = crtc_state->cpu_transcoder;
5660
5661         if (!crtc_state->base.active)
5662                 return 0;
5663
5664         mask = BIT_ULL(POWER_DOMAIN_PIPE(pipe));
5665         mask |= BIT_ULL(POWER_DOMAIN_TRANSCODER(transcoder));
5666         if (crtc_state->pch_pfit.enabled ||
5667             crtc_state->pch_pfit.force_thru)
5668                 mask |= BIT_ULL(POWER_DOMAIN_PIPE_PANEL_FITTER(pipe));
5669
5670         drm_for_each_encoder_mask(encoder, dev, crtc_state->base.encoder_mask) {
5671                 struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5672
5673                 mask |= BIT_ULL(intel_encoder->power_domain);
5674         }
5675
5676         if (HAS_DDI(dev_priv) && crtc_state->has_audio)
5677                 mask |= BIT_ULL(POWER_DOMAIN_AUDIO);
5678
5679         if (crtc_state->shared_dpll)
5680                 mask |= BIT_ULL(POWER_DOMAIN_PLLS);
5681
5682         return mask;
5683 }
5684
5685 static u64
5686 modeset_get_crtc_power_domains(struct drm_crtc *crtc,
5687                                struct intel_crtc_state *crtc_state)
5688 {
5689         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5690         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5691         enum intel_display_power_domain domain;
5692         u64 domains, new_domains, old_domains;
5693
5694         old_domains = intel_crtc->enabled_power_domains;
5695         intel_crtc->enabled_power_domains = new_domains =
5696                 get_crtc_power_domains(crtc, crtc_state);
5697
5698         domains = new_domains & ~old_domains;
5699
5700         for_each_power_domain(domain, domains)
5701                 intel_display_power_get(dev_priv, domain);
5702
5703         return old_domains & ~new_domains;
5704 }
5705
5706 static void modeset_put_power_domains(struct drm_i915_private *dev_priv,
5707                                       u64 domains)
5708 {
5709         enum intel_display_power_domain domain;
5710
5711         for_each_power_domain(domain, domains)
5712                 intel_display_power_put(dev_priv, domain);
5713 }
5714
5715 static void valleyview_crtc_enable(struct intel_crtc_state *pipe_config,
5716                                    struct drm_atomic_state *old_state)
5717 {
5718         struct intel_atomic_state *old_intel_state =
5719                 to_intel_atomic_state(old_state);
5720         struct drm_crtc *crtc = pipe_config->base.crtc;
5721         struct drm_device *dev = crtc->dev;
5722         struct drm_i915_private *dev_priv = to_i915(dev);
5723         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5724         int pipe = intel_crtc->pipe;
5725
5726         if (WARN_ON(intel_crtc->active))
5727                 return;
5728
5729         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5730                 intel_dp_set_m_n(intel_crtc, M1_N1);
5731
5732         intel_set_pipe_timings(intel_crtc);
5733         intel_set_pipe_src_size(intel_crtc);
5734
5735         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
5736                 struct drm_i915_private *dev_priv = to_i915(dev);
5737
5738                 I915_WRITE(CHV_BLEND(pipe), CHV_BLEND_LEGACY);
5739                 I915_WRITE(CHV_CANVAS(pipe), 0);
5740         }
5741
5742         i9xx_set_pipeconf(intel_crtc);
5743
5744         intel_crtc->active = true;
5745
5746         intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5747
5748         intel_encoders_pre_pll_enable(crtc, pipe_config, old_state);
5749
5750         if (IS_CHERRYVIEW(dev_priv)) {
5751                 chv_prepare_pll(intel_crtc, intel_crtc->config);
5752                 chv_enable_pll(intel_crtc, intel_crtc->config);
5753         } else {
5754                 vlv_prepare_pll(intel_crtc, intel_crtc->config);
5755                 vlv_enable_pll(intel_crtc, intel_crtc->config);
5756         }
5757
5758         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5759
5760         i9xx_pfit_enable(intel_crtc);
5761
5762         intel_color_load_luts(&pipe_config->base);
5763
5764         dev_priv->display.initial_watermarks(old_intel_state,
5765                                              pipe_config);
5766         intel_enable_pipe(pipe_config);
5767
5768         assert_vblank_disabled(crtc);
5769         drm_crtc_vblank_on(crtc);
5770
5771         intel_encoders_enable(crtc, pipe_config, old_state);
5772 }
5773
5774 static void i9xx_set_pll_dividers(struct intel_crtc *crtc)
5775 {
5776         struct drm_device *dev = crtc->base.dev;
5777         struct drm_i915_private *dev_priv = to_i915(dev);
5778
5779         I915_WRITE(FP0(crtc->pipe), crtc->config->dpll_hw_state.fp0);
5780         I915_WRITE(FP1(crtc->pipe), crtc->config->dpll_hw_state.fp1);
5781 }
5782
5783 static void i9xx_crtc_enable(struct intel_crtc_state *pipe_config,
5784                              struct drm_atomic_state *old_state)
5785 {
5786         struct intel_atomic_state *old_intel_state =
5787                 to_intel_atomic_state(old_state);
5788         struct drm_crtc *crtc = pipe_config->base.crtc;
5789         struct drm_device *dev = crtc->dev;
5790         struct drm_i915_private *dev_priv = to_i915(dev);
5791         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5792         enum pipe pipe = intel_crtc->pipe;
5793
5794         if (WARN_ON(intel_crtc->active))
5795                 return;
5796
5797         i9xx_set_pll_dividers(intel_crtc);
5798
5799         if (intel_crtc_has_dp_encoder(intel_crtc->config))
5800                 intel_dp_set_m_n(intel_crtc, M1_N1);
5801
5802         intel_set_pipe_timings(intel_crtc);
5803         intel_set_pipe_src_size(intel_crtc);
5804
5805         i9xx_set_pipeconf(intel_crtc);
5806
5807         intel_crtc->active = true;
5808
5809         if (!IS_GEN2(dev_priv))
5810                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, true);
5811
5812         intel_encoders_pre_enable(crtc, pipe_config, old_state);
5813
5814         i9xx_enable_pll(intel_crtc, pipe_config);
5815
5816         i9xx_pfit_enable(intel_crtc);
5817
5818         intel_color_load_luts(&pipe_config->base);
5819
5820         if (dev_priv->display.initial_watermarks != NULL)
5821                 dev_priv->display.initial_watermarks(old_intel_state,
5822                                                      intel_crtc->config);
5823         else
5824                 intel_update_watermarks(intel_crtc);
5825         intel_enable_pipe(pipe_config);
5826
5827         assert_vblank_disabled(crtc);
5828         drm_crtc_vblank_on(crtc);
5829
5830         intel_encoders_enable(crtc, pipe_config, old_state);
5831 }
5832
5833 static void i9xx_pfit_disable(struct intel_crtc *crtc)
5834 {
5835         struct drm_device *dev = crtc->base.dev;
5836         struct drm_i915_private *dev_priv = to_i915(dev);
5837
5838         if (!crtc->config->gmch_pfit.control)
5839                 return;
5840
5841         assert_pipe_disabled(dev_priv, crtc->pipe);
5842
5843         DRM_DEBUG_DRIVER("disabling pfit, current: 0x%08x\n",
5844                          I915_READ(PFIT_CONTROL));
5845         I915_WRITE(PFIT_CONTROL, 0);
5846 }
5847
5848 static void i9xx_crtc_disable(struct intel_crtc_state *old_crtc_state,
5849                               struct drm_atomic_state *old_state)
5850 {
5851         struct drm_crtc *crtc = old_crtc_state->base.crtc;
5852         struct drm_device *dev = crtc->dev;
5853         struct drm_i915_private *dev_priv = to_i915(dev);
5854         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5855         int pipe = intel_crtc->pipe;
5856
5857         /*
5858          * On gen2 planes are double buffered but the pipe isn't, so we must
5859          * wait for planes to fully turn off before disabling the pipe.
5860          */
5861         if (IS_GEN2(dev_priv))
5862                 intel_wait_for_vblank(dev_priv, pipe);
5863
5864         intel_encoders_disable(crtc, old_crtc_state, old_state);
5865
5866         drm_crtc_vblank_off(crtc);
5867         assert_vblank_disabled(crtc);
5868
5869         intel_disable_pipe(old_crtc_state);
5870
5871         i9xx_pfit_disable(intel_crtc);
5872
5873         intel_encoders_post_disable(crtc, old_crtc_state, old_state);
5874
5875         if (!intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_DSI)) {
5876                 if (IS_CHERRYVIEW(dev_priv))
5877                         chv_disable_pll(dev_priv, pipe);
5878                 else if (IS_VALLEYVIEW(dev_priv))
5879                         vlv_disable_pll(dev_priv, pipe);
5880                 else
5881                         i9xx_disable_pll(intel_crtc);
5882         }
5883
5884         intel_encoders_post_pll_disable(crtc, old_crtc_state, old_state);
5885
5886         if (!IS_GEN2(dev_priv))
5887                 intel_set_cpu_fifo_underrun_reporting(dev_priv, pipe, false);
5888
5889         if (!dev_priv->display.initial_watermarks)
5890                 intel_update_watermarks(intel_crtc);
5891
5892         /* clock the pipe down to 640x480@60 to potentially save power */
5893         if (IS_I830(dev_priv))
5894                 i830_enable_pipe(dev_priv, pipe);
5895 }
5896
5897 static void intel_crtc_disable_noatomic(struct drm_crtc *crtc,
5898                                         struct drm_modeset_acquire_ctx *ctx)
5899 {
5900         struct intel_encoder *encoder;
5901         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
5902         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
5903         enum intel_display_power_domain domain;
5904         struct intel_plane *plane;
5905         u64 domains;
5906         struct drm_atomic_state *state;
5907         struct intel_crtc_state *crtc_state;
5908         int ret;
5909
5910         if (!intel_crtc->active)
5911                 return;
5912
5913         for_each_intel_plane_on_crtc(&dev_priv->drm, intel_crtc, plane) {
5914                 const struct intel_plane_state *plane_state =
5915                         to_intel_plane_state(plane->base.state);
5916
5917                 if (plane_state->base.visible)
5918                         intel_plane_disable_noatomic(intel_crtc, plane);
5919         }
5920
5921         state = drm_atomic_state_alloc(crtc->dev);
5922         if (!state) {
5923                 DRM_DEBUG_KMS("failed to disable [CRTC:%d:%s], out of memory",
5924                               crtc->base.id, crtc->name);
5925                 return;
5926         }
5927
5928         state->acquire_ctx = ctx;
5929
5930         /* Everything's already locked, -EDEADLK can't happen. */
5931         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
5932         ret = drm_atomic_add_affected_connectors(state, crtc);
5933
5934         WARN_ON(IS_ERR(crtc_state) || ret);
5935
5936         dev_priv->display.crtc_disable(crtc_state, state);
5937
5938         drm_atomic_state_put(state);
5939
5940         DRM_DEBUG_KMS("[CRTC:%d:%s] hw state adjusted, was enabled, now disabled\n",
5941                       crtc->base.id, crtc->name);
5942
5943         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->state, NULL) < 0);
5944         crtc->state->active = false;
5945         intel_crtc->active = false;
5946         crtc->enabled = false;
5947         crtc->state->connector_mask = 0;
5948         crtc->state->encoder_mask = 0;
5949
5950         for_each_encoder_on_crtc(crtc->dev, crtc, encoder)
5951                 encoder->base.crtc = NULL;
5952
5953         intel_fbc_disable(intel_crtc);
5954         intel_update_watermarks(intel_crtc);
5955         intel_disable_shared_dpll(intel_crtc);
5956
5957         domains = intel_crtc->enabled_power_domains;
5958         for_each_power_domain(domain, domains)
5959                 intel_display_power_put(dev_priv, domain);
5960         intel_crtc->enabled_power_domains = 0;
5961
5962         dev_priv->active_crtcs &= ~(1 << intel_crtc->pipe);
5963         dev_priv->min_cdclk[intel_crtc->pipe] = 0;
5964         dev_priv->min_voltage_level[intel_crtc->pipe] = 0;
5965 }
5966
5967 /*
5968  * turn all crtc's off, but do not adjust state
5969  * This has to be paired with a call to intel_modeset_setup_hw_state.
5970  */
5971 int intel_display_suspend(struct drm_device *dev)
5972 {
5973         struct drm_i915_private *dev_priv = to_i915(dev);
5974         struct drm_atomic_state *state;
5975         int ret;
5976
5977         state = drm_atomic_helper_suspend(dev);
5978         ret = PTR_ERR_OR_ZERO(state);
5979         if (ret)
5980                 DRM_ERROR("Suspending crtc's failed with %i\n", ret);
5981         else
5982                 dev_priv->modeset_restore_state = state;
5983         return ret;
5984 }
5985
5986 void intel_encoder_destroy(struct drm_encoder *encoder)
5987 {
5988         struct intel_encoder *intel_encoder = to_intel_encoder(encoder);
5989
5990         drm_encoder_cleanup(encoder);
5991         kfree(intel_encoder);
5992 }
5993
5994 /* Cross check the actual hw state with our own modeset state tracking (and it's
5995  * internal consistency). */
5996 static void intel_connector_verify_state(struct drm_crtc_state *crtc_state,
5997                                          struct drm_connector_state *conn_state)
5998 {
5999         struct intel_connector *connector = to_intel_connector(conn_state->connector);
6000
6001         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n",
6002                       connector->base.base.id,
6003                       connector->base.name);
6004
6005         if (connector->get_hw_state(connector)) {
6006                 struct intel_encoder *encoder = connector->encoder;
6007
6008                 I915_STATE_WARN(!crtc_state,
6009                          "connector enabled without attached crtc\n");
6010
6011                 if (!crtc_state)
6012                         return;
6013
6014                 I915_STATE_WARN(!crtc_state->active,
6015                       "connector is active, but attached crtc isn't\n");
6016
6017                 if (!encoder || encoder->type == INTEL_OUTPUT_DP_MST)
6018                         return;
6019
6020                 I915_STATE_WARN(conn_state->best_encoder != &encoder->base,
6021                         "atomic encoder doesn't match attached encoder\n");
6022
6023                 I915_STATE_WARN(conn_state->crtc != encoder->base.crtc,
6024                         "attached encoder crtc differs from connector crtc\n");
6025         } else {
6026                 I915_STATE_WARN(crtc_state && crtc_state->active,
6027                         "attached crtc is active, but connector isn't\n");
6028                 I915_STATE_WARN(!crtc_state && conn_state->best_encoder,
6029                         "best encoder set without crtc!\n");
6030         }
6031 }
6032
6033 int intel_connector_init(struct intel_connector *connector)
6034 {
6035         struct intel_digital_connector_state *conn_state;
6036
6037         /*
6038          * Allocate enough memory to hold intel_digital_connector_state,
6039          * This might be a few bytes too many, but for connectors that don't
6040          * need it we'll free the state and allocate a smaller one on the first
6041          * succesful commit anyway.
6042          */
6043         conn_state = kzalloc(sizeof(*conn_state), GFP_KERNEL);
6044         if (!conn_state)
6045                 return -ENOMEM;
6046
6047         __drm_atomic_helper_connector_reset(&connector->base,
6048                                             &conn_state->base);
6049
6050         return 0;
6051 }
6052
6053 struct intel_connector *intel_connector_alloc(void)
6054 {
6055         struct intel_connector *connector;
6056
6057         connector = kzalloc(sizeof *connector, GFP_KERNEL);
6058         if (!connector)
6059                 return NULL;
6060
6061         if (intel_connector_init(connector) < 0) {
6062                 kfree(connector);
6063                 return NULL;
6064         }
6065
6066         return connector;
6067 }
6068
6069 /*
6070  * Free the bits allocated by intel_connector_alloc.
6071  * This should only be used after intel_connector_alloc has returned
6072  * successfully, and before drm_connector_init returns successfully.
6073  * Otherwise the destroy callbacks for the connector and the state should
6074  * take care of proper cleanup/free
6075  */
6076 void intel_connector_free(struct intel_connector *connector)
6077 {
6078         kfree(to_intel_digital_connector_state(connector->base.state));
6079         kfree(connector);
6080 }
6081
6082 /* Simple connector->get_hw_state implementation for encoders that support only
6083  * one connector and no cloning and hence the encoder state determines the state
6084  * of the connector. */
6085 bool intel_connector_get_hw_state(struct intel_connector *connector)
6086 {
6087         enum pipe pipe = 0;
6088         struct intel_encoder *encoder = connector->encoder;
6089
6090         return encoder->get_hw_state(encoder, &pipe);
6091 }
6092
6093 static int pipe_required_fdi_lanes(struct intel_crtc_state *crtc_state)
6094 {
6095         if (crtc_state->base.enable && crtc_state->has_pch_encoder)
6096                 return crtc_state->fdi_lanes;
6097
6098         return 0;
6099 }
6100
6101 static int ironlake_check_fdi_lanes(struct drm_device *dev, enum pipe pipe,
6102                                      struct intel_crtc_state *pipe_config)
6103 {
6104         struct drm_i915_private *dev_priv = to_i915(dev);
6105         struct drm_atomic_state *state = pipe_config->base.state;
6106         struct intel_crtc *other_crtc;
6107         struct intel_crtc_state *other_crtc_state;
6108
6109         DRM_DEBUG_KMS("checking fdi config on pipe %c, lanes %i\n",
6110                       pipe_name(pipe), pipe_config->fdi_lanes);
6111         if (pipe_config->fdi_lanes > 4) {
6112                 DRM_DEBUG_KMS("invalid fdi lane config on pipe %c: %i lanes\n",
6113                               pipe_name(pipe), pipe_config->fdi_lanes);
6114                 return -EINVAL;
6115         }
6116
6117         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
6118                 if (pipe_config->fdi_lanes > 2) {
6119                         DRM_DEBUG_KMS("only 2 lanes on haswell, required: %i lanes\n",
6120                                       pipe_config->fdi_lanes);
6121                         return -EINVAL;
6122                 } else {
6123                         return 0;
6124                 }
6125         }
6126
6127         if (INTEL_INFO(dev_priv)->num_pipes == 2)
6128                 return 0;
6129
6130         /* Ivybridge 3 pipe is really complicated */
6131         switch (pipe) {
6132         case PIPE_A:
6133                 return 0;
6134         case PIPE_B:
6135                 if (pipe_config->fdi_lanes <= 2)
6136                         return 0;
6137
6138                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_C);
6139                 other_crtc_state =
6140                         intel_atomic_get_crtc_state(state, other_crtc);
6141                 if (IS_ERR(other_crtc_state))
6142                         return PTR_ERR(other_crtc_state);
6143
6144                 if (pipe_required_fdi_lanes(other_crtc_state) > 0) {
6145                         DRM_DEBUG_KMS("invalid shared fdi lane config on pipe %c: %i lanes\n",
6146                                       pipe_name(pipe), pipe_config->fdi_lanes);
6147                         return -EINVAL;
6148                 }
6149                 return 0;
6150         case PIPE_C:
6151                 if (pipe_config->fdi_lanes > 2) {
6152                         DRM_DEBUG_KMS("only 2 lanes on pipe %c: required %i lanes\n",
6153                                       pipe_name(pipe), pipe_config->fdi_lanes);
6154                         return -EINVAL;
6155                 }
6156
6157                 other_crtc = intel_get_crtc_for_pipe(dev_priv, PIPE_B);
6158                 other_crtc_state =
6159                         intel_atomic_get_crtc_state(state, other_crtc);
6160                 if (IS_ERR(other_crtc_state))
6161                         return PTR_ERR(other_crtc_state);
6162
6163                 if (pipe_required_fdi_lanes(other_crtc_state) > 2) {
6164                         DRM_DEBUG_KMS("fdi link B uses too many lanes to enable link C\n");
6165                         return -EINVAL;
6166                 }
6167                 return 0;
6168         default:
6169                 BUG();
6170         }
6171 }
6172
6173 #define RETRY 1
6174 static int ironlake_fdi_compute_config(struct intel_crtc *intel_crtc,
6175                                        struct intel_crtc_state *pipe_config)
6176 {
6177         struct drm_device *dev = intel_crtc->base.dev;
6178         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6179         int lane, link_bw, fdi_dotclock, ret;
6180         bool needs_recompute = false;
6181
6182 retry:
6183         /* FDI is a binary signal running at ~2.7GHz, encoding
6184          * each output octet as 10 bits. The actual frequency
6185          * is stored as a divider into a 100MHz clock, and the
6186          * mode pixel clock is stored in units of 1KHz.
6187          * Hence the bw of each lane in terms of the mode signal
6188          * is:
6189          */
6190         link_bw = intel_fdi_link_freq(to_i915(dev), pipe_config);
6191
6192         fdi_dotclock = adjusted_mode->crtc_clock;
6193
6194         lane = ironlake_get_lanes_required(fdi_dotclock, link_bw,
6195                                            pipe_config->pipe_bpp);
6196
6197         pipe_config->fdi_lanes = lane;
6198
6199         intel_link_compute_m_n(pipe_config->pipe_bpp, lane, fdi_dotclock,
6200                                link_bw, &pipe_config->fdi_m_n, false);
6201
6202         ret = ironlake_check_fdi_lanes(dev, intel_crtc->pipe, pipe_config);
6203         if (ret == -EINVAL && pipe_config->pipe_bpp > 6*3) {
6204                 pipe_config->pipe_bpp -= 2*3;
6205                 DRM_DEBUG_KMS("fdi link bw constraint, reducing pipe bpp to %i\n",
6206                               pipe_config->pipe_bpp);
6207                 needs_recompute = true;
6208                 pipe_config->bw_constrained = true;
6209
6210                 goto retry;
6211         }
6212
6213         if (needs_recompute)
6214                 return RETRY;
6215
6216         return ret;
6217 }
6218
6219 bool hsw_crtc_state_ips_capable(const struct intel_crtc_state *crtc_state)
6220 {
6221         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
6222         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6223
6224         /* IPS only exists on ULT machines and is tied to pipe A. */
6225         if (!hsw_crtc_supports_ips(crtc))
6226                 return false;
6227
6228         if (!i915_modparams.enable_ips)
6229                 return false;
6230
6231         if (crtc_state->pipe_bpp > 24)
6232                 return false;
6233
6234         /*
6235          * We compare against max which means we must take
6236          * the increased cdclk requirement into account when
6237          * calculating the new cdclk.
6238          *
6239          * Should measure whether using a lower cdclk w/o IPS
6240          */
6241         if (IS_BROADWELL(dev_priv) &&
6242             crtc_state->pixel_rate > dev_priv->max_cdclk_freq * 95 / 100)
6243                 return false;
6244
6245         return true;
6246 }
6247
6248 static bool hsw_compute_ips_config(struct intel_crtc_state *crtc_state)
6249 {
6250         struct drm_i915_private *dev_priv =
6251                 to_i915(crtc_state->base.crtc->dev);
6252         struct intel_atomic_state *intel_state =
6253                 to_intel_atomic_state(crtc_state->base.state);
6254
6255         if (!hsw_crtc_state_ips_capable(crtc_state))
6256                 return false;
6257
6258         if (crtc_state->ips_force_disable)
6259                 return false;
6260
6261         /* IPS should be fine as long as at least one plane is enabled. */
6262         if (!(crtc_state->active_planes & ~BIT(PLANE_CURSOR)))
6263                 return false;
6264
6265         /* pixel rate mustn't exceed 95% of cdclk with IPS on BDW */
6266         if (IS_BROADWELL(dev_priv) &&
6267             crtc_state->pixel_rate > intel_state->cdclk.logical.cdclk * 95 / 100)
6268                 return false;
6269
6270         return true;
6271 }
6272
6273 static bool intel_crtc_supports_double_wide(const struct intel_crtc *crtc)
6274 {
6275         const struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6276
6277         /* GDG double wide on either pipe, otherwise pipe A only */
6278         return INTEL_INFO(dev_priv)->gen < 4 &&
6279                 (crtc->pipe == PIPE_A || IS_I915G(dev_priv));
6280 }
6281
6282 static uint32_t ilk_pipe_pixel_rate(const struct intel_crtc_state *pipe_config)
6283 {
6284         uint32_t pixel_rate;
6285
6286         pixel_rate = pipe_config->base.adjusted_mode.crtc_clock;
6287
6288         /*
6289          * We only use IF-ID interlacing. If we ever use
6290          * PF-ID we'll need to adjust the pixel_rate here.
6291          */
6292
6293         if (pipe_config->pch_pfit.enabled) {
6294                 uint64_t pipe_w, pipe_h, pfit_w, pfit_h;
6295                 uint32_t pfit_size = pipe_config->pch_pfit.size;
6296
6297                 pipe_w = pipe_config->pipe_src_w;
6298                 pipe_h = pipe_config->pipe_src_h;
6299
6300                 pfit_w = (pfit_size >> 16) & 0xFFFF;
6301                 pfit_h = pfit_size & 0xFFFF;
6302                 if (pipe_w < pfit_w)
6303                         pipe_w = pfit_w;
6304                 if (pipe_h < pfit_h)
6305                         pipe_h = pfit_h;
6306
6307                 if (WARN_ON(!pfit_w || !pfit_h))
6308                         return pixel_rate;
6309
6310                 pixel_rate = div_u64((uint64_t) pixel_rate * pipe_w * pipe_h,
6311                                      pfit_w * pfit_h);
6312         }
6313
6314         return pixel_rate;
6315 }
6316
6317 static void intel_crtc_compute_pixel_rate(struct intel_crtc_state *crtc_state)
6318 {
6319         struct drm_i915_private *dev_priv = to_i915(crtc_state->base.crtc->dev);
6320
6321         if (HAS_GMCH_DISPLAY(dev_priv))
6322                 /* FIXME calculate proper pipe pixel rate for GMCH pfit */
6323                 crtc_state->pixel_rate =
6324                         crtc_state->base.adjusted_mode.crtc_clock;
6325         else
6326                 crtc_state->pixel_rate =
6327                         ilk_pipe_pixel_rate(crtc_state);
6328 }
6329
6330 static int intel_crtc_compute_config(struct intel_crtc *crtc,
6331                                      struct intel_crtc_state *pipe_config)
6332 {
6333         struct drm_device *dev = crtc->base.dev;
6334         struct drm_i915_private *dev_priv = to_i915(dev);
6335         const struct drm_display_mode *adjusted_mode = &pipe_config->base.adjusted_mode;
6336         int clock_limit = dev_priv->max_dotclk_freq;
6337
6338         if (INTEL_GEN(dev_priv) < 4) {
6339                 clock_limit = dev_priv->max_cdclk_freq * 9 / 10;
6340
6341                 /*
6342                  * Enable double wide mode when the dot clock
6343                  * is > 90% of the (display) core speed.
6344                  */
6345                 if (intel_crtc_supports_double_wide(crtc) &&
6346                     adjusted_mode->crtc_clock > clock_limit) {
6347                         clock_limit = dev_priv->max_dotclk_freq;
6348                         pipe_config->double_wide = true;
6349                 }
6350         }
6351
6352         if (adjusted_mode->crtc_clock > clock_limit) {
6353                 DRM_DEBUG_KMS("requested pixel clock (%d kHz) too high (max: %d kHz, double wide: %s)\n",
6354                               adjusted_mode->crtc_clock, clock_limit,
6355                               yesno(pipe_config->double_wide));
6356                 return -EINVAL;
6357         }
6358
6359         if (pipe_config->ycbcr420 && pipe_config->base.ctm) {
6360                 /*
6361                  * There is only one pipe CSC unit per pipe, and we need that
6362                  * for output conversion from RGB->YCBCR. So if CTM is already
6363                  * applied we can't support YCBCR420 output.
6364                  */
6365                 DRM_DEBUG_KMS("YCBCR420 and CTM together are not possible\n");
6366                 return -EINVAL;
6367         }
6368
6369         /*
6370          * Pipe horizontal size must be even in:
6371          * - DVO ganged mode
6372          * - LVDS dual channel mode
6373          * - Double wide pipe
6374          */
6375         if ((intel_crtc_has_type(pipe_config, INTEL_OUTPUT_LVDS) &&
6376              intel_is_dual_link_lvds(dev)) || pipe_config->double_wide)
6377                 pipe_config->pipe_src_w &= ~1;
6378
6379         /* Cantiga+ cannot handle modes with a hsync front porch of 0.
6380          * WaPruneModeWithIncorrectHsyncOffset:ctg,elk,ilk,snb,ivb,vlv,hsw.
6381          */
6382         if ((INTEL_GEN(dev_priv) > 4 || IS_G4X(dev_priv)) &&
6383                 adjusted_mode->crtc_hsync_start == adjusted_mode->crtc_hdisplay)
6384                 return -EINVAL;
6385
6386         intel_crtc_compute_pixel_rate(pipe_config);
6387
6388         if (pipe_config->has_pch_encoder)
6389                 return ironlake_fdi_compute_config(crtc, pipe_config);
6390
6391         return 0;
6392 }
6393
6394 static void
6395 intel_reduce_m_n_ratio(uint32_t *num, uint32_t *den)
6396 {
6397         while (*num > DATA_LINK_M_N_MASK ||
6398                *den > DATA_LINK_M_N_MASK) {
6399                 *num >>= 1;
6400                 *den >>= 1;
6401         }
6402 }
6403
6404 static void compute_m_n(unsigned int m, unsigned int n,
6405                         uint32_t *ret_m, uint32_t *ret_n,
6406                         bool reduce_m_n)
6407 {
6408         /*
6409          * Reduce M/N as much as possible without loss in precision. Several DP
6410          * dongles in particular seem to be fussy about too large *link* M/N
6411          * values. The passed in values are more likely to have the least
6412          * significant bits zero than M after rounding below, so do this first.
6413          */
6414         if (reduce_m_n) {
6415                 while ((m & 1) == 0 && (n & 1) == 0) {
6416                         m >>= 1;
6417                         n >>= 1;
6418                 }
6419         }
6420
6421         *ret_n = min_t(unsigned int, roundup_pow_of_two(n), DATA_LINK_N_MAX);
6422         *ret_m = div_u64((uint64_t) m * *ret_n, n);
6423         intel_reduce_m_n_ratio(ret_m, ret_n);
6424 }
6425
6426 void
6427 intel_link_compute_m_n(int bits_per_pixel, int nlanes,
6428                        int pixel_clock, int link_clock,
6429                        struct intel_link_m_n *m_n,
6430                        bool reduce_m_n)
6431 {
6432         m_n->tu = 64;
6433
6434         compute_m_n(bits_per_pixel * pixel_clock,
6435                     link_clock * nlanes * 8,
6436                     &m_n->gmch_m, &m_n->gmch_n,
6437                     reduce_m_n);
6438
6439         compute_m_n(pixel_clock, link_clock,
6440                     &m_n->link_m, &m_n->link_n,
6441                     reduce_m_n);
6442 }
6443
6444 static inline bool intel_panel_use_ssc(struct drm_i915_private *dev_priv)
6445 {
6446         if (i915_modparams.panel_use_ssc >= 0)
6447                 return i915_modparams.panel_use_ssc != 0;
6448         return dev_priv->vbt.lvds_use_ssc
6449                 && !(dev_priv->quirks & QUIRK_LVDS_SSC_DISABLE);
6450 }
6451
6452 static uint32_t pnv_dpll_compute_fp(struct dpll *dpll)
6453 {
6454         return (1 << dpll->n) << 16 | dpll->m2;
6455 }
6456
6457 static uint32_t i9xx_dpll_compute_fp(struct dpll *dpll)
6458 {
6459         return dpll->n << 16 | dpll->m1 << 8 | dpll->m2;
6460 }
6461
6462 static void i9xx_update_pll_dividers(struct intel_crtc *crtc,
6463                                      struct intel_crtc_state *crtc_state,
6464                                      struct dpll *reduced_clock)
6465 {
6466         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6467         u32 fp, fp2 = 0;
6468
6469         if (IS_PINEVIEW(dev_priv)) {
6470                 fp = pnv_dpll_compute_fp(&crtc_state->dpll);
6471                 if (reduced_clock)
6472                         fp2 = pnv_dpll_compute_fp(reduced_clock);
6473         } else {
6474                 fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
6475                 if (reduced_clock)
6476                         fp2 = i9xx_dpll_compute_fp(reduced_clock);
6477         }
6478
6479         crtc_state->dpll_hw_state.fp0 = fp;
6480
6481         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6482             reduced_clock) {
6483                 crtc_state->dpll_hw_state.fp1 = fp2;
6484         } else {
6485                 crtc_state->dpll_hw_state.fp1 = fp;
6486         }
6487 }
6488
6489 static void vlv_pllb_recal_opamp(struct drm_i915_private *dev_priv, enum pipe
6490                 pipe)
6491 {
6492         u32 reg_val;
6493
6494         /*
6495          * PLLB opamp always calibrates to max value of 0x3f, force enable it
6496          * and set it to a reasonable value instead.
6497          */
6498         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6499         reg_val &= 0xffffff00;
6500         reg_val |= 0x00000030;
6501         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6502
6503         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6504         reg_val &= 0x00ffffff;
6505         reg_val |= 0x8c000000;
6506         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6507
6508         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW9(1));
6509         reg_val &= 0xffffff00;
6510         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9(1), reg_val);
6511
6512         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_REF_DW13);
6513         reg_val &= 0x00ffffff;
6514         reg_val |= 0xb0000000;
6515         vlv_dpio_write(dev_priv, pipe, VLV_REF_DW13, reg_val);
6516 }
6517
6518 static void intel_pch_transcoder_set_m_n(struct intel_crtc *crtc,
6519                                          struct intel_link_m_n *m_n)
6520 {
6521         struct drm_device *dev = crtc->base.dev;
6522         struct drm_i915_private *dev_priv = to_i915(dev);
6523         int pipe = crtc->pipe;
6524
6525         I915_WRITE(PCH_TRANS_DATA_M1(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6526         I915_WRITE(PCH_TRANS_DATA_N1(pipe), m_n->gmch_n);
6527         I915_WRITE(PCH_TRANS_LINK_M1(pipe), m_n->link_m);
6528         I915_WRITE(PCH_TRANS_LINK_N1(pipe), m_n->link_n);
6529 }
6530
6531 static void intel_cpu_transcoder_set_m_n(struct intel_crtc *crtc,
6532                                          struct intel_link_m_n *m_n,
6533                                          struct intel_link_m_n *m2_n2)
6534 {
6535         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6536         int pipe = crtc->pipe;
6537         enum transcoder transcoder = crtc->config->cpu_transcoder;
6538
6539         if (INTEL_GEN(dev_priv) >= 5) {
6540                 I915_WRITE(PIPE_DATA_M1(transcoder), TU_SIZE(m_n->tu) | m_n->gmch_m);
6541                 I915_WRITE(PIPE_DATA_N1(transcoder), m_n->gmch_n);
6542                 I915_WRITE(PIPE_LINK_M1(transcoder), m_n->link_m);
6543                 I915_WRITE(PIPE_LINK_N1(transcoder), m_n->link_n);
6544                 /* M2_N2 registers to be set only for gen < 8 (M2_N2 available
6545                  * for gen < 8) and if DRRS is supported (to make sure the
6546                  * registers are not unnecessarily accessed).
6547                  */
6548                 if (m2_n2 && (IS_CHERRYVIEW(dev_priv) ||
6549                     INTEL_GEN(dev_priv) < 8) && crtc->config->has_drrs) {
6550                         I915_WRITE(PIPE_DATA_M2(transcoder),
6551                                         TU_SIZE(m2_n2->tu) | m2_n2->gmch_m);
6552                         I915_WRITE(PIPE_DATA_N2(transcoder), m2_n2->gmch_n);
6553                         I915_WRITE(PIPE_LINK_M2(transcoder), m2_n2->link_m);
6554                         I915_WRITE(PIPE_LINK_N2(transcoder), m2_n2->link_n);
6555                 }
6556         } else {
6557                 I915_WRITE(PIPE_DATA_M_G4X(pipe), TU_SIZE(m_n->tu) | m_n->gmch_m);
6558                 I915_WRITE(PIPE_DATA_N_G4X(pipe), m_n->gmch_n);
6559                 I915_WRITE(PIPE_LINK_M_G4X(pipe), m_n->link_m);
6560                 I915_WRITE(PIPE_LINK_N_G4X(pipe), m_n->link_n);
6561         }
6562 }
6563
6564 void intel_dp_set_m_n(struct intel_crtc *crtc, enum link_m_n_set m_n)
6565 {
6566         struct intel_link_m_n *dp_m_n, *dp_m2_n2 = NULL;
6567
6568         if (m_n == M1_N1) {
6569                 dp_m_n = &crtc->config->dp_m_n;
6570                 dp_m2_n2 = &crtc->config->dp_m2_n2;
6571         } else if (m_n == M2_N2) {
6572
6573                 /*
6574                  * M2_N2 registers are not supported. Hence m2_n2 divider value
6575                  * needs to be programmed into M1_N1.
6576                  */
6577                 dp_m_n = &crtc->config->dp_m2_n2;
6578         } else {
6579                 DRM_ERROR("Unsupported divider value\n");
6580                 return;
6581         }
6582
6583         if (crtc->config->has_pch_encoder)
6584                 intel_pch_transcoder_set_m_n(crtc, &crtc->config->dp_m_n);
6585         else
6586                 intel_cpu_transcoder_set_m_n(crtc, dp_m_n, dp_m2_n2);
6587 }
6588
6589 static void vlv_compute_dpll(struct intel_crtc *crtc,
6590                              struct intel_crtc_state *pipe_config)
6591 {
6592         pipe_config->dpll_hw_state.dpll = DPLL_INTEGRATED_REF_CLK_VLV |
6593                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6594         if (crtc->pipe != PIPE_A)
6595                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6596
6597         /* DPLL not used with DSI, but still need the rest set up */
6598         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6599                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE |
6600                         DPLL_EXT_BUFFER_ENABLE_VLV;
6601
6602         pipe_config->dpll_hw_state.dpll_md =
6603                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6604 }
6605
6606 static void chv_compute_dpll(struct intel_crtc *crtc,
6607                              struct intel_crtc_state *pipe_config)
6608 {
6609         pipe_config->dpll_hw_state.dpll = DPLL_SSC_REF_CLK_CHV |
6610                 DPLL_REF_CLK_ENABLE_VLV | DPLL_VGA_MODE_DIS;
6611         if (crtc->pipe != PIPE_A)
6612                 pipe_config->dpll_hw_state.dpll |= DPLL_INTEGRATED_CRI_CLK_VLV;
6613
6614         /* DPLL not used with DSI, but still need the rest set up */
6615         if (!intel_crtc_has_type(pipe_config, INTEL_OUTPUT_DSI))
6616                 pipe_config->dpll_hw_state.dpll |= DPLL_VCO_ENABLE;
6617
6618         pipe_config->dpll_hw_state.dpll_md =
6619                 (pipe_config->pixel_multiplier - 1) << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6620 }
6621
6622 static void vlv_prepare_pll(struct intel_crtc *crtc,
6623                             const struct intel_crtc_state *pipe_config)
6624 {
6625         struct drm_device *dev = crtc->base.dev;
6626         struct drm_i915_private *dev_priv = to_i915(dev);
6627         enum pipe pipe = crtc->pipe;
6628         u32 mdiv;
6629         u32 bestn, bestm1, bestm2, bestp1, bestp2;
6630         u32 coreclk, reg_val;
6631
6632         /* Enable Refclk */
6633         I915_WRITE(DPLL(pipe),
6634                    pipe_config->dpll_hw_state.dpll &
6635                    ~(DPLL_VCO_ENABLE | DPLL_EXT_BUFFER_ENABLE_VLV));
6636
6637         /* No need to actually set up the DPLL with DSI */
6638         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6639                 return;
6640
6641         mutex_lock(&dev_priv->sb_lock);
6642
6643         bestn = pipe_config->dpll.n;
6644         bestm1 = pipe_config->dpll.m1;
6645         bestm2 = pipe_config->dpll.m2;
6646         bestp1 = pipe_config->dpll.p1;
6647         bestp2 = pipe_config->dpll.p2;
6648
6649         /* See eDP HDMI DPIO driver vbios notes doc */
6650
6651         /* PLL B needs special handling */
6652         if (pipe == PIPE_B)
6653                 vlv_pllb_recal_opamp(dev_priv, pipe);
6654
6655         /* Set up Tx target for periodic Rcomp update */
6656         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW9_BCAST, 0x0100000f);
6657
6658         /* Disable target IRef on PLL */
6659         reg_val = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW8(pipe));
6660         reg_val &= 0x00ffffff;
6661         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW8(pipe), reg_val);
6662
6663         /* Disable fast lock */
6664         vlv_dpio_write(dev_priv, pipe, VLV_CMN_DW0, 0x610);
6665
6666         /* Set idtafcrecal before PLL is enabled */
6667         mdiv = ((bestm1 << DPIO_M1DIV_SHIFT) | (bestm2 & DPIO_M2DIV_MASK));
6668         mdiv |= ((bestp1 << DPIO_P1_SHIFT) | (bestp2 << DPIO_P2_SHIFT));
6669         mdiv |= ((bestn << DPIO_N_SHIFT));
6670         mdiv |= (1 << DPIO_K_SHIFT);
6671
6672         /*
6673          * Post divider depends on pixel clock rate, DAC vs digital (and LVDS,
6674          * but we don't support that).
6675          * Note: don't use the DAC post divider as it seems unstable.
6676          */
6677         mdiv |= (DPIO_POST_DIV_HDMIDP << DPIO_POST_DIV_SHIFT);
6678         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6679
6680         mdiv |= DPIO_ENABLE_CALIBRATION;
6681         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW3(pipe), mdiv);
6682
6683         /* Set HBR and RBR LPF coefficients */
6684         if (pipe_config->port_clock == 162000 ||
6685             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_ANALOG) ||
6686             intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI))
6687                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6688                                  0x009f0003);
6689         else
6690                 vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW10(pipe),
6691                                  0x00d0000f);
6692
6693         if (intel_crtc_has_dp_encoder(pipe_config)) {
6694                 /* Use SSC source */
6695                 if (pipe == PIPE_A)
6696                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6697                                          0x0df40000);
6698                 else
6699                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6700                                          0x0df70000);
6701         } else { /* HDMI or VGA */
6702                 /* Use bend source */
6703                 if (pipe == PIPE_A)
6704                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6705                                          0x0df70000);
6706                 else
6707                         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW5(pipe),
6708                                          0x0df40000);
6709         }
6710
6711         coreclk = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW7(pipe));
6712         coreclk = (coreclk & 0x0000ff00) | 0x01c00000;
6713         if (intel_crtc_has_dp_encoder(crtc->config))
6714                 coreclk |= 0x01000000;
6715         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW7(pipe), coreclk);
6716
6717         vlv_dpio_write(dev_priv, pipe, VLV_PLL_DW11(pipe), 0x87871000);
6718         mutex_unlock(&dev_priv->sb_lock);
6719 }
6720
6721 static void chv_prepare_pll(struct intel_crtc *crtc,
6722                             const struct intel_crtc_state *pipe_config)
6723 {
6724         struct drm_device *dev = crtc->base.dev;
6725         struct drm_i915_private *dev_priv = to_i915(dev);
6726         enum pipe pipe = crtc->pipe;
6727         enum dpio_channel port = vlv_pipe_to_channel(pipe);
6728         u32 loopfilter, tribuf_calcntr;
6729         u32 bestn, bestm1, bestm2, bestp1, bestp2, bestm2_frac;
6730         u32 dpio_val;
6731         int vco;
6732
6733         /* Enable Refclk and SSC */
6734         I915_WRITE(DPLL(pipe),
6735                    pipe_config->dpll_hw_state.dpll & ~DPLL_VCO_ENABLE);
6736
6737         /* No need to actually set up the DPLL with DSI */
6738         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
6739                 return;
6740
6741         bestn = pipe_config->dpll.n;
6742         bestm2_frac = pipe_config->dpll.m2 & 0x3fffff;
6743         bestm1 = pipe_config->dpll.m1;
6744         bestm2 = pipe_config->dpll.m2 >> 22;
6745         bestp1 = pipe_config->dpll.p1;
6746         bestp2 = pipe_config->dpll.p2;
6747         vco = pipe_config->dpll.vco;
6748         dpio_val = 0;
6749         loopfilter = 0;
6750
6751         mutex_lock(&dev_priv->sb_lock);
6752
6753         /* p1 and p2 divider */
6754         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW13(port),
6755                         5 << DPIO_CHV_S1_DIV_SHIFT |
6756                         bestp1 << DPIO_CHV_P1_DIV_SHIFT |
6757                         bestp2 << DPIO_CHV_P2_DIV_SHIFT |
6758                         1 << DPIO_CHV_K_DIV_SHIFT);
6759
6760         /* Feedback post-divider - m2 */
6761         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW0(port), bestm2);
6762
6763         /* Feedback refclk divider - n and m1 */
6764         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW1(port),
6765                         DPIO_CHV_M1_DIV_BY_2 |
6766                         1 << DPIO_CHV_N_DIV_SHIFT);
6767
6768         /* M2 fraction division */
6769         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW2(port), bestm2_frac);
6770
6771         /* M2 fraction division enable */
6772         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
6773         dpio_val &= ~(DPIO_CHV_FEEDFWD_GAIN_MASK | DPIO_CHV_FRAC_DIV_EN);
6774         dpio_val |= (2 << DPIO_CHV_FEEDFWD_GAIN_SHIFT);
6775         if (bestm2_frac)
6776                 dpio_val |= DPIO_CHV_FRAC_DIV_EN;
6777         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW3(port), dpio_val);
6778
6779         /* Program digital lock detect threshold */
6780         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW9(port));
6781         dpio_val &= ~(DPIO_CHV_INT_LOCK_THRESHOLD_MASK |
6782                                         DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE);
6783         dpio_val |= (0x5 << DPIO_CHV_INT_LOCK_THRESHOLD_SHIFT);
6784         if (!bestm2_frac)
6785                 dpio_val |= DPIO_CHV_INT_LOCK_THRESHOLD_SEL_COARSE;
6786         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW9(port), dpio_val);
6787
6788         /* Loop filter */
6789         if (vco == 5400000) {
6790                 loopfilter |= (0x3 << DPIO_CHV_PROP_COEFF_SHIFT);
6791                 loopfilter |= (0x8 << DPIO_CHV_INT_COEFF_SHIFT);
6792                 loopfilter |= (0x1 << DPIO_CHV_GAIN_CTRL_SHIFT);
6793                 tribuf_calcntr = 0x9;
6794         } else if (vco <= 6200000) {
6795                 loopfilter |= (0x5 << DPIO_CHV_PROP_COEFF_SHIFT);
6796                 loopfilter |= (0xB << DPIO_CHV_INT_COEFF_SHIFT);
6797                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6798                 tribuf_calcntr = 0x9;
6799         } else if (vco <= 6480000) {
6800                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6801                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6802                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6803                 tribuf_calcntr = 0x8;
6804         } else {
6805                 /* Not supported. Apply the same limits as in the max case */
6806                 loopfilter |= (0x4 << DPIO_CHV_PROP_COEFF_SHIFT);
6807                 loopfilter |= (0x9 << DPIO_CHV_INT_COEFF_SHIFT);
6808                 loopfilter |= (0x3 << DPIO_CHV_GAIN_CTRL_SHIFT);
6809                 tribuf_calcntr = 0;
6810         }
6811         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW6(port), loopfilter);
6812
6813         dpio_val = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW8(port));
6814         dpio_val &= ~DPIO_CHV_TDC_TARGET_CNT_MASK;
6815         dpio_val |= (tribuf_calcntr << DPIO_CHV_TDC_TARGET_CNT_SHIFT);
6816         vlv_dpio_write(dev_priv, pipe, CHV_PLL_DW8(port), dpio_val);
6817
6818         /* AFC Recal */
6819         vlv_dpio_write(dev_priv, pipe, CHV_CMN_DW14(port),
6820                         vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW14(port)) |
6821                         DPIO_AFC_RECAL);
6822
6823         mutex_unlock(&dev_priv->sb_lock);
6824 }
6825
6826 /**
6827  * vlv_force_pll_on - forcibly enable just the PLL
6828  * @dev_priv: i915 private structure
6829  * @pipe: pipe PLL to enable
6830  * @dpll: PLL configuration
6831  *
6832  * Enable the PLL for @pipe using the supplied @dpll config. To be used
6833  * in cases where we need the PLL enabled even when @pipe is not going to
6834  * be enabled.
6835  */
6836 int vlv_force_pll_on(struct drm_i915_private *dev_priv, enum pipe pipe,
6837                      const struct dpll *dpll)
6838 {
6839         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
6840         struct intel_crtc_state *pipe_config;
6841
6842         pipe_config = kzalloc(sizeof(*pipe_config), GFP_KERNEL);
6843         if (!pipe_config)
6844                 return -ENOMEM;
6845
6846         pipe_config->base.crtc = &crtc->base;
6847         pipe_config->pixel_multiplier = 1;
6848         pipe_config->dpll = *dpll;
6849
6850         if (IS_CHERRYVIEW(dev_priv)) {
6851                 chv_compute_dpll(crtc, pipe_config);
6852                 chv_prepare_pll(crtc, pipe_config);
6853                 chv_enable_pll(crtc, pipe_config);
6854         } else {
6855                 vlv_compute_dpll(crtc, pipe_config);
6856                 vlv_prepare_pll(crtc, pipe_config);
6857                 vlv_enable_pll(crtc, pipe_config);
6858         }
6859
6860         kfree(pipe_config);
6861
6862         return 0;
6863 }
6864
6865 /**
6866  * vlv_force_pll_off - forcibly disable just the PLL
6867  * @dev_priv: i915 private structure
6868  * @pipe: pipe PLL to disable
6869  *
6870  * Disable the PLL for @pipe. To be used in cases where we need
6871  * the PLL enabled even when @pipe is not going to be enabled.
6872  */
6873 void vlv_force_pll_off(struct drm_i915_private *dev_priv, enum pipe pipe)
6874 {
6875         if (IS_CHERRYVIEW(dev_priv))
6876                 chv_disable_pll(dev_priv, pipe);
6877         else
6878                 vlv_disable_pll(dev_priv, pipe);
6879 }
6880
6881 static void i9xx_compute_dpll(struct intel_crtc *crtc,
6882                               struct intel_crtc_state *crtc_state,
6883                               struct dpll *reduced_clock)
6884 {
6885         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
6886         u32 dpll;
6887         struct dpll *clock = &crtc_state->dpll;
6888
6889         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6890
6891         dpll = DPLL_VGA_MODE_DIS;
6892
6893         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
6894                 dpll |= DPLLB_MODE_LVDS;
6895         else
6896                 dpll |= DPLLB_MODE_DAC_SERIAL;
6897
6898         if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
6899             IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
6900                 dpll |= (crtc_state->pixel_multiplier - 1)
6901                         << SDVO_MULTIPLIER_SHIFT_HIRES;
6902         }
6903
6904         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
6905             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
6906                 dpll |= DPLL_SDVO_HIGH_SPEED;
6907
6908         if (intel_crtc_has_dp_encoder(crtc_state))
6909                 dpll |= DPLL_SDVO_HIGH_SPEED;
6910
6911         /* compute bitmask from p1 value */
6912         if (IS_PINEVIEW(dev_priv))
6913                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW;
6914         else {
6915                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6916                 if (IS_G4X(dev_priv) && reduced_clock)
6917                         dpll |= (1 << (reduced_clock->p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
6918         }
6919         switch (clock->p2) {
6920         case 5:
6921                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
6922                 break;
6923         case 7:
6924                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
6925                 break;
6926         case 10:
6927                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
6928                 break;
6929         case 14:
6930                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
6931                 break;
6932         }
6933         if (INTEL_GEN(dev_priv) >= 4)
6934                 dpll |= (6 << PLL_LOAD_PULSE_PHASE_SHIFT);
6935
6936         if (crtc_state->sdvo_tv_clock)
6937                 dpll |= PLL_REF_INPUT_TVCLKINBC;
6938         else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6939                  intel_panel_use_ssc(dev_priv))
6940                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6941         else
6942                 dpll |= PLL_REF_INPUT_DREFCLK;
6943
6944         dpll |= DPLL_VCO_ENABLE;
6945         crtc_state->dpll_hw_state.dpll = dpll;
6946
6947         if (INTEL_GEN(dev_priv) >= 4) {
6948                 u32 dpll_md = (crtc_state->pixel_multiplier - 1)
6949                         << DPLL_MD_UDI_MULTIPLIER_SHIFT;
6950                 crtc_state->dpll_hw_state.dpll_md = dpll_md;
6951         }
6952 }
6953
6954 static void i8xx_compute_dpll(struct intel_crtc *crtc,
6955                               struct intel_crtc_state *crtc_state,
6956                               struct dpll *reduced_clock)
6957 {
6958         struct drm_device *dev = crtc->base.dev;
6959         struct drm_i915_private *dev_priv = to_i915(dev);
6960         u32 dpll;
6961         struct dpll *clock = &crtc_state->dpll;
6962
6963         i9xx_update_pll_dividers(crtc, crtc_state, reduced_clock);
6964
6965         dpll = DPLL_VGA_MODE_DIS;
6966
6967         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
6968                 dpll |= (1 << (clock->p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6969         } else {
6970                 if (clock->p1 == 2)
6971                         dpll |= PLL_P1_DIVIDE_BY_TWO;
6972                 else
6973                         dpll |= (clock->p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT;
6974                 if (clock->p2 == 4)
6975                         dpll |= PLL_P2_DIVIDE_BY_4;
6976         }
6977
6978         if (!IS_I830(dev_priv) &&
6979             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO))
6980                 dpll |= DPLL_DVO_2X_MODE;
6981
6982         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
6983             intel_panel_use_ssc(dev_priv))
6984                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
6985         else
6986                 dpll |= PLL_REF_INPUT_DREFCLK;
6987
6988         dpll |= DPLL_VCO_ENABLE;
6989         crtc_state->dpll_hw_state.dpll = dpll;
6990 }
6991
6992 static void intel_set_pipe_timings(struct intel_crtc *intel_crtc)
6993 {
6994         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
6995         enum pipe pipe = intel_crtc->pipe;
6996         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
6997         const struct drm_display_mode *adjusted_mode = &intel_crtc->config->base.adjusted_mode;
6998         uint32_t crtc_vtotal, crtc_vblank_end;
6999         int vsyncshift = 0;
7000
7001         /* We need to be careful not to changed the adjusted mode, for otherwise
7002          * the hw state checker will get angry at the mismatch. */
7003         crtc_vtotal = adjusted_mode->crtc_vtotal;
7004         crtc_vblank_end = adjusted_mode->crtc_vblank_end;
7005
7006         if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE) {
7007                 /* the chip adds 2 halflines automatically */
7008                 crtc_vtotal -= 1;
7009                 crtc_vblank_end -= 1;
7010
7011                 if (intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7012                         vsyncshift = (adjusted_mode->crtc_htotal - 1) / 2;
7013                 else
7014                         vsyncshift = adjusted_mode->crtc_hsync_start -
7015                                 adjusted_mode->crtc_htotal / 2;
7016                 if (vsyncshift < 0)
7017                         vsyncshift += adjusted_mode->crtc_htotal;
7018         }
7019
7020         if (INTEL_GEN(dev_priv) > 3)
7021                 I915_WRITE(VSYNCSHIFT(cpu_transcoder), vsyncshift);
7022
7023         I915_WRITE(HTOTAL(cpu_transcoder),
7024                    (adjusted_mode->crtc_hdisplay - 1) |
7025                    ((adjusted_mode->crtc_htotal - 1) << 16));
7026         I915_WRITE(HBLANK(cpu_transcoder),
7027                    (adjusted_mode->crtc_hblank_start - 1) |
7028                    ((adjusted_mode->crtc_hblank_end - 1) << 16));
7029         I915_WRITE(HSYNC(cpu_transcoder),
7030                    (adjusted_mode->crtc_hsync_start - 1) |
7031                    ((adjusted_mode->crtc_hsync_end - 1) << 16));
7032
7033         I915_WRITE(VTOTAL(cpu_transcoder),
7034                    (adjusted_mode->crtc_vdisplay - 1) |
7035                    ((crtc_vtotal - 1) << 16));
7036         I915_WRITE(VBLANK(cpu_transcoder),
7037                    (adjusted_mode->crtc_vblank_start - 1) |
7038                    ((crtc_vblank_end - 1) << 16));
7039         I915_WRITE(VSYNC(cpu_transcoder),
7040                    (adjusted_mode->crtc_vsync_start - 1) |
7041                    ((adjusted_mode->crtc_vsync_end - 1) << 16));
7042
7043         /* Workaround: when the EDP input selection is B, the VTOTAL_B must be
7044          * programmed with the VTOTAL_EDP value. Same for VTOTAL_C. This is
7045          * documented on the DDI_FUNC_CTL register description, EDP Input Select
7046          * bits. */
7047         if (IS_HASWELL(dev_priv) && cpu_transcoder == TRANSCODER_EDP &&
7048             (pipe == PIPE_B || pipe == PIPE_C))
7049                 I915_WRITE(VTOTAL(pipe), I915_READ(VTOTAL(cpu_transcoder)));
7050
7051 }
7052
7053 static void intel_set_pipe_src_size(struct intel_crtc *intel_crtc)
7054 {
7055         struct drm_device *dev = intel_crtc->base.dev;
7056         struct drm_i915_private *dev_priv = to_i915(dev);
7057         enum pipe pipe = intel_crtc->pipe;
7058
7059         /* pipesrc controls the size that is scaled from, which should
7060          * always be the user's requested size.
7061          */
7062         I915_WRITE(PIPESRC(pipe),
7063                    ((intel_crtc->config->pipe_src_w - 1) << 16) |
7064                    (intel_crtc->config->pipe_src_h - 1));
7065 }
7066
7067 static void intel_get_pipe_timings(struct intel_crtc *crtc,
7068                                    struct intel_crtc_state *pipe_config)
7069 {
7070         struct drm_device *dev = crtc->base.dev;
7071         struct drm_i915_private *dev_priv = to_i915(dev);
7072         enum transcoder cpu_transcoder = pipe_config->cpu_transcoder;
7073         uint32_t tmp;
7074
7075         tmp = I915_READ(HTOTAL(cpu_transcoder));
7076         pipe_config->base.adjusted_mode.crtc_hdisplay = (tmp & 0xffff) + 1;
7077         pipe_config->base.adjusted_mode.crtc_htotal = ((tmp >> 16) & 0xffff) + 1;
7078         tmp = I915_READ(HBLANK(cpu_transcoder));
7079         pipe_config->base.adjusted_mode.crtc_hblank_start = (tmp & 0xffff) + 1;
7080         pipe_config->base.adjusted_mode.crtc_hblank_end = ((tmp >> 16) & 0xffff) + 1;
7081         tmp = I915_READ(HSYNC(cpu_transcoder));
7082         pipe_config->base.adjusted_mode.crtc_hsync_start = (tmp & 0xffff) + 1;
7083         pipe_config->base.adjusted_mode.crtc_hsync_end = ((tmp >> 16) & 0xffff) + 1;
7084
7085         tmp = I915_READ(VTOTAL(cpu_transcoder));
7086         pipe_config->base.adjusted_mode.crtc_vdisplay = (tmp & 0xffff) + 1;
7087         pipe_config->base.adjusted_mode.crtc_vtotal = ((tmp >> 16) & 0xffff) + 1;
7088         tmp = I915_READ(VBLANK(cpu_transcoder));
7089         pipe_config->base.adjusted_mode.crtc_vblank_start = (tmp & 0xffff) + 1;
7090         pipe_config->base.adjusted_mode.crtc_vblank_end = ((tmp >> 16) & 0xffff) + 1;
7091         tmp = I915_READ(VSYNC(cpu_transcoder));
7092         pipe_config->base.adjusted_mode.crtc_vsync_start = (tmp & 0xffff) + 1;
7093         pipe_config->base.adjusted_mode.crtc_vsync_end = ((tmp >> 16) & 0xffff) + 1;
7094
7095         if (I915_READ(PIPECONF(cpu_transcoder)) & PIPECONF_INTERLACE_MASK) {
7096                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_INTERLACE;
7097                 pipe_config->base.adjusted_mode.crtc_vtotal += 1;
7098                 pipe_config->base.adjusted_mode.crtc_vblank_end += 1;
7099         }
7100 }
7101
7102 static void intel_get_pipe_src_size(struct intel_crtc *crtc,
7103                                     struct intel_crtc_state *pipe_config)
7104 {
7105         struct drm_device *dev = crtc->base.dev;
7106         struct drm_i915_private *dev_priv = to_i915(dev);
7107         u32 tmp;
7108
7109         tmp = I915_READ(PIPESRC(crtc->pipe));
7110         pipe_config->pipe_src_h = (tmp & 0xffff) + 1;
7111         pipe_config->pipe_src_w = ((tmp >> 16) & 0xffff) + 1;
7112
7113         pipe_config->base.mode.vdisplay = pipe_config->pipe_src_h;
7114         pipe_config->base.mode.hdisplay = pipe_config->pipe_src_w;
7115 }
7116
7117 void intel_mode_from_pipe_config(struct drm_display_mode *mode,
7118                                  struct intel_crtc_state *pipe_config)
7119 {
7120         mode->hdisplay = pipe_config->base.adjusted_mode.crtc_hdisplay;
7121         mode->htotal = pipe_config->base.adjusted_mode.crtc_htotal;
7122         mode->hsync_start = pipe_config->base.adjusted_mode.crtc_hsync_start;
7123         mode->hsync_end = pipe_config->base.adjusted_mode.crtc_hsync_end;
7124
7125         mode->vdisplay = pipe_config->base.adjusted_mode.crtc_vdisplay;
7126         mode->vtotal = pipe_config->base.adjusted_mode.crtc_vtotal;
7127         mode->vsync_start = pipe_config->base.adjusted_mode.crtc_vsync_start;
7128         mode->vsync_end = pipe_config->base.adjusted_mode.crtc_vsync_end;
7129
7130         mode->flags = pipe_config->base.adjusted_mode.flags;
7131         mode->type = DRM_MODE_TYPE_DRIVER;
7132
7133         mode->clock = pipe_config->base.adjusted_mode.crtc_clock;
7134
7135         mode->hsync = drm_mode_hsync(mode);
7136         mode->vrefresh = drm_mode_vrefresh(mode);
7137         drm_mode_set_name(mode);
7138 }
7139
7140 static void i9xx_set_pipeconf(struct intel_crtc *intel_crtc)
7141 {
7142         struct drm_i915_private *dev_priv = to_i915(intel_crtc->base.dev);
7143         uint32_t pipeconf;
7144
7145         pipeconf = 0;
7146
7147         /* we keep both pipes enabled on 830 */
7148         if (IS_I830(dev_priv))
7149                 pipeconf |= I915_READ(PIPECONF(intel_crtc->pipe)) & PIPECONF_ENABLE;
7150
7151         if (intel_crtc->config->double_wide)
7152                 pipeconf |= PIPECONF_DOUBLE_WIDE;
7153
7154         /* only g4x and later have fancy bpc/dither controls */
7155         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7156             IS_CHERRYVIEW(dev_priv)) {
7157                 /* Bspec claims that we can't use dithering for 30bpp pipes. */
7158                 if (intel_crtc->config->dither && intel_crtc->config->pipe_bpp != 30)
7159                         pipeconf |= PIPECONF_DITHER_EN |
7160                                     PIPECONF_DITHER_TYPE_SP;
7161
7162                 switch (intel_crtc->config->pipe_bpp) {
7163                 case 18:
7164                         pipeconf |= PIPECONF_6BPC;
7165                         break;
7166                 case 24:
7167                         pipeconf |= PIPECONF_8BPC;
7168                         break;
7169                 case 30:
7170                         pipeconf |= PIPECONF_10BPC;
7171                         break;
7172                 default:
7173                         /* Case prevented by intel_choose_pipe_bpp_dither. */
7174                         BUG();
7175                 }
7176         }
7177
7178         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE) {
7179                 if (INTEL_GEN(dev_priv) < 4 ||
7180                     intel_crtc_has_type(intel_crtc->config, INTEL_OUTPUT_SDVO))
7181                         pipeconf |= PIPECONF_INTERLACE_W_FIELD_INDICATION;
7182                 else
7183                         pipeconf |= PIPECONF_INTERLACE_W_SYNC_SHIFT;
7184         } else
7185                 pipeconf |= PIPECONF_PROGRESSIVE;
7186
7187         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7188              intel_crtc->config->limited_color_range)
7189                 pipeconf |= PIPECONF_COLOR_RANGE_SELECT;
7190
7191         I915_WRITE(PIPECONF(intel_crtc->pipe), pipeconf);
7192         POSTING_READ(PIPECONF(intel_crtc->pipe));
7193 }
7194
7195 static int i8xx_crtc_compute_clock(struct intel_crtc *crtc,
7196                                    struct intel_crtc_state *crtc_state)
7197 {
7198         struct drm_device *dev = crtc->base.dev;
7199         struct drm_i915_private *dev_priv = to_i915(dev);
7200         const struct intel_limit *limit;
7201         int refclk = 48000;
7202
7203         memset(&crtc_state->dpll_hw_state, 0,
7204                sizeof(crtc_state->dpll_hw_state));
7205
7206         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7207                 if (intel_panel_use_ssc(dev_priv)) {
7208                         refclk = dev_priv->vbt.lvds_ssc_freq;
7209                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7210                 }
7211
7212                 limit = &intel_limits_i8xx_lvds;
7213         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DVO)) {
7214                 limit = &intel_limits_i8xx_dvo;
7215         } else {
7216                 limit = &intel_limits_i8xx_dac;
7217         }
7218
7219         if (!crtc_state->clock_set &&
7220             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7221                                  refclk, NULL, &crtc_state->dpll)) {
7222                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7223                 return -EINVAL;
7224         }
7225
7226         i8xx_compute_dpll(crtc, crtc_state, NULL);
7227
7228         return 0;
7229 }
7230
7231 static int g4x_crtc_compute_clock(struct intel_crtc *crtc,
7232                                   struct intel_crtc_state *crtc_state)
7233 {
7234         struct drm_device *dev = crtc->base.dev;
7235         struct drm_i915_private *dev_priv = to_i915(dev);
7236         const struct intel_limit *limit;
7237         int refclk = 96000;
7238
7239         memset(&crtc_state->dpll_hw_state, 0,
7240                sizeof(crtc_state->dpll_hw_state));
7241
7242         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7243                 if (intel_panel_use_ssc(dev_priv)) {
7244                         refclk = dev_priv->vbt.lvds_ssc_freq;
7245                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7246                 }
7247
7248                 if (intel_is_dual_link_lvds(dev))
7249                         limit = &intel_limits_g4x_dual_channel_lvds;
7250                 else
7251                         limit = &intel_limits_g4x_single_channel_lvds;
7252         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI) ||
7253                    intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG)) {
7254                 limit = &intel_limits_g4x_hdmi;
7255         } else if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO)) {
7256                 limit = &intel_limits_g4x_sdvo;
7257         } else {
7258                 /* The option is for other outputs */
7259                 limit = &intel_limits_i9xx_sdvo;
7260         }
7261
7262         if (!crtc_state->clock_set &&
7263             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7264                                 refclk, NULL, &crtc_state->dpll)) {
7265                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7266                 return -EINVAL;
7267         }
7268
7269         i9xx_compute_dpll(crtc, crtc_state, NULL);
7270
7271         return 0;
7272 }
7273
7274 static int pnv_crtc_compute_clock(struct intel_crtc *crtc,
7275                                   struct intel_crtc_state *crtc_state)
7276 {
7277         struct drm_device *dev = crtc->base.dev;
7278         struct drm_i915_private *dev_priv = to_i915(dev);
7279         const struct intel_limit *limit;
7280         int refclk = 96000;
7281
7282         memset(&crtc_state->dpll_hw_state, 0,
7283                sizeof(crtc_state->dpll_hw_state));
7284
7285         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7286                 if (intel_panel_use_ssc(dev_priv)) {
7287                         refclk = dev_priv->vbt.lvds_ssc_freq;
7288                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7289                 }
7290
7291                 limit = &intel_limits_pineview_lvds;
7292         } else {
7293                 limit = &intel_limits_pineview_sdvo;
7294         }
7295
7296         if (!crtc_state->clock_set &&
7297             !pnv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7298                                 refclk, NULL, &crtc_state->dpll)) {
7299                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7300                 return -EINVAL;
7301         }
7302
7303         i9xx_compute_dpll(crtc, crtc_state, NULL);
7304
7305         return 0;
7306 }
7307
7308 static int i9xx_crtc_compute_clock(struct intel_crtc *crtc,
7309                                    struct intel_crtc_state *crtc_state)
7310 {
7311         struct drm_device *dev = crtc->base.dev;
7312         struct drm_i915_private *dev_priv = to_i915(dev);
7313         const struct intel_limit *limit;
7314         int refclk = 96000;
7315
7316         memset(&crtc_state->dpll_hw_state, 0,
7317                sizeof(crtc_state->dpll_hw_state));
7318
7319         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
7320                 if (intel_panel_use_ssc(dev_priv)) {
7321                         refclk = dev_priv->vbt.lvds_ssc_freq;
7322                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n", refclk);
7323                 }
7324
7325                 limit = &intel_limits_i9xx_lvds;
7326         } else {
7327                 limit = &intel_limits_i9xx_sdvo;
7328         }
7329
7330         if (!crtc_state->clock_set &&
7331             !i9xx_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7332                                  refclk, NULL, &crtc_state->dpll)) {
7333                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7334                 return -EINVAL;
7335         }
7336
7337         i9xx_compute_dpll(crtc, crtc_state, NULL);
7338
7339         return 0;
7340 }
7341
7342 static int chv_crtc_compute_clock(struct intel_crtc *crtc,
7343                                   struct intel_crtc_state *crtc_state)
7344 {
7345         int refclk = 100000;
7346         const struct intel_limit *limit = &intel_limits_chv;
7347
7348         memset(&crtc_state->dpll_hw_state, 0,
7349                sizeof(crtc_state->dpll_hw_state));
7350
7351         if (!crtc_state->clock_set &&
7352             !chv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7353                                 refclk, NULL, &crtc_state->dpll)) {
7354                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7355                 return -EINVAL;
7356         }
7357
7358         chv_compute_dpll(crtc, crtc_state);
7359
7360         return 0;
7361 }
7362
7363 static int vlv_crtc_compute_clock(struct intel_crtc *crtc,
7364                                   struct intel_crtc_state *crtc_state)
7365 {
7366         int refclk = 100000;
7367         const struct intel_limit *limit = &intel_limits_vlv;
7368
7369         memset(&crtc_state->dpll_hw_state, 0,
7370                sizeof(crtc_state->dpll_hw_state));
7371
7372         if (!crtc_state->clock_set &&
7373             !vlv_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
7374                                 refclk, NULL, &crtc_state->dpll)) {
7375                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
7376                 return -EINVAL;
7377         }
7378
7379         vlv_compute_dpll(crtc, crtc_state);
7380
7381         return 0;
7382 }
7383
7384 static void i9xx_get_pfit_config(struct intel_crtc *crtc,
7385                                  struct intel_crtc_state *pipe_config)
7386 {
7387         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7388         uint32_t tmp;
7389
7390         if (INTEL_GEN(dev_priv) <= 3 &&
7391             (IS_I830(dev_priv) || !IS_MOBILE(dev_priv)))
7392                 return;
7393
7394         tmp = I915_READ(PFIT_CONTROL);
7395         if (!(tmp & PFIT_ENABLE))
7396                 return;
7397
7398         /* Check whether the pfit is attached to our pipe. */
7399         if (INTEL_GEN(dev_priv) < 4) {
7400                 if (crtc->pipe != PIPE_B)
7401                         return;
7402         } else {
7403                 if ((tmp & PFIT_PIPE_MASK) != (crtc->pipe << PFIT_PIPE_SHIFT))
7404                         return;
7405         }
7406
7407         pipe_config->gmch_pfit.control = tmp;
7408         pipe_config->gmch_pfit.pgm_ratios = I915_READ(PFIT_PGM_RATIOS);
7409 }
7410
7411 static void vlv_crtc_clock_get(struct intel_crtc *crtc,
7412                                struct intel_crtc_state *pipe_config)
7413 {
7414         struct drm_device *dev = crtc->base.dev;
7415         struct drm_i915_private *dev_priv = to_i915(dev);
7416         int pipe = pipe_config->cpu_transcoder;
7417         struct dpll clock;
7418         u32 mdiv;
7419         int refclk = 100000;
7420
7421         /* In case of DSI, DPLL will not be used */
7422         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7423                 return;
7424
7425         mutex_lock(&dev_priv->sb_lock);
7426         mdiv = vlv_dpio_read(dev_priv, pipe, VLV_PLL_DW3(pipe));
7427         mutex_unlock(&dev_priv->sb_lock);
7428
7429         clock.m1 = (mdiv >> DPIO_M1DIV_SHIFT) & 7;
7430         clock.m2 = mdiv & DPIO_M2DIV_MASK;
7431         clock.n = (mdiv >> DPIO_N_SHIFT) & 0xf;
7432         clock.p1 = (mdiv >> DPIO_P1_SHIFT) & 7;
7433         clock.p2 = (mdiv >> DPIO_P2_SHIFT) & 0x1f;
7434
7435         pipe_config->port_clock = vlv_calc_dpll_params(refclk, &clock);
7436 }
7437
7438 static void
7439 i9xx_get_initial_plane_config(struct intel_crtc *crtc,
7440                               struct intel_initial_plane_config *plane_config)
7441 {
7442         struct drm_device *dev = crtc->base.dev;
7443         struct drm_i915_private *dev_priv = to_i915(dev);
7444         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
7445         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
7446         enum pipe pipe = crtc->pipe;
7447         u32 val, base, offset;
7448         int fourcc, pixel_format;
7449         unsigned int aligned_height;
7450         struct drm_framebuffer *fb;
7451         struct intel_framebuffer *intel_fb;
7452
7453         if (!plane->get_hw_state(plane))
7454                 return;
7455
7456         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
7457         if (!intel_fb) {
7458                 DRM_DEBUG_KMS("failed to alloc fb\n");
7459                 return;
7460         }
7461
7462         fb = &intel_fb->base;
7463
7464         fb->dev = dev;
7465
7466         val = I915_READ(DSPCNTR(i9xx_plane));
7467
7468         if (INTEL_GEN(dev_priv) >= 4) {
7469                 if (val & DISPPLANE_TILED) {
7470                         plane_config->tiling = I915_TILING_X;
7471                         fb->modifier = I915_FORMAT_MOD_X_TILED;
7472                 }
7473         }
7474
7475         pixel_format = val & DISPPLANE_PIXFORMAT_MASK;
7476         fourcc = i9xx_format_to_fourcc(pixel_format);
7477         fb->format = drm_format_info(fourcc);
7478
7479         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
7480                 offset = I915_READ(DSPOFFSET(i9xx_plane));
7481                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7482         } else if (INTEL_GEN(dev_priv) >= 4) {
7483                 if (plane_config->tiling)
7484                         offset = I915_READ(DSPTILEOFF(i9xx_plane));
7485                 else
7486                         offset = I915_READ(DSPLINOFF(i9xx_plane));
7487                 base = I915_READ(DSPSURF(i9xx_plane)) & 0xfffff000;
7488         } else {
7489                 base = I915_READ(DSPADDR(i9xx_plane));
7490         }
7491         plane_config->base = base;
7492
7493         val = I915_READ(PIPESRC(pipe));
7494         fb->width = ((val >> 16) & 0xfff) + 1;
7495         fb->height = ((val >> 0) & 0xfff) + 1;
7496
7497         val = I915_READ(DSPSTRIDE(i9xx_plane));
7498         fb->pitches[0] = val & 0xffffffc0;
7499
7500         aligned_height = intel_fb_align_height(fb, 0, fb->height);
7501
7502         plane_config->size = fb->pitches[0] * aligned_height;
7503
7504         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
7505                       crtc->base.name, plane->base.name, fb->width, fb->height,
7506                       fb->format->cpp[0] * 8, base, fb->pitches[0],
7507                       plane_config->size);
7508
7509         plane_config->fb = intel_fb;
7510 }
7511
7512 static void chv_crtc_clock_get(struct intel_crtc *crtc,
7513                                struct intel_crtc_state *pipe_config)
7514 {
7515         struct drm_device *dev = crtc->base.dev;
7516         struct drm_i915_private *dev_priv = to_i915(dev);
7517         int pipe = pipe_config->cpu_transcoder;
7518         enum dpio_channel port = vlv_pipe_to_channel(pipe);
7519         struct dpll clock;
7520         u32 cmn_dw13, pll_dw0, pll_dw1, pll_dw2, pll_dw3;
7521         int refclk = 100000;
7522
7523         /* In case of DSI, DPLL will not be used */
7524         if ((pipe_config->dpll_hw_state.dpll & DPLL_VCO_ENABLE) == 0)
7525                 return;
7526
7527         mutex_lock(&dev_priv->sb_lock);
7528         cmn_dw13 = vlv_dpio_read(dev_priv, pipe, CHV_CMN_DW13(port));
7529         pll_dw0 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW0(port));
7530         pll_dw1 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW1(port));
7531         pll_dw2 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW2(port));
7532         pll_dw3 = vlv_dpio_read(dev_priv, pipe, CHV_PLL_DW3(port));
7533         mutex_unlock(&dev_priv->sb_lock);
7534
7535         clock.m1 = (pll_dw1 & 0x7) == DPIO_CHV_M1_DIV_BY_2 ? 2 : 0;
7536         clock.m2 = (pll_dw0 & 0xff) << 22;
7537         if (pll_dw3 & DPIO_CHV_FRAC_DIV_EN)
7538                 clock.m2 |= pll_dw2 & 0x3fffff;
7539         clock.n = (pll_dw1 >> DPIO_CHV_N_DIV_SHIFT) & 0xf;
7540         clock.p1 = (cmn_dw13 >> DPIO_CHV_P1_DIV_SHIFT) & 0x7;
7541         clock.p2 = (cmn_dw13 >> DPIO_CHV_P2_DIV_SHIFT) & 0x1f;
7542
7543         pipe_config->port_clock = chv_calc_dpll_params(refclk, &clock);
7544 }
7545
7546 static bool i9xx_get_pipe_config(struct intel_crtc *crtc,
7547                                  struct intel_crtc_state *pipe_config)
7548 {
7549         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
7550         enum intel_display_power_domain power_domain;
7551         uint32_t tmp;
7552         bool ret;
7553
7554         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
7555         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
7556                 return false;
7557
7558         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
7559         pipe_config->shared_dpll = NULL;
7560
7561         ret = false;
7562
7563         tmp = I915_READ(PIPECONF(crtc->pipe));
7564         if (!(tmp & PIPECONF_ENABLE))
7565                 goto out;
7566
7567         if (IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
7568             IS_CHERRYVIEW(dev_priv)) {
7569                 switch (tmp & PIPECONF_BPC_MASK) {
7570                 case PIPECONF_6BPC:
7571                         pipe_config->pipe_bpp = 18;
7572                         break;
7573                 case PIPECONF_8BPC:
7574                         pipe_config->pipe_bpp = 24;
7575                         break;
7576                 case PIPECONF_10BPC:
7577                         pipe_config->pipe_bpp = 30;
7578                         break;
7579                 default:
7580                         break;
7581                 }
7582         }
7583
7584         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
7585             (tmp & PIPECONF_COLOR_RANGE_SELECT))
7586                 pipe_config->limited_color_range = true;
7587
7588         if (INTEL_GEN(dev_priv) < 4)
7589                 pipe_config->double_wide = tmp & PIPECONF_DOUBLE_WIDE;
7590
7591         intel_get_pipe_timings(crtc, pipe_config);
7592         intel_get_pipe_src_size(crtc, pipe_config);
7593
7594         i9xx_get_pfit_config(crtc, pipe_config);
7595
7596         if (INTEL_GEN(dev_priv) >= 4) {
7597                 /* No way to read it out on pipes B and C */
7598                 if (IS_CHERRYVIEW(dev_priv) && crtc->pipe != PIPE_A)
7599                         tmp = dev_priv->chv_dpll_md[crtc->pipe];
7600                 else
7601                         tmp = I915_READ(DPLL_MD(crtc->pipe));
7602                 pipe_config->pixel_multiplier =
7603                         ((tmp & DPLL_MD_UDI_MULTIPLIER_MASK)
7604                          >> DPLL_MD_UDI_MULTIPLIER_SHIFT) + 1;
7605                 pipe_config->dpll_hw_state.dpll_md = tmp;
7606         } else if (IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
7607                    IS_G33(dev_priv) || IS_PINEVIEW(dev_priv)) {
7608                 tmp = I915_READ(DPLL(crtc->pipe));
7609                 pipe_config->pixel_multiplier =
7610                         ((tmp & SDVO_MULTIPLIER_MASK)
7611                          >> SDVO_MULTIPLIER_SHIFT_HIRES) + 1;
7612         } else {
7613                 /* Note that on i915G/GM the pixel multiplier is in the sdvo
7614                  * port and will be fixed up in the encoder->get_config
7615                  * function. */
7616                 pipe_config->pixel_multiplier = 1;
7617         }
7618         pipe_config->dpll_hw_state.dpll = I915_READ(DPLL(crtc->pipe));
7619         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
7620                 /*
7621                  * DPLL_DVO_2X_MODE must be enabled for both DPLLs
7622                  * on 830. Filter it out here so that we don't
7623                  * report errors due to that.
7624                  */
7625                 if (IS_I830(dev_priv))
7626                         pipe_config->dpll_hw_state.dpll &= ~DPLL_DVO_2X_MODE;
7627
7628                 pipe_config->dpll_hw_state.fp0 = I915_READ(FP0(crtc->pipe));
7629                 pipe_config->dpll_hw_state.fp1 = I915_READ(FP1(crtc->pipe));
7630         } else {
7631                 /* Mask out read-only status bits. */
7632                 pipe_config->dpll_hw_state.dpll &= ~(DPLL_LOCK_VLV |
7633                                                      DPLL_PORTC_READY_MASK |
7634                                                      DPLL_PORTB_READY_MASK);
7635         }
7636
7637         if (IS_CHERRYVIEW(dev_priv))
7638                 chv_crtc_clock_get(crtc, pipe_config);
7639         else if (IS_VALLEYVIEW(dev_priv))
7640                 vlv_crtc_clock_get(crtc, pipe_config);
7641         else
7642                 i9xx_crtc_clock_get(crtc, pipe_config);
7643
7644         /*
7645          * Normally the dotclock is filled in by the encoder .get_config()
7646          * but in case the pipe is enabled w/o any ports we need a sane
7647          * default.
7648          */
7649         pipe_config->base.adjusted_mode.crtc_clock =
7650                 pipe_config->port_clock / pipe_config->pixel_multiplier;
7651
7652         ret = true;
7653
7654 out:
7655         intel_display_power_put(dev_priv, power_domain);
7656
7657         return ret;
7658 }
7659
7660 static void ironlake_init_pch_refclk(struct drm_i915_private *dev_priv)
7661 {
7662         struct intel_encoder *encoder;
7663         int i;
7664         u32 val, final;
7665         bool has_lvds = false;
7666         bool has_cpu_edp = false;
7667         bool has_panel = false;
7668         bool has_ck505 = false;
7669         bool can_ssc = false;
7670         bool using_ssc_source = false;
7671
7672         /* We need to take the global config into account */
7673         for_each_intel_encoder(&dev_priv->drm, encoder) {
7674                 switch (encoder->type) {
7675                 case INTEL_OUTPUT_LVDS:
7676                         has_panel = true;
7677                         has_lvds = true;
7678                         break;
7679                 case INTEL_OUTPUT_EDP:
7680                         has_panel = true;
7681                         if (encoder->port == PORT_A)
7682                                 has_cpu_edp = true;
7683                         break;
7684                 default:
7685                         break;
7686                 }
7687         }
7688
7689         if (HAS_PCH_IBX(dev_priv)) {
7690                 has_ck505 = dev_priv->vbt.display_clock_mode;
7691                 can_ssc = has_ck505;
7692         } else {
7693                 has_ck505 = false;
7694                 can_ssc = true;
7695         }
7696
7697         /* Check if any DPLLs are using the SSC source */
7698         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
7699                 u32 temp = I915_READ(PCH_DPLL(i));
7700
7701                 if (!(temp & DPLL_VCO_ENABLE))
7702                         continue;
7703
7704                 if ((temp & PLL_REF_INPUT_MASK) ==
7705                     PLLB_REF_INPUT_SPREADSPECTRUMIN) {
7706                         using_ssc_source = true;
7707                         break;
7708                 }
7709         }
7710
7711         DRM_DEBUG_KMS("has_panel %d has_lvds %d has_ck505 %d using_ssc_source %d\n",
7712                       has_panel, has_lvds, has_ck505, using_ssc_source);
7713
7714         /* Ironlake: try to setup display ref clock before DPLL
7715          * enabling. This is only under driver's control after
7716          * PCH B stepping, previous chipset stepping should be
7717          * ignoring this setting.
7718          */
7719         val = I915_READ(PCH_DREF_CONTROL);
7720
7721         /* As we must carefully and slowly disable/enable each source in turn,
7722          * compute the final state we want first and check if we need to
7723          * make any changes at all.
7724          */
7725         final = val;
7726         final &= ~DREF_NONSPREAD_SOURCE_MASK;
7727         if (has_ck505)
7728                 final |= DREF_NONSPREAD_CK505_ENABLE;
7729         else
7730                 final |= DREF_NONSPREAD_SOURCE_ENABLE;
7731
7732         final &= ~DREF_SSC_SOURCE_MASK;
7733         final &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7734         final &= ~DREF_SSC1_ENABLE;
7735
7736         if (has_panel) {
7737                 final |= DREF_SSC_SOURCE_ENABLE;
7738
7739                 if (intel_panel_use_ssc(dev_priv) && can_ssc)
7740                         final |= DREF_SSC1_ENABLE;
7741
7742                 if (has_cpu_edp) {
7743                         if (intel_panel_use_ssc(dev_priv) && can_ssc)
7744                                 final |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7745                         else
7746                                 final |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7747                 } else
7748                         final |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7749         } else if (using_ssc_source) {
7750                 final |= DREF_SSC_SOURCE_ENABLE;
7751                 final |= DREF_SSC1_ENABLE;
7752         }
7753
7754         if (final == val)
7755                 return;
7756
7757         /* Always enable nonspread source */
7758         val &= ~DREF_NONSPREAD_SOURCE_MASK;
7759
7760         if (has_ck505)
7761                 val |= DREF_NONSPREAD_CK505_ENABLE;
7762         else
7763                 val |= DREF_NONSPREAD_SOURCE_ENABLE;
7764
7765         if (has_panel) {
7766                 val &= ~DREF_SSC_SOURCE_MASK;
7767                 val |= DREF_SSC_SOURCE_ENABLE;
7768
7769                 /* SSC must be turned on before enabling the CPU output  */
7770                 if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7771                         DRM_DEBUG_KMS("Using SSC on panel\n");
7772                         val |= DREF_SSC1_ENABLE;
7773                 } else
7774                         val &= ~DREF_SSC1_ENABLE;
7775
7776                 /* Get SSC going before enabling the outputs */
7777                 I915_WRITE(PCH_DREF_CONTROL, val);
7778                 POSTING_READ(PCH_DREF_CONTROL);
7779                 udelay(200);
7780
7781                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7782
7783                 /* Enable CPU source on CPU attached eDP */
7784                 if (has_cpu_edp) {
7785                         if (intel_panel_use_ssc(dev_priv) && can_ssc) {
7786                                 DRM_DEBUG_KMS("Using SSC on eDP\n");
7787                                 val |= DREF_CPU_SOURCE_OUTPUT_DOWNSPREAD;
7788                         } else
7789                                 val |= DREF_CPU_SOURCE_OUTPUT_NONSPREAD;
7790                 } else
7791                         val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7792
7793                 I915_WRITE(PCH_DREF_CONTROL, val);
7794                 POSTING_READ(PCH_DREF_CONTROL);
7795                 udelay(200);
7796         } else {
7797                 DRM_DEBUG_KMS("Disabling CPU source output\n");
7798
7799                 val &= ~DREF_CPU_SOURCE_OUTPUT_MASK;
7800
7801                 /* Turn off CPU output */
7802                 val |= DREF_CPU_SOURCE_OUTPUT_DISABLE;
7803
7804                 I915_WRITE(PCH_DREF_CONTROL, val);
7805                 POSTING_READ(PCH_DREF_CONTROL);
7806                 udelay(200);
7807
7808                 if (!using_ssc_source) {
7809                         DRM_DEBUG_KMS("Disabling SSC source\n");
7810
7811                         /* Turn off the SSC source */
7812                         val &= ~DREF_SSC_SOURCE_MASK;
7813                         val |= DREF_SSC_SOURCE_DISABLE;
7814
7815                         /* Turn off SSC1 */
7816                         val &= ~DREF_SSC1_ENABLE;
7817
7818                         I915_WRITE(PCH_DREF_CONTROL, val);
7819                         POSTING_READ(PCH_DREF_CONTROL);
7820                         udelay(200);
7821                 }
7822         }
7823
7824         BUG_ON(val != final);
7825 }
7826
7827 static void lpt_reset_fdi_mphy(struct drm_i915_private *dev_priv)
7828 {
7829         uint32_t tmp;
7830
7831         tmp = I915_READ(SOUTH_CHICKEN2);
7832         tmp |= FDI_MPHY_IOSFSB_RESET_CTL;
7833         I915_WRITE(SOUTH_CHICKEN2, tmp);
7834
7835         if (wait_for_us(I915_READ(SOUTH_CHICKEN2) &
7836                         FDI_MPHY_IOSFSB_RESET_STATUS, 100))
7837                 DRM_ERROR("FDI mPHY reset assert timeout\n");
7838
7839         tmp = I915_READ(SOUTH_CHICKEN2);
7840         tmp &= ~FDI_MPHY_IOSFSB_RESET_CTL;
7841         I915_WRITE(SOUTH_CHICKEN2, tmp);
7842
7843         if (wait_for_us((I915_READ(SOUTH_CHICKEN2) &
7844                          FDI_MPHY_IOSFSB_RESET_STATUS) == 0, 100))
7845                 DRM_ERROR("FDI mPHY reset de-assert timeout\n");
7846 }
7847
7848 /* WaMPhyProgramming:hsw */
7849 static void lpt_program_fdi_mphy(struct drm_i915_private *dev_priv)
7850 {
7851         uint32_t tmp;
7852
7853         tmp = intel_sbi_read(dev_priv, 0x8008, SBI_MPHY);
7854         tmp &= ~(0xFF << 24);
7855         tmp |= (0x12 << 24);
7856         intel_sbi_write(dev_priv, 0x8008, tmp, SBI_MPHY);
7857
7858         tmp = intel_sbi_read(dev_priv, 0x2008, SBI_MPHY);
7859         tmp |= (1 << 11);
7860         intel_sbi_write(dev_priv, 0x2008, tmp, SBI_MPHY);
7861
7862         tmp = intel_sbi_read(dev_priv, 0x2108, SBI_MPHY);
7863         tmp |= (1 << 11);
7864         intel_sbi_write(dev_priv, 0x2108, tmp, SBI_MPHY);
7865
7866         tmp = intel_sbi_read(dev_priv, 0x206C, SBI_MPHY);
7867         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7868         intel_sbi_write(dev_priv, 0x206C, tmp, SBI_MPHY);
7869
7870         tmp = intel_sbi_read(dev_priv, 0x216C, SBI_MPHY);
7871         tmp |= (1 << 24) | (1 << 21) | (1 << 18);
7872         intel_sbi_write(dev_priv, 0x216C, tmp, SBI_MPHY);
7873
7874         tmp = intel_sbi_read(dev_priv, 0x2080, SBI_MPHY);
7875         tmp &= ~(7 << 13);
7876         tmp |= (5 << 13);
7877         intel_sbi_write(dev_priv, 0x2080, tmp, SBI_MPHY);
7878
7879         tmp = intel_sbi_read(dev_priv, 0x2180, SBI_MPHY);
7880         tmp &= ~(7 << 13);
7881         tmp |= (5 << 13);
7882         intel_sbi_write(dev_priv, 0x2180, tmp, SBI_MPHY);
7883
7884         tmp = intel_sbi_read(dev_priv, 0x208C, SBI_MPHY);
7885         tmp &= ~0xFF;
7886         tmp |= 0x1C;
7887         intel_sbi_write(dev_priv, 0x208C, tmp, SBI_MPHY);
7888
7889         tmp = intel_sbi_read(dev_priv, 0x218C, SBI_MPHY);
7890         tmp &= ~0xFF;
7891         tmp |= 0x1C;
7892         intel_sbi_write(dev_priv, 0x218C, tmp, SBI_MPHY);
7893
7894         tmp = intel_sbi_read(dev_priv, 0x2098, SBI_MPHY);
7895         tmp &= ~(0xFF << 16);
7896         tmp |= (0x1C << 16);
7897         intel_sbi_write(dev_priv, 0x2098, tmp, SBI_MPHY);
7898
7899         tmp = intel_sbi_read(dev_priv, 0x2198, SBI_MPHY);
7900         tmp &= ~(0xFF << 16);
7901         tmp |= (0x1C << 16);
7902         intel_sbi_write(dev_priv, 0x2198, tmp, SBI_MPHY);
7903
7904         tmp = intel_sbi_read(dev_priv, 0x20C4, SBI_MPHY);
7905         tmp |= (1 << 27);
7906         intel_sbi_write(dev_priv, 0x20C4, tmp, SBI_MPHY);
7907
7908         tmp = intel_sbi_read(dev_priv, 0x21C4, SBI_MPHY);
7909         tmp |= (1 << 27);
7910         intel_sbi_write(dev_priv, 0x21C4, tmp, SBI_MPHY);
7911
7912         tmp = intel_sbi_read(dev_priv, 0x20EC, SBI_MPHY);
7913         tmp &= ~(0xF << 28);
7914         tmp |= (4 << 28);
7915         intel_sbi_write(dev_priv, 0x20EC, tmp, SBI_MPHY);
7916
7917         tmp = intel_sbi_read(dev_priv, 0x21EC, SBI_MPHY);
7918         tmp &= ~(0xF << 28);
7919         tmp |= (4 << 28);
7920         intel_sbi_write(dev_priv, 0x21EC, tmp, SBI_MPHY);
7921 }
7922
7923 /* Implements 3 different sequences from BSpec chapter "Display iCLK
7924  * Programming" based on the parameters passed:
7925  * - Sequence to enable CLKOUT_DP
7926  * - Sequence to enable CLKOUT_DP without spread
7927  * - Sequence to enable CLKOUT_DP for FDI usage and configure PCH FDI I/O
7928  */
7929 static void lpt_enable_clkout_dp(struct drm_i915_private *dev_priv,
7930                                  bool with_spread, bool with_fdi)
7931 {
7932         uint32_t reg, tmp;
7933
7934         if (WARN(with_fdi && !with_spread, "FDI requires downspread\n"))
7935                 with_spread = true;
7936         if (WARN(HAS_PCH_LPT_LP(dev_priv) &&
7937             with_fdi, "LP PCH doesn't have FDI\n"))
7938                 with_fdi = false;
7939
7940         mutex_lock(&dev_priv->sb_lock);
7941
7942         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7943         tmp &= ~SBI_SSCCTL_DISABLE;
7944         tmp |= SBI_SSCCTL_PATHALT;
7945         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7946
7947         udelay(24);
7948
7949         if (with_spread) {
7950                 tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7951                 tmp &= ~SBI_SSCCTL_PATHALT;
7952                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7953
7954                 if (with_fdi) {
7955                         lpt_reset_fdi_mphy(dev_priv);
7956                         lpt_program_fdi_mphy(dev_priv);
7957                 }
7958         }
7959
7960         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
7961         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7962         tmp |= SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7963         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7964
7965         mutex_unlock(&dev_priv->sb_lock);
7966 }
7967
7968 /* Sequence to disable CLKOUT_DP */
7969 static void lpt_disable_clkout_dp(struct drm_i915_private *dev_priv)
7970 {
7971         uint32_t reg, tmp;
7972
7973         mutex_lock(&dev_priv->sb_lock);
7974
7975         reg = HAS_PCH_LPT_LP(dev_priv) ? SBI_GEN0 : SBI_DBUFF0;
7976         tmp = intel_sbi_read(dev_priv, reg, SBI_ICLK);
7977         tmp &= ~SBI_GEN0_CFG_BUFFENABLE_DISABLE;
7978         intel_sbi_write(dev_priv, reg, tmp, SBI_ICLK);
7979
7980         tmp = intel_sbi_read(dev_priv, SBI_SSCCTL, SBI_ICLK);
7981         if (!(tmp & SBI_SSCCTL_DISABLE)) {
7982                 if (!(tmp & SBI_SSCCTL_PATHALT)) {
7983                         tmp |= SBI_SSCCTL_PATHALT;
7984                         intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7985                         udelay(32);
7986                 }
7987                 tmp |= SBI_SSCCTL_DISABLE;
7988                 intel_sbi_write(dev_priv, SBI_SSCCTL, tmp, SBI_ICLK);
7989         }
7990
7991         mutex_unlock(&dev_priv->sb_lock);
7992 }
7993
7994 #define BEND_IDX(steps) ((50 + (steps)) / 5)
7995
7996 static const uint16_t sscdivintphase[] = {
7997         [BEND_IDX( 50)] = 0x3B23,
7998         [BEND_IDX( 45)] = 0x3B23,
7999         [BEND_IDX( 40)] = 0x3C23,
8000         [BEND_IDX( 35)] = 0x3C23,
8001         [BEND_IDX( 30)] = 0x3D23,
8002         [BEND_IDX( 25)] = 0x3D23,
8003         [BEND_IDX( 20)] = 0x3E23,
8004         [BEND_IDX( 15)] = 0x3E23,
8005         [BEND_IDX( 10)] = 0x3F23,
8006         [BEND_IDX(  5)] = 0x3F23,
8007         [BEND_IDX(  0)] = 0x0025,
8008         [BEND_IDX( -5)] = 0x0025,
8009         [BEND_IDX(-10)] = 0x0125,
8010         [BEND_IDX(-15)] = 0x0125,
8011         [BEND_IDX(-20)] = 0x0225,
8012         [BEND_IDX(-25)] = 0x0225,
8013         [BEND_IDX(-30)] = 0x0325,
8014         [BEND_IDX(-35)] = 0x0325,
8015         [BEND_IDX(-40)] = 0x0425,
8016         [BEND_IDX(-45)] = 0x0425,
8017         [BEND_IDX(-50)] = 0x0525,
8018 };
8019
8020 /*
8021  * Bend CLKOUT_DP
8022  * steps -50 to 50 inclusive, in steps of 5
8023  * < 0 slow down the clock, > 0 speed up the clock, 0 == no bend (135MHz)
8024  * change in clock period = -(steps / 10) * 5.787 ps
8025  */
8026 static void lpt_bend_clkout_dp(struct drm_i915_private *dev_priv, int steps)
8027 {
8028         uint32_t tmp;
8029         int idx = BEND_IDX(steps);
8030
8031         if (WARN_ON(steps % 5 != 0))
8032                 return;
8033
8034         if (WARN_ON(idx >= ARRAY_SIZE(sscdivintphase)))
8035                 return;
8036
8037         mutex_lock(&dev_priv->sb_lock);
8038
8039         if (steps % 10 != 0)
8040                 tmp = 0xAAAAAAAB;
8041         else
8042                 tmp = 0x00000000;
8043         intel_sbi_write(dev_priv, SBI_SSCDITHPHASE, tmp, SBI_ICLK);
8044
8045         tmp = intel_sbi_read(dev_priv, SBI_SSCDIVINTPHASE, SBI_ICLK);
8046         tmp &= 0xffff0000;
8047         tmp |= sscdivintphase[idx];
8048         intel_sbi_write(dev_priv, SBI_SSCDIVINTPHASE, tmp, SBI_ICLK);
8049
8050         mutex_unlock(&dev_priv->sb_lock);
8051 }
8052
8053 #undef BEND_IDX
8054
8055 static void lpt_init_pch_refclk(struct drm_i915_private *dev_priv)
8056 {
8057         struct intel_encoder *encoder;
8058         bool has_vga = false;
8059
8060         for_each_intel_encoder(&dev_priv->drm, encoder) {
8061                 switch (encoder->type) {
8062                 case INTEL_OUTPUT_ANALOG:
8063                         has_vga = true;
8064                         break;
8065                 default:
8066                         break;
8067                 }
8068         }
8069
8070         if (has_vga) {
8071                 lpt_bend_clkout_dp(dev_priv, 0);
8072                 lpt_enable_clkout_dp(dev_priv, true, true);
8073         } else {
8074                 lpt_disable_clkout_dp(dev_priv);
8075         }
8076 }
8077
8078 /*
8079  * Initialize reference clocks when the driver loads
8080  */
8081 void intel_init_pch_refclk(struct drm_i915_private *dev_priv)
8082 {
8083         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv))
8084                 ironlake_init_pch_refclk(dev_priv);
8085         else if (HAS_PCH_LPT(dev_priv))
8086                 lpt_init_pch_refclk(dev_priv);
8087 }
8088
8089 static void ironlake_set_pipeconf(struct drm_crtc *crtc)
8090 {
8091         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8092         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8093         int pipe = intel_crtc->pipe;
8094         uint32_t val;
8095
8096         val = 0;
8097
8098         switch (intel_crtc->config->pipe_bpp) {
8099         case 18:
8100                 val |= PIPECONF_6BPC;
8101                 break;
8102         case 24:
8103                 val |= PIPECONF_8BPC;
8104                 break;
8105         case 30:
8106                 val |= PIPECONF_10BPC;
8107                 break;
8108         case 36:
8109                 val |= PIPECONF_12BPC;
8110                 break;
8111         default:
8112                 /* Case prevented by intel_choose_pipe_bpp_dither. */
8113                 BUG();
8114         }
8115
8116         if (intel_crtc->config->dither)
8117                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8118
8119         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8120                 val |= PIPECONF_INTERLACED_ILK;
8121         else
8122                 val |= PIPECONF_PROGRESSIVE;
8123
8124         if (intel_crtc->config->limited_color_range)
8125                 val |= PIPECONF_COLOR_RANGE_SELECT;
8126
8127         I915_WRITE(PIPECONF(pipe), val);
8128         POSTING_READ(PIPECONF(pipe));
8129 }
8130
8131 static void haswell_set_pipeconf(struct drm_crtc *crtc)
8132 {
8133         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8134         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8135         enum transcoder cpu_transcoder = intel_crtc->config->cpu_transcoder;
8136         u32 val = 0;
8137
8138         if (IS_HASWELL(dev_priv) && intel_crtc->config->dither)
8139                 val |= (PIPECONF_DITHER_EN | PIPECONF_DITHER_TYPE_SP);
8140
8141         if (intel_crtc->config->base.adjusted_mode.flags & DRM_MODE_FLAG_INTERLACE)
8142                 val |= PIPECONF_INTERLACED_ILK;
8143         else
8144                 val |= PIPECONF_PROGRESSIVE;
8145
8146         I915_WRITE(PIPECONF(cpu_transcoder), val);
8147         POSTING_READ(PIPECONF(cpu_transcoder));
8148 }
8149
8150 static void haswell_set_pipemisc(struct drm_crtc *crtc)
8151 {
8152         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
8153         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
8154         struct intel_crtc_state *config = intel_crtc->config;
8155
8156         if (IS_BROADWELL(dev_priv) || INTEL_INFO(dev_priv)->gen >= 9) {
8157                 u32 val = 0;
8158
8159                 switch (intel_crtc->config->pipe_bpp) {
8160                 case 18:
8161                         val |= PIPEMISC_DITHER_6_BPC;
8162                         break;
8163                 case 24:
8164                         val |= PIPEMISC_DITHER_8_BPC;
8165                         break;
8166                 case 30:
8167                         val |= PIPEMISC_DITHER_10_BPC;
8168                         break;
8169                 case 36:
8170                         val |= PIPEMISC_DITHER_12_BPC;
8171                         break;
8172                 default:
8173                         /* Case prevented by pipe_config_set_bpp. */
8174                         BUG();
8175                 }
8176
8177                 if (intel_crtc->config->dither)
8178                         val |= PIPEMISC_DITHER_ENABLE | PIPEMISC_DITHER_TYPE_SP;
8179
8180                 if (config->ycbcr420) {
8181                         val |= PIPEMISC_OUTPUT_COLORSPACE_YUV |
8182                                 PIPEMISC_YUV420_ENABLE |
8183                                 PIPEMISC_YUV420_MODE_FULL_BLEND;
8184                 }
8185
8186                 I915_WRITE(PIPEMISC(intel_crtc->pipe), val);
8187         }
8188 }
8189
8190 int ironlake_get_lanes_required(int target_clock, int link_bw, int bpp)
8191 {
8192         /*
8193          * Account for spread spectrum to avoid
8194          * oversubscribing the link. Max center spread
8195          * is 2.5%; use 5% for safety's sake.
8196          */
8197         u32 bps = target_clock * bpp * 21 / 20;
8198         return DIV_ROUND_UP(bps, link_bw * 8);
8199 }
8200
8201 static bool ironlake_needs_fb_cb_tune(struct dpll *dpll, int factor)
8202 {
8203         return i9xx_dpll_compute_m(dpll) < factor * dpll->n;
8204 }
8205
8206 static void ironlake_compute_dpll(struct intel_crtc *intel_crtc,
8207                                   struct intel_crtc_state *crtc_state,
8208                                   struct dpll *reduced_clock)
8209 {
8210         struct drm_crtc *crtc = &intel_crtc->base;
8211         struct drm_device *dev = crtc->dev;
8212         struct drm_i915_private *dev_priv = to_i915(dev);
8213         u32 dpll, fp, fp2;
8214         int factor;
8215
8216         /* Enable autotuning of the PLL clock (if permissible) */
8217         factor = 21;
8218         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8219                 if ((intel_panel_use_ssc(dev_priv) &&
8220                      dev_priv->vbt.lvds_ssc_freq == 100000) ||
8221                     (HAS_PCH_IBX(dev_priv) && intel_is_dual_link_lvds(dev)))
8222                         factor = 25;
8223         } else if (crtc_state->sdvo_tv_clock)
8224                 factor = 20;
8225
8226         fp = i9xx_dpll_compute_fp(&crtc_state->dpll);
8227
8228         if (ironlake_needs_fb_cb_tune(&crtc_state->dpll, factor))
8229                 fp |= FP_CB_TUNE;
8230
8231         if (reduced_clock) {
8232                 fp2 = i9xx_dpll_compute_fp(reduced_clock);
8233
8234                 if (reduced_clock->m < factor * reduced_clock->n)
8235                         fp2 |= FP_CB_TUNE;
8236         } else {
8237                 fp2 = fp;
8238         }
8239
8240         dpll = 0;
8241
8242         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS))
8243                 dpll |= DPLLB_MODE_LVDS;
8244         else
8245                 dpll |= DPLLB_MODE_DAC_SERIAL;
8246
8247         dpll |= (crtc_state->pixel_multiplier - 1)
8248                 << PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT;
8249
8250         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_SDVO) ||
8251             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_HDMI))
8252                 dpll |= DPLL_SDVO_HIGH_SPEED;
8253
8254         if (intel_crtc_has_dp_encoder(crtc_state))
8255                 dpll |= DPLL_SDVO_HIGH_SPEED;
8256
8257         /*
8258          * The high speed IO clock is only really required for
8259          * SDVO/HDMI/DP, but we also enable it for CRT to make it
8260          * possible to share the DPLL between CRT and HDMI. Enabling
8261          * the clock needlessly does no real harm, except use up a
8262          * bit of power potentially.
8263          *
8264          * We'll limit this to IVB with 3 pipes, since it has only two
8265          * DPLLs and so DPLL sharing is the only way to get three pipes
8266          * driving PCH ports at the same time. On SNB we could do this,
8267          * and potentially avoid enabling the second DPLL, but it's not
8268          * clear if it''s a win or loss power wise. No point in doing
8269          * this on ILK at all since it has a fixed DPLL<->pipe mapping.
8270          */
8271         if (INTEL_INFO(dev_priv)->num_pipes == 3 &&
8272             intel_crtc_has_type(crtc_state, INTEL_OUTPUT_ANALOG))
8273                 dpll |= DPLL_SDVO_HIGH_SPEED;
8274
8275         /* compute bitmask from p1 value */
8276         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA01_P1_POST_DIV_SHIFT;
8277         /* also FPA1 */
8278         dpll |= (1 << (crtc_state->dpll.p1 - 1)) << DPLL_FPA1_P1_POST_DIV_SHIFT;
8279
8280         switch (crtc_state->dpll.p2) {
8281         case 5:
8282                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_5;
8283                 break;
8284         case 7:
8285                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_7;
8286                 break;
8287         case 10:
8288                 dpll |= DPLL_DAC_SERIAL_P2_CLOCK_DIV_10;
8289                 break;
8290         case 14:
8291                 dpll |= DPLLB_LVDS_P2_CLOCK_DIV_14;
8292                 break;
8293         }
8294
8295         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS) &&
8296             intel_panel_use_ssc(dev_priv))
8297                 dpll |= PLLB_REF_INPUT_SPREADSPECTRUMIN;
8298         else
8299                 dpll |= PLL_REF_INPUT_DREFCLK;
8300
8301         dpll |= DPLL_VCO_ENABLE;
8302
8303         crtc_state->dpll_hw_state.dpll = dpll;
8304         crtc_state->dpll_hw_state.fp0 = fp;
8305         crtc_state->dpll_hw_state.fp1 = fp2;
8306 }
8307
8308 static int ironlake_crtc_compute_clock(struct intel_crtc *crtc,
8309                                        struct intel_crtc_state *crtc_state)
8310 {
8311         struct drm_device *dev = crtc->base.dev;
8312         struct drm_i915_private *dev_priv = to_i915(dev);
8313         const struct intel_limit *limit;
8314         int refclk = 120000;
8315
8316         memset(&crtc_state->dpll_hw_state, 0,
8317                sizeof(crtc_state->dpll_hw_state));
8318
8319         /* CPU eDP is the only output that doesn't need a PCH PLL of its own. */
8320         if (!crtc_state->has_pch_encoder)
8321                 return 0;
8322
8323         if (intel_crtc_has_type(crtc_state, INTEL_OUTPUT_LVDS)) {
8324                 if (intel_panel_use_ssc(dev_priv)) {
8325                         DRM_DEBUG_KMS("using SSC reference clock of %d kHz\n",
8326                                       dev_priv->vbt.lvds_ssc_freq);
8327                         refclk = dev_priv->vbt.lvds_ssc_freq;
8328                 }
8329
8330                 if (intel_is_dual_link_lvds(dev)) {
8331                         if (refclk == 100000)
8332                                 limit = &intel_limits_ironlake_dual_lvds_100m;
8333                         else
8334                                 limit = &intel_limits_ironlake_dual_lvds;
8335                 } else {
8336                         if (refclk == 100000)
8337                                 limit = &intel_limits_ironlake_single_lvds_100m;
8338                         else
8339                                 limit = &intel_limits_ironlake_single_lvds;
8340                 }
8341         } else {
8342                 limit = &intel_limits_ironlake_dac;
8343         }
8344
8345         if (!crtc_state->clock_set &&
8346             !g4x_find_best_dpll(limit, crtc_state, crtc_state->port_clock,
8347                                 refclk, NULL, &crtc_state->dpll)) {
8348                 DRM_ERROR("Couldn't find PLL settings for mode!\n");
8349                 return -EINVAL;
8350         }
8351
8352         ironlake_compute_dpll(crtc, crtc_state, NULL);
8353
8354         if (!intel_get_shared_dpll(crtc, crtc_state, NULL)) {
8355                 DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8356                                  pipe_name(crtc->pipe));
8357                 return -EINVAL;
8358         }
8359
8360         return 0;
8361 }
8362
8363 static void intel_pch_transcoder_get_m_n(struct intel_crtc *crtc,
8364                                          struct intel_link_m_n *m_n)
8365 {
8366         struct drm_device *dev = crtc->base.dev;
8367         struct drm_i915_private *dev_priv = to_i915(dev);
8368         enum pipe pipe = crtc->pipe;
8369
8370         m_n->link_m = I915_READ(PCH_TRANS_LINK_M1(pipe));
8371         m_n->link_n = I915_READ(PCH_TRANS_LINK_N1(pipe));
8372         m_n->gmch_m = I915_READ(PCH_TRANS_DATA_M1(pipe))
8373                 & ~TU_SIZE_MASK;
8374         m_n->gmch_n = I915_READ(PCH_TRANS_DATA_N1(pipe));
8375         m_n->tu = ((I915_READ(PCH_TRANS_DATA_M1(pipe))
8376                     & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8377 }
8378
8379 static void intel_cpu_transcoder_get_m_n(struct intel_crtc *crtc,
8380                                          enum transcoder transcoder,
8381                                          struct intel_link_m_n *m_n,
8382                                          struct intel_link_m_n *m2_n2)
8383 {
8384         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
8385         enum pipe pipe = crtc->pipe;
8386
8387         if (INTEL_GEN(dev_priv) >= 5) {
8388                 m_n->link_m = I915_READ(PIPE_LINK_M1(transcoder));
8389                 m_n->link_n = I915_READ(PIPE_LINK_N1(transcoder));
8390                 m_n->gmch_m = I915_READ(PIPE_DATA_M1(transcoder))
8391                         & ~TU_SIZE_MASK;
8392                 m_n->gmch_n = I915_READ(PIPE_DATA_N1(transcoder));
8393                 m_n->tu = ((I915_READ(PIPE_DATA_M1(transcoder))
8394                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8395                 /* Read M2_N2 registers only for gen < 8 (M2_N2 available for
8396                  * gen < 8) and if DRRS is supported (to make sure the
8397                  * registers are not unnecessarily read).
8398                  */
8399                 if (m2_n2 && INTEL_GEN(dev_priv) < 8 &&
8400                         crtc->config->has_drrs) {
8401                         m2_n2->link_m = I915_READ(PIPE_LINK_M2(transcoder));
8402                         m2_n2->link_n = I915_READ(PIPE_LINK_N2(transcoder));
8403                         m2_n2->gmch_m = I915_READ(PIPE_DATA_M2(transcoder))
8404                                         & ~TU_SIZE_MASK;
8405                         m2_n2->gmch_n = I915_READ(PIPE_DATA_N2(transcoder));
8406                         m2_n2->tu = ((I915_READ(PIPE_DATA_M2(transcoder))
8407                                         & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8408                 }
8409         } else {
8410                 m_n->link_m = I915_READ(PIPE_LINK_M_G4X(pipe));
8411                 m_n->link_n = I915_READ(PIPE_LINK_N_G4X(pipe));
8412                 m_n->gmch_m = I915_READ(PIPE_DATA_M_G4X(pipe))
8413                         & ~TU_SIZE_MASK;
8414                 m_n->gmch_n = I915_READ(PIPE_DATA_N_G4X(pipe));
8415                 m_n->tu = ((I915_READ(PIPE_DATA_M_G4X(pipe))
8416                             & TU_SIZE_MASK) >> TU_SIZE_SHIFT) + 1;
8417         }
8418 }
8419
8420 void intel_dp_get_m_n(struct intel_crtc *crtc,
8421                       struct intel_crtc_state *pipe_config)
8422 {
8423         if (pipe_config->has_pch_encoder)
8424                 intel_pch_transcoder_get_m_n(crtc, &pipe_config->dp_m_n);
8425         else
8426                 intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8427                                              &pipe_config->dp_m_n,
8428                                              &pipe_config->dp_m2_n2);
8429 }
8430
8431 static void ironlake_get_fdi_m_n_config(struct intel_crtc *crtc,
8432                                         struct intel_crtc_state *pipe_config)
8433 {
8434         intel_cpu_transcoder_get_m_n(crtc, pipe_config->cpu_transcoder,
8435                                      &pipe_config->fdi_m_n, NULL);
8436 }
8437
8438 static void skylake_get_pfit_config(struct intel_crtc *crtc,
8439                                     struct intel_crtc_state *pipe_config)
8440 {
8441         struct drm_device *dev = crtc->base.dev;
8442         struct drm_i915_private *dev_priv = to_i915(dev);
8443         struct intel_crtc_scaler_state *scaler_state = &pipe_config->scaler_state;
8444         uint32_t ps_ctrl = 0;
8445         int id = -1;
8446         int i;
8447
8448         /* find scaler attached to this pipe */
8449         for (i = 0; i < crtc->num_scalers; i++) {
8450                 ps_ctrl = I915_READ(SKL_PS_CTRL(crtc->pipe, i));
8451                 if (ps_ctrl & PS_SCALER_EN && !(ps_ctrl & PS_PLANE_SEL_MASK)) {
8452                         id = i;
8453                         pipe_config->pch_pfit.enabled = true;
8454                         pipe_config->pch_pfit.pos = I915_READ(SKL_PS_WIN_POS(crtc->pipe, i));
8455                         pipe_config->pch_pfit.size = I915_READ(SKL_PS_WIN_SZ(crtc->pipe, i));
8456                         break;
8457                 }
8458         }
8459
8460         scaler_state->scaler_id = id;
8461         if (id >= 0) {
8462                 scaler_state->scaler_users |= (1 << SKL_CRTC_INDEX);
8463         } else {
8464                 scaler_state->scaler_users &= ~(1 << SKL_CRTC_INDEX);
8465         }
8466 }
8467
8468 static void
8469 skylake_get_initial_plane_config(struct intel_crtc *crtc,
8470                                  struct intel_initial_plane_config *plane_config)
8471 {
8472         struct drm_device *dev = crtc->base.dev;
8473         struct drm_i915_private *dev_priv = to_i915(dev);
8474         struct intel_plane *plane = to_intel_plane(crtc->base.primary);
8475         enum plane_id plane_id = plane->id;
8476         enum pipe pipe = crtc->pipe;
8477         u32 val, base, offset, stride_mult, tiling, alpha;
8478         int fourcc, pixel_format;
8479         unsigned int aligned_height;
8480         struct drm_framebuffer *fb;
8481         struct intel_framebuffer *intel_fb;
8482
8483         if (!plane->get_hw_state(plane))
8484                 return;
8485
8486         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
8487         if (!intel_fb) {
8488                 DRM_DEBUG_KMS("failed to alloc fb\n");
8489                 return;
8490         }
8491
8492         fb = &intel_fb->base;
8493
8494         fb->dev = dev;
8495
8496         val = I915_READ(PLANE_CTL(pipe, plane_id));
8497
8498         pixel_format = val & PLANE_CTL_FORMAT_MASK;
8499
8500         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) {
8501                 alpha = I915_READ(PLANE_COLOR_CTL(pipe, plane_id));
8502                 alpha &= PLANE_COLOR_ALPHA_MASK;
8503         } else {
8504                 alpha = val & PLANE_CTL_ALPHA_MASK;
8505         }
8506
8507         fourcc = skl_format_to_fourcc(pixel_format,
8508                                       val & PLANE_CTL_ORDER_RGBX, alpha);
8509         fb->format = drm_format_info(fourcc);
8510
8511         tiling = val & PLANE_CTL_TILED_MASK;
8512         switch (tiling) {
8513         case PLANE_CTL_TILED_LINEAR:
8514                 fb->modifier = DRM_FORMAT_MOD_LINEAR;
8515                 break;
8516         case PLANE_CTL_TILED_X:
8517                 plane_config->tiling = I915_TILING_X;
8518                 fb->modifier = I915_FORMAT_MOD_X_TILED;
8519                 break;
8520         case PLANE_CTL_TILED_Y:
8521                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8522                         fb->modifier = I915_FORMAT_MOD_Y_TILED_CCS;
8523                 else
8524                         fb->modifier = I915_FORMAT_MOD_Y_TILED;
8525                 break;
8526         case PLANE_CTL_TILED_YF:
8527                 if (val & PLANE_CTL_DECOMPRESSION_ENABLE)
8528                         fb->modifier = I915_FORMAT_MOD_Yf_TILED_CCS;
8529                 else
8530                         fb->modifier = I915_FORMAT_MOD_Yf_TILED;
8531                 break;
8532         default:
8533                 MISSING_CASE(tiling);
8534                 goto error;
8535         }
8536
8537         base = I915_READ(PLANE_SURF(pipe, plane_id)) & 0xfffff000;
8538         plane_config->base = base;
8539
8540         offset = I915_READ(PLANE_OFFSET(pipe, plane_id));
8541
8542         val = I915_READ(PLANE_SIZE(pipe, plane_id));
8543         fb->height = ((val >> 16) & 0xfff) + 1;
8544         fb->width = ((val >> 0) & 0x1fff) + 1;
8545
8546         val = I915_READ(PLANE_STRIDE(pipe, plane_id));
8547         stride_mult = intel_fb_stride_alignment(fb, 0);
8548         fb->pitches[0] = (val & 0x3ff) * stride_mult;
8549
8550         aligned_height = intel_fb_align_height(fb, 0, fb->height);
8551
8552         plane_config->size = fb->pitches[0] * aligned_height;
8553
8554         DRM_DEBUG_KMS("%s/%s with fb: size=%dx%d@%d, offset=%x, pitch %d, size 0x%x\n",
8555                       crtc->base.name, plane->base.name, fb->width, fb->height,
8556                       fb->format->cpp[0] * 8, base, fb->pitches[0],
8557                       plane_config->size);
8558
8559         plane_config->fb = intel_fb;
8560         return;
8561
8562 error:
8563         kfree(intel_fb);
8564 }
8565
8566 static void ironlake_get_pfit_config(struct intel_crtc *crtc,
8567                                      struct intel_crtc_state *pipe_config)
8568 {
8569         struct drm_device *dev = crtc->base.dev;
8570         struct drm_i915_private *dev_priv = to_i915(dev);
8571         uint32_t tmp;
8572
8573         tmp = I915_READ(PF_CTL(crtc->pipe));
8574
8575         if (tmp & PF_ENABLE) {
8576                 pipe_config->pch_pfit.enabled = true;
8577                 pipe_config->pch_pfit.pos = I915_READ(PF_WIN_POS(crtc->pipe));
8578                 pipe_config->pch_pfit.size = I915_READ(PF_WIN_SZ(crtc->pipe));
8579
8580                 /* We currently do not free assignements of panel fitters on
8581                  * ivb/hsw (since we don't use the higher upscaling modes which
8582                  * differentiates them) so just WARN about this case for now. */
8583                 if (IS_GEN7(dev_priv)) {
8584                         WARN_ON((tmp & PF_PIPE_SEL_MASK_IVB) !=
8585                                 PF_PIPE_SEL_IVB(crtc->pipe));
8586                 }
8587         }
8588 }
8589
8590 static bool ironlake_get_pipe_config(struct intel_crtc *crtc,
8591                                      struct intel_crtc_state *pipe_config)
8592 {
8593         struct drm_device *dev = crtc->base.dev;
8594         struct drm_i915_private *dev_priv = to_i915(dev);
8595         enum intel_display_power_domain power_domain;
8596         uint32_t tmp;
8597         bool ret;
8598
8599         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
8600         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
8601                 return false;
8602
8603         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
8604         pipe_config->shared_dpll = NULL;
8605
8606         ret = false;
8607         tmp = I915_READ(PIPECONF(crtc->pipe));
8608         if (!(tmp & PIPECONF_ENABLE))
8609                 goto out;
8610
8611         switch (tmp & PIPECONF_BPC_MASK) {
8612         case PIPECONF_6BPC:
8613                 pipe_config->pipe_bpp = 18;
8614                 break;
8615         case PIPECONF_8BPC:
8616                 pipe_config->pipe_bpp = 24;
8617                 break;
8618         case PIPECONF_10BPC:
8619                 pipe_config->pipe_bpp = 30;
8620                 break;
8621         case PIPECONF_12BPC:
8622                 pipe_config->pipe_bpp = 36;
8623                 break;
8624         default:
8625                 break;
8626         }
8627
8628         if (tmp & PIPECONF_COLOR_RANGE_SELECT)
8629                 pipe_config->limited_color_range = true;
8630
8631         if (I915_READ(PCH_TRANSCONF(crtc->pipe)) & TRANS_ENABLE) {
8632                 struct intel_shared_dpll *pll;
8633                 enum intel_dpll_id pll_id;
8634
8635                 pipe_config->has_pch_encoder = true;
8636
8637                 tmp = I915_READ(FDI_RX_CTL(crtc->pipe));
8638                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
8639                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
8640
8641                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
8642
8643                 if (HAS_PCH_IBX(dev_priv)) {
8644                         /*
8645                          * The pipe->pch transcoder and pch transcoder->pll
8646                          * mapping is fixed.
8647                          */
8648                         pll_id = (enum intel_dpll_id) crtc->pipe;
8649                 } else {
8650                         tmp = I915_READ(PCH_DPLL_SEL);
8651                         if (tmp & TRANS_DPLLB_SEL(crtc->pipe))
8652                                 pll_id = DPLL_ID_PCH_PLL_B;
8653                         else
8654                                 pll_id= DPLL_ID_PCH_PLL_A;
8655                 }
8656
8657                 pipe_config->shared_dpll =
8658                         intel_get_shared_dpll_by_id(dev_priv, pll_id);
8659                 pll = pipe_config->shared_dpll;
8660
8661                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
8662                                                  &pipe_config->dpll_hw_state));
8663
8664                 tmp = pipe_config->dpll_hw_state.dpll;
8665                 pipe_config->pixel_multiplier =
8666                         ((tmp & PLL_REF_SDVO_HDMI_MULTIPLIER_MASK)
8667                          >> PLL_REF_SDVO_HDMI_MULTIPLIER_SHIFT) + 1;
8668
8669                 ironlake_pch_clock_get(crtc, pipe_config);
8670         } else {
8671                 pipe_config->pixel_multiplier = 1;
8672         }
8673
8674         intel_get_pipe_timings(crtc, pipe_config);
8675         intel_get_pipe_src_size(crtc, pipe_config);
8676
8677         ironlake_get_pfit_config(crtc, pipe_config);
8678
8679         ret = true;
8680
8681 out:
8682         intel_display_power_put(dev_priv, power_domain);
8683
8684         return ret;
8685 }
8686
8687 static void assert_can_disable_lcpll(struct drm_i915_private *dev_priv)
8688 {
8689         struct drm_device *dev = &dev_priv->drm;
8690         struct intel_crtc *crtc;
8691
8692         for_each_intel_crtc(dev, crtc)
8693                 I915_STATE_WARN(crtc->active, "CRTC for pipe %c enabled\n",
8694                      pipe_name(crtc->pipe));
8695
8696         I915_STATE_WARN(I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL)),
8697                         "Display power well on\n");
8698         I915_STATE_WARN(I915_READ(SPLL_CTL) & SPLL_PLL_ENABLE, "SPLL enabled\n");
8699         I915_STATE_WARN(I915_READ(WRPLL_CTL(0)) & WRPLL_PLL_ENABLE, "WRPLL1 enabled\n");
8700         I915_STATE_WARN(I915_READ(WRPLL_CTL(1)) & WRPLL_PLL_ENABLE, "WRPLL2 enabled\n");
8701         I915_STATE_WARN(I915_READ(PP_STATUS(0)) & PP_ON, "Panel power on\n");
8702         I915_STATE_WARN(I915_READ(BLC_PWM_CPU_CTL2) & BLM_PWM_ENABLE,
8703              "CPU PWM1 enabled\n");
8704         if (IS_HASWELL(dev_priv))
8705                 I915_STATE_WARN(I915_READ(HSW_BLC_PWM2_CTL) & BLM_PWM_ENABLE,
8706                      "CPU PWM2 enabled\n");
8707         I915_STATE_WARN(I915_READ(BLC_PWM_PCH_CTL1) & BLM_PCH_PWM_ENABLE,
8708              "PCH PWM1 enabled\n");
8709         I915_STATE_WARN(I915_READ(UTIL_PIN_CTL) & UTIL_PIN_ENABLE,
8710              "Utility pin enabled\n");
8711         I915_STATE_WARN(I915_READ(PCH_GTC_CTL) & PCH_GTC_ENABLE, "PCH GTC enabled\n");
8712
8713         /*
8714          * In theory we can still leave IRQs enabled, as long as only the HPD
8715          * interrupts remain enabled. We used to check for that, but since it's
8716          * gen-specific and since we only disable LCPLL after we fully disable
8717          * the interrupts, the check below should be enough.
8718          */
8719         I915_STATE_WARN(intel_irqs_enabled(dev_priv), "IRQs enabled\n");
8720 }
8721
8722 static uint32_t hsw_read_dcomp(struct drm_i915_private *dev_priv)
8723 {
8724         if (IS_HASWELL(dev_priv))
8725                 return I915_READ(D_COMP_HSW);
8726         else
8727                 return I915_READ(D_COMP_BDW);
8728 }
8729
8730 static void hsw_write_dcomp(struct drm_i915_private *dev_priv, uint32_t val)
8731 {
8732         if (IS_HASWELL(dev_priv)) {
8733                 mutex_lock(&dev_priv->pcu_lock);
8734                 if (sandybridge_pcode_write(dev_priv, GEN6_PCODE_WRITE_D_COMP,
8735                                             val))
8736                         DRM_DEBUG_KMS("Failed to write to D_COMP\n");
8737                 mutex_unlock(&dev_priv->pcu_lock);
8738         } else {
8739                 I915_WRITE(D_COMP_BDW, val);
8740                 POSTING_READ(D_COMP_BDW);
8741         }
8742 }
8743
8744 /*
8745  * This function implements pieces of two sequences from BSpec:
8746  * - Sequence for display software to disable LCPLL
8747  * - Sequence for display software to allow package C8+
8748  * The steps implemented here are just the steps that actually touch the LCPLL
8749  * register. Callers should take care of disabling all the display engine
8750  * functions, doing the mode unset, fixing interrupts, etc.
8751  */
8752 static void hsw_disable_lcpll(struct drm_i915_private *dev_priv,
8753                               bool switch_to_fclk, bool allow_power_down)
8754 {
8755         uint32_t val;
8756
8757         assert_can_disable_lcpll(dev_priv);
8758
8759         val = I915_READ(LCPLL_CTL);
8760
8761         if (switch_to_fclk) {
8762                 val |= LCPLL_CD_SOURCE_FCLK;
8763                 I915_WRITE(LCPLL_CTL, val);
8764
8765                 if (wait_for_us(I915_READ(LCPLL_CTL) &
8766                                 LCPLL_CD_SOURCE_FCLK_DONE, 1))
8767                         DRM_ERROR("Switching to FCLK failed\n");
8768
8769                 val = I915_READ(LCPLL_CTL);
8770         }
8771
8772         val |= LCPLL_PLL_DISABLE;
8773         I915_WRITE(LCPLL_CTL, val);
8774         POSTING_READ(LCPLL_CTL);
8775
8776         if (intel_wait_for_register(dev_priv, LCPLL_CTL, LCPLL_PLL_LOCK, 0, 1))
8777                 DRM_ERROR("LCPLL still locked\n");
8778
8779         val = hsw_read_dcomp(dev_priv);
8780         val |= D_COMP_COMP_DISABLE;
8781         hsw_write_dcomp(dev_priv, val);
8782         ndelay(100);
8783
8784         if (wait_for((hsw_read_dcomp(dev_priv) & D_COMP_RCOMP_IN_PROGRESS) == 0,
8785                      1))
8786                 DRM_ERROR("D_COMP RCOMP still in progress\n");
8787
8788         if (allow_power_down) {
8789                 val = I915_READ(LCPLL_CTL);
8790                 val |= LCPLL_POWER_DOWN_ALLOW;
8791                 I915_WRITE(LCPLL_CTL, val);
8792                 POSTING_READ(LCPLL_CTL);
8793         }
8794 }
8795
8796 /*
8797  * Fully restores LCPLL, disallowing power down and switching back to LCPLL
8798  * source.
8799  */
8800 static void hsw_restore_lcpll(struct drm_i915_private *dev_priv)
8801 {
8802         uint32_t val;
8803
8804         val = I915_READ(LCPLL_CTL);
8805
8806         if ((val & (LCPLL_PLL_LOCK | LCPLL_PLL_DISABLE | LCPLL_CD_SOURCE_FCLK |
8807                     LCPLL_POWER_DOWN_ALLOW)) == LCPLL_PLL_LOCK)
8808                 return;
8809
8810         /*
8811          * Make sure we're not on PC8 state before disabling PC8, otherwise
8812          * we'll hang the machine. To prevent PC8 state, just enable force_wake.
8813          */
8814         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
8815
8816         if (val & LCPLL_POWER_DOWN_ALLOW) {
8817                 val &= ~LCPLL_POWER_DOWN_ALLOW;
8818                 I915_WRITE(LCPLL_CTL, val);
8819                 POSTING_READ(LCPLL_CTL);
8820         }
8821
8822         val = hsw_read_dcomp(dev_priv);
8823         val |= D_COMP_COMP_FORCE;
8824         val &= ~D_COMP_COMP_DISABLE;
8825         hsw_write_dcomp(dev_priv, val);
8826
8827         val = I915_READ(LCPLL_CTL);
8828         val &= ~LCPLL_PLL_DISABLE;
8829         I915_WRITE(LCPLL_CTL, val);
8830
8831         if (intel_wait_for_register(dev_priv,
8832                                     LCPLL_CTL, LCPLL_PLL_LOCK, LCPLL_PLL_LOCK,
8833                                     5))
8834                 DRM_ERROR("LCPLL not locked yet\n");
8835
8836         if (val & LCPLL_CD_SOURCE_FCLK) {
8837                 val = I915_READ(LCPLL_CTL);
8838                 val &= ~LCPLL_CD_SOURCE_FCLK;
8839                 I915_WRITE(LCPLL_CTL, val);
8840
8841                 if (wait_for_us((I915_READ(LCPLL_CTL) &
8842                                  LCPLL_CD_SOURCE_FCLK_DONE) == 0, 1))
8843                         DRM_ERROR("Switching back to LCPLL failed\n");
8844         }
8845
8846         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
8847
8848         intel_update_cdclk(dev_priv);
8849         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
8850 }
8851
8852 /*
8853  * Package states C8 and deeper are really deep PC states that can only be
8854  * reached when all the devices on the system allow it, so even if the graphics
8855  * device allows PC8+, it doesn't mean the system will actually get to these
8856  * states. Our driver only allows PC8+ when going into runtime PM.
8857  *
8858  * The requirements for PC8+ are that all the outputs are disabled, the power
8859  * well is disabled and most interrupts are disabled, and these are also
8860  * requirements for runtime PM. When these conditions are met, we manually do
8861  * the other conditions: disable the interrupts, clocks and switch LCPLL refclk
8862  * to Fclk. If we're in PC8+ and we get an non-hotplug interrupt, we can hard
8863  * hang the machine.
8864  *
8865  * When we really reach PC8 or deeper states (not just when we allow it) we lose
8866  * the state of some registers, so when we come back from PC8+ we need to
8867  * restore this state. We don't get into PC8+ if we're not in RC6, so we don't
8868  * need to take care of the registers kept by RC6. Notice that this happens even
8869  * if we don't put the device in PCI D3 state (which is what currently happens
8870  * because of the runtime PM support).
8871  *
8872  * For more, read "Display Sequences for Package C8" on the hardware
8873  * documentation.
8874  */
8875 void hsw_enable_pc8(struct drm_i915_private *dev_priv)
8876 {
8877         uint32_t val;
8878
8879         DRM_DEBUG_KMS("Enabling package C8+\n");
8880
8881         if (HAS_PCH_LPT_LP(dev_priv)) {
8882                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8883                 val &= ~PCH_LP_PARTITION_LEVEL_DISABLE;
8884                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8885         }
8886
8887         lpt_disable_clkout_dp(dev_priv);
8888         hsw_disable_lcpll(dev_priv, true, true);
8889 }
8890
8891 void hsw_disable_pc8(struct drm_i915_private *dev_priv)
8892 {
8893         uint32_t val;
8894
8895         DRM_DEBUG_KMS("Disabling package C8+\n");
8896
8897         hsw_restore_lcpll(dev_priv);
8898         lpt_init_pch_refclk(dev_priv);
8899
8900         if (HAS_PCH_LPT_LP(dev_priv)) {
8901                 val = I915_READ(SOUTH_DSPCLK_GATE_D);
8902                 val |= PCH_LP_PARTITION_LEVEL_DISABLE;
8903                 I915_WRITE(SOUTH_DSPCLK_GATE_D, val);
8904         }
8905 }
8906
8907 static int haswell_crtc_compute_clock(struct intel_crtc *crtc,
8908                                       struct intel_crtc_state *crtc_state)
8909 {
8910         if (!intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DSI)) {
8911                 struct intel_encoder *encoder =
8912                         intel_ddi_get_crtc_new_encoder(crtc_state);
8913
8914                 if (!intel_get_shared_dpll(crtc, crtc_state, encoder)) {
8915                         DRM_DEBUG_DRIVER("failed to find PLL for pipe %c\n",
8916                                          pipe_name(crtc->pipe));
8917                         return -EINVAL;
8918                 }
8919         }
8920
8921         return 0;
8922 }
8923
8924 static void cannonlake_get_ddi_pll(struct drm_i915_private *dev_priv,
8925                                    enum port port,
8926                                    struct intel_crtc_state *pipe_config)
8927 {
8928         enum intel_dpll_id id;
8929         u32 temp;
8930
8931         temp = I915_READ(DPCLKA_CFGCR0) & DPCLKA_CFGCR0_DDI_CLK_SEL_MASK(port);
8932         id = temp >> DPCLKA_CFGCR0_DDI_CLK_SEL_SHIFT(port);
8933
8934         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL2))
8935                 return;
8936
8937         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8938 }
8939
8940 static void bxt_get_ddi_pll(struct drm_i915_private *dev_priv,
8941                                 enum port port,
8942                                 struct intel_crtc_state *pipe_config)
8943 {
8944         enum intel_dpll_id id;
8945
8946         switch (port) {
8947         case PORT_A:
8948                 id = DPLL_ID_SKL_DPLL0;
8949                 break;
8950         case PORT_B:
8951                 id = DPLL_ID_SKL_DPLL1;
8952                 break;
8953         case PORT_C:
8954                 id = DPLL_ID_SKL_DPLL2;
8955                 break;
8956         default:
8957                 DRM_ERROR("Incorrect port type\n");
8958                 return;
8959         }
8960
8961         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8962 }
8963
8964 static void skylake_get_ddi_pll(struct drm_i915_private *dev_priv,
8965                                 enum port port,
8966                                 struct intel_crtc_state *pipe_config)
8967 {
8968         enum intel_dpll_id id;
8969         u32 temp;
8970
8971         temp = I915_READ(DPLL_CTRL2) & DPLL_CTRL2_DDI_CLK_SEL_MASK(port);
8972         id = temp >> (port * 3 + 1);
8973
8974         if (WARN_ON(id < SKL_DPLL0 || id > SKL_DPLL3))
8975                 return;
8976
8977         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
8978 }
8979
8980 static void haswell_get_ddi_pll(struct drm_i915_private *dev_priv,
8981                                 enum port port,
8982                                 struct intel_crtc_state *pipe_config)
8983 {
8984         enum intel_dpll_id id;
8985         uint32_t ddi_pll_sel = I915_READ(PORT_CLK_SEL(port));
8986
8987         switch (ddi_pll_sel) {
8988         case PORT_CLK_SEL_WRPLL1:
8989                 id = DPLL_ID_WRPLL1;
8990                 break;
8991         case PORT_CLK_SEL_WRPLL2:
8992                 id = DPLL_ID_WRPLL2;
8993                 break;
8994         case PORT_CLK_SEL_SPLL:
8995                 id = DPLL_ID_SPLL;
8996                 break;
8997         case PORT_CLK_SEL_LCPLL_810:
8998                 id = DPLL_ID_LCPLL_810;
8999                 break;
9000         case PORT_CLK_SEL_LCPLL_1350:
9001                 id = DPLL_ID_LCPLL_1350;
9002                 break;
9003         case PORT_CLK_SEL_LCPLL_2700:
9004                 id = DPLL_ID_LCPLL_2700;
9005                 break;
9006         default:
9007                 MISSING_CASE(ddi_pll_sel);
9008                 /* fall through */
9009         case PORT_CLK_SEL_NONE:
9010                 return;
9011         }
9012
9013         pipe_config->shared_dpll = intel_get_shared_dpll_by_id(dev_priv, id);
9014 }
9015
9016 static bool hsw_get_transcoder_state(struct intel_crtc *crtc,
9017                                      struct intel_crtc_state *pipe_config,
9018                                      u64 *power_domain_mask)
9019 {
9020         struct drm_device *dev = crtc->base.dev;
9021         struct drm_i915_private *dev_priv = to_i915(dev);
9022         enum intel_display_power_domain power_domain;
9023         u32 tmp;
9024
9025         /*
9026          * The pipe->transcoder mapping is fixed with the exception of the eDP
9027          * transcoder handled below.
9028          */
9029         pipe_config->cpu_transcoder = (enum transcoder) crtc->pipe;
9030
9031         /*
9032          * XXX: Do intel_display_power_get_if_enabled before reading this (for
9033          * consistency and less surprising code; it's in always on power).
9034          */
9035         tmp = I915_READ(TRANS_DDI_FUNC_CTL(TRANSCODER_EDP));
9036         if (tmp & TRANS_DDI_FUNC_ENABLE) {
9037                 enum pipe trans_edp_pipe;
9038                 switch (tmp & TRANS_DDI_EDP_INPUT_MASK) {
9039                 default:
9040                         WARN(1, "unknown pipe linked to edp transcoder\n");
9041                 case TRANS_DDI_EDP_INPUT_A_ONOFF:
9042                 case TRANS_DDI_EDP_INPUT_A_ON:
9043                         trans_edp_pipe = PIPE_A;
9044                         break;
9045                 case TRANS_DDI_EDP_INPUT_B_ONOFF:
9046                         trans_edp_pipe = PIPE_B;
9047                         break;
9048                 case TRANS_DDI_EDP_INPUT_C_ONOFF:
9049                         trans_edp_pipe = PIPE_C;
9050                         break;
9051                 }
9052
9053                 if (trans_edp_pipe == crtc->pipe)
9054                         pipe_config->cpu_transcoder = TRANSCODER_EDP;
9055         }
9056
9057         power_domain = POWER_DOMAIN_TRANSCODER(pipe_config->cpu_transcoder);
9058         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9059                 return false;
9060         *power_domain_mask |= BIT_ULL(power_domain);
9061
9062         tmp = I915_READ(PIPECONF(pipe_config->cpu_transcoder));
9063
9064         return tmp & PIPECONF_ENABLE;
9065 }
9066
9067 static bool bxt_get_dsi_transcoder_state(struct intel_crtc *crtc,
9068                                          struct intel_crtc_state *pipe_config,
9069                                          u64 *power_domain_mask)
9070 {
9071         struct drm_device *dev = crtc->base.dev;
9072         struct drm_i915_private *dev_priv = to_i915(dev);
9073         enum intel_display_power_domain power_domain;
9074         enum port port;
9075         enum transcoder cpu_transcoder;
9076         u32 tmp;
9077
9078         for_each_port_masked(port, BIT(PORT_A) | BIT(PORT_C)) {
9079                 if (port == PORT_A)
9080                         cpu_transcoder = TRANSCODER_DSI_A;
9081                 else
9082                         cpu_transcoder = TRANSCODER_DSI_C;
9083
9084                 power_domain = POWER_DOMAIN_TRANSCODER(cpu_transcoder);
9085                 if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9086                         continue;
9087                 *power_domain_mask |= BIT_ULL(power_domain);
9088
9089                 /*
9090                  * The PLL needs to be enabled with a valid divider
9091                  * configuration, otherwise accessing DSI registers will hang
9092                  * the machine. See BSpec North Display Engine
9093                  * registers/MIPI[BXT]. We can break out here early, since we
9094                  * need the same DSI PLL to be enabled for both DSI ports.
9095                  */
9096                 if (!intel_dsi_pll_is_enabled(dev_priv))
9097                         break;
9098
9099                 /* XXX: this works for video mode only */
9100                 tmp = I915_READ(BXT_MIPI_PORT_CTRL(port));
9101                 if (!(tmp & DPI_ENABLE))
9102                         continue;
9103
9104                 tmp = I915_READ(MIPI_CTRL(port));
9105                 if ((tmp & BXT_PIPE_SELECT_MASK) != BXT_PIPE_SELECT(crtc->pipe))
9106                         continue;
9107
9108                 pipe_config->cpu_transcoder = cpu_transcoder;
9109                 break;
9110         }
9111
9112         return transcoder_is_dsi(pipe_config->cpu_transcoder);
9113 }
9114
9115 static void haswell_get_ddi_port_state(struct intel_crtc *crtc,
9116                                        struct intel_crtc_state *pipe_config)
9117 {
9118         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9119         struct intel_shared_dpll *pll;
9120         enum port port;
9121         uint32_t tmp;
9122
9123         tmp = I915_READ(TRANS_DDI_FUNC_CTL(pipe_config->cpu_transcoder));
9124
9125         port = (tmp & TRANS_DDI_PORT_MASK) >> TRANS_DDI_PORT_SHIFT;
9126
9127         if (IS_CANNONLAKE(dev_priv))
9128                 cannonlake_get_ddi_pll(dev_priv, port, pipe_config);
9129         else if (IS_GEN9_BC(dev_priv))
9130                 skylake_get_ddi_pll(dev_priv, port, pipe_config);
9131         else if (IS_GEN9_LP(dev_priv))
9132                 bxt_get_ddi_pll(dev_priv, port, pipe_config);
9133         else
9134                 haswell_get_ddi_pll(dev_priv, port, pipe_config);
9135
9136         pll = pipe_config->shared_dpll;
9137         if (pll) {
9138                 WARN_ON(!pll->funcs.get_hw_state(dev_priv, pll,
9139                                                  &pipe_config->dpll_hw_state));
9140         }
9141
9142         /*
9143          * Haswell has only FDI/PCH transcoder A. It is which is connected to
9144          * DDI E. So just check whether this pipe is wired to DDI E and whether
9145          * the PCH transcoder is on.
9146          */
9147         if (INTEL_GEN(dev_priv) < 9 &&
9148             (port == PORT_E) && I915_READ(LPT_TRANSCONF) & TRANS_ENABLE) {
9149                 pipe_config->has_pch_encoder = true;
9150
9151                 tmp = I915_READ(FDI_RX_CTL(PIPE_A));
9152                 pipe_config->fdi_lanes = ((FDI_DP_PORT_WIDTH_MASK & tmp) >>
9153                                           FDI_DP_PORT_WIDTH_SHIFT) + 1;
9154
9155                 ironlake_get_fdi_m_n_config(crtc, pipe_config);
9156         }
9157 }
9158
9159 static bool haswell_get_pipe_config(struct intel_crtc *crtc,
9160                                     struct intel_crtc_state *pipe_config)
9161 {
9162         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
9163         enum intel_display_power_domain power_domain;
9164         u64 power_domain_mask;
9165         bool active;
9166
9167         intel_crtc_init_scalers(crtc, pipe_config);
9168
9169         power_domain = POWER_DOMAIN_PIPE(crtc->pipe);
9170         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9171                 return false;
9172         power_domain_mask = BIT_ULL(power_domain);
9173
9174         pipe_config->shared_dpll = NULL;
9175
9176         active = hsw_get_transcoder_state(crtc, pipe_config, &power_domain_mask);
9177
9178         if (IS_GEN9_LP(dev_priv) &&
9179             bxt_get_dsi_transcoder_state(crtc, pipe_config, &power_domain_mask)) {
9180                 WARN_ON(active);
9181                 active = true;
9182         }
9183
9184         if (!active)
9185                 goto out;
9186
9187         if (!transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9188                 haswell_get_ddi_port_state(crtc, pipe_config);
9189                 intel_get_pipe_timings(crtc, pipe_config);
9190         }
9191
9192         intel_get_pipe_src_size(crtc, pipe_config);
9193
9194         pipe_config->gamma_mode =
9195                 I915_READ(GAMMA_MODE(crtc->pipe)) & GAMMA_MODE_MODE_MASK;
9196
9197         if (IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9) {
9198                 u32 tmp = I915_READ(PIPEMISC(crtc->pipe));
9199                 bool clrspace_yuv = tmp & PIPEMISC_OUTPUT_COLORSPACE_YUV;
9200
9201                 if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10) {
9202                         bool blend_mode_420 = tmp &
9203                                               PIPEMISC_YUV420_MODE_FULL_BLEND;
9204
9205                         pipe_config->ycbcr420 = tmp & PIPEMISC_YUV420_ENABLE;
9206                         if (pipe_config->ycbcr420 != clrspace_yuv ||
9207                             pipe_config->ycbcr420 != blend_mode_420)
9208                                 DRM_DEBUG_KMS("Bad 4:2:0 mode (%08x)\n", tmp);
9209                 } else if (clrspace_yuv) {
9210                         DRM_DEBUG_KMS("YCbCr 4:2:0 Unsupported\n");
9211                 }
9212         }
9213
9214         power_domain = POWER_DOMAIN_PIPE_PANEL_FITTER(crtc->pipe);
9215         if (intel_display_power_get_if_enabled(dev_priv, power_domain)) {
9216                 power_domain_mask |= BIT_ULL(power_domain);
9217                 if (INTEL_GEN(dev_priv) >= 9)
9218                         skylake_get_pfit_config(crtc, pipe_config);
9219                 else
9220                         ironlake_get_pfit_config(crtc, pipe_config);
9221         }
9222
9223         if (hsw_crtc_supports_ips(crtc)) {
9224                 if (IS_HASWELL(dev_priv))
9225                         pipe_config->ips_enabled = I915_READ(IPS_CTL) & IPS_ENABLE;
9226                 else {
9227                         /*
9228                          * We cannot readout IPS state on broadwell, set to
9229                          * true so we can set it to a defined state on first
9230                          * commit.
9231                          */
9232                         pipe_config->ips_enabled = true;
9233                 }
9234         }
9235
9236         if (pipe_config->cpu_transcoder != TRANSCODER_EDP &&
9237             !transcoder_is_dsi(pipe_config->cpu_transcoder)) {
9238                 pipe_config->pixel_multiplier =
9239                         I915_READ(PIPE_MULT(pipe_config->cpu_transcoder)) + 1;
9240         } else {
9241                 pipe_config->pixel_multiplier = 1;
9242         }
9243
9244 out:
9245         for_each_power_domain(power_domain, power_domain_mask)
9246                 intel_display_power_put(dev_priv, power_domain);
9247
9248         return active;
9249 }
9250
9251 static u32 intel_cursor_base(const struct intel_plane_state *plane_state)
9252 {
9253         struct drm_i915_private *dev_priv =
9254                 to_i915(plane_state->base.plane->dev);
9255         const struct drm_framebuffer *fb = plane_state->base.fb;
9256         const struct drm_i915_gem_object *obj = intel_fb_obj(fb);
9257         u32 base;
9258
9259         if (INTEL_INFO(dev_priv)->cursor_needs_physical)
9260                 base = obj->phys_handle->busaddr;
9261         else
9262                 base = intel_plane_ggtt_offset(plane_state);
9263
9264         base += plane_state->main.offset;
9265
9266         /* ILK+ do this automagically */
9267         if (HAS_GMCH_DISPLAY(dev_priv) &&
9268             plane_state->base.rotation & DRM_MODE_ROTATE_180)
9269                 base += (plane_state->base.crtc_h *
9270                          plane_state->base.crtc_w - 1) * fb->format->cpp[0];
9271
9272         return base;
9273 }
9274
9275 static u32 intel_cursor_position(const struct intel_plane_state *plane_state)
9276 {
9277         int x = plane_state->base.crtc_x;
9278         int y = plane_state->base.crtc_y;
9279         u32 pos = 0;
9280
9281         if (x < 0) {
9282                 pos |= CURSOR_POS_SIGN << CURSOR_X_SHIFT;
9283                 x = -x;
9284         }
9285         pos |= x << CURSOR_X_SHIFT;
9286
9287         if (y < 0) {
9288                 pos |= CURSOR_POS_SIGN << CURSOR_Y_SHIFT;
9289                 y = -y;
9290         }
9291         pos |= y << CURSOR_Y_SHIFT;
9292
9293         return pos;
9294 }
9295
9296 static bool intel_cursor_size_ok(const struct intel_plane_state *plane_state)
9297 {
9298         const struct drm_mode_config *config =
9299                 &plane_state->base.plane->dev->mode_config;
9300         int width = plane_state->base.crtc_w;
9301         int height = plane_state->base.crtc_h;
9302
9303         return width > 0 && width <= config->cursor_width &&
9304                 height > 0 && height <= config->cursor_height;
9305 }
9306
9307 static int intel_check_cursor(struct intel_crtc_state *crtc_state,
9308                               struct intel_plane_state *plane_state)
9309 {
9310         const struct drm_framebuffer *fb = plane_state->base.fb;
9311         int src_x, src_y;
9312         u32 offset;
9313         int ret;
9314
9315         ret = drm_atomic_helper_check_plane_state(&plane_state->base,
9316                                                   &crtc_state->base,
9317                                                   &plane_state->clip,
9318                                                   DRM_PLANE_HELPER_NO_SCALING,
9319                                                   DRM_PLANE_HELPER_NO_SCALING,
9320                                                   true, true);
9321         if (ret)
9322                 return ret;
9323
9324         if (!fb)
9325                 return 0;
9326
9327         if (fb->modifier != DRM_FORMAT_MOD_LINEAR) {
9328                 DRM_DEBUG_KMS("cursor cannot be tiled\n");
9329                 return -EINVAL;
9330         }
9331
9332         src_x = plane_state->base.src_x >> 16;
9333         src_y = plane_state->base.src_y >> 16;
9334
9335         intel_add_fb_offsets(&src_x, &src_y, plane_state, 0);
9336         offset = intel_compute_tile_offset(&src_x, &src_y, plane_state, 0);
9337
9338         if (src_x != 0 || src_y != 0) {
9339                 DRM_DEBUG_KMS("Arbitrary cursor panning not supported\n");
9340                 return -EINVAL;
9341         }
9342
9343         plane_state->main.offset = offset;
9344
9345         return 0;
9346 }
9347
9348 static u32 i845_cursor_ctl(const struct intel_crtc_state *crtc_state,
9349                            const struct intel_plane_state *plane_state)
9350 {
9351         const struct drm_framebuffer *fb = plane_state->base.fb;
9352
9353         return CURSOR_ENABLE |
9354                 CURSOR_GAMMA_ENABLE |
9355                 CURSOR_FORMAT_ARGB |
9356                 CURSOR_STRIDE(fb->pitches[0]);
9357 }
9358
9359 static bool i845_cursor_size_ok(const struct intel_plane_state *plane_state)
9360 {
9361         int width = plane_state->base.crtc_w;
9362
9363         /*
9364          * 845g/865g are only limited by the width of their cursors,
9365          * the height is arbitrary up to the precision of the register.
9366          */
9367         return intel_cursor_size_ok(plane_state) && IS_ALIGNED(width, 64);
9368 }
9369
9370 static int i845_check_cursor(struct intel_plane *plane,
9371                              struct intel_crtc_state *crtc_state,
9372                              struct intel_plane_state *plane_state)
9373 {
9374         const struct drm_framebuffer *fb = plane_state->base.fb;
9375         int ret;
9376
9377         ret = intel_check_cursor(crtc_state, plane_state);
9378         if (ret)
9379                 return ret;
9380
9381         /* if we want to turn off the cursor ignore width and height */
9382         if (!fb)
9383                 return 0;
9384
9385         /* Check for which cursor types we support */
9386         if (!i845_cursor_size_ok(plane_state)) {
9387                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9388                           plane_state->base.crtc_w,
9389                           plane_state->base.crtc_h);
9390                 return -EINVAL;
9391         }
9392
9393         switch (fb->pitches[0]) {
9394         case 256:
9395         case 512:
9396         case 1024:
9397         case 2048:
9398                 break;
9399         default:
9400                 DRM_DEBUG_KMS("Invalid cursor stride (%u)\n",
9401                               fb->pitches[0]);
9402                 return -EINVAL;
9403         }
9404
9405         plane_state->ctl = i845_cursor_ctl(crtc_state, plane_state);
9406
9407         return 0;
9408 }
9409
9410 static void i845_update_cursor(struct intel_plane *plane,
9411                                const struct intel_crtc_state *crtc_state,
9412                                const struct intel_plane_state *plane_state)
9413 {
9414         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9415         u32 cntl = 0, base = 0, pos = 0, size = 0;
9416         unsigned long irqflags;
9417
9418         if (plane_state && plane_state->base.visible) {
9419                 unsigned int width = plane_state->base.crtc_w;
9420                 unsigned int height = plane_state->base.crtc_h;
9421
9422                 cntl = plane_state->ctl;
9423                 size = (height << 12) | width;
9424
9425                 base = intel_cursor_base(plane_state);
9426                 pos = intel_cursor_position(plane_state);
9427         }
9428
9429         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9430
9431         /* On these chipsets we can only modify the base/size/stride
9432          * whilst the cursor is disabled.
9433          */
9434         if (plane->cursor.base != base ||
9435             plane->cursor.size != size ||
9436             plane->cursor.cntl != cntl) {
9437                 I915_WRITE_FW(CURCNTR(PIPE_A), 0);
9438                 I915_WRITE_FW(CURBASE(PIPE_A), base);
9439                 I915_WRITE_FW(CURSIZE, size);
9440                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9441                 I915_WRITE_FW(CURCNTR(PIPE_A), cntl);
9442
9443                 plane->cursor.base = base;
9444                 plane->cursor.size = size;
9445                 plane->cursor.cntl = cntl;
9446         } else {
9447                 I915_WRITE_FW(CURPOS(PIPE_A), pos);
9448         }
9449
9450         POSTING_READ_FW(CURCNTR(PIPE_A));
9451
9452         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9453 }
9454
9455 static void i845_disable_cursor(struct intel_plane *plane,
9456                                 struct intel_crtc *crtc)
9457 {
9458         i845_update_cursor(plane, NULL, NULL);
9459 }
9460
9461 static bool i845_cursor_get_hw_state(struct intel_plane *plane)
9462 {
9463         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9464         enum intel_display_power_domain power_domain;
9465         bool ret;
9466
9467         power_domain = POWER_DOMAIN_PIPE(PIPE_A);
9468         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9469                 return false;
9470
9471         ret = I915_READ(CURCNTR(PIPE_A)) & CURSOR_ENABLE;
9472
9473         intel_display_power_put(dev_priv, power_domain);
9474
9475         return ret;
9476 }
9477
9478 static u32 i9xx_cursor_ctl(const struct intel_crtc_state *crtc_state,
9479                            const struct intel_plane_state *plane_state)
9480 {
9481         struct drm_i915_private *dev_priv =
9482                 to_i915(plane_state->base.plane->dev);
9483         struct intel_crtc *crtc = to_intel_crtc(crtc_state->base.crtc);
9484         u32 cntl;
9485
9486         cntl = MCURSOR_GAMMA_ENABLE;
9487
9488         if (HAS_DDI(dev_priv))
9489                 cntl |= CURSOR_PIPE_CSC_ENABLE;
9490
9491         cntl |= MCURSOR_PIPE_SELECT(crtc->pipe);
9492
9493         switch (plane_state->base.crtc_w) {
9494         case 64:
9495                 cntl |= CURSOR_MODE_64_ARGB_AX;
9496                 break;
9497         case 128:
9498                 cntl |= CURSOR_MODE_128_ARGB_AX;
9499                 break;
9500         case 256:
9501                 cntl |= CURSOR_MODE_256_ARGB_AX;
9502                 break;
9503         default:
9504                 MISSING_CASE(plane_state->base.crtc_w);
9505                 return 0;
9506         }
9507
9508         if (plane_state->base.rotation & DRM_MODE_ROTATE_180)
9509                 cntl |= CURSOR_ROTATE_180;
9510
9511         return cntl;
9512 }
9513
9514 static bool i9xx_cursor_size_ok(const struct intel_plane_state *plane_state)
9515 {
9516         struct drm_i915_private *dev_priv =
9517                 to_i915(plane_state->base.plane->dev);
9518         int width = plane_state->base.crtc_w;
9519         int height = plane_state->base.crtc_h;
9520
9521         if (!intel_cursor_size_ok(plane_state))
9522                 return false;
9523
9524         /* Cursor width is limited to a few power-of-two sizes */
9525         switch (width) {
9526         case 256:
9527         case 128:
9528         case 64:
9529                 break;
9530         default:
9531                 return false;
9532         }
9533
9534         /*
9535          * IVB+ have CUR_FBC_CTL which allows an arbitrary cursor
9536          * height from 8 lines up to the cursor width, when the
9537          * cursor is not rotated. Everything else requires square
9538          * cursors.
9539          */
9540         if (HAS_CUR_FBC(dev_priv) &&
9541             plane_state->base.rotation & DRM_MODE_ROTATE_0) {
9542                 if (height < 8 || height > width)
9543                         return false;
9544         } else {
9545                 if (height != width)
9546                         return false;
9547         }
9548
9549         return true;
9550 }
9551
9552 static int i9xx_check_cursor(struct intel_plane *plane,
9553                              struct intel_crtc_state *crtc_state,
9554                              struct intel_plane_state *plane_state)
9555 {
9556         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9557         const struct drm_framebuffer *fb = plane_state->base.fb;
9558         enum pipe pipe = plane->pipe;
9559         int ret;
9560
9561         ret = intel_check_cursor(crtc_state, plane_state);
9562         if (ret)
9563                 return ret;
9564
9565         /* if we want to turn off the cursor ignore width and height */
9566         if (!fb)
9567                 return 0;
9568
9569         /* Check for which cursor types we support */
9570         if (!i9xx_cursor_size_ok(plane_state)) {
9571                 DRM_DEBUG("Cursor dimension %dx%d not supported\n",
9572                           plane_state->base.crtc_w,
9573                           plane_state->base.crtc_h);
9574                 return -EINVAL;
9575         }
9576
9577         if (fb->pitches[0] != plane_state->base.crtc_w * fb->format->cpp[0]) {
9578                 DRM_DEBUG_KMS("Invalid cursor stride (%u) (cursor width %d)\n",
9579                               fb->pitches[0], plane_state->base.crtc_w);
9580                 return -EINVAL;
9581         }
9582
9583         /*
9584          * There's something wrong with the cursor on CHV pipe C.
9585          * If it straddles the left edge of the screen then
9586          * moving it away from the edge or disabling it often
9587          * results in a pipe underrun, and often that can lead to
9588          * dead pipe (constant underrun reported, and it scans
9589          * out just a solid color). To recover from that, the
9590          * display power well must be turned off and on again.
9591          * Refuse the put the cursor into that compromised position.
9592          */
9593         if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_C &&
9594             plane_state->base.visible && plane_state->base.crtc_x < 0) {
9595                 DRM_DEBUG_KMS("CHV cursor C not allowed to straddle the left screen edge\n");
9596                 return -EINVAL;
9597         }
9598
9599         plane_state->ctl = i9xx_cursor_ctl(crtc_state, plane_state);
9600
9601         return 0;
9602 }
9603
9604 static void i9xx_update_cursor(struct intel_plane *plane,
9605                                const struct intel_crtc_state *crtc_state,
9606                                const struct intel_plane_state *plane_state)
9607 {
9608         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9609         enum pipe pipe = plane->pipe;
9610         u32 cntl = 0, base = 0, pos = 0, fbc_ctl = 0;
9611         unsigned long irqflags;
9612
9613         if (plane_state && plane_state->base.visible) {
9614                 cntl = plane_state->ctl;
9615
9616                 if (plane_state->base.crtc_h != plane_state->base.crtc_w)
9617                         fbc_ctl = CUR_FBC_CTL_EN | (plane_state->base.crtc_h - 1);
9618
9619                 base = intel_cursor_base(plane_state);
9620                 pos = intel_cursor_position(plane_state);
9621         }
9622
9623         spin_lock_irqsave(&dev_priv->uncore.lock, irqflags);
9624
9625         /*
9626          * On some platforms writing CURCNTR first will also
9627          * cause CURPOS to be armed by the CURBASE write.
9628          * Without the CURCNTR write the CURPOS write would
9629          * arm itself. Thus we always start the full update
9630          * with a CURCNTR write.
9631          *
9632          * On other platforms CURPOS always requires the
9633          * CURBASE write to arm the update. Additonally
9634          * a write to any of the cursor register will cancel
9635          * an already armed cursor update. Thus leaving out
9636          * the CURBASE write after CURPOS could lead to a
9637          * cursor that doesn't appear to move, or even change
9638          * shape. Thus we always write CURBASE.
9639          *
9640          * CURCNTR and CUR_FBC_CTL are always
9641          * armed by the CURBASE write only.
9642          */
9643         if (plane->cursor.base != base ||
9644             plane->cursor.size != fbc_ctl ||
9645             plane->cursor.cntl != cntl) {
9646                 I915_WRITE_FW(CURCNTR(pipe), cntl);
9647                 if (HAS_CUR_FBC(dev_priv))
9648                         I915_WRITE_FW(CUR_FBC_CTL(pipe), fbc_ctl);
9649                 I915_WRITE_FW(CURPOS(pipe), pos);
9650                 I915_WRITE_FW(CURBASE(pipe), base);
9651
9652                 plane->cursor.base = base;
9653                 plane->cursor.size = fbc_ctl;
9654                 plane->cursor.cntl = cntl;
9655         } else {
9656                 I915_WRITE_FW(CURPOS(pipe), pos);
9657                 I915_WRITE_FW(CURBASE(pipe), base);
9658         }
9659
9660         POSTING_READ_FW(CURBASE(pipe));
9661
9662         spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags);
9663 }
9664
9665 static void i9xx_disable_cursor(struct intel_plane *plane,
9666                                 struct intel_crtc *crtc)
9667 {
9668         i9xx_update_cursor(plane, NULL, NULL);
9669 }
9670
9671 static bool i9xx_cursor_get_hw_state(struct intel_plane *plane)
9672 {
9673         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
9674         enum intel_display_power_domain power_domain;
9675         enum pipe pipe = plane->pipe;
9676         bool ret;
9677
9678         /*
9679          * Not 100% correct for planes that can move between pipes,
9680          * but that's only the case for gen2-3 which don't have any
9681          * display power wells.
9682          */
9683         power_domain = POWER_DOMAIN_PIPE(pipe);
9684         if (!intel_display_power_get_if_enabled(dev_priv, power_domain))
9685                 return false;
9686
9687         ret = I915_READ(CURCNTR(pipe)) & CURSOR_MODE;
9688
9689         intel_display_power_put(dev_priv, power_domain);
9690
9691         return ret;
9692 }
9693
9694 /* VESA 640x480x72Hz mode to set on the pipe */
9695 static const struct drm_display_mode load_detect_mode = {
9696         DRM_MODE("640x480", DRM_MODE_TYPE_DEFAULT, 31500, 640, 664,
9697                  704, 832, 0, 480, 489, 491, 520, 0, DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC),
9698 };
9699
9700 struct drm_framebuffer *
9701 intel_framebuffer_create(struct drm_i915_gem_object *obj,
9702                          struct drm_mode_fb_cmd2 *mode_cmd)
9703 {
9704         struct intel_framebuffer *intel_fb;
9705         int ret;
9706
9707         intel_fb = kzalloc(sizeof(*intel_fb), GFP_KERNEL);
9708         if (!intel_fb)
9709                 return ERR_PTR(-ENOMEM);
9710
9711         ret = intel_framebuffer_init(intel_fb, obj, mode_cmd);
9712         if (ret)
9713                 goto err;
9714
9715         return &intel_fb->base;
9716
9717 err:
9718         kfree(intel_fb);
9719         return ERR_PTR(ret);
9720 }
9721
9722 static int intel_modeset_disable_planes(struct drm_atomic_state *state,
9723                                         struct drm_crtc *crtc)
9724 {
9725         struct drm_plane *plane;
9726         struct drm_plane_state *plane_state;
9727         int ret, i;
9728
9729         ret = drm_atomic_add_affected_planes(state, crtc);
9730         if (ret)
9731                 return ret;
9732
9733         for_each_new_plane_in_state(state, plane, plane_state, i) {
9734                 if (plane_state->crtc != crtc)
9735                         continue;
9736
9737                 ret = drm_atomic_set_crtc_for_plane(plane_state, NULL);
9738                 if (ret)
9739                         return ret;
9740
9741                 drm_atomic_set_fb_for_plane(plane_state, NULL);
9742         }
9743
9744         return 0;
9745 }
9746
9747 int intel_get_load_detect_pipe(struct drm_connector *connector,
9748                                const struct drm_display_mode *mode,
9749                                struct intel_load_detect_pipe *old,
9750                                struct drm_modeset_acquire_ctx *ctx)
9751 {
9752         struct intel_crtc *intel_crtc;
9753         struct intel_encoder *intel_encoder =
9754                 intel_attached_encoder(connector);
9755         struct drm_crtc *possible_crtc;
9756         struct drm_encoder *encoder = &intel_encoder->base;
9757         struct drm_crtc *crtc = NULL;
9758         struct drm_device *dev = encoder->dev;
9759         struct drm_i915_private *dev_priv = to_i915(dev);
9760         struct drm_mode_config *config = &dev->mode_config;
9761         struct drm_atomic_state *state = NULL, *restore_state = NULL;
9762         struct drm_connector_state *connector_state;
9763         struct intel_crtc_state *crtc_state;
9764         int ret, i = -1;
9765
9766         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9767                       connector->base.id, connector->name,
9768                       encoder->base.id, encoder->name);
9769
9770         old->restore_state = NULL;
9771
9772         WARN_ON(!drm_modeset_is_locked(&config->connection_mutex));
9773
9774         /*
9775          * Algorithm gets a little messy:
9776          *
9777          *   - if the connector already has an assigned crtc, use it (but make
9778          *     sure it's on first)
9779          *
9780          *   - try to find the first unused crtc that can drive this connector,
9781          *     and use that if we find one
9782          */
9783
9784         /* See if we already have a CRTC for this connector */
9785         if (connector->state->crtc) {
9786                 crtc = connector->state->crtc;
9787
9788                 ret = drm_modeset_lock(&crtc->mutex, ctx);
9789                 if (ret)
9790                         goto fail;
9791
9792                 /* Make sure the crtc and connector are running */
9793                 goto found;
9794         }
9795
9796         /* Find an unused one (if possible) */
9797         for_each_crtc(dev, possible_crtc) {
9798                 i++;
9799                 if (!(encoder->possible_crtcs & (1 << i)))
9800                         continue;
9801
9802                 ret = drm_modeset_lock(&possible_crtc->mutex, ctx);
9803                 if (ret)
9804                         goto fail;
9805
9806                 if (possible_crtc->state->enable) {
9807                         drm_modeset_unlock(&possible_crtc->mutex);
9808                         continue;
9809                 }
9810
9811                 crtc = possible_crtc;
9812                 break;
9813         }
9814
9815         /*
9816          * If we didn't find an unused CRTC, don't use any.
9817          */
9818         if (!crtc) {
9819                 DRM_DEBUG_KMS("no pipe available for load-detect\n");
9820                 ret = -ENODEV;
9821                 goto fail;
9822         }
9823
9824 found:
9825         intel_crtc = to_intel_crtc(crtc);
9826
9827         state = drm_atomic_state_alloc(dev);
9828         restore_state = drm_atomic_state_alloc(dev);
9829         if (!state || !restore_state) {
9830                 ret = -ENOMEM;
9831                 goto fail;
9832         }
9833
9834         state->acquire_ctx = ctx;
9835         restore_state->acquire_ctx = ctx;
9836
9837         connector_state = drm_atomic_get_connector_state(state, connector);
9838         if (IS_ERR(connector_state)) {
9839                 ret = PTR_ERR(connector_state);
9840                 goto fail;
9841         }
9842
9843         ret = drm_atomic_set_crtc_for_connector(connector_state, crtc);
9844         if (ret)
9845                 goto fail;
9846
9847         crtc_state = intel_atomic_get_crtc_state(state, intel_crtc);
9848         if (IS_ERR(crtc_state)) {
9849                 ret = PTR_ERR(crtc_state);
9850                 goto fail;
9851         }
9852
9853         crtc_state->base.active = crtc_state->base.enable = true;
9854
9855         if (!mode)
9856                 mode = &load_detect_mode;
9857
9858         ret = drm_atomic_set_mode_for_crtc(&crtc_state->base, mode);
9859         if (ret)
9860                 goto fail;
9861
9862         ret = intel_modeset_disable_planes(state, crtc);
9863         if (ret)
9864                 goto fail;
9865
9866         ret = PTR_ERR_OR_ZERO(drm_atomic_get_connector_state(restore_state, connector));
9867         if (!ret)
9868                 ret = PTR_ERR_OR_ZERO(drm_atomic_get_crtc_state(restore_state, crtc));
9869         if (ret) {
9870                 DRM_DEBUG_KMS("Failed to create a copy of old state to restore: %i\n", ret);
9871                 goto fail;
9872         }
9873
9874         ret = drm_atomic_commit(state);
9875         if (ret) {
9876                 DRM_DEBUG_KMS("failed to set mode on load-detect pipe\n");
9877                 goto fail;
9878         }
9879
9880         old->restore_state = restore_state;
9881         drm_atomic_state_put(state);
9882
9883         /* let the connector get through one full cycle before testing */
9884         intel_wait_for_vblank(dev_priv, intel_crtc->pipe);
9885         return true;
9886
9887 fail:
9888         if (state) {
9889                 drm_atomic_state_put(state);
9890                 state = NULL;
9891         }
9892         if (restore_state) {
9893                 drm_atomic_state_put(restore_state);
9894                 restore_state = NULL;
9895         }
9896
9897         if (ret == -EDEADLK)
9898                 return ret;
9899
9900         return false;
9901 }
9902
9903 void intel_release_load_detect_pipe(struct drm_connector *connector,
9904                                     struct intel_load_detect_pipe *old,
9905                                     struct drm_modeset_acquire_ctx *ctx)
9906 {
9907         struct intel_encoder *intel_encoder =
9908                 intel_attached_encoder(connector);
9909         struct drm_encoder *encoder = &intel_encoder->base;
9910         struct drm_atomic_state *state = old->restore_state;
9911         int ret;
9912
9913         DRM_DEBUG_KMS("[CONNECTOR:%d:%s], [ENCODER:%d:%s]\n",
9914                       connector->base.id, connector->name,
9915                       encoder->base.id, encoder->name);
9916
9917         if (!state)
9918                 return;
9919
9920         ret = drm_atomic_helper_commit_duplicated_state(state, ctx);
9921         if (ret)
9922                 DRM_DEBUG_KMS("Couldn't release load detect pipe: %i\n", ret);
9923         drm_atomic_state_put(state);
9924 }
9925
9926 static int i9xx_pll_refclk(struct drm_device *dev,
9927                            const struct intel_crtc_state *pipe_config)
9928 {
9929         struct drm_i915_private *dev_priv = to_i915(dev);
9930         u32 dpll = pipe_config->dpll_hw_state.dpll;
9931
9932         if ((dpll & PLL_REF_INPUT_MASK) == PLLB_REF_INPUT_SPREADSPECTRUMIN)
9933                 return dev_priv->vbt.lvds_ssc_freq;
9934         else if (HAS_PCH_SPLIT(dev_priv))
9935                 return 120000;
9936         else if (!IS_GEN2(dev_priv))
9937                 return 96000;
9938         else
9939                 return 48000;
9940 }
9941
9942 /* Returns the clock of the currently programmed mode of the given pipe. */
9943 static void i9xx_crtc_clock_get(struct intel_crtc *crtc,
9944                                 struct intel_crtc_state *pipe_config)
9945 {
9946         struct drm_device *dev = crtc->base.dev;
9947         struct drm_i915_private *dev_priv = to_i915(dev);
9948         int pipe = pipe_config->cpu_transcoder;
9949         u32 dpll = pipe_config->dpll_hw_state.dpll;
9950         u32 fp;
9951         struct dpll clock;
9952         int port_clock;
9953         int refclk = i9xx_pll_refclk(dev, pipe_config);
9954
9955         if ((dpll & DISPLAY_RATE_SELECT_FPA1) == 0)
9956                 fp = pipe_config->dpll_hw_state.fp0;
9957         else
9958                 fp = pipe_config->dpll_hw_state.fp1;
9959
9960         clock.m1 = (fp & FP_M1_DIV_MASK) >> FP_M1_DIV_SHIFT;
9961         if (IS_PINEVIEW(dev_priv)) {
9962                 clock.n = ffs((fp & FP_N_PINEVIEW_DIV_MASK) >> FP_N_DIV_SHIFT) - 1;
9963                 clock.m2 = (fp & FP_M2_PINEVIEW_DIV_MASK) >> FP_M2_DIV_SHIFT;
9964         } else {
9965                 clock.n = (fp & FP_N_DIV_MASK) >> FP_N_DIV_SHIFT;
9966                 clock.m2 = (fp & FP_M2_DIV_MASK) >> FP_M2_DIV_SHIFT;
9967         }
9968
9969         if (!IS_GEN2(dev_priv)) {
9970                 if (IS_PINEVIEW(dev_priv))
9971                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_PINEVIEW) >>
9972                                 DPLL_FPA01_P1_POST_DIV_SHIFT_PINEVIEW);
9973                 else
9974                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK) >>
9975                                DPLL_FPA01_P1_POST_DIV_SHIFT);
9976
9977                 switch (dpll & DPLL_MODE_MASK) {
9978                 case DPLLB_MODE_DAC_SERIAL:
9979                         clock.p2 = dpll & DPLL_DAC_SERIAL_P2_CLOCK_DIV_5 ?
9980                                 5 : 10;
9981                         break;
9982                 case DPLLB_MODE_LVDS:
9983                         clock.p2 = dpll & DPLLB_LVDS_P2_CLOCK_DIV_7 ?
9984                                 7 : 14;
9985                         break;
9986                 default:
9987                         DRM_DEBUG_KMS("Unknown DPLL mode %08x in programmed "
9988                                   "mode\n", (int)(dpll & DPLL_MODE_MASK));
9989                         return;
9990                 }
9991
9992                 if (IS_PINEVIEW(dev_priv))
9993                         port_clock = pnv_calc_dpll_params(refclk, &clock);
9994                 else
9995                         port_clock = i9xx_calc_dpll_params(refclk, &clock);
9996         } else {
9997                 u32 lvds = IS_I830(dev_priv) ? 0 : I915_READ(LVDS);
9998                 bool is_lvds = (pipe == 1) && (lvds & LVDS_PORT_EN);
9999
10000                 if (is_lvds) {
10001                         clock.p1 = ffs((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830_LVDS) >>
10002                                        DPLL_FPA01_P1_POST_DIV_SHIFT);
10003
10004                         if (lvds & LVDS_CLKB_POWER_UP)
10005                                 clock.p2 = 7;
10006                         else
10007                                 clock.p2 = 14;
10008                 } else {
10009                         if (dpll & PLL_P1_DIVIDE_BY_TWO)
10010                                 clock.p1 = 2;
10011                         else {
10012                                 clock.p1 = ((dpll & DPLL_FPA01_P1_POST_DIV_MASK_I830) >>
10013                                             DPLL_FPA01_P1_POST_DIV_SHIFT) + 2;
10014                         }
10015                         if (dpll & PLL_P2_DIVIDE_BY_4)
10016                                 clock.p2 = 4;
10017                         else
10018                                 clock.p2 = 2;
10019                 }
10020
10021                 port_clock = i9xx_calc_dpll_params(refclk, &clock);
10022         }
10023
10024         /*
10025          * This value includes pixel_multiplier. We will use
10026          * port_clock to compute adjusted_mode.crtc_clock in the
10027          * encoder's get_config() function.
10028          */
10029         pipe_config->port_clock = port_clock;
10030 }
10031
10032 int intel_dotclock_calculate(int link_freq,
10033                              const struct intel_link_m_n *m_n)
10034 {
10035         /*
10036          * The calculation for the data clock is:
10037          * pixel_clock = ((m/n)*(link_clock * nr_lanes))/bpp
10038          * But we want to avoid losing precison if possible, so:
10039          * pixel_clock = ((m * link_clock * nr_lanes)/(n*bpp))
10040          *
10041          * and the link clock is simpler:
10042          * link_clock = (m * link_clock) / n
10043          */
10044
10045         if (!m_n->link_n)
10046                 return 0;
10047
10048         return div_u64(mul_u32_u32(m_n->link_m, link_freq), m_n->link_n);
10049 }
10050
10051 static void ironlake_pch_clock_get(struct intel_crtc *crtc,
10052                                    struct intel_crtc_state *pipe_config)
10053 {
10054         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10055
10056         /* read out port_clock from the DPLL */
10057         i9xx_crtc_clock_get(crtc, pipe_config);
10058
10059         /*
10060          * In case there is an active pipe without active ports,
10061          * we may need some idea for the dotclock anyway.
10062          * Calculate one based on the FDI configuration.
10063          */
10064         pipe_config->base.adjusted_mode.crtc_clock =
10065                 intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
10066                                          &pipe_config->fdi_m_n);
10067 }
10068
10069 /* Returns the currently programmed mode of the given encoder. */
10070 struct drm_display_mode *
10071 intel_encoder_current_mode(struct intel_encoder *encoder)
10072 {
10073         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
10074         struct intel_crtc_state *crtc_state;
10075         struct drm_display_mode *mode;
10076         struct intel_crtc *crtc;
10077         enum pipe pipe;
10078
10079         if (!encoder->get_hw_state(encoder, &pipe))
10080                 return NULL;
10081
10082         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
10083
10084         mode = kzalloc(sizeof(*mode), GFP_KERNEL);
10085         if (!mode)
10086                 return NULL;
10087
10088         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
10089         if (!crtc_state) {
10090                 kfree(mode);
10091                 return NULL;
10092         }
10093
10094         crtc_state->base.crtc = &crtc->base;
10095
10096         if (!dev_priv->display.get_pipe_config(crtc, crtc_state)) {
10097                 kfree(crtc_state);
10098                 kfree(mode);
10099                 return NULL;
10100         }
10101
10102         encoder->get_config(encoder, crtc_state);
10103
10104         intel_mode_from_pipe_config(mode, crtc_state);
10105
10106         kfree(crtc_state);
10107
10108         return mode;
10109 }
10110
10111 static void intel_crtc_destroy(struct drm_crtc *crtc)
10112 {
10113         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10114
10115         drm_crtc_cleanup(crtc);
10116         kfree(intel_crtc);
10117 }
10118
10119 /**
10120  * intel_wm_need_update - Check whether watermarks need updating
10121  * @plane: drm plane
10122  * @state: new plane state
10123  *
10124  * Check current plane state versus the new one to determine whether
10125  * watermarks need to be recalculated.
10126  *
10127  * Returns true or false.
10128  */
10129 static bool intel_wm_need_update(struct drm_plane *plane,
10130                                  struct drm_plane_state *state)
10131 {
10132         struct intel_plane_state *new = to_intel_plane_state(state);
10133         struct intel_plane_state *cur = to_intel_plane_state(plane->state);
10134
10135         /* Update watermarks on tiling or size changes. */
10136         if (new->base.visible != cur->base.visible)
10137                 return true;
10138
10139         if (!cur->base.fb || !new->base.fb)
10140                 return false;
10141
10142         if (cur->base.fb->modifier != new->base.fb->modifier ||
10143             cur->base.rotation != new->base.rotation ||
10144             drm_rect_width(&new->base.src) != drm_rect_width(&cur->base.src) ||
10145             drm_rect_height(&new->base.src) != drm_rect_height(&cur->base.src) ||
10146             drm_rect_width(&new->base.dst) != drm_rect_width(&cur->base.dst) ||
10147             drm_rect_height(&new->base.dst) != drm_rect_height(&cur->base.dst))
10148                 return true;
10149
10150         return false;
10151 }
10152
10153 static bool needs_scaling(const struct intel_plane_state *state)
10154 {
10155         int src_w = drm_rect_width(&state->base.src) >> 16;
10156         int src_h = drm_rect_height(&state->base.src) >> 16;
10157         int dst_w = drm_rect_width(&state->base.dst);
10158         int dst_h = drm_rect_height(&state->base.dst);
10159
10160         return (src_w != dst_w || src_h != dst_h);
10161 }
10162
10163 int intel_plane_atomic_calc_changes(const struct intel_crtc_state *old_crtc_state,
10164                                     struct drm_crtc_state *crtc_state,
10165                                     const struct intel_plane_state *old_plane_state,
10166                                     struct drm_plane_state *plane_state)
10167 {
10168         struct intel_crtc_state *pipe_config = to_intel_crtc_state(crtc_state);
10169         struct drm_crtc *crtc = crtc_state->crtc;
10170         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10171         struct intel_plane *plane = to_intel_plane(plane_state->plane);
10172         struct drm_device *dev = crtc->dev;
10173         struct drm_i915_private *dev_priv = to_i915(dev);
10174         bool mode_changed = needs_modeset(crtc_state);
10175         bool was_crtc_enabled = old_crtc_state->base.active;
10176         bool is_crtc_enabled = crtc_state->active;
10177         bool turn_off, turn_on, visible, was_visible;
10178         struct drm_framebuffer *fb = plane_state->fb;
10179         int ret;
10180
10181         if (INTEL_GEN(dev_priv) >= 9 && plane->id != PLANE_CURSOR) {
10182                 ret = skl_update_scaler_plane(
10183                         to_intel_crtc_state(crtc_state),
10184                         to_intel_plane_state(plane_state));
10185                 if (ret)
10186                         return ret;
10187         }
10188
10189         was_visible = old_plane_state->base.visible;
10190         visible = plane_state->visible;
10191
10192         if (!was_crtc_enabled && WARN_ON(was_visible))
10193                 was_visible = false;
10194
10195         /*
10196          * Visibility is calculated as if the crtc was on, but
10197          * after scaler setup everything depends on it being off
10198          * when the crtc isn't active.
10199          *
10200          * FIXME this is wrong for watermarks. Watermarks should also
10201          * be computed as if the pipe would be active. Perhaps move
10202          * per-plane wm computation to the .check_plane() hook, and
10203          * only combine the results from all planes in the current place?
10204          */
10205         if (!is_crtc_enabled) {
10206                 plane_state->visible = visible = false;
10207                 to_intel_crtc_state(crtc_state)->active_planes &= ~BIT(plane->id);
10208         }
10209
10210         if (!was_visible && !visible)
10211                 return 0;
10212
10213         if (fb != old_plane_state->base.fb)
10214                 pipe_config->fb_changed = true;
10215
10216         turn_off = was_visible && (!visible || mode_changed);
10217         turn_on = visible && (!was_visible || mode_changed);
10218
10219         DRM_DEBUG_ATOMIC("[CRTC:%d:%s] has [PLANE:%d:%s] with fb %i\n",
10220                          intel_crtc->base.base.id, intel_crtc->base.name,
10221                          plane->base.base.id, plane->base.name,
10222                          fb ? fb->base.id : -1);
10223
10224         DRM_DEBUG_ATOMIC("[PLANE:%d:%s] visible %i -> %i, off %i, on %i, ms %i\n",
10225                          plane->base.base.id, plane->base.name,
10226                          was_visible, visible,
10227                          turn_off, turn_on, mode_changed);
10228
10229         if (turn_on) {
10230                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10231                         pipe_config->update_wm_pre = true;
10232
10233                 /* must disable cxsr around plane enable/disable */
10234                 if (plane->id != PLANE_CURSOR)
10235                         pipe_config->disable_cxsr = true;
10236         } else if (turn_off) {
10237                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv))
10238                         pipe_config->update_wm_post = true;
10239
10240                 /* must disable cxsr around plane enable/disable */
10241                 if (plane->id != PLANE_CURSOR)
10242                         pipe_config->disable_cxsr = true;
10243         } else if (intel_wm_need_update(&plane->base, plane_state)) {
10244                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
10245                         /* FIXME bollocks */
10246                         pipe_config->update_wm_pre = true;
10247                         pipe_config->update_wm_post = true;
10248                 }
10249         }
10250
10251         if (visible || was_visible)
10252                 pipe_config->fb_bits |= plane->frontbuffer_bit;
10253
10254         /*
10255          * WaCxSRDisabledForSpriteScaling:ivb
10256          *
10257          * cstate->update_wm was already set above, so this flag will
10258          * take effect when we commit and program watermarks.
10259          */
10260         if (plane->id == PLANE_SPRITE0 && IS_IVYBRIDGE(dev_priv) &&
10261             needs_scaling(to_intel_plane_state(plane_state)) &&
10262             !needs_scaling(old_plane_state))
10263                 pipe_config->disable_lp_wm = true;
10264
10265         return 0;
10266 }
10267
10268 static bool encoders_cloneable(const struct intel_encoder *a,
10269                                const struct intel_encoder *b)
10270 {
10271         /* masks could be asymmetric, so check both ways */
10272         return a == b || (a->cloneable & (1 << b->type) &&
10273                           b->cloneable & (1 << a->type));
10274 }
10275
10276 static bool check_single_encoder_cloning(struct drm_atomic_state *state,
10277                                          struct intel_crtc *crtc,
10278                                          struct intel_encoder *encoder)
10279 {
10280         struct intel_encoder *source_encoder;
10281         struct drm_connector *connector;
10282         struct drm_connector_state *connector_state;
10283         int i;
10284
10285         for_each_new_connector_in_state(state, connector, connector_state, i) {
10286                 if (connector_state->crtc != &crtc->base)
10287                         continue;
10288
10289                 source_encoder =
10290                         to_intel_encoder(connector_state->best_encoder);
10291                 if (!encoders_cloneable(encoder, source_encoder))
10292                         return false;
10293         }
10294
10295         return true;
10296 }
10297
10298 static int intel_crtc_atomic_check(struct drm_crtc *crtc,
10299                                    struct drm_crtc_state *crtc_state)
10300 {
10301         struct drm_device *dev = crtc->dev;
10302         struct drm_i915_private *dev_priv = to_i915(dev);
10303         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
10304         struct intel_crtc_state *pipe_config =
10305                 to_intel_crtc_state(crtc_state);
10306         struct drm_atomic_state *state = crtc_state->state;
10307         int ret;
10308         bool mode_changed = needs_modeset(crtc_state);
10309
10310         if (mode_changed && !crtc_state->active)
10311                 pipe_config->update_wm_post = true;
10312
10313         if (mode_changed && crtc_state->enable &&
10314             dev_priv->display.crtc_compute_clock &&
10315             !WARN_ON(pipe_config->shared_dpll)) {
10316                 ret = dev_priv->display.crtc_compute_clock(intel_crtc,
10317                                                            pipe_config);
10318                 if (ret)
10319                         return ret;
10320         }
10321
10322         if (crtc_state->color_mgmt_changed) {
10323                 ret = intel_color_check(crtc, crtc_state);
10324                 if (ret)
10325                         return ret;
10326
10327                 /*
10328                  * Changing color management on Intel hardware is
10329                  * handled as part of planes update.
10330                  */
10331                 crtc_state->planes_changed = true;
10332         }
10333
10334         ret = 0;
10335         if (dev_priv->display.compute_pipe_wm) {
10336                 ret = dev_priv->display.compute_pipe_wm(pipe_config);
10337                 if (ret) {
10338                         DRM_DEBUG_KMS("Target pipe watermarks are invalid\n");
10339                         return ret;
10340                 }
10341         }
10342
10343         if (dev_priv->display.compute_intermediate_wm &&
10344             !to_intel_atomic_state(state)->skip_intermediate_wm) {
10345                 if (WARN_ON(!dev_priv->display.compute_pipe_wm))
10346                         return 0;
10347
10348                 /*
10349                  * Calculate 'intermediate' watermarks that satisfy both the
10350                  * old state and the new state.  We can program these
10351                  * immediately.
10352                  */
10353                 ret = dev_priv->display.compute_intermediate_wm(dev,
10354                                                                 intel_crtc,
10355                                                                 pipe_config);
10356                 if (ret) {
10357                         DRM_DEBUG_KMS("No valid intermediate pipe watermarks are possible\n");
10358                         return ret;
10359                 }
10360         } else if (dev_priv->display.compute_intermediate_wm) {
10361                 if (HAS_PCH_SPLIT(dev_priv) && INTEL_GEN(dev_priv) < 9)
10362                         pipe_config->wm.ilk.intermediate = pipe_config->wm.ilk.optimal;
10363         }
10364
10365         if (INTEL_GEN(dev_priv) >= 9) {
10366                 if (mode_changed)
10367                         ret = skl_update_scaler_crtc(pipe_config);
10368
10369                 if (!ret)
10370                         ret = skl_check_pipe_max_pixel_rate(intel_crtc,
10371                                                             pipe_config);
10372                 if (!ret)
10373                         ret = intel_atomic_setup_scalers(dev_priv, intel_crtc,
10374                                                          pipe_config);
10375         }
10376
10377         if (HAS_IPS(dev_priv))
10378                 pipe_config->ips_enabled = hsw_compute_ips_config(pipe_config);
10379
10380         return ret;
10381 }
10382
10383 static const struct drm_crtc_helper_funcs intel_helper_funcs = {
10384         .atomic_begin = intel_begin_crtc_commit,
10385         .atomic_flush = intel_finish_crtc_commit,
10386         .atomic_check = intel_crtc_atomic_check,
10387 };
10388
10389 static void intel_modeset_update_connector_atomic_state(struct drm_device *dev)
10390 {
10391         struct intel_connector *connector;
10392         struct drm_connector_list_iter conn_iter;
10393
10394         drm_connector_list_iter_begin(dev, &conn_iter);
10395         for_each_intel_connector_iter(connector, &conn_iter) {
10396                 if (connector->base.state->crtc)
10397                         drm_connector_unreference(&connector->base);
10398
10399                 if (connector->base.encoder) {
10400                         connector->base.state->best_encoder =
10401                                 connector->base.encoder;
10402                         connector->base.state->crtc =
10403                                 connector->base.encoder->crtc;
10404
10405                         drm_connector_reference(&connector->base);
10406                 } else {
10407                         connector->base.state->best_encoder = NULL;
10408                         connector->base.state->crtc = NULL;
10409                 }
10410         }
10411         drm_connector_list_iter_end(&conn_iter);
10412 }
10413
10414 static void
10415 connected_sink_compute_bpp(struct intel_connector *connector,
10416                            struct intel_crtc_state *pipe_config)
10417 {
10418         const struct drm_display_info *info = &connector->base.display_info;
10419         int bpp = pipe_config->pipe_bpp;
10420
10421         DRM_DEBUG_KMS("[CONNECTOR:%d:%s] checking for sink bpp constrains\n",
10422                       connector->base.base.id,
10423                       connector->base.name);
10424
10425         /* Don't use an invalid EDID bpc value */
10426         if (info->bpc != 0 && info->bpc * 3 < bpp) {
10427                 DRM_DEBUG_KMS("clamping display bpp (was %d) to EDID reported max of %d\n",
10428                               bpp, info->bpc * 3);
10429                 pipe_config->pipe_bpp = info->bpc * 3;
10430         }
10431
10432         /* Clamp bpp to 8 on screens without EDID 1.4 */
10433         if (info->bpc == 0 && bpp > 24) {
10434                 DRM_DEBUG_KMS("clamping display bpp (was %d) to default limit of 24\n",
10435                               bpp);
10436                 pipe_config->pipe_bpp = 24;
10437         }
10438 }
10439
10440 static int
10441 compute_baseline_pipe_bpp(struct intel_crtc *crtc,
10442                           struct intel_crtc_state *pipe_config)
10443 {
10444         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
10445         struct drm_atomic_state *state;
10446         struct drm_connector *connector;
10447         struct drm_connector_state *connector_state;
10448         int bpp, i;
10449
10450         if ((IS_G4X(dev_priv) || IS_VALLEYVIEW(dev_priv) ||
10451             IS_CHERRYVIEW(dev_priv)))
10452                 bpp = 10*3;
10453         else if (INTEL_GEN(dev_priv) >= 5)
10454                 bpp = 12*3;
10455         else
10456                 bpp = 8*3;
10457
10458
10459         pipe_config->pipe_bpp = bpp;
10460
10461         state = pipe_config->base.state;
10462
10463         /* Clamp display bpp to EDID value */
10464         for_each_new_connector_in_state(state, connector, connector_state, i) {
10465                 if (connector_state->crtc != &crtc->base)
10466                         continue;
10467
10468                 connected_sink_compute_bpp(to_intel_connector(connector),
10469                                            pipe_config);
10470         }
10471
10472         return bpp;
10473 }
10474
10475 static void intel_dump_crtc_timings(const struct drm_display_mode *mode)
10476 {
10477         DRM_DEBUG_KMS("crtc timings: %d %d %d %d %d %d %d %d %d, "
10478                         "type: 0x%x flags: 0x%x\n",
10479                 mode->crtc_clock,
10480                 mode->crtc_hdisplay, mode->crtc_hsync_start,
10481                 mode->crtc_hsync_end, mode->crtc_htotal,
10482                 mode->crtc_vdisplay, mode->crtc_vsync_start,
10483                 mode->crtc_vsync_end, mode->crtc_vtotal, mode->type, mode->flags);
10484 }
10485
10486 static inline void
10487 intel_dump_m_n_config(struct intel_crtc_state *pipe_config, char *id,
10488                       unsigned int lane_count, struct intel_link_m_n *m_n)
10489 {
10490         DRM_DEBUG_KMS("%s: lanes: %i; gmch_m: %u, gmch_n: %u, link_m: %u, link_n: %u, tu: %u\n",
10491                       id, lane_count,
10492                       m_n->gmch_m, m_n->gmch_n,
10493                       m_n->link_m, m_n->link_n, m_n->tu);
10494 }
10495
10496 #define OUTPUT_TYPE(x) [INTEL_OUTPUT_ ## x] = #x
10497
10498 static const char * const output_type_str[] = {
10499         OUTPUT_TYPE(UNUSED),
10500         OUTPUT_TYPE(ANALOG),
10501         OUTPUT_TYPE(DVO),
10502         OUTPUT_TYPE(SDVO),
10503         OUTPUT_TYPE(LVDS),
10504         OUTPUT_TYPE(TVOUT),
10505         OUTPUT_TYPE(HDMI),
10506         OUTPUT_TYPE(DP),
10507         OUTPUT_TYPE(EDP),
10508         OUTPUT_TYPE(DSI),
10509         OUTPUT_TYPE(DDI),
10510         OUTPUT_TYPE(DP_MST),
10511 };
10512
10513 #undef OUTPUT_TYPE
10514
10515 static void snprintf_output_types(char *buf, size_t len,
10516                                   unsigned int output_types)
10517 {
10518         char *str = buf;
10519         int i;
10520
10521         str[0] = '\0';
10522
10523         for (i = 0; i < ARRAY_SIZE(output_type_str); i++) {
10524                 int r;
10525
10526                 if ((output_types & BIT(i)) == 0)
10527                         continue;
10528
10529                 r = snprintf(str, len, "%s%s",
10530                              str != buf ? "," : "", output_type_str[i]);
10531                 if (r >= len)
10532                         break;
10533                 str += r;
10534                 len -= r;
10535
10536                 output_types &= ~BIT(i);
10537         }
10538
10539         WARN_ON_ONCE(output_types != 0);
10540 }
10541
10542 static void intel_dump_pipe_config(struct intel_crtc *crtc,
10543                                    struct intel_crtc_state *pipe_config,
10544                                    const char *context)
10545 {
10546         struct drm_device *dev = crtc->base.dev;
10547         struct drm_i915_private *dev_priv = to_i915(dev);
10548         struct drm_plane *plane;
10549         struct intel_plane *intel_plane;
10550         struct intel_plane_state *state;
10551         struct drm_framebuffer *fb;
10552         char buf[64];
10553
10554         DRM_DEBUG_KMS("[CRTC:%d:%s]%s\n",
10555                       crtc->base.base.id, crtc->base.name, context);
10556
10557         snprintf_output_types(buf, sizeof(buf), pipe_config->output_types);
10558         DRM_DEBUG_KMS("output_types: %s (0x%x)\n",
10559                       buf, pipe_config->output_types);
10560
10561         DRM_DEBUG_KMS("cpu_transcoder: %s, pipe bpp: %i, dithering: %i\n",
10562                       transcoder_name(pipe_config->cpu_transcoder),
10563                       pipe_config->pipe_bpp, pipe_config->dither);
10564
10565         if (pipe_config->has_pch_encoder)
10566                 intel_dump_m_n_config(pipe_config, "fdi",
10567                                       pipe_config->fdi_lanes,
10568                                       &pipe_config->fdi_m_n);
10569
10570         if (pipe_config->ycbcr420)
10571                 DRM_DEBUG_KMS("YCbCr 4:2:0 output enabled\n");
10572
10573         if (intel_crtc_has_dp_encoder(pipe_config)) {
10574                 intel_dump_m_n_config(pipe_config, "dp m_n",
10575                                 pipe_config->lane_count, &pipe_config->dp_m_n);
10576                 if (pipe_config->has_drrs)
10577                         intel_dump_m_n_config(pipe_config, "dp m2_n2",
10578                                               pipe_config->lane_count,
10579                                               &pipe_config->dp_m2_n2);
10580         }
10581
10582         DRM_DEBUG_KMS("audio: %i, infoframes: %i\n",
10583                       pipe_config->has_audio, pipe_config->has_infoframe);
10584
10585         DRM_DEBUG_KMS("requested mode:\n");
10586         drm_mode_debug_printmodeline(&pipe_config->base.mode);
10587         DRM_DEBUG_KMS("adjusted mode:\n");
10588         drm_mode_debug_printmodeline(&pipe_config->base.adjusted_mode);
10589         intel_dump_crtc_timings(&pipe_config->base.adjusted_mode);
10590         DRM_DEBUG_KMS("port clock: %d, pipe src size: %dx%d, pixel rate %d\n",
10591                       pipe_config->port_clock,
10592                       pipe_config->pipe_src_w, pipe_config->pipe_src_h,
10593                       pipe_config->pixel_rate);
10594
10595         if (INTEL_GEN(dev_priv) >= 9)
10596                 DRM_DEBUG_KMS("num_scalers: %d, scaler_users: 0x%x, scaler_id: %d\n",
10597                               crtc->num_scalers,
10598                               pipe_config->scaler_state.scaler_users,
10599                               pipe_config->scaler_state.scaler_id);
10600
10601         if (HAS_GMCH_DISPLAY(dev_priv))
10602                 DRM_DEBUG_KMS("gmch pfit: control: 0x%08x, ratios: 0x%08x, lvds border: 0x%08x\n",
10603                               pipe_config->gmch_pfit.control,
10604                               pipe_config->gmch_pfit.pgm_ratios,
10605                               pipe_config->gmch_pfit.lvds_border_bits);
10606         else
10607                 DRM_DEBUG_KMS("pch pfit: pos: 0x%08x, size: 0x%08x, %s\n",
10608                               pipe_config->pch_pfit.pos,
10609                               pipe_config->pch_pfit.size,
10610                               enableddisabled(pipe_config->pch_pfit.enabled));
10611
10612         DRM_DEBUG_KMS("ips: %i, double wide: %i\n",
10613                       pipe_config->ips_enabled, pipe_config->double_wide);
10614
10615         intel_dpll_dump_hw_state(dev_priv, &pipe_config->dpll_hw_state);
10616
10617         DRM_DEBUG_KMS("planes on this crtc\n");
10618         list_for_each_entry(plane, &dev->mode_config.plane_list, head) {
10619                 struct drm_format_name_buf format_name;
10620                 intel_plane = to_intel_plane(plane);
10621                 if (intel_plane->pipe != crtc->pipe)
10622                         continue;
10623
10624                 state = to_intel_plane_state(plane->state);
10625                 fb = state->base.fb;
10626                 if (!fb) {
10627                         DRM_DEBUG_KMS("[PLANE:%d:%s] disabled, scaler_id = %d\n",
10628                                       plane->base.id, plane->name, state->scaler_id);
10629                         continue;
10630                 }
10631
10632                 DRM_DEBUG_KMS("[PLANE:%d:%s] FB:%d, fb = %ux%u format = %s\n",
10633                               plane->base.id, plane->name,
10634                               fb->base.id, fb->width, fb->height,
10635                               drm_get_format_name(fb->format->format, &format_name));
10636                 if (INTEL_GEN(dev_priv) >= 9)
10637                         DRM_DEBUG_KMS("\tscaler:%d src %dx%d+%d+%d dst %dx%d+%d+%d\n",
10638                                       state->scaler_id,
10639                                       state->base.src.x1 >> 16,
10640                                       state->base.src.y1 >> 16,
10641                                       drm_rect_width(&state->base.src) >> 16,
10642                                       drm_rect_height(&state->base.src) >> 16,
10643                                       state->base.dst.x1, state->base.dst.y1,
10644                                       drm_rect_width(&state->base.dst),
10645                                       drm_rect_height(&state->base.dst));
10646         }
10647 }
10648
10649 static bool check_digital_port_conflicts(struct drm_atomic_state *state)
10650 {
10651         struct drm_device *dev = state->dev;
10652         struct drm_connector *connector;
10653         struct drm_connector_list_iter conn_iter;
10654         unsigned int used_ports = 0;
10655         unsigned int used_mst_ports = 0;
10656
10657         /*
10658          * Walk the connector list instead of the encoder
10659          * list to detect the problem on ddi platforms
10660          * where there's just one encoder per digital port.
10661          */
10662         drm_connector_list_iter_begin(dev, &conn_iter);
10663         drm_for_each_connector_iter(connector, &conn_iter) {
10664                 struct drm_connector_state *connector_state;
10665                 struct intel_encoder *encoder;
10666
10667                 connector_state = drm_atomic_get_existing_connector_state(state, connector);
10668                 if (!connector_state)
10669                         connector_state = connector->state;
10670
10671                 if (!connector_state->best_encoder)
10672                         continue;
10673
10674                 encoder = to_intel_encoder(connector_state->best_encoder);
10675
10676                 WARN_ON(!connector_state->crtc);
10677
10678                 switch (encoder->type) {
10679                         unsigned int port_mask;
10680                 case INTEL_OUTPUT_DDI:
10681                         if (WARN_ON(!HAS_DDI(to_i915(dev))))
10682                                 break;
10683                 case INTEL_OUTPUT_DP:
10684                 case INTEL_OUTPUT_HDMI:
10685                 case INTEL_OUTPUT_EDP:
10686                         port_mask = 1 << encoder->port;
10687
10688                         /* the same port mustn't appear more than once */
10689                         if (used_ports & port_mask)
10690                                 return false;
10691
10692                         used_ports |= port_mask;
10693                         break;
10694                 case INTEL_OUTPUT_DP_MST:
10695                         used_mst_ports |=
10696                                 1 << encoder->port;
10697                         break;
10698                 default:
10699                         break;
10700                 }
10701         }
10702         drm_connector_list_iter_end(&conn_iter);
10703
10704         /* can't mix MST and SST/HDMI on the same port */
10705         if (used_ports & used_mst_ports)
10706                 return false;
10707
10708         return true;
10709 }
10710
10711 static void
10712 clear_intel_crtc_state(struct intel_crtc_state *crtc_state)
10713 {
10714         struct drm_i915_private *dev_priv =
10715                 to_i915(crtc_state->base.crtc->dev);
10716         struct intel_crtc_scaler_state scaler_state;
10717         struct intel_dpll_hw_state dpll_hw_state;
10718         struct intel_shared_dpll *shared_dpll;
10719         struct intel_crtc_wm_state wm_state;
10720         bool force_thru, ips_force_disable;
10721
10722         /* FIXME: before the switch to atomic started, a new pipe_config was
10723          * kzalloc'd. Code that depends on any field being zero should be
10724          * fixed, so that the crtc_state can be safely duplicated. For now,
10725          * only fields that are know to not cause problems are preserved. */
10726
10727         scaler_state = crtc_state->scaler_state;
10728         shared_dpll = crtc_state->shared_dpll;
10729         dpll_hw_state = crtc_state->dpll_hw_state;
10730         force_thru = crtc_state->pch_pfit.force_thru;
10731         ips_force_disable = crtc_state->ips_force_disable;
10732         if (IS_G4X(dev_priv) ||
10733             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10734                 wm_state = crtc_state->wm;
10735
10736         /* Keep base drm_crtc_state intact, only clear our extended struct */
10737         BUILD_BUG_ON(offsetof(struct intel_crtc_state, base));
10738         memset(&crtc_state->base + 1, 0,
10739                sizeof(*crtc_state) - sizeof(crtc_state->base));
10740
10741         crtc_state->scaler_state = scaler_state;
10742         crtc_state->shared_dpll = shared_dpll;
10743         crtc_state->dpll_hw_state = dpll_hw_state;
10744         crtc_state->pch_pfit.force_thru = force_thru;
10745         crtc_state->ips_force_disable = ips_force_disable;
10746         if (IS_G4X(dev_priv) ||
10747             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
10748                 crtc_state->wm = wm_state;
10749 }
10750
10751 static int
10752 intel_modeset_pipe_config(struct drm_crtc *crtc,
10753                           struct intel_crtc_state *pipe_config)
10754 {
10755         struct drm_atomic_state *state = pipe_config->base.state;
10756         struct intel_encoder *encoder;
10757         struct drm_connector *connector;
10758         struct drm_connector_state *connector_state;
10759         int base_bpp, ret = -EINVAL;
10760         int i;
10761         bool retry = true;
10762
10763         clear_intel_crtc_state(pipe_config);
10764
10765         pipe_config->cpu_transcoder =
10766                 (enum transcoder) to_intel_crtc(crtc)->pipe;
10767
10768         /*
10769          * Sanitize sync polarity flags based on requested ones. If neither
10770          * positive or negative polarity is requested, treat this as meaning
10771          * negative polarity.
10772          */
10773         if (!(pipe_config->base.adjusted_mode.flags &
10774               (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NHSYNC)))
10775                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NHSYNC;
10776
10777         if (!(pipe_config->base.adjusted_mode.flags &
10778               (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NVSYNC)))
10779                 pipe_config->base.adjusted_mode.flags |= DRM_MODE_FLAG_NVSYNC;
10780
10781         base_bpp = compute_baseline_pipe_bpp(to_intel_crtc(crtc),
10782                                              pipe_config);
10783         if (base_bpp < 0)
10784                 goto fail;
10785
10786         /*
10787          * Determine the real pipe dimensions. Note that stereo modes can
10788          * increase the actual pipe size due to the frame doubling and
10789          * insertion of additional space for blanks between the frame. This
10790          * is stored in the crtc timings. We use the requested mode to do this
10791          * computation to clearly distinguish it from the adjusted mode, which
10792          * can be changed by the connectors in the below retry loop.
10793          */
10794         drm_mode_get_hv_timing(&pipe_config->base.mode,
10795                                &pipe_config->pipe_src_w,
10796                                &pipe_config->pipe_src_h);
10797
10798         for_each_new_connector_in_state(state, connector, connector_state, i) {
10799                 if (connector_state->crtc != crtc)
10800                         continue;
10801
10802                 encoder = to_intel_encoder(connector_state->best_encoder);
10803
10804                 if (!check_single_encoder_cloning(state, to_intel_crtc(crtc), encoder)) {
10805                         DRM_DEBUG_KMS("rejecting invalid cloning configuration\n");
10806                         goto fail;
10807                 }
10808
10809                 /*
10810                  * Determine output_types before calling the .compute_config()
10811                  * hooks so that the hooks can use this information safely.
10812                  */
10813                 if (encoder->compute_output_type)
10814                         pipe_config->output_types |=
10815                                 BIT(encoder->compute_output_type(encoder, pipe_config,
10816                                                                  connector_state));
10817                 else
10818                         pipe_config->output_types |= BIT(encoder->type);
10819         }
10820
10821 encoder_retry:
10822         /* Ensure the port clock defaults are reset when retrying. */
10823         pipe_config->port_clock = 0;
10824         pipe_config->pixel_multiplier = 1;
10825
10826         /* Fill in default crtc timings, allow encoders to overwrite them. */
10827         drm_mode_set_crtcinfo(&pipe_config->base.adjusted_mode,
10828                               CRTC_STEREO_DOUBLE);
10829
10830         /* Pass our mode to the connectors and the CRTC to give them a chance to
10831          * adjust it according to limitations or connector properties, and also
10832          * a chance to reject the mode entirely.
10833          */
10834         for_each_new_connector_in_state(state, connector, connector_state, i) {
10835                 if (connector_state->crtc != crtc)
10836                         continue;
10837
10838                 encoder = to_intel_encoder(connector_state->best_encoder);
10839
10840                 if (!(encoder->compute_config(encoder, pipe_config, connector_state))) {
10841                         DRM_DEBUG_KMS("Encoder config failure\n");
10842                         goto fail;
10843                 }
10844         }
10845
10846         /* Set default port clock if not overwritten by the encoder. Needs to be
10847          * done afterwards in case the encoder adjusts the mode. */
10848         if (!pipe_config->port_clock)
10849                 pipe_config->port_clock = pipe_config->base.adjusted_mode.crtc_clock
10850                         * pipe_config->pixel_multiplier;
10851
10852         ret = intel_crtc_compute_config(to_intel_crtc(crtc), pipe_config);
10853         if (ret < 0) {
10854                 DRM_DEBUG_KMS("CRTC fixup failed\n");
10855                 goto fail;
10856         }
10857
10858         if (ret == RETRY) {
10859                 if (WARN(!retry, "loop in pipe configuration computation\n")) {
10860                         ret = -EINVAL;
10861                         goto fail;
10862                 }
10863
10864                 DRM_DEBUG_KMS("CRTC bw constrained, retrying\n");
10865                 retry = false;
10866                 goto encoder_retry;
10867         }
10868
10869         /* Dithering seems to not pass-through bits correctly when it should, so
10870          * only enable it on 6bpc panels and when its not a compliance
10871          * test requesting 6bpc video pattern.
10872          */
10873         pipe_config->dither = (pipe_config->pipe_bpp == 6*3) &&
10874                 !pipe_config->dither_force_disable;
10875         DRM_DEBUG_KMS("hw max bpp: %i, pipe bpp: %i, dithering: %i\n",
10876                       base_bpp, pipe_config->pipe_bpp, pipe_config->dither);
10877
10878 fail:
10879         return ret;
10880 }
10881
10882 static bool intel_fuzzy_clock_check(int clock1, int clock2)
10883 {
10884         int diff;
10885
10886         if (clock1 == clock2)
10887                 return true;
10888
10889         if (!clock1 || !clock2)
10890                 return false;
10891
10892         diff = abs(clock1 - clock2);
10893
10894         if (((((diff + clock1 + clock2) * 100)) / (clock1 + clock2)) < 105)
10895                 return true;
10896
10897         return false;
10898 }
10899
10900 static bool
10901 intel_compare_m_n(unsigned int m, unsigned int n,
10902                   unsigned int m2, unsigned int n2,
10903                   bool exact)
10904 {
10905         if (m == m2 && n == n2)
10906                 return true;
10907
10908         if (exact || !m || !n || !m2 || !n2)
10909                 return false;
10910
10911         BUILD_BUG_ON(DATA_LINK_M_N_MASK > INT_MAX);
10912
10913         if (n > n2) {
10914                 while (n > n2) {
10915                         m2 <<= 1;
10916                         n2 <<= 1;
10917                 }
10918         } else if (n < n2) {
10919                 while (n < n2) {
10920                         m <<= 1;
10921                         n <<= 1;
10922                 }
10923         }
10924
10925         if (n != n2)
10926                 return false;
10927
10928         return intel_fuzzy_clock_check(m, m2);
10929 }
10930
10931 static bool
10932 intel_compare_link_m_n(const struct intel_link_m_n *m_n,
10933                        struct intel_link_m_n *m2_n2,
10934                        bool adjust)
10935 {
10936         if (m_n->tu == m2_n2->tu &&
10937             intel_compare_m_n(m_n->gmch_m, m_n->gmch_n,
10938                               m2_n2->gmch_m, m2_n2->gmch_n, !adjust) &&
10939             intel_compare_m_n(m_n->link_m, m_n->link_n,
10940                               m2_n2->link_m, m2_n2->link_n, !adjust)) {
10941                 if (adjust)
10942                         *m2_n2 = *m_n;
10943
10944                 return true;
10945         }
10946
10947         return false;
10948 }
10949
10950 static void __printf(3, 4)
10951 pipe_config_err(bool adjust, const char *name, const char *format, ...)
10952 {
10953         char *level;
10954         unsigned int category;
10955         struct va_format vaf;
10956         va_list args;
10957
10958         if (adjust) {
10959                 level = KERN_DEBUG;
10960                 category = DRM_UT_KMS;
10961         } else {
10962                 level = KERN_ERR;
10963                 category = DRM_UT_NONE;
10964         }
10965
10966         va_start(args, format);
10967         vaf.fmt = format;
10968         vaf.va = &args;
10969
10970         drm_printk(level, category, "mismatch in %s %pV", name, &vaf);
10971
10972         va_end(args);
10973 }
10974
10975 static bool
10976 intel_pipe_config_compare(struct drm_i915_private *dev_priv,
10977                           struct intel_crtc_state *current_config,
10978                           struct intel_crtc_state *pipe_config,
10979                           bool adjust)
10980 {
10981         bool ret = true;
10982         bool fixup_inherited = adjust &&
10983                 (current_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED) &&
10984                 !(pipe_config->base.mode.private_flags & I915_MODE_FLAG_INHERITED);
10985
10986 #define PIPE_CONF_CHECK_X(name) \
10987         if (current_config->name != pipe_config->name) { \
10988                 pipe_config_err(adjust, __stringify(name), \
10989                           "(expected 0x%08x, found 0x%08x)\n", \
10990                           current_config->name, \
10991                           pipe_config->name); \
10992                 ret = false; \
10993         }
10994
10995 #define PIPE_CONF_CHECK_I(name) \
10996         if (current_config->name != pipe_config->name) { \
10997                 pipe_config_err(adjust, __stringify(name), \
10998                           "(expected %i, found %i)\n", \
10999                           current_config->name, \
11000                           pipe_config->name); \
11001                 ret = false; \
11002         }
11003
11004 #define PIPE_CONF_CHECK_BOOL(name)      \
11005         if (current_config->name != pipe_config->name) { \
11006                 pipe_config_err(adjust, __stringify(name), \
11007                           "(expected %s, found %s)\n", \
11008                           yesno(current_config->name), \
11009                           yesno(pipe_config->name)); \
11010                 ret = false; \
11011         }
11012
11013 /*
11014  * Checks state where we only read out the enabling, but not the entire
11015  * state itself (like full infoframes or ELD for audio). These states
11016  * require a full modeset on bootup to fix up.
11017  */
11018 #define PIPE_CONF_CHECK_BOOL_INCOMPLETE(name) \
11019         if (!fixup_inherited || (!current_config->name && !pipe_config->name)) { \
11020                 PIPE_CONF_CHECK_BOOL(name); \
11021         } else { \
11022                 pipe_config_err(adjust, __stringify(name), \
11023                           "unable to verify whether state matches exactly, forcing modeset (expected %s, found %s)\n", \
11024                           yesno(current_config->name), \
11025                           yesno(pipe_config->name)); \
11026                 ret = false; \
11027         }
11028
11029 #define PIPE_CONF_CHECK_P(name) \
11030         if (current_config->name != pipe_config->name) { \
11031                 pipe_config_err(adjust, __stringify(name), \
11032                           "(expected %p, found %p)\n", \
11033                           current_config->name, \
11034                           pipe_config->name); \
11035                 ret = false; \
11036         }
11037
11038 #define PIPE_CONF_CHECK_M_N(name) \
11039         if (!intel_compare_link_m_n(&current_config->name, \
11040                                     &pipe_config->name,\
11041                                     adjust)) { \
11042                 pipe_config_err(adjust, __stringify(name), \
11043                           "(expected tu %i gmch %i/%i link %i/%i, " \
11044                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11045                           current_config->name.tu, \
11046                           current_config->name.gmch_m, \
11047                           current_config->name.gmch_n, \
11048                           current_config->name.link_m, \
11049                           current_config->name.link_n, \
11050                           pipe_config->name.tu, \
11051                           pipe_config->name.gmch_m, \
11052                           pipe_config->name.gmch_n, \
11053                           pipe_config->name.link_m, \
11054                           pipe_config->name.link_n); \
11055                 ret = false; \
11056         }
11057
11058 /* This is required for BDW+ where there is only one set of registers for
11059  * switching between high and low RR.
11060  * This macro can be used whenever a comparison has to be made between one
11061  * hw state and multiple sw state variables.
11062  */
11063 #define PIPE_CONF_CHECK_M_N_ALT(name, alt_name) \
11064         if (!intel_compare_link_m_n(&current_config->name, \
11065                                     &pipe_config->name, adjust) && \
11066             !intel_compare_link_m_n(&current_config->alt_name, \
11067                                     &pipe_config->name, adjust)) { \
11068                 pipe_config_err(adjust, __stringify(name), \
11069                           "(expected tu %i gmch %i/%i link %i/%i, " \
11070                           "or tu %i gmch %i/%i link %i/%i, " \
11071                           "found tu %i, gmch %i/%i link %i/%i)\n", \
11072                           current_config->name.tu, \
11073                           current_config->name.gmch_m, \
11074                           current_config->name.gmch_n, \
11075                           current_config->name.link_m, \
11076                           current_config->name.link_n, \
11077                           current_config->alt_name.tu, \
11078                           current_config->alt_name.gmch_m, \
11079                           current_config->alt_name.gmch_n, \
11080                           current_config->alt_name.link_m, \
11081                           current_config->alt_name.link_n, \
11082                           pipe_config->name.tu, \
11083                           pipe_config->name.gmch_m, \
11084                           pipe_config->name.gmch_n, \
11085                           pipe_config->name.link_m, \
11086                           pipe_config->name.link_n); \
11087                 ret = false; \
11088         }
11089
11090 #define PIPE_CONF_CHECK_FLAGS(name, mask)       \
11091         if ((current_config->name ^ pipe_config->name) & (mask)) { \
11092                 pipe_config_err(adjust, __stringify(name), \
11093                           "(%x) (expected %i, found %i)\n", \
11094                           (mask), \
11095                           current_config->name & (mask), \
11096                           pipe_config->name & (mask)); \
11097                 ret = false; \
11098         }
11099
11100 #define PIPE_CONF_CHECK_CLOCK_FUZZY(name) \
11101         if (!intel_fuzzy_clock_check(current_config->name, pipe_config->name)) { \
11102                 pipe_config_err(adjust, __stringify(name), \
11103                           "(expected %i, found %i)\n", \
11104                           current_config->name, \
11105                           pipe_config->name); \
11106                 ret = false; \
11107         }
11108
11109 #define PIPE_CONF_QUIRK(quirk)  \
11110         ((current_config->quirks | pipe_config->quirks) & (quirk))
11111
11112         PIPE_CONF_CHECK_I(cpu_transcoder);
11113
11114         PIPE_CONF_CHECK_BOOL(has_pch_encoder);
11115         PIPE_CONF_CHECK_I(fdi_lanes);
11116         PIPE_CONF_CHECK_M_N(fdi_m_n);
11117
11118         PIPE_CONF_CHECK_I(lane_count);
11119         PIPE_CONF_CHECK_X(lane_lat_optim_mask);
11120
11121         if (INTEL_GEN(dev_priv) < 8) {
11122                 PIPE_CONF_CHECK_M_N(dp_m_n);
11123
11124                 if (current_config->has_drrs)
11125                         PIPE_CONF_CHECK_M_N(dp_m2_n2);
11126         } else
11127                 PIPE_CONF_CHECK_M_N_ALT(dp_m_n, dp_m2_n2);
11128
11129         PIPE_CONF_CHECK_X(output_types);
11130
11131         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hdisplay);
11132         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_htotal);
11133         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_start);
11134         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hblank_end);
11135         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_start);
11136         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_hsync_end);
11137
11138         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vdisplay);
11139         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vtotal);
11140         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_start);
11141         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vblank_end);
11142         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_start);
11143         PIPE_CONF_CHECK_I(base.adjusted_mode.crtc_vsync_end);
11144
11145         PIPE_CONF_CHECK_I(pixel_multiplier);
11146         PIPE_CONF_CHECK_BOOL(has_hdmi_sink);
11147         if ((INTEL_GEN(dev_priv) < 8 && !IS_HASWELL(dev_priv)) ||
11148             IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
11149                 PIPE_CONF_CHECK_BOOL(limited_color_range);
11150
11151         PIPE_CONF_CHECK_BOOL(hdmi_scrambling);
11152         PIPE_CONF_CHECK_BOOL(hdmi_high_tmds_clock_ratio);
11153         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_infoframe);
11154         PIPE_CONF_CHECK_BOOL(ycbcr420);
11155
11156         PIPE_CONF_CHECK_BOOL_INCOMPLETE(has_audio);
11157
11158         PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11159                               DRM_MODE_FLAG_INTERLACE);
11160
11161         if (!PIPE_CONF_QUIRK(PIPE_CONFIG_QUIRK_MODE_SYNC_FLAGS)) {
11162                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11163                                       DRM_MODE_FLAG_PHSYNC);
11164                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11165                                       DRM_MODE_FLAG_NHSYNC);
11166                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11167                                       DRM_MODE_FLAG_PVSYNC);
11168                 PIPE_CONF_CHECK_FLAGS(base.adjusted_mode.flags,
11169                                       DRM_MODE_FLAG_NVSYNC);
11170         }
11171
11172         PIPE_CONF_CHECK_X(gmch_pfit.control);
11173         /* pfit ratios are autocomputed by the hw on gen4+ */
11174         if (INTEL_GEN(dev_priv) < 4)
11175                 PIPE_CONF_CHECK_X(gmch_pfit.pgm_ratios);
11176         PIPE_CONF_CHECK_X(gmch_pfit.lvds_border_bits);
11177
11178         if (!adjust) {
11179                 PIPE_CONF_CHECK_I(pipe_src_w);
11180                 PIPE_CONF_CHECK_I(pipe_src_h);
11181
11182                 PIPE_CONF_CHECK_BOOL(pch_pfit.enabled);
11183                 if (current_config->pch_pfit.enabled) {
11184                         PIPE_CONF_CHECK_X(pch_pfit.pos);
11185                         PIPE_CONF_CHECK_X(pch_pfit.size);
11186                 }
11187
11188                 PIPE_CONF_CHECK_I(scaler_state.scaler_id);
11189                 PIPE_CONF_CHECK_CLOCK_FUZZY(pixel_rate);
11190         }
11191
11192         PIPE_CONF_CHECK_BOOL(double_wide);
11193
11194         PIPE_CONF_CHECK_P(shared_dpll);
11195         PIPE_CONF_CHECK_X(dpll_hw_state.dpll);
11196         PIPE_CONF_CHECK_X(dpll_hw_state.dpll_md);
11197         PIPE_CONF_CHECK_X(dpll_hw_state.fp0);
11198         PIPE_CONF_CHECK_X(dpll_hw_state.fp1);
11199         PIPE_CONF_CHECK_X(dpll_hw_state.wrpll);
11200         PIPE_CONF_CHECK_X(dpll_hw_state.spll);
11201         PIPE_CONF_CHECK_X(dpll_hw_state.ctrl1);
11202         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr1);
11203         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr2);
11204         PIPE_CONF_CHECK_X(dpll_hw_state.cfgcr0);
11205         PIPE_CONF_CHECK_X(dpll_hw_state.ebb0);
11206         PIPE_CONF_CHECK_X(dpll_hw_state.ebb4);
11207         PIPE_CONF_CHECK_X(dpll_hw_state.pll0);
11208         PIPE_CONF_CHECK_X(dpll_hw_state.pll1);
11209         PIPE_CONF_CHECK_X(dpll_hw_state.pll2);
11210         PIPE_CONF_CHECK_X(dpll_hw_state.pll3);
11211         PIPE_CONF_CHECK_X(dpll_hw_state.pll6);
11212         PIPE_CONF_CHECK_X(dpll_hw_state.pll8);
11213         PIPE_CONF_CHECK_X(dpll_hw_state.pll9);
11214         PIPE_CONF_CHECK_X(dpll_hw_state.pll10);
11215         PIPE_CONF_CHECK_X(dpll_hw_state.pcsdw12);
11216
11217         PIPE_CONF_CHECK_X(dsi_pll.ctrl);
11218         PIPE_CONF_CHECK_X(dsi_pll.div);
11219
11220         if (IS_G4X(dev_priv) || INTEL_GEN(dev_priv) >= 5)
11221                 PIPE_CONF_CHECK_I(pipe_bpp);
11222
11223         PIPE_CONF_CHECK_CLOCK_FUZZY(base.adjusted_mode.crtc_clock);
11224         PIPE_CONF_CHECK_CLOCK_FUZZY(port_clock);
11225
11226         PIPE_CONF_CHECK_I(min_voltage_level);
11227
11228 #undef PIPE_CONF_CHECK_X
11229 #undef PIPE_CONF_CHECK_I
11230 #undef PIPE_CONF_CHECK_BOOL
11231 #undef PIPE_CONF_CHECK_BOOL_INCOMPLETE
11232 #undef PIPE_CONF_CHECK_P
11233 #undef PIPE_CONF_CHECK_FLAGS
11234 #undef PIPE_CONF_CHECK_CLOCK_FUZZY
11235 #undef PIPE_CONF_QUIRK
11236
11237         return ret;
11238 }
11239
11240 static void intel_pipe_config_sanity_check(struct drm_i915_private *dev_priv,
11241                                            const struct intel_crtc_state *pipe_config)
11242 {
11243         if (pipe_config->has_pch_encoder) {
11244                 int fdi_dotclock = intel_dotclock_calculate(intel_fdi_link_freq(dev_priv, pipe_config),
11245                                                             &pipe_config->fdi_m_n);
11246                 int dotclock = pipe_config->base.adjusted_mode.crtc_clock;
11247
11248                 /*
11249                  * FDI already provided one idea for the dotclock.
11250                  * Yell if the encoder disagrees.
11251                  */
11252                 WARN(!intel_fuzzy_clock_check(fdi_dotclock, dotclock),
11253                      "FDI dotclock and encoder dotclock mismatch, fdi: %i, encoder: %i\n",
11254                      fdi_dotclock, dotclock);
11255         }
11256 }
11257
11258 static void verify_wm_state(struct drm_crtc *crtc,
11259                             struct drm_crtc_state *new_state)
11260 {
11261         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
11262         struct skl_ddb_allocation hw_ddb, *sw_ddb;
11263         struct skl_pipe_wm hw_wm, *sw_wm;
11264         struct skl_plane_wm *hw_plane_wm, *sw_plane_wm;
11265         struct skl_ddb_entry *hw_ddb_entry, *sw_ddb_entry;
11266         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11267         const enum pipe pipe = intel_crtc->pipe;
11268         int plane, level, max_level = ilk_wm_max_level(dev_priv);
11269
11270         if (INTEL_GEN(dev_priv) < 9 || !new_state->active)
11271                 return;
11272
11273         skl_pipe_wm_get_hw_state(crtc, &hw_wm);
11274         sw_wm = &to_intel_crtc_state(new_state)->wm.skl.optimal;
11275
11276         skl_ddb_get_hw_state(dev_priv, &hw_ddb);
11277         sw_ddb = &dev_priv->wm.skl_hw.ddb;
11278
11279         /* planes */
11280         for_each_universal_plane(dev_priv, pipe, plane) {
11281                 hw_plane_wm = &hw_wm.planes[plane];
11282                 sw_plane_wm = &sw_wm->planes[plane];
11283
11284                 /* Watermarks */
11285                 for (level = 0; level <= max_level; level++) {
11286                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11287                                                 &sw_plane_wm->wm[level]))
11288                                 continue;
11289
11290                         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",
11291                                   pipe_name(pipe), plane + 1, level,
11292                                   sw_plane_wm->wm[level].plane_en,
11293                                   sw_plane_wm->wm[level].plane_res_b,
11294                                   sw_plane_wm->wm[level].plane_res_l,
11295                                   hw_plane_wm->wm[level].plane_en,
11296                                   hw_plane_wm->wm[level].plane_res_b,
11297                                   hw_plane_wm->wm[level].plane_res_l);
11298                 }
11299
11300                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11301                                          &sw_plane_wm->trans_wm)) {
11302                         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",
11303                                   pipe_name(pipe), plane + 1,
11304                                   sw_plane_wm->trans_wm.plane_en,
11305                                   sw_plane_wm->trans_wm.plane_res_b,
11306                                   sw_plane_wm->trans_wm.plane_res_l,
11307                                   hw_plane_wm->trans_wm.plane_en,
11308                                   hw_plane_wm->trans_wm.plane_res_b,
11309                                   hw_plane_wm->trans_wm.plane_res_l);
11310                 }
11311
11312                 /* DDB */
11313                 hw_ddb_entry = &hw_ddb.plane[pipe][plane];
11314                 sw_ddb_entry = &sw_ddb->plane[pipe][plane];
11315
11316                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11317                         DRM_ERROR("mismatch in DDB state pipe %c plane %d (expected (%u,%u), found (%u,%u))\n",
11318                                   pipe_name(pipe), plane + 1,
11319                                   sw_ddb_entry->start, sw_ddb_entry->end,
11320                                   hw_ddb_entry->start, hw_ddb_entry->end);
11321                 }
11322         }
11323
11324         /*
11325          * cursor
11326          * If the cursor plane isn't active, we may not have updated it's ddb
11327          * allocation. In that case since the ddb allocation will be updated
11328          * once the plane becomes visible, we can skip this check
11329          */
11330         if (1) {
11331                 hw_plane_wm = &hw_wm.planes[PLANE_CURSOR];
11332                 sw_plane_wm = &sw_wm->planes[PLANE_CURSOR];
11333
11334                 /* Watermarks */
11335                 for (level = 0; level <= max_level; level++) {
11336                         if (skl_wm_level_equals(&hw_plane_wm->wm[level],
11337                                                 &sw_plane_wm->wm[level]))
11338                                 continue;
11339
11340                         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",
11341                                   pipe_name(pipe), level,
11342                                   sw_plane_wm->wm[level].plane_en,
11343                                   sw_plane_wm->wm[level].plane_res_b,
11344                                   sw_plane_wm->wm[level].plane_res_l,
11345                                   hw_plane_wm->wm[level].plane_en,
11346                                   hw_plane_wm->wm[level].plane_res_b,
11347                                   hw_plane_wm->wm[level].plane_res_l);
11348                 }
11349
11350                 if (!skl_wm_level_equals(&hw_plane_wm->trans_wm,
11351                                          &sw_plane_wm->trans_wm)) {
11352                         DRM_ERROR("mismatch in trans WM pipe %c cursor (expected e=%d b=%u l=%u, got e=%d b=%u l=%u)\n",
11353                                   pipe_name(pipe),
11354                                   sw_plane_wm->trans_wm.plane_en,
11355                                   sw_plane_wm->trans_wm.plane_res_b,
11356                                   sw_plane_wm->trans_wm.plane_res_l,
11357                                   hw_plane_wm->trans_wm.plane_en,
11358                                   hw_plane_wm->trans_wm.plane_res_b,
11359                                   hw_plane_wm->trans_wm.plane_res_l);
11360                 }
11361
11362                 /* DDB */
11363                 hw_ddb_entry = &hw_ddb.plane[pipe][PLANE_CURSOR];
11364                 sw_ddb_entry = &sw_ddb->plane[pipe][PLANE_CURSOR];
11365
11366                 if (!skl_ddb_entry_equal(hw_ddb_entry, sw_ddb_entry)) {
11367                         DRM_ERROR("mismatch in DDB state pipe %c cursor (expected (%u,%u), found (%u,%u))\n",
11368                                   pipe_name(pipe),
11369                                   sw_ddb_entry->start, sw_ddb_entry->end,
11370                                   hw_ddb_entry->start, hw_ddb_entry->end);
11371                 }
11372         }
11373 }
11374
11375 static void
11376 verify_connector_state(struct drm_device *dev,
11377                        struct drm_atomic_state *state,
11378                        struct drm_crtc *crtc)
11379 {
11380         struct drm_connector *connector;
11381         struct drm_connector_state *new_conn_state;
11382         int i;
11383
11384         for_each_new_connector_in_state(state, connector, new_conn_state, i) {
11385                 struct drm_encoder *encoder = connector->encoder;
11386                 struct drm_crtc_state *crtc_state = NULL;
11387
11388                 if (new_conn_state->crtc != crtc)
11389                         continue;
11390
11391                 if (crtc)
11392                         crtc_state = drm_atomic_get_new_crtc_state(state, new_conn_state->crtc);
11393
11394                 intel_connector_verify_state(crtc_state, new_conn_state);
11395
11396                 I915_STATE_WARN(new_conn_state->best_encoder != encoder,
11397                      "connector's atomic encoder doesn't match legacy encoder\n");
11398         }
11399 }
11400
11401 static void
11402 verify_encoder_state(struct drm_device *dev, struct drm_atomic_state *state)
11403 {
11404         struct intel_encoder *encoder;
11405         struct drm_connector *connector;
11406         struct drm_connector_state *old_conn_state, *new_conn_state;
11407         int i;
11408
11409         for_each_intel_encoder(dev, encoder) {
11410                 bool enabled = false, found = false;
11411                 enum pipe pipe;
11412
11413                 DRM_DEBUG_KMS("[ENCODER:%d:%s]\n",
11414                               encoder->base.base.id,
11415                               encoder->base.name);
11416
11417                 for_each_oldnew_connector_in_state(state, connector, old_conn_state,
11418                                                    new_conn_state, i) {
11419                         if (old_conn_state->best_encoder == &encoder->base)
11420                                 found = true;
11421
11422                         if (new_conn_state->best_encoder != &encoder->base)
11423                                 continue;
11424                         found = enabled = true;
11425
11426                         I915_STATE_WARN(new_conn_state->crtc !=
11427                                         encoder->base.crtc,
11428                              "connector's crtc doesn't match encoder crtc\n");
11429                 }
11430
11431                 if (!found)
11432                         continue;
11433
11434                 I915_STATE_WARN(!!encoder->base.crtc != enabled,
11435                      "encoder's enabled state mismatch "
11436                      "(expected %i, found %i)\n",
11437                      !!encoder->base.crtc, enabled);
11438
11439                 if (!encoder->base.crtc) {
11440                         bool active;
11441
11442                         active = encoder->get_hw_state(encoder, &pipe);
11443                         I915_STATE_WARN(active,
11444                              "encoder detached but still enabled on pipe %c.\n",
11445                              pipe_name(pipe));
11446                 }
11447         }
11448 }
11449
11450 static void
11451 verify_crtc_state(struct drm_crtc *crtc,
11452                   struct drm_crtc_state *old_crtc_state,
11453                   struct drm_crtc_state *new_crtc_state)
11454 {
11455         struct drm_device *dev = crtc->dev;
11456         struct drm_i915_private *dev_priv = to_i915(dev);
11457         struct intel_encoder *encoder;
11458         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11459         struct intel_crtc_state *pipe_config, *sw_config;
11460         struct drm_atomic_state *old_state;
11461         bool active;
11462
11463         old_state = old_crtc_state->state;
11464         __drm_atomic_helper_crtc_destroy_state(old_crtc_state);
11465         pipe_config = to_intel_crtc_state(old_crtc_state);
11466         memset(pipe_config, 0, sizeof(*pipe_config));
11467         pipe_config->base.crtc = crtc;
11468         pipe_config->base.state = old_state;
11469
11470         DRM_DEBUG_KMS("[CRTC:%d:%s]\n", crtc->base.id, crtc->name);
11471
11472         active = dev_priv->display.get_pipe_config(intel_crtc, pipe_config);
11473
11474         /* we keep both pipes enabled on 830 */
11475         if (IS_I830(dev_priv))
11476                 active = new_crtc_state->active;
11477
11478         I915_STATE_WARN(new_crtc_state->active != active,
11479              "crtc active state doesn't match with hw state "
11480              "(expected %i, found %i)\n", new_crtc_state->active, active);
11481
11482         I915_STATE_WARN(intel_crtc->active != new_crtc_state->active,
11483              "transitional active state does not match atomic hw state "
11484              "(expected %i, found %i)\n", new_crtc_state->active, intel_crtc->active);
11485
11486         for_each_encoder_on_crtc(dev, crtc, encoder) {
11487                 enum pipe pipe;
11488
11489                 active = encoder->get_hw_state(encoder, &pipe);
11490                 I915_STATE_WARN(active != new_crtc_state->active,
11491                         "[ENCODER:%i] active %i with crtc active %i\n",
11492                         encoder->base.base.id, active, new_crtc_state->active);
11493
11494                 I915_STATE_WARN(active && intel_crtc->pipe != pipe,
11495                                 "Encoder connected to wrong pipe %c\n",
11496                                 pipe_name(pipe));
11497
11498                 if (active)
11499                         encoder->get_config(encoder, pipe_config);
11500         }
11501
11502         intel_crtc_compute_pixel_rate(pipe_config);
11503
11504         if (!new_crtc_state->active)
11505                 return;
11506
11507         intel_pipe_config_sanity_check(dev_priv, pipe_config);
11508
11509         sw_config = to_intel_crtc_state(new_crtc_state);
11510         if (!intel_pipe_config_compare(dev_priv, sw_config,
11511                                        pipe_config, false)) {
11512                 I915_STATE_WARN(1, "pipe state doesn't match!\n");
11513                 intel_dump_pipe_config(intel_crtc, pipe_config,
11514                                        "[hw state]");
11515                 intel_dump_pipe_config(intel_crtc, sw_config,
11516                                        "[sw state]");
11517         }
11518 }
11519
11520 static void
11521 intel_verify_planes(struct intel_atomic_state *state)
11522 {
11523         struct intel_plane *plane;
11524         const struct intel_plane_state *plane_state;
11525         int i;
11526
11527         for_each_new_intel_plane_in_state(state, plane,
11528                                           plane_state, i)
11529                 assert_plane(plane, plane_state->base.visible);
11530 }
11531
11532 static void
11533 verify_single_dpll_state(struct drm_i915_private *dev_priv,
11534                          struct intel_shared_dpll *pll,
11535                          struct drm_crtc *crtc,
11536                          struct drm_crtc_state *new_state)
11537 {
11538         struct intel_dpll_hw_state dpll_hw_state;
11539         unsigned crtc_mask;
11540         bool active;
11541
11542         memset(&dpll_hw_state, 0, sizeof(dpll_hw_state));
11543
11544         DRM_DEBUG_KMS("%s\n", pll->name);
11545
11546         active = pll->funcs.get_hw_state(dev_priv, pll, &dpll_hw_state);
11547
11548         if (!(pll->flags & INTEL_DPLL_ALWAYS_ON)) {
11549                 I915_STATE_WARN(!pll->on && pll->active_mask,
11550                      "pll in active use but not on in sw tracking\n");
11551                 I915_STATE_WARN(pll->on && !pll->active_mask,
11552                      "pll is on but not used by any active crtc\n");
11553                 I915_STATE_WARN(pll->on != active,
11554                      "pll on state mismatch (expected %i, found %i)\n",
11555                      pll->on, active);
11556         }
11557
11558         if (!crtc) {
11559                 I915_STATE_WARN(pll->active_mask & ~pll->state.crtc_mask,
11560                                 "more active pll users than references: %x vs %x\n",
11561                                 pll->active_mask, pll->state.crtc_mask);
11562
11563                 return;
11564         }
11565
11566         crtc_mask = 1 << drm_crtc_index(crtc);
11567
11568         if (new_state->active)
11569                 I915_STATE_WARN(!(pll->active_mask & crtc_mask),
11570                                 "pll active mismatch (expected pipe %c in active mask 0x%02x)\n",
11571                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11572         else
11573                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11574                                 "pll active mismatch (didn't expect pipe %c in active mask 0x%02x)\n",
11575                                 pipe_name(drm_crtc_index(crtc)), pll->active_mask);
11576
11577         I915_STATE_WARN(!(pll->state.crtc_mask & crtc_mask),
11578                         "pll enabled crtcs mismatch (expected 0x%x in 0x%02x)\n",
11579                         crtc_mask, pll->state.crtc_mask);
11580
11581         I915_STATE_WARN(pll->on && memcmp(&pll->state.hw_state,
11582                                           &dpll_hw_state,
11583                                           sizeof(dpll_hw_state)),
11584                         "pll hw state mismatch\n");
11585 }
11586
11587 static void
11588 verify_shared_dpll_state(struct drm_device *dev, struct drm_crtc *crtc,
11589                          struct drm_crtc_state *old_crtc_state,
11590                          struct drm_crtc_state *new_crtc_state)
11591 {
11592         struct drm_i915_private *dev_priv = to_i915(dev);
11593         struct intel_crtc_state *old_state = to_intel_crtc_state(old_crtc_state);
11594         struct intel_crtc_state *new_state = to_intel_crtc_state(new_crtc_state);
11595
11596         if (new_state->shared_dpll)
11597                 verify_single_dpll_state(dev_priv, new_state->shared_dpll, crtc, new_crtc_state);
11598
11599         if (old_state->shared_dpll &&
11600             old_state->shared_dpll != new_state->shared_dpll) {
11601                 unsigned crtc_mask = 1 << drm_crtc_index(crtc);
11602                 struct intel_shared_dpll *pll = old_state->shared_dpll;
11603
11604                 I915_STATE_WARN(pll->active_mask & crtc_mask,
11605                                 "pll active mismatch (didn't expect pipe %c in active mask)\n",
11606                                 pipe_name(drm_crtc_index(crtc)));
11607                 I915_STATE_WARN(pll->state.crtc_mask & crtc_mask,
11608                                 "pll enabled crtcs mismatch (found %x in enabled mask)\n",
11609                                 pipe_name(drm_crtc_index(crtc)));
11610         }
11611 }
11612
11613 static void
11614 intel_modeset_verify_crtc(struct drm_crtc *crtc,
11615                           struct drm_atomic_state *state,
11616                           struct drm_crtc_state *old_state,
11617                           struct drm_crtc_state *new_state)
11618 {
11619         if (!needs_modeset(new_state) &&
11620             !to_intel_crtc_state(new_state)->update_pipe)
11621                 return;
11622
11623         verify_wm_state(crtc, new_state);
11624         verify_connector_state(crtc->dev, state, crtc);
11625         verify_crtc_state(crtc, old_state, new_state);
11626         verify_shared_dpll_state(crtc->dev, crtc, old_state, new_state);
11627 }
11628
11629 static void
11630 verify_disabled_dpll_state(struct drm_device *dev)
11631 {
11632         struct drm_i915_private *dev_priv = to_i915(dev);
11633         int i;
11634
11635         for (i = 0; i < dev_priv->num_shared_dpll; i++)
11636                 verify_single_dpll_state(dev_priv, &dev_priv->shared_dplls[i], NULL, NULL);
11637 }
11638
11639 static void
11640 intel_modeset_verify_disabled(struct drm_device *dev,
11641                               struct drm_atomic_state *state)
11642 {
11643         verify_encoder_state(dev, state);
11644         verify_connector_state(dev, state, NULL);
11645         verify_disabled_dpll_state(dev);
11646 }
11647
11648 static void update_scanline_offset(struct intel_crtc *crtc)
11649 {
11650         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
11651
11652         /*
11653          * The scanline counter increments at the leading edge of hsync.
11654          *
11655          * On most platforms it starts counting from vtotal-1 on the
11656          * first active line. That means the scanline counter value is
11657          * always one less than what we would expect. Ie. just after
11658          * start of vblank, which also occurs at start of hsync (on the
11659          * last active line), the scanline counter will read vblank_start-1.
11660          *
11661          * On gen2 the scanline counter starts counting from 1 instead
11662          * of vtotal-1, so we have to subtract one (or rather add vtotal-1
11663          * to keep the value positive), instead of adding one.
11664          *
11665          * On HSW+ the behaviour of the scanline counter depends on the output
11666          * type. For DP ports it behaves like most other platforms, but on HDMI
11667          * there's an extra 1 line difference. So we need to add two instead of
11668          * one to the value.
11669          *
11670          * On VLV/CHV DSI the scanline counter would appear to increment
11671          * approx. 1/3 of a scanline before start of vblank. Unfortunately
11672          * that means we can't tell whether we're in vblank or not while
11673          * we're on that particular line. We must still set scanline_offset
11674          * to 1 so that the vblank timestamps come out correct when we query
11675          * the scanline counter from within the vblank interrupt handler.
11676          * However if queried just before the start of vblank we'll get an
11677          * answer that's slightly in the future.
11678          */
11679         if (IS_GEN2(dev_priv)) {
11680                 const struct drm_display_mode *adjusted_mode = &crtc->config->base.adjusted_mode;
11681                 int vtotal;
11682
11683                 vtotal = adjusted_mode->crtc_vtotal;
11684                 if (adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
11685                         vtotal /= 2;
11686
11687                 crtc->scanline_offset = vtotal - 1;
11688         } else if (HAS_DDI(dev_priv) &&
11689                    intel_crtc_has_type(crtc->config, INTEL_OUTPUT_HDMI)) {
11690                 crtc->scanline_offset = 2;
11691         } else
11692                 crtc->scanline_offset = 1;
11693 }
11694
11695 static void intel_modeset_clear_plls(struct drm_atomic_state *state)
11696 {
11697         struct drm_device *dev = state->dev;
11698         struct drm_i915_private *dev_priv = to_i915(dev);
11699         struct drm_crtc *crtc;
11700         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11701         int i;
11702
11703         if (!dev_priv->display.crtc_compute_clock)
11704                 return;
11705
11706         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11707                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
11708                 struct intel_shared_dpll *old_dpll =
11709                         to_intel_crtc_state(old_crtc_state)->shared_dpll;
11710
11711                 if (!needs_modeset(new_crtc_state))
11712                         continue;
11713
11714                 to_intel_crtc_state(new_crtc_state)->shared_dpll = NULL;
11715
11716                 if (!old_dpll)
11717                         continue;
11718
11719                 intel_release_shared_dpll(old_dpll, intel_crtc, state);
11720         }
11721 }
11722
11723 /*
11724  * This implements the workaround described in the "notes" section of the mode
11725  * set sequence documentation. When going from no pipes or single pipe to
11726  * multiple pipes, and planes are enabled after the pipe, we need to wait at
11727  * least 2 vblanks on the first pipe before enabling planes on the second pipe.
11728  */
11729 static int haswell_mode_set_planes_workaround(struct drm_atomic_state *state)
11730 {
11731         struct drm_crtc_state *crtc_state;
11732         struct intel_crtc *intel_crtc;
11733         struct drm_crtc *crtc;
11734         struct intel_crtc_state *first_crtc_state = NULL;
11735         struct intel_crtc_state *other_crtc_state = NULL;
11736         enum pipe first_pipe = INVALID_PIPE, enabled_pipe = INVALID_PIPE;
11737         int i;
11738
11739         /* look at all crtc's that are going to be enabled in during modeset */
11740         for_each_new_crtc_in_state(state, crtc, crtc_state, i) {
11741                 intel_crtc = to_intel_crtc(crtc);
11742
11743                 if (!crtc_state->active || !needs_modeset(crtc_state))
11744                         continue;
11745
11746                 if (first_crtc_state) {
11747                         other_crtc_state = to_intel_crtc_state(crtc_state);
11748                         break;
11749                 } else {
11750                         first_crtc_state = to_intel_crtc_state(crtc_state);
11751                         first_pipe = intel_crtc->pipe;
11752                 }
11753         }
11754
11755         /* No workaround needed? */
11756         if (!first_crtc_state)
11757                 return 0;
11758
11759         /* w/a possibly needed, check how many crtc's are already enabled. */
11760         for_each_intel_crtc(state->dev, intel_crtc) {
11761                 struct intel_crtc_state *pipe_config;
11762
11763                 pipe_config = intel_atomic_get_crtc_state(state, intel_crtc);
11764                 if (IS_ERR(pipe_config))
11765                         return PTR_ERR(pipe_config);
11766
11767                 pipe_config->hsw_workaround_pipe = INVALID_PIPE;
11768
11769                 if (!pipe_config->base.active ||
11770                     needs_modeset(&pipe_config->base))
11771                         continue;
11772
11773                 /* 2 or more enabled crtcs means no need for w/a */
11774                 if (enabled_pipe != INVALID_PIPE)
11775                         return 0;
11776
11777                 enabled_pipe = intel_crtc->pipe;
11778         }
11779
11780         if (enabled_pipe != INVALID_PIPE)
11781                 first_crtc_state->hsw_workaround_pipe = enabled_pipe;
11782         else if (other_crtc_state)
11783                 other_crtc_state->hsw_workaround_pipe = first_pipe;
11784
11785         return 0;
11786 }
11787
11788 static int intel_lock_all_pipes(struct drm_atomic_state *state)
11789 {
11790         struct drm_crtc *crtc;
11791
11792         /* Add all pipes to the state */
11793         for_each_crtc(state->dev, crtc) {
11794                 struct drm_crtc_state *crtc_state;
11795
11796                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11797                 if (IS_ERR(crtc_state))
11798                         return PTR_ERR(crtc_state);
11799         }
11800
11801         return 0;
11802 }
11803
11804 static int intel_modeset_all_pipes(struct drm_atomic_state *state)
11805 {
11806         struct drm_crtc *crtc;
11807
11808         /*
11809          * Add all pipes to the state, and force
11810          * a modeset on all the active ones.
11811          */
11812         for_each_crtc(state->dev, crtc) {
11813                 struct drm_crtc_state *crtc_state;
11814                 int ret;
11815
11816                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
11817                 if (IS_ERR(crtc_state))
11818                         return PTR_ERR(crtc_state);
11819
11820                 if (!crtc_state->active || needs_modeset(crtc_state))
11821                         continue;
11822
11823                 crtc_state->mode_changed = true;
11824
11825                 ret = drm_atomic_add_affected_connectors(state, crtc);
11826                 if (ret)
11827                         return ret;
11828
11829                 ret = drm_atomic_add_affected_planes(state, crtc);
11830                 if (ret)
11831                         return ret;
11832         }
11833
11834         return 0;
11835 }
11836
11837 static int intel_modeset_checks(struct drm_atomic_state *state)
11838 {
11839         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
11840         struct drm_i915_private *dev_priv = to_i915(state->dev);
11841         struct drm_crtc *crtc;
11842         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11843         int ret = 0, i;
11844
11845         if (!check_digital_port_conflicts(state)) {
11846                 DRM_DEBUG_KMS("rejecting conflicting digital port configuration\n");
11847                 return -EINVAL;
11848         }
11849
11850         intel_state->modeset = true;
11851         intel_state->active_crtcs = dev_priv->active_crtcs;
11852         intel_state->cdclk.logical = dev_priv->cdclk.logical;
11853         intel_state->cdclk.actual = dev_priv->cdclk.actual;
11854
11855         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11856                 if (new_crtc_state->active)
11857                         intel_state->active_crtcs |= 1 << i;
11858                 else
11859                         intel_state->active_crtcs &= ~(1 << i);
11860
11861                 if (old_crtc_state->active != new_crtc_state->active)
11862                         intel_state->active_pipe_changes |= drm_crtc_mask(crtc);
11863         }
11864
11865         /*
11866          * See if the config requires any additional preparation, e.g.
11867          * to adjust global state with pipes off.  We need to do this
11868          * here so we can get the modeset_pipe updated config for the new
11869          * mode set on this crtc.  For other crtcs we need to use the
11870          * adjusted_mode bits in the crtc directly.
11871          */
11872         if (dev_priv->display.modeset_calc_cdclk) {
11873                 ret = dev_priv->display.modeset_calc_cdclk(state);
11874                 if (ret < 0)
11875                         return ret;
11876
11877                 /*
11878                  * Writes to dev_priv->cdclk.logical must protected by
11879                  * holding all the crtc locks, even if we don't end up
11880                  * touching the hardware
11881                  */
11882                 if (intel_cdclk_changed(&dev_priv->cdclk.logical,
11883                                         &intel_state->cdclk.logical)) {
11884                         ret = intel_lock_all_pipes(state);
11885                         if (ret < 0)
11886                                 return ret;
11887                 }
11888
11889                 /* All pipes must be switched off while we change the cdclk. */
11890                 if (intel_cdclk_needs_modeset(&dev_priv->cdclk.actual,
11891                                               &intel_state->cdclk.actual)) {
11892                         ret = intel_modeset_all_pipes(state);
11893                         if (ret < 0)
11894                                 return ret;
11895                 }
11896
11897                 DRM_DEBUG_KMS("New cdclk calculated to be logical %u kHz, actual %u kHz\n",
11898                               intel_state->cdclk.logical.cdclk,
11899                               intel_state->cdclk.actual.cdclk);
11900                 DRM_DEBUG_KMS("New voltage level calculated to be logical %u, actual %u\n",
11901                               intel_state->cdclk.logical.voltage_level,
11902                               intel_state->cdclk.actual.voltage_level);
11903         } else {
11904                 to_intel_atomic_state(state)->cdclk.logical = dev_priv->cdclk.logical;
11905         }
11906
11907         intel_modeset_clear_plls(state);
11908
11909         if (IS_HASWELL(dev_priv))
11910                 return haswell_mode_set_planes_workaround(state);
11911
11912         return 0;
11913 }
11914
11915 /*
11916  * Handle calculation of various watermark data at the end of the atomic check
11917  * phase.  The code here should be run after the per-crtc and per-plane 'check'
11918  * handlers to ensure that all derived state has been updated.
11919  */
11920 static int calc_watermark_data(struct drm_atomic_state *state)
11921 {
11922         struct drm_device *dev = state->dev;
11923         struct drm_i915_private *dev_priv = to_i915(dev);
11924
11925         /* Is there platform-specific watermark information to calculate? */
11926         if (dev_priv->display.compute_global_watermarks)
11927                 return dev_priv->display.compute_global_watermarks(state);
11928
11929         return 0;
11930 }
11931
11932 /**
11933  * intel_atomic_check - validate state object
11934  * @dev: drm device
11935  * @state: state to validate
11936  */
11937 static int intel_atomic_check(struct drm_device *dev,
11938                               struct drm_atomic_state *state)
11939 {
11940         struct drm_i915_private *dev_priv = to_i915(dev);
11941         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
11942         struct drm_crtc *crtc;
11943         struct drm_crtc_state *old_crtc_state, *crtc_state;
11944         int ret, i;
11945         bool any_ms = false;
11946
11947         ret = drm_atomic_helper_check_modeset(dev, state);
11948         if (ret)
11949                 return ret;
11950
11951         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, crtc_state, i) {
11952                 struct intel_crtc_state *pipe_config =
11953                         to_intel_crtc_state(crtc_state);
11954
11955                 /* Catch I915_MODE_FLAG_INHERITED */
11956                 if (crtc_state->mode.private_flags != old_crtc_state->mode.private_flags)
11957                         crtc_state->mode_changed = true;
11958
11959                 if (!needs_modeset(crtc_state))
11960                         continue;
11961
11962                 if (!crtc_state->enable) {
11963                         any_ms = true;
11964                         continue;
11965                 }
11966
11967                 /* FIXME: For only active_changed we shouldn't need to do any
11968                  * state recomputation at all. */
11969
11970                 ret = drm_atomic_add_affected_connectors(state, crtc);
11971                 if (ret)
11972                         return ret;
11973
11974                 ret = intel_modeset_pipe_config(crtc, pipe_config);
11975                 if (ret) {
11976                         intel_dump_pipe_config(to_intel_crtc(crtc),
11977                                                pipe_config, "[failed]");
11978                         return ret;
11979                 }
11980
11981                 if (i915_modparams.fastboot &&
11982                     intel_pipe_config_compare(dev_priv,
11983                                         to_intel_crtc_state(old_crtc_state),
11984                                         pipe_config, true)) {
11985                         crtc_state->mode_changed = false;
11986                         pipe_config->update_pipe = true;
11987                 }
11988
11989                 if (needs_modeset(crtc_state))
11990                         any_ms = true;
11991
11992                 ret = drm_atomic_add_affected_planes(state, crtc);
11993                 if (ret)
11994                         return ret;
11995
11996                 intel_dump_pipe_config(to_intel_crtc(crtc), pipe_config,
11997                                        needs_modeset(crtc_state) ?
11998                                        "[modeset]" : "[fastset]");
11999         }
12000
12001         if (any_ms) {
12002                 ret = intel_modeset_checks(state);
12003
12004                 if (ret)
12005                         return ret;
12006         } else {
12007                 intel_state->cdclk.logical = dev_priv->cdclk.logical;
12008         }
12009
12010         ret = drm_atomic_helper_check_planes(dev, state);
12011         if (ret)
12012                 return ret;
12013
12014         intel_fbc_choose_crtc(dev_priv, intel_state);
12015         return calc_watermark_data(state);
12016 }
12017
12018 static int intel_atomic_prepare_commit(struct drm_device *dev,
12019                                        struct drm_atomic_state *state)
12020 {
12021         return drm_atomic_helper_prepare_planes(dev, state);
12022 }
12023
12024 u32 intel_crtc_get_vblank_counter(struct intel_crtc *crtc)
12025 {
12026         struct drm_device *dev = crtc->base.dev;
12027
12028         if (!dev->max_vblank_count)
12029                 return drm_crtc_accurate_vblank_count(&crtc->base);
12030
12031         return dev->driver->get_vblank_counter(dev, crtc->pipe);
12032 }
12033
12034 static void intel_update_crtc(struct drm_crtc *crtc,
12035                               struct drm_atomic_state *state,
12036                               struct drm_crtc_state *old_crtc_state,
12037                               struct drm_crtc_state *new_crtc_state)
12038 {
12039         struct drm_device *dev = crtc->dev;
12040         struct drm_i915_private *dev_priv = to_i915(dev);
12041         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12042         struct intel_crtc_state *pipe_config = to_intel_crtc_state(new_crtc_state);
12043         bool modeset = needs_modeset(new_crtc_state);
12044
12045         if (modeset) {
12046                 update_scanline_offset(intel_crtc);
12047                 dev_priv->display.crtc_enable(pipe_config, state);
12048         } else {
12049                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12050                                        pipe_config);
12051         }
12052
12053         if (drm_atomic_get_existing_plane_state(state, crtc->primary)) {
12054                 intel_fbc_enable(
12055                     intel_crtc, pipe_config,
12056                     to_intel_plane_state(crtc->primary->state));
12057         }
12058
12059         drm_atomic_helper_commit_planes_on_crtc(old_crtc_state);
12060 }
12061
12062 static void intel_update_crtcs(struct drm_atomic_state *state)
12063 {
12064         struct drm_crtc *crtc;
12065         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12066         int i;
12067
12068         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12069                 if (!new_crtc_state->active)
12070                         continue;
12071
12072                 intel_update_crtc(crtc, state, old_crtc_state,
12073                                   new_crtc_state);
12074         }
12075 }
12076
12077 static void skl_update_crtcs(struct drm_atomic_state *state)
12078 {
12079         struct drm_i915_private *dev_priv = to_i915(state->dev);
12080         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12081         struct drm_crtc *crtc;
12082         struct intel_crtc *intel_crtc;
12083         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12084         struct intel_crtc_state *cstate;
12085         unsigned int updated = 0;
12086         bool progress;
12087         enum pipe pipe;
12088         int i;
12089
12090         const struct skl_ddb_entry *entries[I915_MAX_PIPES] = {};
12091
12092         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
12093                 /* ignore allocations for crtc's that have been turned off. */
12094                 if (new_crtc_state->active)
12095                         entries[i] = &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb;
12096
12097         /*
12098          * Whenever the number of active pipes changes, we need to make sure we
12099          * update the pipes in the right order so that their ddb allocations
12100          * never overlap with eachother inbetween CRTC updates. Otherwise we'll
12101          * cause pipe underruns and other bad stuff.
12102          */
12103         do {
12104                 progress = false;
12105
12106                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12107                         bool vbl_wait = false;
12108                         unsigned int cmask = drm_crtc_mask(crtc);
12109
12110                         intel_crtc = to_intel_crtc(crtc);
12111                         cstate = to_intel_crtc_state(new_crtc_state);
12112                         pipe = intel_crtc->pipe;
12113
12114                         if (updated & cmask || !cstate->base.active)
12115                                 continue;
12116
12117                         if (skl_ddb_allocation_overlaps(dev_priv,
12118                                                         entries,
12119                                                         &cstate->wm.skl.ddb,
12120                                                         i))
12121                                 continue;
12122
12123                         updated |= cmask;
12124                         entries[i] = &cstate->wm.skl.ddb;
12125
12126                         /*
12127                          * If this is an already active pipe, it's DDB changed,
12128                          * and this isn't the last pipe that needs updating
12129                          * then we need to wait for a vblank to pass for the
12130                          * new ddb allocation to take effect.
12131                          */
12132                         if (!skl_ddb_entry_equal(&cstate->wm.skl.ddb,
12133                                                  &to_intel_crtc_state(old_crtc_state)->wm.skl.ddb) &&
12134                             !new_crtc_state->active_changed &&
12135                             intel_state->wm_results.dirty_pipes != updated)
12136                                 vbl_wait = true;
12137
12138                         intel_update_crtc(crtc, state, old_crtc_state,
12139                                           new_crtc_state);
12140
12141                         if (vbl_wait)
12142                                 intel_wait_for_vblank(dev_priv, pipe);
12143
12144                         progress = true;
12145                 }
12146         } while (progress);
12147 }
12148
12149 static void intel_atomic_helper_free_state(struct drm_i915_private *dev_priv)
12150 {
12151         struct intel_atomic_state *state, *next;
12152         struct llist_node *freed;
12153
12154         freed = llist_del_all(&dev_priv->atomic_helper.free_list);
12155         llist_for_each_entry_safe(state, next, freed, freed)
12156                 drm_atomic_state_put(&state->base);
12157 }
12158
12159 static void intel_atomic_helper_free_state_worker(struct work_struct *work)
12160 {
12161         struct drm_i915_private *dev_priv =
12162                 container_of(work, typeof(*dev_priv), atomic_helper.free_work);
12163
12164         intel_atomic_helper_free_state(dev_priv);
12165 }
12166
12167 static void intel_atomic_commit_fence_wait(struct intel_atomic_state *intel_state)
12168 {
12169         struct wait_queue_entry wait_fence, wait_reset;
12170         struct drm_i915_private *dev_priv = to_i915(intel_state->base.dev);
12171
12172         init_wait_entry(&wait_fence, 0);
12173         init_wait_entry(&wait_reset, 0);
12174         for (;;) {
12175                 prepare_to_wait(&intel_state->commit_ready.wait,
12176                                 &wait_fence, TASK_UNINTERRUPTIBLE);
12177                 prepare_to_wait(&dev_priv->gpu_error.wait_queue,
12178                                 &wait_reset, TASK_UNINTERRUPTIBLE);
12179
12180
12181                 if (i915_sw_fence_done(&intel_state->commit_ready)
12182                     || test_bit(I915_RESET_MODESET, &dev_priv->gpu_error.flags))
12183                         break;
12184
12185                 schedule();
12186         }
12187         finish_wait(&intel_state->commit_ready.wait, &wait_fence);
12188         finish_wait(&dev_priv->gpu_error.wait_queue, &wait_reset);
12189 }
12190
12191 static void intel_atomic_commit_tail(struct drm_atomic_state *state)
12192 {
12193         struct drm_device *dev = state->dev;
12194         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12195         struct drm_i915_private *dev_priv = to_i915(dev);
12196         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12197         struct drm_crtc *crtc;
12198         struct intel_crtc_state *intel_cstate;
12199         u64 put_domains[I915_MAX_PIPES] = {};
12200         int i;
12201
12202         intel_atomic_commit_fence_wait(intel_state);
12203
12204         drm_atomic_helper_wait_for_dependencies(state);
12205
12206         if (intel_state->modeset)
12207                 intel_display_power_get(dev_priv, POWER_DOMAIN_MODESET);
12208
12209         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12210                 struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12211
12212                 if (needs_modeset(new_crtc_state) ||
12213                     to_intel_crtc_state(new_crtc_state)->update_pipe) {
12214
12215                         put_domains[to_intel_crtc(crtc)->pipe] =
12216                                 modeset_get_crtc_power_domains(crtc,
12217                                         to_intel_crtc_state(new_crtc_state));
12218                 }
12219
12220                 if (!needs_modeset(new_crtc_state))
12221                         continue;
12222
12223                 intel_pre_plane_update(to_intel_crtc_state(old_crtc_state),
12224                                        to_intel_crtc_state(new_crtc_state));
12225
12226                 if (old_crtc_state->active) {
12227                         intel_crtc_disable_planes(crtc, old_crtc_state->plane_mask);
12228                         dev_priv->display.crtc_disable(to_intel_crtc_state(old_crtc_state), state);
12229                         intel_crtc->active = false;
12230                         intel_fbc_disable(intel_crtc);
12231                         intel_disable_shared_dpll(intel_crtc);
12232
12233                         /*
12234                          * Underruns don't always raise
12235                          * interrupts, so check manually.
12236                          */
12237                         intel_check_cpu_fifo_underruns(dev_priv);
12238                         intel_check_pch_fifo_underruns(dev_priv);
12239
12240                         if (!new_crtc_state->active) {
12241                                 /*
12242                                  * Make sure we don't call initial_watermarks
12243                                  * for ILK-style watermark updates.
12244                                  *
12245                                  * No clue what this is supposed to achieve.
12246                                  */
12247                                 if (INTEL_GEN(dev_priv) >= 9)
12248                                         dev_priv->display.initial_watermarks(intel_state,
12249                                                                              to_intel_crtc_state(new_crtc_state));
12250                         }
12251                 }
12252         }
12253
12254         /* FIXME: Eventually get rid of our intel_crtc->config pointer */
12255         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
12256                 to_intel_crtc(crtc)->config = to_intel_crtc_state(new_crtc_state);
12257
12258         if (intel_state->modeset) {
12259                 drm_atomic_helper_update_legacy_modeset_state(state->dev, state);
12260
12261                 intel_set_cdclk(dev_priv, &dev_priv->cdclk.actual);
12262
12263                 /*
12264                  * SKL workaround: bspec recommends we disable the SAGV when we
12265                  * have more then one pipe enabled
12266                  */
12267                 if (!intel_can_enable_sagv(state))
12268                         intel_disable_sagv(dev_priv);
12269
12270                 intel_modeset_verify_disabled(dev, state);
12271         }
12272
12273         /* Complete the events for pipes that have now been disabled */
12274         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12275                 bool modeset = needs_modeset(new_crtc_state);
12276
12277                 /* Complete events for now disable pipes here. */
12278                 if (modeset && !new_crtc_state->active && new_crtc_state->event) {
12279                         spin_lock_irq(&dev->event_lock);
12280                         drm_crtc_send_vblank_event(crtc, new_crtc_state->event);
12281                         spin_unlock_irq(&dev->event_lock);
12282
12283                         new_crtc_state->event = NULL;
12284                 }
12285         }
12286
12287         /* Now enable the clocks, plane, pipe, and connectors that we set up. */
12288         dev_priv->display.update_crtcs(state);
12289
12290         /* FIXME: We should call drm_atomic_helper_commit_hw_done() here
12291          * already, but still need the state for the delayed optimization. To
12292          * fix this:
12293          * - wrap the optimization/post_plane_update stuff into a per-crtc work.
12294          * - schedule that vblank worker _before_ calling hw_done
12295          * - at the start of commit_tail, cancel it _synchrously
12296          * - switch over to the vblank wait helper in the core after that since
12297          *   we don't need out special handling any more.
12298          */
12299         drm_atomic_helper_wait_for_flip_done(dev, state);
12300
12301         /*
12302          * Now that the vblank has passed, we can go ahead and program the
12303          * optimal watermarks on platforms that need two-step watermark
12304          * programming.
12305          *
12306          * TODO: Move this (and other cleanup) to an async worker eventually.
12307          */
12308         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12309                 intel_cstate = to_intel_crtc_state(new_crtc_state);
12310
12311                 if (dev_priv->display.optimize_watermarks)
12312                         dev_priv->display.optimize_watermarks(intel_state,
12313                                                               intel_cstate);
12314         }
12315
12316         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12317                 intel_post_plane_update(to_intel_crtc_state(old_crtc_state));
12318
12319                 if (put_domains[i])
12320                         modeset_put_power_domains(dev_priv, put_domains[i]);
12321
12322                 intel_modeset_verify_crtc(crtc, state, old_crtc_state, new_crtc_state);
12323         }
12324
12325         if (intel_state->modeset)
12326                 intel_verify_planes(intel_state);
12327
12328         if (intel_state->modeset && intel_can_enable_sagv(state))
12329                 intel_enable_sagv(dev_priv);
12330
12331         drm_atomic_helper_commit_hw_done(state);
12332
12333         if (intel_state->modeset) {
12334                 /* As one of the primary mmio accessors, KMS has a high
12335                  * likelihood of triggering bugs in unclaimed access. After we
12336                  * finish modesetting, see if an error has been flagged, and if
12337                  * so enable debugging for the next modeset - and hope we catch
12338                  * the culprit.
12339                  */
12340                 intel_uncore_arm_unclaimed_mmio_detection(dev_priv);
12341                 intel_display_power_put(dev_priv, POWER_DOMAIN_MODESET);
12342         }
12343
12344         drm_atomic_helper_cleanup_planes(dev, state);
12345
12346         drm_atomic_helper_commit_cleanup_done(state);
12347
12348         drm_atomic_state_put(state);
12349
12350         intel_atomic_helper_free_state(dev_priv);
12351 }
12352
12353 static void intel_atomic_commit_work(struct work_struct *work)
12354 {
12355         struct drm_atomic_state *state =
12356                 container_of(work, struct drm_atomic_state, commit_work);
12357
12358         intel_atomic_commit_tail(state);
12359 }
12360
12361 static int __i915_sw_fence_call
12362 intel_atomic_commit_ready(struct i915_sw_fence *fence,
12363                           enum i915_sw_fence_notify notify)
12364 {
12365         struct intel_atomic_state *state =
12366                 container_of(fence, struct intel_atomic_state, commit_ready);
12367
12368         switch (notify) {
12369         case FENCE_COMPLETE:
12370                 /* we do blocking waits in the worker, nothing to do here */
12371                 break;
12372         case FENCE_FREE:
12373                 {
12374                         struct intel_atomic_helper *helper =
12375                                 &to_i915(state->base.dev)->atomic_helper;
12376
12377                         if (llist_add(&state->freed, &helper->free_list))
12378                                 schedule_work(&helper->free_work);
12379                         break;
12380                 }
12381         }
12382
12383         return NOTIFY_DONE;
12384 }
12385
12386 static void intel_atomic_track_fbs(struct drm_atomic_state *state)
12387 {
12388         struct drm_plane_state *old_plane_state, *new_plane_state;
12389         struct drm_plane *plane;
12390         int i;
12391
12392         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i)
12393                 i915_gem_track_fb(intel_fb_obj(old_plane_state->fb),
12394                                   intel_fb_obj(new_plane_state->fb),
12395                                   to_intel_plane(plane)->frontbuffer_bit);
12396 }
12397
12398 /**
12399  * intel_atomic_commit - commit validated state object
12400  * @dev: DRM device
12401  * @state: the top-level driver state object
12402  * @nonblock: nonblocking commit
12403  *
12404  * This function commits a top-level state object that has been validated
12405  * with drm_atomic_helper_check().
12406  *
12407  * RETURNS
12408  * Zero for success or -errno.
12409  */
12410 static int intel_atomic_commit(struct drm_device *dev,
12411                                struct drm_atomic_state *state,
12412                                bool nonblock)
12413 {
12414         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
12415         struct drm_i915_private *dev_priv = to_i915(dev);
12416         int ret = 0;
12417
12418         drm_atomic_state_get(state);
12419         i915_sw_fence_init(&intel_state->commit_ready,
12420                            intel_atomic_commit_ready);
12421
12422         /*
12423          * The intel_legacy_cursor_update() fast path takes care
12424          * of avoiding the vblank waits for simple cursor
12425          * movement and flips. For cursor on/off and size changes,
12426          * we want to perform the vblank waits so that watermark
12427          * updates happen during the correct frames. Gen9+ have
12428          * double buffered watermarks and so shouldn't need this.
12429          *
12430          * Unset state->legacy_cursor_update before the call to
12431          * drm_atomic_helper_setup_commit() because otherwise
12432          * drm_atomic_helper_wait_for_flip_done() is a noop and
12433          * we get FIFO underruns because we didn't wait
12434          * for vblank.
12435          *
12436          * FIXME doing watermarks and fb cleanup from a vblank worker
12437          * (assuming we had any) would solve these problems.
12438          */
12439         if (INTEL_GEN(dev_priv) < 9 && state->legacy_cursor_update) {
12440                 struct intel_crtc_state *new_crtc_state;
12441                 struct intel_crtc *crtc;
12442                 int i;
12443
12444                 for_each_new_intel_crtc_in_state(intel_state, crtc, new_crtc_state, i)
12445                         if (new_crtc_state->wm.need_postvbl_update ||
12446                             new_crtc_state->update_wm_post)
12447                                 state->legacy_cursor_update = false;
12448         }
12449
12450         ret = intel_atomic_prepare_commit(dev, state);
12451         if (ret) {
12452                 DRM_DEBUG_ATOMIC("Preparing state failed with %i\n", ret);
12453                 i915_sw_fence_commit(&intel_state->commit_ready);
12454                 return ret;
12455         }
12456
12457         ret = drm_atomic_helper_setup_commit(state, nonblock);
12458         if (!ret)
12459                 ret = drm_atomic_helper_swap_state(state, true);
12460
12461         if (ret) {
12462                 i915_sw_fence_commit(&intel_state->commit_ready);
12463
12464                 drm_atomic_helper_cleanup_planes(dev, state);
12465                 return ret;
12466         }
12467         dev_priv->wm.distrust_bios_wm = false;
12468         intel_shared_dpll_swap_state(state);
12469         intel_atomic_track_fbs(state);
12470
12471         if (intel_state->modeset) {
12472                 memcpy(dev_priv->min_cdclk, intel_state->min_cdclk,
12473                        sizeof(intel_state->min_cdclk));
12474                 memcpy(dev_priv->min_voltage_level,
12475                        intel_state->min_voltage_level,
12476                        sizeof(intel_state->min_voltage_level));
12477                 dev_priv->active_crtcs = intel_state->active_crtcs;
12478                 dev_priv->cdclk.logical = intel_state->cdclk.logical;
12479                 dev_priv->cdclk.actual = intel_state->cdclk.actual;
12480         }
12481
12482         drm_atomic_state_get(state);
12483         INIT_WORK(&state->commit_work, intel_atomic_commit_work);
12484
12485         i915_sw_fence_commit(&intel_state->commit_ready);
12486         if (nonblock && intel_state->modeset) {
12487                 queue_work(dev_priv->modeset_wq, &state->commit_work);
12488         } else if (nonblock) {
12489                 queue_work(system_unbound_wq, &state->commit_work);
12490         } else {
12491                 if (intel_state->modeset)
12492                         flush_workqueue(dev_priv->modeset_wq);
12493                 intel_atomic_commit_tail(state);
12494         }
12495
12496         return 0;
12497 }
12498
12499 static const struct drm_crtc_funcs intel_crtc_funcs = {
12500         .gamma_set = drm_atomic_helper_legacy_gamma_set,
12501         .set_config = drm_atomic_helper_set_config,
12502         .destroy = intel_crtc_destroy,
12503         .page_flip = drm_atomic_helper_page_flip,
12504         .atomic_duplicate_state = intel_crtc_duplicate_state,
12505         .atomic_destroy_state = intel_crtc_destroy_state,
12506         .set_crc_source = intel_crtc_set_crc_source,
12507 };
12508
12509 struct wait_rps_boost {
12510         struct wait_queue_entry wait;
12511
12512         struct drm_crtc *crtc;
12513         struct drm_i915_gem_request *request;
12514 };
12515
12516 static int do_rps_boost(struct wait_queue_entry *_wait,
12517                         unsigned mode, int sync, void *key)
12518 {
12519         struct wait_rps_boost *wait = container_of(_wait, typeof(*wait), wait);
12520         struct drm_i915_gem_request *rq = wait->request;
12521
12522         gen6_rps_boost(rq, NULL);
12523         i915_gem_request_put(rq);
12524
12525         drm_crtc_vblank_put(wait->crtc);
12526
12527         list_del(&wait->wait.entry);
12528         kfree(wait);
12529         return 1;
12530 }
12531
12532 static void add_rps_boost_after_vblank(struct drm_crtc *crtc,
12533                                        struct dma_fence *fence)
12534 {
12535         struct wait_rps_boost *wait;
12536
12537         if (!dma_fence_is_i915(fence))
12538                 return;
12539
12540         if (INTEL_GEN(to_i915(crtc->dev)) < 6)
12541                 return;
12542
12543         if (drm_crtc_vblank_get(crtc))
12544                 return;
12545
12546         wait = kmalloc(sizeof(*wait), GFP_KERNEL);
12547         if (!wait) {
12548                 drm_crtc_vblank_put(crtc);
12549                 return;
12550         }
12551
12552         wait->request = to_request(dma_fence_get(fence));
12553         wait->crtc = crtc;
12554
12555         wait->wait.func = do_rps_boost;
12556         wait->wait.flags = 0;
12557
12558         add_wait_queue(drm_crtc_vblank_waitqueue(crtc), &wait->wait);
12559 }
12560
12561 /**
12562  * intel_prepare_plane_fb - Prepare fb for usage on plane
12563  * @plane: drm plane to prepare for
12564  * @fb: framebuffer to prepare for presentation
12565  *
12566  * Prepares a framebuffer for usage on a display plane.  Generally this
12567  * involves pinning the underlying object and updating the frontbuffer tracking
12568  * bits.  Some older platforms need special physical address handling for
12569  * cursor planes.
12570  *
12571  * Must be called with struct_mutex held.
12572  *
12573  * Returns 0 on success, negative error code on failure.
12574  */
12575 int
12576 intel_prepare_plane_fb(struct drm_plane *plane,
12577                        struct drm_plane_state *new_state)
12578 {
12579         struct intel_atomic_state *intel_state =
12580                 to_intel_atomic_state(new_state->state);
12581         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12582         struct drm_framebuffer *fb = new_state->fb;
12583         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
12584         struct drm_i915_gem_object *old_obj = intel_fb_obj(plane->state->fb);
12585         int ret;
12586
12587         if (old_obj) {
12588                 struct drm_crtc_state *crtc_state =
12589                         drm_atomic_get_existing_crtc_state(new_state->state,
12590                                                            plane->state->crtc);
12591
12592                 /* Big Hammer, we also need to ensure that any pending
12593                  * MI_WAIT_FOR_EVENT inside a user batch buffer on the
12594                  * current scanout is retired before unpinning the old
12595                  * framebuffer. Note that we rely on userspace rendering
12596                  * into the buffer attached to the pipe they are waiting
12597                  * on. If not, userspace generates a GPU hang with IPEHR
12598                  * point to the MI_WAIT_FOR_EVENT.
12599                  *
12600                  * This should only fail upon a hung GPU, in which case we
12601                  * can safely continue.
12602                  */
12603                 if (needs_modeset(crtc_state)) {
12604                         ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12605                                                               old_obj->resv, NULL,
12606                                                               false, 0,
12607                                                               GFP_KERNEL);
12608                         if (ret < 0)
12609                                 return ret;
12610                 }
12611         }
12612
12613         if (new_state->fence) { /* explicit fencing */
12614                 ret = i915_sw_fence_await_dma_fence(&intel_state->commit_ready,
12615                                                     new_state->fence,
12616                                                     I915_FENCE_TIMEOUT,
12617                                                     GFP_KERNEL);
12618                 if (ret < 0)
12619                         return ret;
12620         }
12621
12622         if (!obj)
12623                 return 0;
12624
12625         ret = i915_gem_object_pin_pages(obj);
12626         if (ret)
12627                 return ret;
12628
12629         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
12630         if (ret) {
12631                 i915_gem_object_unpin_pages(obj);
12632                 return ret;
12633         }
12634
12635         if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12636             INTEL_INFO(dev_priv)->cursor_needs_physical) {
12637                 const int align = intel_cursor_alignment(dev_priv);
12638
12639                 ret = i915_gem_object_attach_phys(obj, align);
12640         } else {
12641                 struct i915_vma *vma;
12642
12643                 vma = intel_pin_and_fence_fb_obj(fb, new_state->rotation);
12644                 if (!IS_ERR(vma))
12645                         to_intel_plane_state(new_state)->vma = vma;
12646                 else
12647                         ret =  PTR_ERR(vma);
12648         }
12649
12650         i915_gem_object_wait_priority(obj, 0, I915_PRIORITY_DISPLAY);
12651
12652         mutex_unlock(&dev_priv->drm.struct_mutex);
12653         i915_gem_object_unpin_pages(obj);
12654         if (ret)
12655                 return ret;
12656
12657         if (!new_state->fence) { /* implicit fencing */
12658                 struct dma_fence *fence;
12659
12660                 ret = i915_sw_fence_await_reservation(&intel_state->commit_ready,
12661                                                       obj->resv, NULL,
12662                                                       false, I915_FENCE_TIMEOUT,
12663                                                       GFP_KERNEL);
12664                 if (ret < 0)
12665                         return ret;
12666
12667                 fence = reservation_object_get_excl_rcu(obj->resv);
12668                 if (fence) {
12669                         add_rps_boost_after_vblank(new_state->crtc, fence);
12670                         dma_fence_put(fence);
12671                 }
12672         } else {
12673                 add_rps_boost_after_vblank(new_state->crtc, new_state->fence);
12674         }
12675
12676         return 0;
12677 }
12678
12679 /**
12680  * intel_cleanup_plane_fb - Cleans up an fb after plane use
12681  * @plane: drm plane to clean up for
12682  * @fb: old framebuffer that was on plane
12683  *
12684  * Cleans up a framebuffer that has just been removed from a plane.
12685  *
12686  * Must be called with struct_mutex held.
12687  */
12688 void
12689 intel_cleanup_plane_fb(struct drm_plane *plane,
12690                        struct drm_plane_state *old_state)
12691 {
12692         struct i915_vma *vma;
12693
12694         /* Should only be called after a successful intel_prepare_plane_fb()! */
12695         vma = fetch_and_zero(&to_intel_plane_state(old_state)->vma);
12696         if (vma) {
12697                 mutex_lock(&plane->dev->struct_mutex);
12698                 intel_unpin_fb_vma(vma);
12699                 mutex_unlock(&plane->dev->struct_mutex);
12700         }
12701 }
12702
12703 int
12704 skl_max_scale(struct intel_crtc *intel_crtc, struct intel_crtc_state *crtc_state)
12705 {
12706         struct drm_i915_private *dev_priv;
12707         int max_scale;
12708         int crtc_clock, max_dotclk;
12709
12710         if (!intel_crtc || !crtc_state->base.enable)
12711                 return DRM_PLANE_HELPER_NO_SCALING;
12712
12713         dev_priv = to_i915(intel_crtc->base.dev);
12714
12715         crtc_clock = crtc_state->base.adjusted_mode.crtc_clock;
12716         max_dotclk = to_intel_atomic_state(crtc_state->base.state)->cdclk.logical.cdclk;
12717
12718         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 10)
12719                 max_dotclk *= 2;
12720
12721         if (WARN_ON_ONCE(!crtc_clock || max_dotclk < crtc_clock))
12722                 return DRM_PLANE_HELPER_NO_SCALING;
12723
12724         /*
12725          * skl max scale is lower of:
12726          *    close to 3 but not 3, -1 is for that purpose
12727          *            or
12728          *    cdclk/crtc_clock
12729          */
12730         max_scale = min((1 << 16) * 3 - 1,
12731                         (1 << 8) * ((max_dotclk << 8) / crtc_clock));
12732
12733         return max_scale;
12734 }
12735
12736 static int
12737 intel_check_primary_plane(struct intel_plane *plane,
12738                           struct intel_crtc_state *crtc_state,
12739                           struct intel_plane_state *state)
12740 {
12741         struct drm_i915_private *dev_priv = to_i915(plane->base.dev);
12742         struct drm_crtc *crtc = state->base.crtc;
12743         int min_scale = DRM_PLANE_HELPER_NO_SCALING;
12744         int max_scale = DRM_PLANE_HELPER_NO_SCALING;
12745         bool can_position = false;
12746         int ret;
12747
12748         if (INTEL_GEN(dev_priv) >= 9) {
12749                 /* use scaler when colorkey is not required */
12750                 if (state->ckey.flags == I915_SET_COLORKEY_NONE) {
12751                         min_scale = 1;
12752                         max_scale = skl_max_scale(to_intel_crtc(crtc), crtc_state);
12753                 }
12754                 can_position = true;
12755         }
12756
12757         ret = drm_atomic_helper_check_plane_state(&state->base,
12758                                                   &crtc_state->base,
12759                                                   &state->clip,
12760                                                   min_scale, max_scale,
12761                                                   can_position, true);
12762         if (ret)
12763                 return ret;
12764
12765         if (!state->base.fb)
12766                 return 0;
12767
12768         if (INTEL_GEN(dev_priv) >= 9) {
12769                 ret = skl_check_plane_surface(state);
12770                 if (ret)
12771                         return ret;
12772
12773                 state->ctl = skl_plane_ctl(crtc_state, state);
12774         } else {
12775                 ret = i9xx_check_plane_surface(state);
12776                 if (ret)
12777                         return ret;
12778
12779                 state->ctl = i9xx_plane_ctl(crtc_state, state);
12780         }
12781
12782         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
12783                 state->color_ctl = glk_plane_color_ctl(crtc_state, state);
12784
12785         return 0;
12786 }
12787
12788 static void intel_begin_crtc_commit(struct drm_crtc *crtc,
12789                                     struct drm_crtc_state *old_crtc_state)
12790 {
12791         struct drm_device *dev = crtc->dev;
12792         struct drm_i915_private *dev_priv = to_i915(dev);
12793         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12794         struct intel_crtc_state *old_intel_cstate =
12795                 to_intel_crtc_state(old_crtc_state);
12796         struct intel_atomic_state *old_intel_state =
12797                 to_intel_atomic_state(old_crtc_state->state);
12798         struct intel_crtc_state *intel_cstate =
12799                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
12800         bool modeset = needs_modeset(&intel_cstate->base);
12801
12802         if (!modeset &&
12803             (intel_cstate->base.color_mgmt_changed ||
12804              intel_cstate->update_pipe)) {
12805                 intel_color_set_csc(&intel_cstate->base);
12806                 intel_color_load_luts(&intel_cstate->base);
12807         }
12808
12809         /* Perform vblank evasion around commit operation */
12810         intel_pipe_update_start(intel_cstate);
12811
12812         if (modeset)
12813                 goto out;
12814
12815         if (intel_cstate->update_pipe)
12816                 intel_update_pipe_config(old_intel_cstate, intel_cstate);
12817         else if (INTEL_GEN(dev_priv) >= 9)
12818                 skl_detach_scalers(intel_crtc);
12819
12820 out:
12821         if (dev_priv->display.atomic_update_watermarks)
12822                 dev_priv->display.atomic_update_watermarks(old_intel_state,
12823                                                            intel_cstate);
12824 }
12825
12826 static void intel_finish_crtc_commit(struct drm_crtc *crtc,
12827                                      struct drm_crtc_state *old_crtc_state)
12828 {
12829         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12830         struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
12831         struct intel_atomic_state *old_intel_state =
12832                 to_intel_atomic_state(old_crtc_state->state);
12833         struct intel_crtc_state *new_crtc_state =
12834                 intel_atomic_get_new_crtc_state(old_intel_state, intel_crtc);
12835
12836         intel_pipe_update_end(new_crtc_state);
12837
12838         if (new_crtc_state->update_pipe &&
12839             !needs_modeset(&new_crtc_state->base) &&
12840             old_crtc_state->mode.private_flags & I915_MODE_FLAG_INHERITED) {
12841                 if (!IS_GEN2(dev_priv))
12842                         intel_set_cpu_fifo_underrun_reporting(dev_priv, intel_crtc->pipe, true);
12843
12844                 if (new_crtc_state->has_pch_encoder) {
12845                         enum pipe pch_transcoder =
12846                                 intel_crtc_pch_transcoder(intel_crtc);
12847
12848                         intel_set_pch_fifo_underrun_reporting(dev_priv, pch_transcoder, true);
12849                 }
12850         }
12851 }
12852
12853 /**
12854  * intel_plane_destroy - destroy a plane
12855  * @plane: plane to destroy
12856  *
12857  * Common destruction function for all types of planes (primary, cursor,
12858  * sprite).
12859  */
12860 void intel_plane_destroy(struct drm_plane *plane)
12861 {
12862         drm_plane_cleanup(plane);
12863         kfree(to_intel_plane(plane));
12864 }
12865
12866 static bool i8xx_mod_supported(uint32_t format, uint64_t modifier)
12867 {
12868         switch (format) {
12869         case DRM_FORMAT_C8:
12870         case DRM_FORMAT_RGB565:
12871         case DRM_FORMAT_XRGB1555:
12872         case DRM_FORMAT_XRGB8888:
12873                 return modifier == DRM_FORMAT_MOD_LINEAR ||
12874                         modifier == I915_FORMAT_MOD_X_TILED;
12875         default:
12876                 return false;
12877         }
12878 }
12879
12880 static bool i965_mod_supported(uint32_t format, uint64_t modifier)
12881 {
12882         switch (format) {
12883         case DRM_FORMAT_C8:
12884         case DRM_FORMAT_RGB565:
12885         case DRM_FORMAT_XRGB8888:
12886         case DRM_FORMAT_XBGR8888:
12887         case DRM_FORMAT_XRGB2101010:
12888         case DRM_FORMAT_XBGR2101010:
12889                 return modifier == DRM_FORMAT_MOD_LINEAR ||
12890                         modifier == I915_FORMAT_MOD_X_TILED;
12891         default:
12892                 return false;
12893         }
12894 }
12895
12896 static bool skl_mod_supported(uint32_t format, uint64_t modifier)
12897 {
12898         switch (format) {
12899         case DRM_FORMAT_XRGB8888:
12900         case DRM_FORMAT_XBGR8888:
12901         case DRM_FORMAT_ARGB8888:
12902         case DRM_FORMAT_ABGR8888:
12903                 if (modifier == I915_FORMAT_MOD_Yf_TILED_CCS ||
12904                     modifier == I915_FORMAT_MOD_Y_TILED_CCS)
12905                         return true;
12906                 /* fall through */
12907         case DRM_FORMAT_RGB565:
12908         case DRM_FORMAT_XRGB2101010:
12909         case DRM_FORMAT_XBGR2101010:
12910         case DRM_FORMAT_YUYV:
12911         case DRM_FORMAT_YVYU:
12912         case DRM_FORMAT_UYVY:
12913         case DRM_FORMAT_VYUY:
12914                 if (modifier == I915_FORMAT_MOD_Yf_TILED)
12915                         return true;
12916                 /* fall through */
12917         case DRM_FORMAT_C8:
12918                 if (modifier == DRM_FORMAT_MOD_LINEAR ||
12919                     modifier == I915_FORMAT_MOD_X_TILED ||
12920                     modifier == I915_FORMAT_MOD_Y_TILED)
12921                         return true;
12922                 /* fall through */
12923         default:
12924                 return false;
12925         }
12926 }
12927
12928 static bool intel_primary_plane_format_mod_supported(struct drm_plane *plane,
12929                                                      uint32_t format,
12930                                                      uint64_t modifier)
12931 {
12932         struct drm_i915_private *dev_priv = to_i915(plane->dev);
12933
12934         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
12935                 return false;
12936
12937         if ((modifier >> 56) != DRM_FORMAT_MOD_VENDOR_INTEL &&
12938             modifier != DRM_FORMAT_MOD_LINEAR)
12939                 return false;
12940
12941         if (INTEL_GEN(dev_priv) >= 9)
12942                 return skl_mod_supported(format, modifier);
12943         else if (INTEL_GEN(dev_priv) >= 4)
12944                 return i965_mod_supported(format, modifier);
12945         else
12946                 return i8xx_mod_supported(format, modifier);
12947
12948         unreachable();
12949 }
12950
12951 static bool intel_cursor_plane_format_mod_supported(struct drm_plane *plane,
12952                                                     uint32_t format,
12953                                                     uint64_t modifier)
12954 {
12955         if (WARN_ON(modifier == DRM_FORMAT_MOD_INVALID))
12956                 return false;
12957
12958         return modifier == DRM_FORMAT_MOD_LINEAR && format == DRM_FORMAT_ARGB8888;
12959 }
12960
12961 static struct drm_plane_funcs intel_plane_funcs = {
12962         .update_plane = drm_atomic_helper_update_plane,
12963         .disable_plane = drm_atomic_helper_disable_plane,
12964         .destroy = intel_plane_destroy,
12965         .atomic_get_property = intel_plane_atomic_get_property,
12966         .atomic_set_property = intel_plane_atomic_set_property,
12967         .atomic_duplicate_state = intel_plane_duplicate_state,
12968         .atomic_destroy_state = intel_plane_destroy_state,
12969         .format_mod_supported = intel_primary_plane_format_mod_supported,
12970 };
12971
12972 static int
12973 intel_legacy_cursor_update(struct drm_plane *plane,
12974                            struct drm_crtc *crtc,
12975                            struct drm_framebuffer *fb,
12976                            int crtc_x, int crtc_y,
12977                            unsigned int crtc_w, unsigned int crtc_h,
12978                            uint32_t src_x, uint32_t src_y,
12979                            uint32_t src_w, uint32_t src_h,
12980                            struct drm_modeset_acquire_ctx *ctx)
12981 {
12982         struct drm_i915_private *dev_priv = to_i915(crtc->dev);
12983         int ret;
12984         struct drm_plane_state *old_plane_state, *new_plane_state;
12985         struct intel_plane *intel_plane = to_intel_plane(plane);
12986         struct drm_framebuffer *old_fb;
12987         struct drm_crtc_state *crtc_state = crtc->state;
12988         struct i915_vma *old_vma, *vma;
12989
12990         /*
12991          * When crtc is inactive or there is a modeset pending,
12992          * wait for it to complete in the slowpath
12993          */
12994         if (!crtc_state->active || needs_modeset(crtc_state) ||
12995             to_intel_crtc_state(crtc_state)->update_pipe)
12996                 goto slow;
12997
12998         old_plane_state = plane->state;
12999         /*
13000          * Don't do an async update if there is an outstanding commit modifying
13001          * the plane.  This prevents our async update's changes from getting
13002          * overridden by a previous synchronous update's state.
13003          */
13004         if (old_plane_state->commit &&
13005             !try_wait_for_completion(&old_plane_state->commit->hw_done))
13006                 goto slow;
13007
13008         /*
13009          * If any parameters change that may affect watermarks,
13010          * take the slowpath. Only changing fb or position should be
13011          * in the fastpath.
13012          */
13013         if (old_plane_state->crtc != crtc ||
13014             old_plane_state->src_w != src_w ||
13015             old_plane_state->src_h != src_h ||
13016             old_plane_state->crtc_w != crtc_w ||
13017             old_plane_state->crtc_h != crtc_h ||
13018             !old_plane_state->fb != !fb)
13019                 goto slow;
13020
13021         new_plane_state = intel_plane_duplicate_state(plane);
13022         if (!new_plane_state)
13023                 return -ENOMEM;
13024
13025         drm_atomic_set_fb_for_plane(new_plane_state, fb);
13026
13027         new_plane_state->src_x = src_x;
13028         new_plane_state->src_y = src_y;
13029         new_plane_state->src_w = src_w;
13030         new_plane_state->src_h = src_h;
13031         new_plane_state->crtc_x = crtc_x;
13032         new_plane_state->crtc_y = crtc_y;
13033         new_plane_state->crtc_w = crtc_w;
13034         new_plane_state->crtc_h = crtc_h;
13035
13036         ret = intel_plane_atomic_check_with_state(to_intel_crtc_state(crtc->state),
13037                                                   to_intel_crtc_state(crtc->state), /* FIXME need a new crtc state? */
13038                                                   to_intel_plane_state(plane->state),
13039                                                   to_intel_plane_state(new_plane_state));
13040         if (ret)
13041                 goto out_free;
13042
13043         ret = mutex_lock_interruptible(&dev_priv->drm.struct_mutex);
13044         if (ret)
13045                 goto out_free;
13046
13047         if (INTEL_INFO(dev_priv)->cursor_needs_physical) {
13048                 int align = intel_cursor_alignment(dev_priv);
13049
13050                 ret = i915_gem_object_attach_phys(intel_fb_obj(fb), align);
13051                 if (ret) {
13052                         DRM_DEBUG_KMS("failed to attach phys object\n");
13053                         goto out_unlock;
13054                 }
13055         } else {
13056                 vma = intel_pin_and_fence_fb_obj(fb, new_plane_state->rotation);
13057                 if (IS_ERR(vma)) {
13058                         DRM_DEBUG_KMS("failed to pin object\n");
13059
13060                         ret = PTR_ERR(vma);
13061                         goto out_unlock;
13062                 }
13063
13064                 to_intel_plane_state(new_plane_state)->vma = vma;
13065         }
13066
13067         old_fb = old_plane_state->fb;
13068
13069         i915_gem_track_fb(intel_fb_obj(old_fb), intel_fb_obj(fb),
13070                           intel_plane->frontbuffer_bit);
13071
13072         /* Swap plane state */
13073         plane->state = new_plane_state;
13074
13075         if (plane->state->visible) {
13076                 trace_intel_update_plane(plane, to_intel_crtc(crtc));
13077                 intel_plane->update_plane(intel_plane,
13078                                           to_intel_crtc_state(crtc->state),
13079                                           to_intel_plane_state(plane->state));
13080         } else {
13081                 trace_intel_disable_plane(plane, to_intel_crtc(crtc));
13082                 intel_plane->disable_plane(intel_plane, to_intel_crtc(crtc));
13083         }
13084
13085         old_vma = fetch_and_zero(&to_intel_plane_state(old_plane_state)->vma);
13086         if (old_vma)
13087                 intel_unpin_fb_vma(old_vma);
13088
13089 out_unlock:
13090         mutex_unlock(&dev_priv->drm.struct_mutex);
13091 out_free:
13092         if (ret)
13093                 intel_plane_destroy_state(plane, new_plane_state);
13094         else
13095                 intel_plane_destroy_state(plane, old_plane_state);
13096         return ret;
13097
13098 slow:
13099         return drm_atomic_helper_update_plane(plane, crtc, fb,
13100                                               crtc_x, crtc_y, crtc_w, crtc_h,
13101                                               src_x, src_y, src_w, src_h, ctx);
13102 }
13103
13104 static const struct drm_plane_funcs intel_cursor_plane_funcs = {
13105         .update_plane = intel_legacy_cursor_update,
13106         .disable_plane = drm_atomic_helper_disable_plane,
13107         .destroy = intel_plane_destroy,
13108         .atomic_get_property = intel_plane_atomic_get_property,
13109         .atomic_set_property = intel_plane_atomic_set_property,
13110         .atomic_duplicate_state = intel_plane_duplicate_state,
13111         .atomic_destroy_state = intel_plane_destroy_state,
13112         .format_mod_supported = intel_cursor_plane_format_mod_supported,
13113 };
13114
13115 static struct intel_plane *
13116 intel_primary_plane_create(struct drm_i915_private *dev_priv, enum pipe pipe)
13117 {
13118         struct intel_plane *primary = NULL;
13119         struct intel_plane_state *state = NULL;
13120         const uint32_t *intel_primary_formats;
13121         unsigned int supported_rotations;
13122         unsigned int num_formats;
13123         const uint64_t *modifiers;
13124         int ret;
13125
13126         primary = kzalloc(sizeof(*primary), GFP_KERNEL);
13127         if (!primary) {
13128                 ret = -ENOMEM;
13129                 goto fail;
13130         }
13131
13132         state = intel_create_plane_state(&primary->base);
13133         if (!state) {
13134                 ret = -ENOMEM;
13135                 goto fail;
13136         }
13137
13138         primary->base.state = &state->base;
13139
13140         primary->can_scale = false;
13141         primary->max_downscale = 1;
13142         if (INTEL_GEN(dev_priv) >= 9) {
13143                 primary->can_scale = true;
13144                 state->scaler_id = -1;
13145         }
13146         primary->pipe = pipe;
13147         /*
13148          * On gen2/3 only plane A can do FBC, but the panel fitter and LVDS
13149          * port is hooked to pipe B. Hence we want plane A feeding pipe B.
13150          */
13151         if (HAS_FBC(dev_priv) && INTEL_GEN(dev_priv) < 4)
13152                 primary->i9xx_plane = (enum i9xx_plane_id) !pipe;
13153         else
13154                 primary->i9xx_plane = (enum i9xx_plane_id) pipe;
13155         primary->id = PLANE_PRIMARY;
13156         primary->frontbuffer_bit = INTEL_FRONTBUFFER_PRIMARY(pipe);
13157         primary->check_plane = intel_check_primary_plane;
13158
13159         if (INTEL_GEN(dev_priv) >= 10) {
13160                 intel_primary_formats = skl_primary_formats;
13161                 num_formats = ARRAY_SIZE(skl_primary_formats);
13162                 modifiers = skl_format_modifiers_ccs;
13163
13164                 primary->update_plane = skl_update_plane;
13165                 primary->disable_plane = skl_disable_plane;
13166                 primary->get_hw_state = skl_plane_get_hw_state;
13167         } else if (INTEL_GEN(dev_priv) >= 9) {
13168                 intel_primary_formats = skl_primary_formats;
13169                 num_formats = ARRAY_SIZE(skl_primary_formats);
13170                 if (pipe < PIPE_C)
13171                         modifiers = skl_format_modifiers_ccs;
13172                 else
13173                         modifiers = skl_format_modifiers_noccs;
13174
13175                 primary->update_plane = skl_update_plane;
13176                 primary->disable_plane = skl_disable_plane;
13177                 primary->get_hw_state = skl_plane_get_hw_state;
13178         } else if (INTEL_GEN(dev_priv) >= 4) {
13179                 intel_primary_formats = i965_primary_formats;
13180                 num_formats = ARRAY_SIZE(i965_primary_formats);
13181                 modifiers = i9xx_format_modifiers;
13182
13183                 primary->update_plane = i9xx_update_plane;
13184                 primary->disable_plane = i9xx_disable_plane;
13185                 primary->get_hw_state = i9xx_plane_get_hw_state;
13186         } else {
13187                 intel_primary_formats = i8xx_primary_formats;
13188                 num_formats = ARRAY_SIZE(i8xx_primary_formats);
13189                 modifiers = i9xx_format_modifiers;
13190
13191                 primary->update_plane = i9xx_update_plane;
13192                 primary->disable_plane = i9xx_disable_plane;
13193                 primary->get_hw_state = i9xx_plane_get_hw_state;
13194         }
13195
13196         if (INTEL_GEN(dev_priv) >= 9)
13197                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13198                                                0, &intel_plane_funcs,
13199                                                intel_primary_formats, num_formats,
13200                                                modifiers,
13201                                                DRM_PLANE_TYPE_PRIMARY,
13202                                                "plane 1%c", pipe_name(pipe));
13203         else if (INTEL_GEN(dev_priv) >= 5 || IS_G4X(dev_priv))
13204                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13205                                                0, &intel_plane_funcs,
13206                                                intel_primary_formats, num_formats,
13207                                                modifiers,
13208                                                DRM_PLANE_TYPE_PRIMARY,
13209                                                "primary %c", pipe_name(pipe));
13210         else
13211                 ret = drm_universal_plane_init(&dev_priv->drm, &primary->base,
13212                                                0, &intel_plane_funcs,
13213                                                intel_primary_formats, num_formats,
13214                                                modifiers,
13215                                                DRM_PLANE_TYPE_PRIMARY,
13216                                                "plane %c",
13217                                                plane_name(primary->i9xx_plane));
13218         if (ret)
13219                 goto fail;
13220
13221         if (INTEL_GEN(dev_priv) >= 10) {
13222                 supported_rotations =
13223                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13224                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270 |
13225                         DRM_MODE_REFLECT_X;
13226         } else if (INTEL_GEN(dev_priv) >= 9) {
13227                 supported_rotations =
13228                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_90 |
13229                         DRM_MODE_ROTATE_180 | DRM_MODE_ROTATE_270;
13230         } else if (IS_CHERRYVIEW(dev_priv) && pipe == PIPE_B) {
13231                 supported_rotations =
13232                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180 |
13233                         DRM_MODE_REFLECT_X;
13234         } else if (INTEL_GEN(dev_priv) >= 4) {
13235                 supported_rotations =
13236                         DRM_MODE_ROTATE_0 | DRM_MODE_ROTATE_180;
13237         } else {
13238                 supported_rotations = DRM_MODE_ROTATE_0;
13239         }
13240
13241         if (INTEL_GEN(dev_priv) >= 4)
13242                 drm_plane_create_rotation_property(&primary->base,
13243                                                    DRM_MODE_ROTATE_0,
13244                                                    supported_rotations);
13245
13246         drm_plane_helper_add(&primary->base, &intel_plane_helper_funcs);
13247
13248         return primary;
13249
13250 fail:
13251         kfree(state);
13252         kfree(primary);
13253
13254         return ERR_PTR(ret);
13255 }
13256
13257 static struct intel_plane *
13258 intel_cursor_plane_create(struct drm_i915_private *dev_priv,
13259                           enum pipe pipe)
13260 {
13261         struct intel_plane *cursor = NULL;
13262         struct intel_plane_state *state = NULL;
13263         int ret;
13264
13265         cursor = kzalloc(sizeof(*cursor), GFP_KERNEL);
13266         if (!cursor) {
13267                 ret = -ENOMEM;
13268                 goto fail;
13269         }
13270
13271         state = intel_create_plane_state(&cursor->base);
13272         if (!state) {
13273                 ret = -ENOMEM;
13274                 goto fail;
13275         }
13276
13277         cursor->base.state = &state->base;
13278
13279         cursor->can_scale = false;
13280         cursor->max_downscale = 1;
13281         cursor->pipe = pipe;
13282         cursor->i9xx_plane = (enum i9xx_plane_id) pipe;
13283         cursor->id = PLANE_CURSOR;
13284         cursor->frontbuffer_bit = INTEL_FRONTBUFFER_CURSOR(pipe);
13285
13286         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
13287                 cursor->update_plane = i845_update_cursor;
13288                 cursor->disable_plane = i845_disable_cursor;
13289                 cursor->get_hw_state = i845_cursor_get_hw_state;
13290                 cursor->check_plane = i845_check_cursor;
13291         } else {
13292                 cursor->update_plane = i9xx_update_cursor;
13293                 cursor->disable_plane = i9xx_disable_cursor;
13294                 cursor->get_hw_state = i9xx_cursor_get_hw_state;
13295                 cursor->check_plane = i9xx_check_cursor;
13296         }
13297
13298         cursor->cursor.base = ~0;
13299         cursor->cursor.cntl = ~0;
13300
13301         if (IS_I845G(dev_priv) || IS_I865G(dev_priv) || HAS_CUR_FBC(dev_priv))
13302                 cursor->cursor.size = ~0;
13303
13304         ret = drm_universal_plane_init(&dev_priv->drm, &cursor->base,
13305                                        0, &intel_cursor_plane_funcs,
13306                                        intel_cursor_formats,
13307                                        ARRAY_SIZE(intel_cursor_formats),
13308                                        cursor_format_modifiers,
13309                                        DRM_PLANE_TYPE_CURSOR,
13310                                        "cursor %c", pipe_name(pipe));
13311         if (ret)
13312                 goto fail;
13313
13314         if (INTEL_GEN(dev_priv) >= 4)
13315                 drm_plane_create_rotation_property(&cursor->base,
13316                                                    DRM_MODE_ROTATE_0,
13317                                                    DRM_MODE_ROTATE_0 |
13318                                                    DRM_MODE_ROTATE_180);
13319
13320         if (INTEL_GEN(dev_priv) >= 9)
13321                 state->scaler_id = -1;
13322
13323         drm_plane_helper_add(&cursor->base, &intel_plane_helper_funcs);
13324
13325         return cursor;
13326
13327 fail:
13328         kfree(state);
13329         kfree(cursor);
13330
13331         return ERR_PTR(ret);
13332 }
13333
13334 static void intel_crtc_init_scalers(struct intel_crtc *crtc,
13335                                     struct intel_crtc_state *crtc_state)
13336 {
13337         struct intel_crtc_scaler_state *scaler_state =
13338                 &crtc_state->scaler_state;
13339         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
13340         int i;
13341
13342         crtc->num_scalers = dev_priv->info.num_scalers[crtc->pipe];
13343         if (!crtc->num_scalers)
13344                 return;
13345
13346         for (i = 0; i < crtc->num_scalers; i++) {
13347                 struct intel_scaler *scaler = &scaler_state->scalers[i];
13348
13349                 scaler->in_use = 0;
13350                 scaler->mode = PS_SCALER_MODE_DYN;
13351         }
13352
13353         scaler_state->scaler_id = -1;
13354 }
13355
13356 static int intel_crtc_init(struct drm_i915_private *dev_priv, enum pipe pipe)
13357 {
13358         struct intel_crtc *intel_crtc;
13359         struct intel_crtc_state *crtc_state = NULL;
13360         struct intel_plane *primary = NULL;
13361         struct intel_plane *cursor = NULL;
13362         int sprite, ret;
13363
13364         intel_crtc = kzalloc(sizeof(*intel_crtc), GFP_KERNEL);
13365         if (!intel_crtc)
13366                 return -ENOMEM;
13367
13368         crtc_state = kzalloc(sizeof(*crtc_state), GFP_KERNEL);
13369         if (!crtc_state) {
13370                 ret = -ENOMEM;
13371                 goto fail;
13372         }
13373         intel_crtc->config = crtc_state;
13374         intel_crtc->base.state = &crtc_state->base;
13375         crtc_state->base.crtc = &intel_crtc->base;
13376
13377         primary = intel_primary_plane_create(dev_priv, pipe);
13378         if (IS_ERR(primary)) {
13379                 ret = PTR_ERR(primary);
13380                 goto fail;
13381         }
13382         intel_crtc->plane_ids_mask |= BIT(primary->id);
13383
13384         for_each_sprite(dev_priv, pipe, sprite) {
13385                 struct intel_plane *plane;
13386
13387                 plane = intel_sprite_plane_create(dev_priv, pipe, sprite);
13388                 if (IS_ERR(plane)) {
13389                         ret = PTR_ERR(plane);
13390                         goto fail;
13391                 }
13392                 intel_crtc->plane_ids_mask |= BIT(plane->id);
13393         }
13394
13395         cursor = intel_cursor_plane_create(dev_priv, pipe);
13396         if (IS_ERR(cursor)) {
13397                 ret = PTR_ERR(cursor);
13398                 goto fail;
13399         }
13400         intel_crtc->plane_ids_mask |= BIT(cursor->id);
13401
13402         ret = drm_crtc_init_with_planes(&dev_priv->drm, &intel_crtc->base,
13403                                         &primary->base, &cursor->base,
13404                                         &intel_crtc_funcs,
13405                                         "pipe %c", pipe_name(pipe));
13406         if (ret)
13407                 goto fail;
13408
13409         intel_crtc->pipe = pipe;
13410
13411         /* initialize shared scalers */
13412         intel_crtc_init_scalers(intel_crtc, crtc_state);
13413
13414         BUG_ON(pipe >= ARRAY_SIZE(dev_priv->plane_to_crtc_mapping) ||
13415                dev_priv->plane_to_crtc_mapping[primary->i9xx_plane] != NULL);
13416         dev_priv->plane_to_crtc_mapping[primary->i9xx_plane] = intel_crtc;
13417         dev_priv->pipe_to_crtc_mapping[intel_crtc->pipe] = intel_crtc;
13418
13419         drm_crtc_helper_add(&intel_crtc->base, &intel_helper_funcs);
13420
13421         intel_color_init(&intel_crtc->base);
13422
13423         WARN_ON(drm_crtc_index(&intel_crtc->base) != intel_crtc->pipe);
13424
13425         return 0;
13426
13427 fail:
13428         /*
13429          * drm_mode_config_cleanup() will free up any
13430          * crtcs/planes already initialized.
13431          */
13432         kfree(crtc_state);
13433         kfree(intel_crtc);
13434
13435         return ret;
13436 }
13437
13438 enum pipe intel_get_pipe_from_connector(struct intel_connector *connector)
13439 {
13440         struct drm_device *dev = connector->base.dev;
13441
13442         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
13443
13444         if (!connector->base.state->crtc)
13445                 return INVALID_PIPE;
13446
13447         return to_intel_crtc(connector->base.state->crtc)->pipe;
13448 }
13449
13450 int intel_get_pipe_from_crtc_id(struct drm_device *dev, void *data,
13451                                 struct drm_file *file)
13452 {
13453         struct drm_i915_get_pipe_from_crtc_id *pipe_from_crtc_id = data;
13454         struct drm_crtc *drmmode_crtc;
13455         struct intel_crtc *crtc;
13456
13457         drmmode_crtc = drm_crtc_find(dev, file, pipe_from_crtc_id->crtc_id);
13458         if (!drmmode_crtc)
13459                 return -ENOENT;
13460
13461         crtc = to_intel_crtc(drmmode_crtc);
13462         pipe_from_crtc_id->pipe = crtc->pipe;
13463
13464         return 0;
13465 }
13466
13467 static int intel_encoder_clones(struct intel_encoder *encoder)
13468 {
13469         struct drm_device *dev = encoder->base.dev;
13470         struct intel_encoder *source_encoder;
13471         int index_mask = 0;
13472         int entry = 0;
13473
13474         for_each_intel_encoder(dev, source_encoder) {
13475                 if (encoders_cloneable(encoder, source_encoder))
13476                         index_mask |= (1 << entry);
13477
13478                 entry++;
13479         }
13480
13481         return index_mask;
13482 }
13483
13484 static bool has_edp_a(struct drm_i915_private *dev_priv)
13485 {
13486         if (!IS_MOBILE(dev_priv))
13487                 return false;
13488
13489         if ((I915_READ(DP_A) & DP_DETECTED) == 0)
13490                 return false;
13491
13492         if (IS_GEN5(dev_priv) && (I915_READ(FUSE_STRAP) & ILK_eDP_A_DISABLE))
13493                 return false;
13494
13495         return true;
13496 }
13497
13498 static bool intel_crt_present(struct drm_i915_private *dev_priv)
13499 {
13500         if (INTEL_GEN(dev_priv) >= 9)
13501                 return false;
13502
13503         if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
13504                 return false;
13505
13506         if (IS_CHERRYVIEW(dev_priv))
13507                 return false;
13508
13509         if (HAS_PCH_LPT_H(dev_priv) &&
13510             I915_READ(SFUSE_STRAP) & SFUSE_STRAP_CRT_DISABLED)
13511                 return false;
13512
13513         /* DDI E can't be used if DDI A requires 4 lanes */
13514         if (HAS_DDI(dev_priv) && I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_A_4_LANES)
13515                 return false;
13516
13517         if (!dev_priv->vbt.int_crt_support)
13518                 return false;
13519
13520         return true;
13521 }
13522
13523 void intel_pps_unlock_regs_wa(struct drm_i915_private *dev_priv)
13524 {
13525         int pps_num;
13526         int pps_idx;
13527
13528         if (HAS_DDI(dev_priv))
13529                 return;
13530         /*
13531          * This w/a is needed at least on CPT/PPT, but to be sure apply it
13532          * everywhere where registers can be write protected.
13533          */
13534         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13535                 pps_num = 2;
13536         else
13537                 pps_num = 1;
13538
13539         for (pps_idx = 0; pps_idx < pps_num; pps_idx++) {
13540                 u32 val = I915_READ(PP_CONTROL(pps_idx));
13541
13542                 val = (val & ~PANEL_UNLOCK_MASK) | PANEL_UNLOCK_REGS;
13543                 I915_WRITE(PP_CONTROL(pps_idx), val);
13544         }
13545 }
13546
13547 static void intel_pps_init(struct drm_i915_private *dev_priv)
13548 {
13549         if (HAS_PCH_SPLIT(dev_priv) || IS_GEN9_LP(dev_priv))
13550                 dev_priv->pps_mmio_base = PCH_PPS_BASE;
13551         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
13552                 dev_priv->pps_mmio_base = VLV_PPS_BASE;
13553         else
13554                 dev_priv->pps_mmio_base = PPS_BASE;
13555
13556         intel_pps_unlock_regs_wa(dev_priv);
13557 }
13558
13559 static void intel_setup_outputs(struct drm_i915_private *dev_priv)
13560 {
13561         struct intel_encoder *encoder;
13562         bool dpd_is_edp = false;
13563
13564         intel_pps_init(dev_priv);
13565
13566         /*
13567          * intel_edp_init_connector() depends on this completing first, to
13568          * prevent the registeration of both eDP and LVDS and the incorrect
13569          * sharing of the PPS.
13570          */
13571         intel_lvds_init(dev_priv);
13572
13573         if (intel_crt_present(dev_priv))
13574                 intel_crt_init(dev_priv);
13575
13576         if (IS_GEN9_LP(dev_priv)) {
13577                 /*
13578                  * FIXME: Broxton doesn't support port detection via the
13579                  * DDI_BUF_CTL_A or SFUSE_STRAP registers, find another way to
13580                  * detect the ports.
13581                  */
13582                 intel_ddi_init(dev_priv, PORT_A);
13583                 intel_ddi_init(dev_priv, PORT_B);
13584                 intel_ddi_init(dev_priv, PORT_C);
13585
13586                 intel_dsi_init(dev_priv);
13587         } else if (HAS_DDI(dev_priv)) {
13588                 int found;
13589
13590                 /*
13591                  * Haswell uses DDI functions to detect digital outputs.
13592                  * On SKL pre-D0 the strap isn't connected, so we assume
13593                  * it's there.
13594                  */
13595                 found = I915_READ(DDI_BUF_CTL(PORT_A)) & DDI_INIT_DISPLAY_DETECTED;
13596                 /* WaIgnoreDDIAStrap: skl */
13597                 if (found || IS_GEN9_BC(dev_priv))
13598                         intel_ddi_init(dev_priv, PORT_A);
13599
13600                 /* DDI B, C and D detection is indicated by the SFUSE_STRAP
13601                  * register */
13602                 found = I915_READ(SFUSE_STRAP);
13603
13604                 if (found & SFUSE_STRAP_DDIB_DETECTED)
13605                         intel_ddi_init(dev_priv, PORT_B);
13606                 if (found & SFUSE_STRAP_DDIC_DETECTED)
13607                         intel_ddi_init(dev_priv, PORT_C);
13608                 if (found & SFUSE_STRAP_DDID_DETECTED)
13609                         intel_ddi_init(dev_priv, PORT_D);
13610                 /*
13611                  * On SKL we don't have a way to detect DDI-E so we rely on VBT.
13612                  */
13613                 if (IS_GEN9_BC(dev_priv) &&
13614                     (dev_priv->vbt.ddi_port_info[PORT_E].supports_dp ||
13615                      dev_priv->vbt.ddi_port_info[PORT_E].supports_dvi ||
13616                      dev_priv->vbt.ddi_port_info[PORT_E].supports_hdmi))
13617                         intel_ddi_init(dev_priv, PORT_E);
13618
13619         } else if (HAS_PCH_SPLIT(dev_priv)) {
13620                 int found;
13621                 dpd_is_edp = intel_dp_is_port_edp(dev_priv, PORT_D);
13622
13623                 if (has_edp_a(dev_priv))
13624                         intel_dp_init(dev_priv, DP_A, PORT_A);
13625
13626                 if (I915_READ(PCH_HDMIB) & SDVO_DETECTED) {
13627                         /* PCH SDVOB multiplex with HDMIB */
13628                         found = intel_sdvo_init(dev_priv, PCH_SDVOB, PORT_B);
13629                         if (!found)
13630                                 intel_hdmi_init(dev_priv, PCH_HDMIB, PORT_B);
13631                         if (!found && (I915_READ(PCH_DP_B) & DP_DETECTED))
13632                                 intel_dp_init(dev_priv, PCH_DP_B, PORT_B);
13633                 }
13634
13635                 if (I915_READ(PCH_HDMIC) & SDVO_DETECTED)
13636                         intel_hdmi_init(dev_priv, PCH_HDMIC, PORT_C);
13637
13638                 if (!dpd_is_edp && I915_READ(PCH_HDMID) & SDVO_DETECTED)
13639                         intel_hdmi_init(dev_priv, PCH_HDMID, PORT_D);
13640
13641                 if (I915_READ(PCH_DP_C) & DP_DETECTED)
13642                         intel_dp_init(dev_priv, PCH_DP_C, PORT_C);
13643
13644                 if (I915_READ(PCH_DP_D) & DP_DETECTED)
13645                         intel_dp_init(dev_priv, PCH_DP_D, PORT_D);
13646         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
13647                 bool has_edp, has_port;
13648
13649                 /*
13650                  * The DP_DETECTED bit is the latched state of the DDC
13651                  * SDA pin at boot. However since eDP doesn't require DDC
13652                  * (no way to plug in a DP->HDMI dongle) the DDC pins for
13653                  * eDP ports may have been muxed to an alternate function.
13654                  * Thus we can't rely on the DP_DETECTED bit alone to detect
13655                  * eDP ports. Consult the VBT as well as DP_DETECTED to
13656                  * detect eDP ports.
13657                  *
13658                  * Sadly the straps seem to be missing sometimes even for HDMI
13659                  * ports (eg. on Voyo V3 - CHT x7-Z8700), so check both strap
13660                  * and VBT for the presence of the port. Additionally we can't
13661                  * trust the port type the VBT declares as we've seen at least
13662                  * HDMI ports that the VBT claim are DP or eDP.
13663                  */
13664                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_B);
13665                 has_port = intel_bios_is_port_present(dev_priv, PORT_B);
13666                 if (I915_READ(VLV_DP_B) & DP_DETECTED || has_port)
13667                         has_edp &= intel_dp_init(dev_priv, VLV_DP_B, PORT_B);
13668                 if ((I915_READ(VLV_HDMIB) & SDVO_DETECTED || has_port) && !has_edp)
13669                         intel_hdmi_init(dev_priv, VLV_HDMIB, PORT_B);
13670
13671                 has_edp = intel_dp_is_port_edp(dev_priv, PORT_C);
13672                 has_port = intel_bios_is_port_present(dev_priv, PORT_C);
13673                 if (I915_READ(VLV_DP_C) & DP_DETECTED || has_port)
13674                         has_edp &= intel_dp_init(dev_priv, VLV_DP_C, PORT_C);
13675                 if ((I915_READ(VLV_HDMIC) & SDVO_DETECTED || has_port) && !has_edp)
13676                         intel_hdmi_init(dev_priv, VLV_HDMIC, PORT_C);
13677
13678                 if (IS_CHERRYVIEW(dev_priv)) {
13679                         /*
13680                          * eDP not supported on port D,
13681                          * so no need to worry about it
13682                          */
13683                         has_port = intel_bios_is_port_present(dev_priv, PORT_D);
13684                         if (I915_READ(CHV_DP_D) & DP_DETECTED || has_port)
13685                                 intel_dp_init(dev_priv, CHV_DP_D, PORT_D);
13686                         if (I915_READ(CHV_HDMID) & SDVO_DETECTED || has_port)
13687                                 intel_hdmi_init(dev_priv, CHV_HDMID, PORT_D);
13688                 }
13689
13690                 intel_dsi_init(dev_priv);
13691         } else if (!IS_GEN2(dev_priv) && !IS_PINEVIEW(dev_priv)) {
13692                 bool found = false;
13693
13694                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13695                         DRM_DEBUG_KMS("probing SDVOB\n");
13696                         found = intel_sdvo_init(dev_priv, GEN3_SDVOB, PORT_B);
13697                         if (!found && IS_G4X(dev_priv)) {
13698                                 DRM_DEBUG_KMS("probing HDMI on SDVOB\n");
13699                                 intel_hdmi_init(dev_priv, GEN4_HDMIB, PORT_B);
13700                         }
13701
13702                         if (!found && IS_G4X(dev_priv))
13703                                 intel_dp_init(dev_priv, DP_B, PORT_B);
13704                 }
13705
13706                 /* Before G4X SDVOC doesn't have its own detect register */
13707
13708                 if (I915_READ(GEN3_SDVOB) & SDVO_DETECTED) {
13709                         DRM_DEBUG_KMS("probing SDVOC\n");
13710                         found = intel_sdvo_init(dev_priv, GEN3_SDVOC, PORT_C);
13711                 }
13712
13713                 if (!found && (I915_READ(GEN3_SDVOC) & SDVO_DETECTED)) {
13714
13715                         if (IS_G4X(dev_priv)) {
13716                                 DRM_DEBUG_KMS("probing HDMI on SDVOC\n");
13717                                 intel_hdmi_init(dev_priv, GEN4_HDMIC, PORT_C);
13718                         }
13719                         if (IS_G4X(dev_priv))
13720                                 intel_dp_init(dev_priv, DP_C, PORT_C);
13721                 }
13722
13723                 if (IS_G4X(dev_priv) && (I915_READ(DP_D) & DP_DETECTED))
13724                         intel_dp_init(dev_priv, DP_D, PORT_D);
13725         } else if (IS_GEN2(dev_priv))
13726                 intel_dvo_init(dev_priv);
13727
13728         if (SUPPORTS_TV(dev_priv))
13729                 intel_tv_init(dev_priv);
13730
13731         intel_psr_init(dev_priv);
13732
13733         for_each_intel_encoder(&dev_priv->drm, encoder) {
13734                 encoder->base.possible_crtcs = encoder->crtc_mask;
13735                 encoder->base.possible_clones =
13736                         intel_encoder_clones(encoder);
13737         }
13738
13739         intel_init_pch_refclk(dev_priv);
13740
13741         drm_helper_move_panel_connectors_to_head(&dev_priv->drm);
13742 }
13743
13744 static void intel_user_framebuffer_destroy(struct drm_framebuffer *fb)
13745 {
13746         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13747
13748         drm_framebuffer_cleanup(fb);
13749
13750         i915_gem_object_lock(intel_fb->obj);
13751         WARN_ON(!intel_fb->obj->framebuffer_references--);
13752         i915_gem_object_unlock(intel_fb->obj);
13753
13754         i915_gem_object_put(intel_fb->obj);
13755
13756         kfree(intel_fb);
13757 }
13758
13759 static int intel_user_framebuffer_create_handle(struct drm_framebuffer *fb,
13760                                                 struct drm_file *file,
13761                                                 unsigned int *handle)
13762 {
13763         struct intel_framebuffer *intel_fb = to_intel_framebuffer(fb);
13764         struct drm_i915_gem_object *obj = intel_fb->obj;
13765
13766         if (obj->userptr.mm) {
13767                 DRM_DEBUG("attempting to use a userptr for a framebuffer, denied\n");
13768                 return -EINVAL;
13769         }
13770
13771         return drm_gem_handle_create(file, &obj->base, handle);
13772 }
13773
13774 static int intel_user_framebuffer_dirty(struct drm_framebuffer *fb,
13775                                         struct drm_file *file,
13776                                         unsigned flags, unsigned color,
13777                                         struct drm_clip_rect *clips,
13778                                         unsigned num_clips)
13779 {
13780         struct drm_i915_gem_object *obj = intel_fb_obj(fb);
13781
13782         i915_gem_object_flush_if_display(obj);
13783         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
13784
13785         return 0;
13786 }
13787
13788 static const struct drm_framebuffer_funcs intel_fb_funcs = {
13789         .destroy = intel_user_framebuffer_destroy,
13790         .create_handle = intel_user_framebuffer_create_handle,
13791         .dirty = intel_user_framebuffer_dirty,
13792 };
13793
13794 static
13795 u32 intel_fb_pitch_limit(struct drm_i915_private *dev_priv,
13796                          uint64_t fb_modifier, uint32_t pixel_format)
13797 {
13798         u32 gen = INTEL_GEN(dev_priv);
13799
13800         if (gen >= 9) {
13801                 int cpp = drm_format_plane_cpp(pixel_format, 0);
13802
13803                 /* "The stride in bytes must not exceed the of the size of 8K
13804                  *  pixels and 32K bytes."
13805                  */
13806                 return min(8192 * cpp, 32768);
13807         } else if (gen >= 5 && !HAS_GMCH_DISPLAY(dev_priv)) {
13808                 return 32*1024;
13809         } else if (gen >= 4) {
13810                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13811                         return 16*1024;
13812                 else
13813                         return 32*1024;
13814         } else if (gen >= 3) {
13815                 if (fb_modifier == I915_FORMAT_MOD_X_TILED)
13816                         return 8*1024;
13817                 else
13818                         return 16*1024;
13819         } else {
13820                 /* XXX DSPC is limited to 4k tiled */
13821                 return 8*1024;
13822         }
13823 }
13824
13825 static int intel_framebuffer_init(struct intel_framebuffer *intel_fb,
13826                                   struct drm_i915_gem_object *obj,
13827                                   struct drm_mode_fb_cmd2 *mode_cmd)
13828 {
13829         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
13830         struct drm_framebuffer *fb = &intel_fb->base;
13831         struct drm_format_name_buf format_name;
13832         u32 pitch_limit;
13833         unsigned int tiling, stride;
13834         int ret = -EINVAL;
13835         int i;
13836
13837         i915_gem_object_lock(obj);
13838         obj->framebuffer_references++;
13839         tiling = i915_gem_object_get_tiling(obj);
13840         stride = i915_gem_object_get_stride(obj);
13841         i915_gem_object_unlock(obj);
13842
13843         if (mode_cmd->flags & DRM_MODE_FB_MODIFIERS) {
13844                 /*
13845                  * If there's a fence, enforce that
13846                  * the fb modifier and tiling mode match.
13847                  */
13848                 if (tiling != I915_TILING_NONE &&
13849                     tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
13850                         DRM_DEBUG_KMS("tiling_mode doesn't match fb modifier\n");
13851                         goto err;
13852                 }
13853         } else {
13854                 if (tiling == I915_TILING_X) {
13855                         mode_cmd->modifier[0] = I915_FORMAT_MOD_X_TILED;
13856                 } else if (tiling == I915_TILING_Y) {
13857                         DRM_DEBUG_KMS("No Y tiling for legacy addfb\n");
13858                         goto err;
13859                 }
13860         }
13861
13862         /* Passed in modifier sanity checking. */
13863         switch (mode_cmd->modifier[0]) {
13864         case I915_FORMAT_MOD_Y_TILED_CCS:
13865         case I915_FORMAT_MOD_Yf_TILED_CCS:
13866                 switch (mode_cmd->pixel_format) {
13867                 case DRM_FORMAT_XBGR8888:
13868                 case DRM_FORMAT_ABGR8888:
13869                 case DRM_FORMAT_XRGB8888:
13870                 case DRM_FORMAT_ARGB8888:
13871                         break;
13872                 default:
13873                         DRM_DEBUG_KMS("RC supported only with RGB8888 formats\n");
13874                         goto err;
13875                 }
13876                 /* fall through */
13877         case I915_FORMAT_MOD_Y_TILED:
13878         case I915_FORMAT_MOD_Yf_TILED:
13879                 if (INTEL_GEN(dev_priv) < 9) {
13880                         DRM_DEBUG_KMS("Unsupported tiling 0x%llx!\n",
13881                                       mode_cmd->modifier[0]);
13882                         goto err;
13883                 }
13884         case DRM_FORMAT_MOD_LINEAR:
13885         case I915_FORMAT_MOD_X_TILED:
13886                 break;
13887         default:
13888                 DRM_DEBUG_KMS("Unsupported fb modifier 0x%llx!\n",
13889                               mode_cmd->modifier[0]);
13890                 goto err;
13891         }
13892
13893         /*
13894          * gen2/3 display engine uses the fence if present,
13895          * so the tiling mode must match the fb modifier exactly.
13896          */
13897         if (INTEL_INFO(dev_priv)->gen < 4 &&
13898             tiling != intel_fb_modifier_to_tiling(mode_cmd->modifier[0])) {
13899                 DRM_DEBUG_KMS("tiling_mode must match fb modifier exactly on gen2/3\n");
13900                 goto err;
13901         }
13902
13903         pitch_limit = intel_fb_pitch_limit(dev_priv, mode_cmd->modifier[0],
13904                                            mode_cmd->pixel_format);
13905         if (mode_cmd->pitches[0] > pitch_limit) {
13906                 DRM_DEBUG_KMS("%s pitch (%u) must be at most %d\n",
13907                               mode_cmd->modifier[0] != DRM_FORMAT_MOD_LINEAR ?
13908                               "tiled" : "linear",
13909                               mode_cmd->pitches[0], pitch_limit);
13910                 goto err;
13911         }
13912
13913         /*
13914          * If there's a fence, enforce that
13915          * the fb pitch and fence stride match.
13916          */
13917         if (tiling != I915_TILING_NONE && mode_cmd->pitches[0] != stride) {
13918                 DRM_DEBUG_KMS("pitch (%d) must match tiling stride (%d)\n",
13919                               mode_cmd->pitches[0], stride);
13920                 goto err;
13921         }
13922
13923         /* Reject formats not supported by any plane early. */
13924         switch (mode_cmd->pixel_format) {
13925         case DRM_FORMAT_C8:
13926         case DRM_FORMAT_RGB565:
13927         case DRM_FORMAT_XRGB8888:
13928         case DRM_FORMAT_ARGB8888:
13929                 break;
13930         case DRM_FORMAT_XRGB1555:
13931                 if (INTEL_GEN(dev_priv) > 3) {
13932                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
13933                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
13934                         goto err;
13935                 }
13936                 break;
13937         case DRM_FORMAT_ABGR8888:
13938                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
13939                     INTEL_GEN(dev_priv) < 9) {
13940                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
13941                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
13942                         goto err;
13943                 }
13944                 break;
13945         case DRM_FORMAT_XBGR8888:
13946         case DRM_FORMAT_XRGB2101010:
13947         case DRM_FORMAT_XBGR2101010:
13948                 if (INTEL_GEN(dev_priv) < 4) {
13949                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
13950                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
13951                         goto err;
13952                 }
13953                 break;
13954         case DRM_FORMAT_ABGR2101010:
13955                 if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
13956                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
13957                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
13958                         goto err;
13959                 }
13960                 break;
13961         case DRM_FORMAT_YUYV:
13962         case DRM_FORMAT_UYVY:
13963         case DRM_FORMAT_YVYU:
13964         case DRM_FORMAT_VYUY:
13965                 if (INTEL_GEN(dev_priv) < 5 && !IS_G4X(dev_priv)) {
13966                         DRM_DEBUG_KMS("unsupported pixel format: %s\n",
13967                                       drm_get_format_name(mode_cmd->pixel_format, &format_name));
13968                         goto err;
13969                 }
13970                 break;
13971         default:
13972                 DRM_DEBUG_KMS("unsupported pixel format: %s\n",
13973                               drm_get_format_name(mode_cmd->pixel_format, &format_name));
13974                 goto err;
13975         }
13976
13977         /* FIXME need to adjust LINOFF/TILEOFF accordingly. */
13978         if (mode_cmd->offsets[0] != 0)
13979                 goto err;
13980
13981         drm_helper_mode_fill_fb_struct(&dev_priv->drm, fb, mode_cmd);
13982
13983         for (i = 0; i < fb->format->num_planes; i++) {
13984                 u32 stride_alignment;
13985
13986                 if (mode_cmd->handles[i] != mode_cmd->handles[0]) {
13987                         DRM_DEBUG_KMS("bad plane %d handle\n", i);
13988                         goto err;
13989                 }
13990
13991                 stride_alignment = intel_fb_stride_alignment(fb, i);
13992
13993                 /*
13994                  * Display WA #0531: skl,bxt,kbl,glk
13995                  *
13996                  * Render decompression and plane width > 3840
13997                  * combined with horizontal panning requires the
13998                  * plane stride to be a multiple of 4. We'll just
13999                  * require the entire fb to accommodate that to avoid
14000                  * potential runtime errors at plane configuration time.
14001                  */
14002                 if (IS_GEN9(dev_priv) && i == 0 && fb->width > 3840 &&
14003                     (fb->modifier == I915_FORMAT_MOD_Y_TILED_CCS ||
14004                      fb->modifier == I915_FORMAT_MOD_Yf_TILED_CCS))
14005                         stride_alignment *= 4;
14006
14007                 if (fb->pitches[i] & (stride_alignment - 1)) {
14008                         DRM_DEBUG_KMS("plane %d pitch (%d) must be at least %u byte aligned\n",
14009                                       i, fb->pitches[i], stride_alignment);
14010                         goto err;
14011                 }
14012         }
14013
14014         intel_fb->obj = obj;
14015
14016         ret = intel_fill_fb_info(dev_priv, fb);
14017         if (ret)
14018                 goto err;
14019
14020         ret = drm_framebuffer_init(&dev_priv->drm, fb, &intel_fb_funcs);
14021         if (ret) {
14022                 DRM_ERROR("framebuffer init failed %d\n", ret);
14023                 goto err;
14024         }
14025
14026         return 0;
14027
14028 err:
14029         i915_gem_object_lock(obj);
14030         obj->framebuffer_references--;
14031         i915_gem_object_unlock(obj);
14032         return ret;
14033 }
14034
14035 static struct drm_framebuffer *
14036 intel_user_framebuffer_create(struct drm_device *dev,
14037                               struct drm_file *filp,
14038                               const struct drm_mode_fb_cmd2 *user_mode_cmd)
14039 {
14040         struct drm_framebuffer *fb;
14041         struct drm_i915_gem_object *obj;
14042         struct drm_mode_fb_cmd2 mode_cmd = *user_mode_cmd;
14043
14044         obj = i915_gem_object_lookup(filp, mode_cmd.handles[0]);
14045         if (!obj)
14046                 return ERR_PTR(-ENOENT);
14047
14048         fb = intel_framebuffer_create(obj, &mode_cmd);
14049         if (IS_ERR(fb))
14050                 i915_gem_object_put(obj);
14051
14052         return fb;
14053 }
14054
14055 static void intel_atomic_state_free(struct drm_atomic_state *state)
14056 {
14057         struct intel_atomic_state *intel_state = to_intel_atomic_state(state);
14058
14059         drm_atomic_state_default_release(state);
14060
14061         i915_sw_fence_fini(&intel_state->commit_ready);
14062
14063         kfree(state);
14064 }
14065
14066 static const struct drm_mode_config_funcs intel_mode_funcs = {
14067         .fb_create = intel_user_framebuffer_create,
14068         .get_format_info = intel_get_format_info,
14069         .output_poll_changed = intel_fbdev_output_poll_changed,
14070         .atomic_check = intel_atomic_check,
14071         .atomic_commit = intel_atomic_commit,
14072         .atomic_state_alloc = intel_atomic_state_alloc,
14073         .atomic_state_clear = intel_atomic_state_clear,
14074         .atomic_state_free = intel_atomic_state_free,
14075 };
14076
14077 /**
14078  * intel_init_display_hooks - initialize the display modesetting hooks
14079  * @dev_priv: device private
14080  */
14081 void intel_init_display_hooks(struct drm_i915_private *dev_priv)
14082 {
14083         intel_init_cdclk_hooks(dev_priv);
14084
14085         if (INTEL_INFO(dev_priv)->gen >= 9) {
14086                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14087                 dev_priv->display.get_initial_plane_config =
14088                         skylake_get_initial_plane_config;
14089                 dev_priv->display.crtc_compute_clock =
14090                         haswell_crtc_compute_clock;
14091                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14092                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14093         } else if (HAS_DDI(dev_priv)) {
14094                 dev_priv->display.get_pipe_config = haswell_get_pipe_config;
14095                 dev_priv->display.get_initial_plane_config =
14096                         i9xx_get_initial_plane_config;
14097                 dev_priv->display.crtc_compute_clock =
14098                         haswell_crtc_compute_clock;
14099                 dev_priv->display.crtc_enable = haswell_crtc_enable;
14100                 dev_priv->display.crtc_disable = haswell_crtc_disable;
14101         } else if (HAS_PCH_SPLIT(dev_priv)) {
14102                 dev_priv->display.get_pipe_config = ironlake_get_pipe_config;
14103                 dev_priv->display.get_initial_plane_config =
14104                         i9xx_get_initial_plane_config;
14105                 dev_priv->display.crtc_compute_clock =
14106                         ironlake_crtc_compute_clock;
14107                 dev_priv->display.crtc_enable = ironlake_crtc_enable;
14108                 dev_priv->display.crtc_disable = ironlake_crtc_disable;
14109         } else if (IS_CHERRYVIEW(dev_priv)) {
14110                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14111                 dev_priv->display.get_initial_plane_config =
14112                         i9xx_get_initial_plane_config;
14113                 dev_priv->display.crtc_compute_clock = chv_crtc_compute_clock;
14114                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14115                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14116         } else if (IS_VALLEYVIEW(dev_priv)) {
14117                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14118                 dev_priv->display.get_initial_plane_config =
14119                         i9xx_get_initial_plane_config;
14120                 dev_priv->display.crtc_compute_clock = vlv_crtc_compute_clock;
14121                 dev_priv->display.crtc_enable = valleyview_crtc_enable;
14122                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14123         } else if (IS_G4X(dev_priv)) {
14124                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14125                 dev_priv->display.get_initial_plane_config =
14126                         i9xx_get_initial_plane_config;
14127                 dev_priv->display.crtc_compute_clock = g4x_crtc_compute_clock;
14128                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14129                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14130         } else if (IS_PINEVIEW(dev_priv)) {
14131                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14132                 dev_priv->display.get_initial_plane_config =
14133                         i9xx_get_initial_plane_config;
14134                 dev_priv->display.crtc_compute_clock = pnv_crtc_compute_clock;
14135                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14136                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14137         } else if (!IS_GEN2(dev_priv)) {
14138                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14139                 dev_priv->display.get_initial_plane_config =
14140                         i9xx_get_initial_plane_config;
14141                 dev_priv->display.crtc_compute_clock = i9xx_crtc_compute_clock;
14142                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14143                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14144         } else {
14145                 dev_priv->display.get_pipe_config = i9xx_get_pipe_config;
14146                 dev_priv->display.get_initial_plane_config =
14147                         i9xx_get_initial_plane_config;
14148                 dev_priv->display.crtc_compute_clock = i8xx_crtc_compute_clock;
14149                 dev_priv->display.crtc_enable = i9xx_crtc_enable;
14150                 dev_priv->display.crtc_disable = i9xx_crtc_disable;
14151         }
14152
14153         if (IS_GEN5(dev_priv)) {
14154                 dev_priv->display.fdi_link_train = ironlake_fdi_link_train;
14155         } else if (IS_GEN6(dev_priv)) {
14156                 dev_priv->display.fdi_link_train = gen6_fdi_link_train;
14157         } else if (IS_IVYBRIDGE(dev_priv)) {
14158                 /* FIXME: detect B0+ stepping and use auto training */
14159                 dev_priv->display.fdi_link_train = ivb_manual_fdi_link_train;
14160         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
14161                 dev_priv->display.fdi_link_train = hsw_fdi_link_train;
14162         }
14163
14164         if (INTEL_GEN(dev_priv) >= 9)
14165                 dev_priv->display.update_crtcs = skl_update_crtcs;
14166         else
14167                 dev_priv->display.update_crtcs = intel_update_crtcs;
14168 }
14169
14170 /*
14171  * Some machines (Lenovo U160) do not work with SSC on LVDS for some reason
14172  */
14173 static void quirk_ssc_force_disable(struct drm_device *dev)
14174 {
14175         struct drm_i915_private *dev_priv = to_i915(dev);
14176         dev_priv->quirks |= QUIRK_LVDS_SSC_DISABLE;
14177         DRM_INFO("applying lvds SSC disable quirk\n");
14178 }
14179
14180 /*
14181  * A machine (e.g. Acer Aspire 5734Z) may need to invert the panel backlight
14182  * brightness value
14183  */
14184 static void quirk_invert_brightness(struct drm_device *dev)
14185 {
14186         struct drm_i915_private *dev_priv = to_i915(dev);
14187         dev_priv->quirks |= QUIRK_INVERT_BRIGHTNESS;
14188         DRM_INFO("applying inverted panel brightness quirk\n");
14189 }
14190
14191 /* Some VBT's incorrectly indicate no backlight is present */
14192 static void quirk_backlight_present(struct drm_device *dev)
14193 {
14194         struct drm_i915_private *dev_priv = to_i915(dev);
14195         dev_priv->quirks |= QUIRK_BACKLIGHT_PRESENT;
14196         DRM_INFO("applying backlight present quirk\n");
14197 }
14198
14199 /* Toshiba Satellite P50-C-18C requires T12 delay to be min 800ms
14200  * which is 300 ms greater than eDP spec T12 min.
14201  */
14202 static void quirk_increase_t12_delay(struct drm_device *dev)
14203 {
14204         struct drm_i915_private *dev_priv = to_i915(dev);
14205
14206         dev_priv->quirks |= QUIRK_INCREASE_T12_DELAY;
14207         DRM_INFO("Applying T12 delay quirk\n");
14208 }
14209
14210 struct intel_quirk {
14211         int device;
14212         int subsystem_vendor;
14213         int subsystem_device;
14214         void (*hook)(struct drm_device *dev);
14215 };
14216
14217 /* For systems that don't have a meaningful PCI subdevice/subvendor ID */
14218 struct intel_dmi_quirk {
14219         void (*hook)(struct drm_device *dev);
14220         const struct dmi_system_id (*dmi_id_list)[];
14221 };
14222
14223 static int intel_dmi_reverse_brightness(const struct dmi_system_id *id)
14224 {
14225         DRM_INFO("Backlight polarity reversed on %s\n", id->ident);
14226         return 1;
14227 }
14228
14229 static const struct intel_dmi_quirk intel_dmi_quirks[] = {
14230         {
14231                 .dmi_id_list = &(const struct dmi_system_id[]) {
14232                         {
14233                                 .callback = intel_dmi_reverse_brightness,
14234                                 .ident = "NCR Corporation",
14235                                 .matches = {DMI_MATCH(DMI_SYS_VENDOR, "NCR Corporation"),
14236                                             DMI_MATCH(DMI_PRODUCT_NAME, ""),
14237                                 },
14238                         },
14239                         { }  /* terminating entry */
14240                 },
14241                 .hook = quirk_invert_brightness,
14242         },
14243 };
14244
14245 static struct intel_quirk intel_quirks[] = {
14246         /* Lenovo U160 cannot use SSC on LVDS */
14247         { 0x0046, 0x17aa, 0x3920, quirk_ssc_force_disable },
14248
14249         /* Sony Vaio Y cannot use SSC on LVDS */
14250         { 0x0046, 0x104d, 0x9076, quirk_ssc_force_disable },
14251
14252         /* Acer Aspire 5734Z must invert backlight brightness */
14253         { 0x2a42, 0x1025, 0x0459, quirk_invert_brightness },
14254
14255         /* Acer/eMachines G725 */
14256         { 0x2a42, 0x1025, 0x0210, quirk_invert_brightness },
14257
14258         /* Acer/eMachines e725 */
14259         { 0x2a42, 0x1025, 0x0212, quirk_invert_brightness },
14260
14261         /* Acer/Packard Bell NCL20 */
14262         { 0x2a42, 0x1025, 0x034b, quirk_invert_brightness },
14263
14264         /* Acer Aspire 4736Z */
14265         { 0x2a42, 0x1025, 0x0260, quirk_invert_brightness },
14266
14267         /* Acer Aspire 5336 */
14268         { 0x2a42, 0x1025, 0x048a, quirk_invert_brightness },
14269
14270         /* Acer C720 and C720P Chromebooks (Celeron 2955U) have backlights */
14271         { 0x0a06, 0x1025, 0x0a11, quirk_backlight_present },
14272
14273         /* Acer C720 Chromebook (Core i3 4005U) */
14274         { 0x0a16, 0x1025, 0x0a11, quirk_backlight_present },
14275
14276         /* Apple Macbook 2,1 (Core 2 T7400) */
14277         { 0x27a2, 0x8086, 0x7270, quirk_backlight_present },
14278
14279         /* Apple Macbook 4,1 */
14280         { 0x2a02, 0x106b, 0x00a1, quirk_backlight_present },
14281
14282         /* Toshiba CB35 Chromebook (Celeron 2955U) */
14283         { 0x0a06, 0x1179, 0x0a88, quirk_backlight_present },
14284
14285         /* HP Chromebook 14 (Celeron 2955U) */
14286         { 0x0a06, 0x103c, 0x21ed, quirk_backlight_present },
14287
14288         /* Dell Chromebook 11 */
14289         { 0x0a06, 0x1028, 0x0a35, quirk_backlight_present },
14290
14291         /* Dell Chromebook 11 (2015 version) */
14292         { 0x0a16, 0x1028, 0x0a35, quirk_backlight_present },
14293
14294         /* Toshiba Satellite P50-C-18C */
14295         { 0x191B, 0x1179, 0xF840, quirk_increase_t12_delay },
14296 };
14297
14298 static void intel_init_quirks(struct drm_device *dev)
14299 {
14300         struct pci_dev *d = dev->pdev;
14301         int i;
14302
14303         for (i = 0; i < ARRAY_SIZE(intel_quirks); i++) {
14304                 struct intel_quirk *q = &intel_quirks[i];
14305
14306                 if (d->device == q->device &&
14307                     (d->subsystem_vendor == q->subsystem_vendor ||
14308                      q->subsystem_vendor == PCI_ANY_ID) &&
14309                     (d->subsystem_device == q->subsystem_device ||
14310                      q->subsystem_device == PCI_ANY_ID))
14311                         q->hook(dev);
14312         }
14313         for (i = 0; i < ARRAY_SIZE(intel_dmi_quirks); i++) {
14314                 if (dmi_check_system(*intel_dmi_quirks[i].dmi_id_list) != 0)
14315                         intel_dmi_quirks[i].hook(dev);
14316         }
14317 }
14318
14319 /* Disable the VGA plane that we never use */
14320 static void i915_disable_vga(struct drm_i915_private *dev_priv)
14321 {
14322         struct pci_dev *pdev = dev_priv->drm.pdev;
14323         u8 sr1;
14324         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14325
14326         /* WaEnableVGAAccessThroughIOPort:ctg,elk,ilk,snb,ivb,vlv,hsw */
14327         vga_get_uninterruptible(pdev, VGA_RSRC_LEGACY_IO);
14328         outb(SR01, VGA_SR_INDEX);
14329         sr1 = inb(VGA_SR_DATA);
14330         outb(sr1 | 1<<5, VGA_SR_DATA);
14331         vga_put(pdev, VGA_RSRC_LEGACY_IO);
14332         udelay(300);
14333
14334         I915_WRITE(vga_reg, VGA_DISP_DISABLE);
14335         POSTING_READ(vga_reg);
14336 }
14337
14338 void intel_modeset_init_hw(struct drm_device *dev)
14339 {
14340         struct drm_i915_private *dev_priv = to_i915(dev);
14341
14342         intel_update_cdclk(dev_priv);
14343         intel_dump_cdclk_state(&dev_priv->cdclk.hw, "Current CDCLK");
14344         dev_priv->cdclk.logical = dev_priv->cdclk.actual = dev_priv->cdclk.hw;
14345 }
14346
14347 /*
14348  * Calculate what we think the watermarks should be for the state we've read
14349  * out of the hardware and then immediately program those watermarks so that
14350  * we ensure the hardware settings match our internal state.
14351  *
14352  * We can calculate what we think WM's should be by creating a duplicate of the
14353  * current state (which was constructed during hardware readout) and running it
14354  * through the atomic check code to calculate new watermark values in the
14355  * state object.
14356  */
14357 static void sanitize_watermarks(struct drm_device *dev)
14358 {
14359         struct drm_i915_private *dev_priv = to_i915(dev);
14360         struct drm_atomic_state *state;
14361         struct intel_atomic_state *intel_state;
14362         struct drm_crtc *crtc;
14363         struct drm_crtc_state *cstate;
14364         struct drm_modeset_acquire_ctx ctx;
14365         int ret;
14366         int i;
14367
14368         /* Only supported on platforms that use atomic watermark design */
14369         if (!dev_priv->display.optimize_watermarks)
14370                 return;
14371
14372         /*
14373          * We need to hold connection_mutex before calling duplicate_state so
14374          * that the connector loop is protected.
14375          */
14376         drm_modeset_acquire_init(&ctx, 0);
14377 retry:
14378         ret = drm_modeset_lock_all_ctx(dev, &ctx);
14379         if (ret == -EDEADLK) {
14380                 drm_modeset_backoff(&ctx);
14381                 goto retry;
14382         } else if (WARN_ON(ret)) {
14383                 goto fail;
14384         }
14385
14386         state = drm_atomic_helper_duplicate_state(dev, &ctx);
14387         if (WARN_ON(IS_ERR(state)))
14388                 goto fail;
14389
14390         intel_state = to_intel_atomic_state(state);
14391
14392         /*
14393          * Hardware readout is the only time we don't want to calculate
14394          * intermediate watermarks (since we don't trust the current
14395          * watermarks).
14396          */
14397         if (!HAS_GMCH_DISPLAY(dev_priv))
14398                 intel_state->skip_intermediate_wm = true;
14399
14400         ret = intel_atomic_check(dev, state);
14401         if (ret) {
14402                 /*
14403                  * If we fail here, it means that the hardware appears to be
14404                  * programmed in a way that shouldn't be possible, given our
14405                  * understanding of watermark requirements.  This might mean a
14406                  * mistake in the hardware readout code or a mistake in the
14407                  * watermark calculations for a given platform.  Raise a WARN
14408                  * so that this is noticeable.
14409                  *
14410                  * If this actually happens, we'll have to just leave the
14411                  * BIOS-programmed watermarks untouched and hope for the best.
14412                  */
14413                 WARN(true, "Could not determine valid watermarks for inherited state\n");
14414                 goto put_state;
14415         }
14416
14417         /* Write calculated watermark values back */
14418         for_each_new_crtc_in_state(state, crtc, cstate, i) {
14419                 struct intel_crtc_state *cs = to_intel_crtc_state(cstate);
14420
14421                 cs->wm.need_postvbl_update = true;
14422                 dev_priv->display.optimize_watermarks(intel_state, cs);
14423
14424                 to_intel_crtc_state(crtc->state)->wm = cs->wm;
14425         }
14426
14427 put_state:
14428         drm_atomic_state_put(state);
14429 fail:
14430         drm_modeset_drop_locks(&ctx);
14431         drm_modeset_acquire_fini(&ctx);
14432 }
14433
14434 static void intel_update_fdi_pll_freq(struct drm_i915_private *dev_priv)
14435 {
14436         if (IS_GEN5(dev_priv)) {
14437                 u32 fdi_pll_clk =
14438                         I915_READ(FDI_PLL_BIOS_0) & FDI_PLL_FB_CLOCK_MASK;
14439
14440                 dev_priv->fdi_pll_freq = (fdi_pll_clk + 2) * 10000;
14441         } else if (IS_GEN6(dev_priv) || IS_IVYBRIDGE(dev_priv)) {
14442                 dev_priv->fdi_pll_freq = 270000;
14443         } else {
14444                 return;
14445         }
14446
14447         DRM_DEBUG_DRIVER("FDI PLL freq=%d\n", dev_priv->fdi_pll_freq);
14448 }
14449
14450 int intel_modeset_init(struct drm_device *dev)
14451 {
14452         struct drm_i915_private *dev_priv = to_i915(dev);
14453         struct i915_ggtt *ggtt = &dev_priv->ggtt;
14454         enum pipe pipe;
14455         struct intel_crtc *crtc;
14456
14457         dev_priv->modeset_wq = alloc_ordered_workqueue("i915_modeset", 0);
14458
14459         drm_mode_config_init(dev);
14460
14461         dev->mode_config.min_width = 0;
14462         dev->mode_config.min_height = 0;
14463
14464         dev->mode_config.preferred_depth = 24;
14465         dev->mode_config.prefer_shadow = 1;
14466
14467         dev->mode_config.allow_fb_modifiers = true;
14468
14469         dev->mode_config.funcs = &intel_mode_funcs;
14470
14471         init_llist_head(&dev_priv->atomic_helper.free_list);
14472         INIT_WORK(&dev_priv->atomic_helper.free_work,
14473                   intel_atomic_helper_free_state_worker);
14474
14475         intel_init_quirks(dev);
14476
14477         intel_init_pm(dev_priv);
14478
14479         if (INTEL_INFO(dev_priv)->num_pipes == 0)
14480                 return 0;
14481
14482         /*
14483          * There may be no VBT; and if the BIOS enabled SSC we can
14484          * just keep using it to avoid unnecessary flicker.  Whereas if the
14485          * BIOS isn't using it, don't assume it will work even if the VBT
14486          * indicates as much.
14487          */
14488         if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
14489                 bool bios_lvds_use_ssc = !!(I915_READ(PCH_DREF_CONTROL) &
14490                                             DREF_SSC1_ENABLE);
14491
14492                 if (dev_priv->vbt.lvds_use_ssc != bios_lvds_use_ssc) {
14493                         DRM_DEBUG_KMS("SSC %sabled by BIOS, overriding VBT which says %sabled\n",
14494                                      bios_lvds_use_ssc ? "en" : "dis",
14495                                      dev_priv->vbt.lvds_use_ssc ? "en" : "dis");
14496                         dev_priv->vbt.lvds_use_ssc = bios_lvds_use_ssc;
14497                 }
14498         }
14499
14500         if (IS_GEN2(dev_priv)) {
14501                 dev->mode_config.max_width = 2048;
14502                 dev->mode_config.max_height = 2048;
14503         } else if (IS_GEN3(dev_priv)) {
14504                 dev->mode_config.max_width = 4096;
14505                 dev->mode_config.max_height = 4096;
14506         } else {
14507                 dev->mode_config.max_width = 8192;
14508                 dev->mode_config.max_height = 8192;
14509         }
14510
14511         if (IS_I845G(dev_priv) || IS_I865G(dev_priv)) {
14512                 dev->mode_config.cursor_width = IS_I845G(dev_priv) ? 64 : 512;
14513                 dev->mode_config.cursor_height = 1023;
14514         } else if (IS_GEN2(dev_priv)) {
14515                 dev->mode_config.cursor_width = GEN2_CURSOR_WIDTH;
14516                 dev->mode_config.cursor_height = GEN2_CURSOR_HEIGHT;
14517         } else {
14518                 dev->mode_config.cursor_width = MAX_CURSOR_WIDTH;
14519                 dev->mode_config.cursor_height = MAX_CURSOR_HEIGHT;
14520         }
14521
14522         dev->mode_config.fb_base = ggtt->gmadr.start;
14523
14524         DRM_DEBUG_KMS("%d display pipe%s available.\n",
14525                       INTEL_INFO(dev_priv)->num_pipes,
14526                       INTEL_INFO(dev_priv)->num_pipes > 1 ? "s" : "");
14527
14528         for_each_pipe(dev_priv, pipe) {
14529                 int ret;
14530
14531                 ret = intel_crtc_init(dev_priv, pipe);
14532                 if (ret) {
14533                         drm_mode_config_cleanup(dev);
14534                         return ret;
14535                 }
14536         }
14537
14538         intel_shared_dpll_init(dev);
14539         intel_update_fdi_pll_freq(dev_priv);
14540
14541         intel_update_czclk(dev_priv);
14542         intel_modeset_init_hw(dev);
14543
14544         if (dev_priv->max_cdclk_freq == 0)
14545                 intel_update_max_cdclk(dev_priv);
14546
14547         /* Just disable it once at startup */
14548         i915_disable_vga(dev_priv);
14549         intel_setup_outputs(dev_priv);
14550
14551         drm_modeset_lock_all(dev);
14552         intel_modeset_setup_hw_state(dev, dev->mode_config.acquire_ctx);
14553         drm_modeset_unlock_all(dev);
14554
14555         for_each_intel_crtc(dev, crtc) {
14556                 struct intel_initial_plane_config plane_config = {};
14557
14558                 if (!crtc->active)
14559                         continue;
14560
14561                 /*
14562                  * Note that reserving the BIOS fb up front prevents us
14563                  * from stuffing other stolen allocations like the ring
14564                  * on top.  This prevents some ugliness at boot time, and
14565                  * can even allow for smooth boot transitions if the BIOS
14566                  * fb is large enough for the active pipe configuration.
14567                  */
14568                 dev_priv->display.get_initial_plane_config(crtc,
14569                                                            &plane_config);
14570
14571                 /*
14572                  * If the fb is shared between multiple heads, we'll
14573                  * just get the first one.
14574                  */
14575                 intel_find_initial_plane_obj(crtc, &plane_config);
14576         }
14577
14578         /*
14579          * Make sure hardware watermarks really match the state we read out.
14580          * Note that we need to do this after reconstructing the BIOS fb's
14581          * since the watermark calculation done here will use pstate->fb.
14582          */
14583         if (!HAS_GMCH_DISPLAY(dev_priv))
14584                 sanitize_watermarks(dev);
14585
14586         return 0;
14587 }
14588
14589 void i830_enable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14590 {
14591         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14592         /* 640x480@60Hz, ~25175 kHz */
14593         struct dpll clock = {
14594                 .m1 = 18,
14595                 .m2 = 7,
14596                 .p1 = 13,
14597                 .p2 = 4,
14598                 .n = 2,
14599         };
14600         u32 dpll, fp;
14601         int i;
14602
14603         WARN_ON(i9xx_calc_dpll_params(48000, &clock) != 25154);
14604
14605         DRM_DEBUG_KMS("enabling pipe %c due to force quirk (vco=%d dot=%d)\n",
14606                       pipe_name(pipe), clock.vco, clock.dot);
14607
14608         fp = i9xx_dpll_compute_fp(&clock);
14609         dpll = (I915_READ(DPLL(pipe)) & DPLL_DVO_2X_MODE) |
14610                 DPLL_VGA_MODE_DIS |
14611                 ((clock.p1 - 2) << DPLL_FPA01_P1_POST_DIV_SHIFT) |
14612                 PLL_P2_DIVIDE_BY_4 |
14613                 PLL_REF_INPUT_DREFCLK |
14614                 DPLL_VCO_ENABLE;
14615
14616         I915_WRITE(FP0(pipe), fp);
14617         I915_WRITE(FP1(pipe), fp);
14618
14619         I915_WRITE(HTOTAL(pipe), (640 - 1) | ((800 - 1) << 16));
14620         I915_WRITE(HBLANK(pipe), (640 - 1) | ((800 - 1) << 16));
14621         I915_WRITE(HSYNC(pipe), (656 - 1) | ((752 - 1) << 16));
14622         I915_WRITE(VTOTAL(pipe), (480 - 1) | ((525 - 1) << 16));
14623         I915_WRITE(VBLANK(pipe), (480 - 1) | ((525 - 1) << 16));
14624         I915_WRITE(VSYNC(pipe), (490 - 1) | ((492 - 1) << 16));
14625         I915_WRITE(PIPESRC(pipe), ((640 - 1) << 16) | (480 - 1));
14626
14627         /*
14628          * Apparently we need to have VGA mode enabled prior to changing
14629          * the P1/P2 dividers. Otherwise the DPLL will keep using the old
14630          * dividers, even though the register value does change.
14631          */
14632         I915_WRITE(DPLL(pipe), dpll & ~DPLL_VGA_MODE_DIS);
14633         I915_WRITE(DPLL(pipe), dpll);
14634
14635         /* Wait for the clocks to stabilize. */
14636         POSTING_READ(DPLL(pipe));
14637         udelay(150);
14638
14639         /* The pixel multiplier can only be updated once the
14640          * DPLL is enabled and the clocks are stable.
14641          *
14642          * So write it again.
14643          */
14644         I915_WRITE(DPLL(pipe), dpll);
14645
14646         /* We do this three times for luck */
14647         for (i = 0; i < 3 ; i++) {
14648                 I915_WRITE(DPLL(pipe), dpll);
14649                 POSTING_READ(DPLL(pipe));
14650                 udelay(150); /* wait for warmup */
14651         }
14652
14653         I915_WRITE(PIPECONF(pipe), PIPECONF_ENABLE | PIPECONF_PROGRESSIVE);
14654         POSTING_READ(PIPECONF(pipe));
14655
14656         intel_wait_for_pipe_scanline_moving(crtc);
14657 }
14658
14659 void i830_disable_pipe(struct drm_i915_private *dev_priv, enum pipe pipe)
14660 {
14661         struct intel_crtc *crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14662
14663         DRM_DEBUG_KMS("disabling pipe %c due to force quirk\n",
14664                       pipe_name(pipe));
14665
14666         WARN_ON(I915_READ(DSPCNTR(PLANE_A)) & DISPLAY_PLANE_ENABLE);
14667         WARN_ON(I915_READ(DSPCNTR(PLANE_B)) & DISPLAY_PLANE_ENABLE);
14668         WARN_ON(I915_READ(DSPCNTR(PLANE_C)) & DISPLAY_PLANE_ENABLE);
14669         WARN_ON(I915_READ(CURCNTR(PIPE_A)) & CURSOR_MODE);
14670         WARN_ON(I915_READ(CURCNTR(PIPE_B)) & CURSOR_MODE);
14671
14672         I915_WRITE(PIPECONF(pipe), 0);
14673         POSTING_READ(PIPECONF(pipe));
14674
14675         intel_wait_for_pipe_scanline_stopped(crtc);
14676
14677         I915_WRITE(DPLL(pipe), DPLL_VGA_MODE_DIS);
14678         POSTING_READ(DPLL(pipe));
14679 }
14680
14681 static bool intel_plane_mapping_ok(struct intel_crtc *crtc,
14682                                    struct intel_plane *plane)
14683 {
14684         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14685         enum i9xx_plane_id i9xx_plane = plane->i9xx_plane;
14686         u32 val = I915_READ(DSPCNTR(i9xx_plane));
14687
14688         return (val & DISPLAY_PLANE_ENABLE) == 0 ||
14689                 (val & DISPPLANE_SEL_PIPE_MASK) == DISPPLANE_SEL_PIPE(crtc->pipe);
14690 }
14691
14692 static void
14693 intel_sanitize_plane_mapping(struct drm_i915_private *dev_priv)
14694 {
14695         struct intel_crtc *crtc;
14696
14697         if (INTEL_GEN(dev_priv) >= 4)
14698                 return;
14699
14700         for_each_intel_crtc(&dev_priv->drm, crtc) {
14701                 struct intel_plane *plane =
14702                         to_intel_plane(crtc->base.primary);
14703
14704                 if (intel_plane_mapping_ok(crtc, plane))
14705                         continue;
14706
14707                 DRM_DEBUG_KMS("%s attached to the wrong pipe, disabling plane\n",
14708                               plane->base.name);
14709                 intel_plane_disable_noatomic(crtc, plane);
14710         }
14711 }
14712
14713 static bool intel_crtc_has_encoders(struct intel_crtc *crtc)
14714 {
14715         struct drm_device *dev = crtc->base.dev;
14716         struct intel_encoder *encoder;
14717
14718         for_each_encoder_on_crtc(dev, &crtc->base, encoder)
14719                 return true;
14720
14721         return false;
14722 }
14723
14724 static struct intel_connector *intel_encoder_find_connector(struct intel_encoder *encoder)
14725 {
14726         struct drm_device *dev = encoder->base.dev;
14727         struct intel_connector *connector;
14728
14729         for_each_connector_on_encoder(dev, &encoder->base, connector)
14730                 return connector;
14731
14732         return NULL;
14733 }
14734
14735 static bool has_pch_trancoder(struct drm_i915_private *dev_priv,
14736                               enum pipe pch_transcoder)
14737 {
14738         return HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv) ||
14739                 (HAS_PCH_LPT_H(dev_priv) && pch_transcoder == PIPE_A);
14740 }
14741
14742 static void intel_sanitize_crtc(struct intel_crtc *crtc,
14743                                 struct drm_modeset_acquire_ctx *ctx)
14744 {
14745         struct drm_device *dev = crtc->base.dev;
14746         struct drm_i915_private *dev_priv = to_i915(dev);
14747         enum transcoder cpu_transcoder = crtc->config->cpu_transcoder;
14748
14749         /* Clear any frame start delays used for debugging left by the BIOS */
14750         if (crtc->active && !transcoder_is_dsi(cpu_transcoder)) {
14751                 i915_reg_t reg = PIPECONF(cpu_transcoder);
14752
14753                 I915_WRITE(reg,
14754                            I915_READ(reg) & ~PIPECONF_FRAME_START_DELAY_MASK);
14755         }
14756
14757         /* restore vblank interrupts to correct state */
14758         drm_crtc_vblank_reset(&crtc->base);
14759         if (crtc->active) {
14760                 struct intel_plane *plane;
14761
14762                 drm_crtc_vblank_on(&crtc->base);
14763
14764                 /* Disable everything but the primary plane */
14765                 for_each_intel_plane_on_crtc(dev, crtc, plane) {
14766                         const struct intel_plane_state *plane_state =
14767                                 to_intel_plane_state(plane->base.state);
14768
14769                         if (plane_state->base.visible &&
14770                             plane->base.type != DRM_PLANE_TYPE_PRIMARY)
14771                                 intel_plane_disable_noatomic(crtc, plane);
14772                 }
14773         }
14774
14775         /* Adjust the state of the output pipe according to whether we
14776          * have active connectors/encoders. */
14777         if (crtc->active && !intel_crtc_has_encoders(crtc))
14778                 intel_crtc_disable_noatomic(&crtc->base, ctx);
14779
14780         if (crtc->active || HAS_GMCH_DISPLAY(dev_priv)) {
14781                 /*
14782                  * We start out with underrun reporting disabled to avoid races.
14783                  * For correct bookkeeping mark this on active crtcs.
14784                  *
14785                  * Also on gmch platforms we dont have any hardware bits to
14786                  * disable the underrun reporting. Which means we need to start
14787                  * out with underrun reporting disabled also on inactive pipes,
14788                  * since otherwise we'll complain about the garbage we read when
14789                  * e.g. coming up after runtime pm.
14790                  *
14791                  * No protection against concurrent access is required - at
14792                  * worst a fifo underrun happens which also sets this to false.
14793                  */
14794                 crtc->cpu_fifo_underrun_disabled = true;
14795                 /*
14796                  * We track the PCH trancoder underrun reporting state
14797                  * within the crtc. With crtc for pipe A housing the underrun
14798                  * reporting state for PCH transcoder A, crtc for pipe B housing
14799                  * it for PCH transcoder B, etc. LPT-H has only PCH transcoder A,
14800                  * and marking underrun reporting as disabled for the non-existing
14801                  * PCH transcoders B and C would prevent enabling the south
14802                  * error interrupt (see cpt_can_enable_serr_int()).
14803                  */
14804                 if (has_pch_trancoder(dev_priv, crtc->pipe))
14805                         crtc->pch_fifo_underrun_disabled = true;
14806         }
14807 }
14808
14809 static void intel_sanitize_encoder(struct intel_encoder *encoder)
14810 {
14811         struct intel_connector *connector;
14812
14813         /* We need to check both for a crtc link (meaning that the
14814          * encoder is active and trying to read from a pipe) and the
14815          * pipe itself being active. */
14816         bool has_active_crtc = encoder->base.crtc &&
14817                 to_intel_crtc(encoder->base.crtc)->active;
14818
14819         connector = intel_encoder_find_connector(encoder);
14820         if (connector && !has_active_crtc) {
14821                 DRM_DEBUG_KMS("[ENCODER:%d:%s] has active connectors but no active pipe!\n",
14822                               encoder->base.base.id,
14823                               encoder->base.name);
14824
14825                 /* Connector is active, but has no active pipe. This is
14826                  * fallout from our resume register restoring. Disable
14827                  * the encoder manually again. */
14828                 if (encoder->base.crtc) {
14829                         struct drm_crtc_state *crtc_state = encoder->base.crtc->state;
14830
14831                         DRM_DEBUG_KMS("[ENCODER:%d:%s] manually disabled\n",
14832                                       encoder->base.base.id,
14833                                       encoder->base.name);
14834                         encoder->disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
14835                         if (encoder->post_disable)
14836                                 encoder->post_disable(encoder, to_intel_crtc_state(crtc_state), connector->base.state);
14837                 }
14838                 encoder->base.crtc = NULL;
14839
14840                 /* Inconsistent output/port/pipe state happens presumably due to
14841                  * a bug in one of the get_hw_state functions. Or someplace else
14842                  * in our code, like the register restore mess on resume. Clamp
14843                  * things to off as a safer default. */
14844
14845                 connector->base.dpms = DRM_MODE_DPMS_OFF;
14846                 connector->base.encoder = NULL;
14847         }
14848 }
14849
14850 void i915_redisable_vga_power_on(struct drm_i915_private *dev_priv)
14851 {
14852         i915_reg_t vga_reg = i915_vgacntrl_reg(dev_priv);
14853
14854         if (!(I915_READ(vga_reg) & VGA_DISP_DISABLE)) {
14855                 DRM_DEBUG_KMS("Something enabled VGA plane, disabling it\n");
14856                 i915_disable_vga(dev_priv);
14857         }
14858 }
14859
14860 void i915_redisable_vga(struct drm_i915_private *dev_priv)
14861 {
14862         /* This function can be called both from intel_modeset_setup_hw_state or
14863          * at a very early point in our resume sequence, where the power well
14864          * structures are not yet restored. Since this function is at a very
14865          * paranoid "someone might have enabled VGA while we were not looking"
14866          * level, just check if the power well is enabled instead of trying to
14867          * follow the "don't touch the power well if we don't need it" policy
14868          * the rest of the driver uses. */
14869         if (!intel_display_power_get_if_enabled(dev_priv, POWER_DOMAIN_VGA))
14870                 return;
14871
14872         i915_redisable_vga_power_on(dev_priv);
14873
14874         intel_display_power_put(dev_priv, POWER_DOMAIN_VGA);
14875 }
14876
14877 /* FIXME read out full plane state for all planes */
14878 static void readout_plane_state(struct intel_crtc *crtc)
14879 {
14880         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
14881         struct intel_crtc_state *crtc_state =
14882                 to_intel_crtc_state(crtc->base.state);
14883         struct intel_plane *plane;
14884
14885         for_each_intel_plane_on_crtc(&dev_priv->drm, crtc, plane) {
14886                 struct intel_plane_state *plane_state =
14887                         to_intel_plane_state(plane->base.state);
14888                 bool visible = plane->get_hw_state(plane);
14889
14890                 intel_set_plane_visible(crtc_state, plane_state, visible);
14891         }
14892 }
14893
14894 static void intel_modeset_readout_hw_state(struct drm_device *dev)
14895 {
14896         struct drm_i915_private *dev_priv = to_i915(dev);
14897         enum pipe pipe;
14898         struct intel_crtc *crtc;
14899         struct intel_encoder *encoder;
14900         struct intel_connector *connector;
14901         struct drm_connector_list_iter conn_iter;
14902         int i;
14903
14904         dev_priv->active_crtcs = 0;
14905
14906         for_each_intel_crtc(dev, crtc) {
14907                 struct intel_crtc_state *crtc_state =
14908                         to_intel_crtc_state(crtc->base.state);
14909
14910                 __drm_atomic_helper_crtc_destroy_state(&crtc_state->base);
14911                 memset(crtc_state, 0, sizeof(*crtc_state));
14912                 crtc_state->base.crtc = &crtc->base;
14913
14914                 crtc_state->base.active = crtc_state->base.enable =
14915                         dev_priv->display.get_pipe_config(crtc, crtc_state);
14916
14917                 crtc->base.enabled = crtc_state->base.enable;
14918                 crtc->active = crtc_state->base.active;
14919
14920                 if (crtc_state->base.active)
14921                         dev_priv->active_crtcs |= 1 << crtc->pipe;
14922
14923                 readout_plane_state(crtc);
14924
14925                 DRM_DEBUG_KMS("[CRTC:%d:%s] hw state readout: %s\n",
14926                               crtc->base.base.id, crtc->base.name,
14927                               enableddisabled(crtc_state->base.active));
14928         }
14929
14930         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
14931                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
14932
14933                 pll->on = pll->funcs.get_hw_state(dev_priv, pll,
14934                                                   &pll->state.hw_state);
14935                 pll->state.crtc_mask = 0;
14936                 for_each_intel_crtc(dev, crtc) {
14937                         struct intel_crtc_state *crtc_state =
14938                                 to_intel_crtc_state(crtc->base.state);
14939
14940                         if (crtc_state->base.active &&
14941                             crtc_state->shared_dpll == pll)
14942                                 pll->state.crtc_mask |= 1 << crtc->pipe;
14943                 }
14944                 pll->active_mask = pll->state.crtc_mask;
14945
14946                 DRM_DEBUG_KMS("%s hw state readout: crtc_mask 0x%08x, on %i\n",
14947                               pll->name, pll->state.crtc_mask, pll->on);
14948         }
14949
14950         for_each_intel_encoder(dev, encoder) {
14951                 pipe = 0;
14952
14953                 if (encoder->get_hw_state(encoder, &pipe)) {
14954                         struct intel_crtc_state *crtc_state;
14955
14956                         crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
14957                         crtc_state = to_intel_crtc_state(crtc->base.state);
14958
14959                         encoder->base.crtc = &crtc->base;
14960                         encoder->get_config(encoder, crtc_state);
14961                 } else {
14962                         encoder->base.crtc = NULL;
14963                 }
14964
14965                 DRM_DEBUG_KMS("[ENCODER:%d:%s] hw state readout: %s, pipe %c\n",
14966                               encoder->base.base.id, encoder->base.name,
14967                               enableddisabled(encoder->base.crtc),
14968                               pipe_name(pipe));
14969         }
14970
14971         drm_connector_list_iter_begin(dev, &conn_iter);
14972         for_each_intel_connector_iter(connector, &conn_iter) {
14973                 if (connector->get_hw_state(connector)) {
14974                         connector->base.dpms = DRM_MODE_DPMS_ON;
14975
14976                         encoder = connector->encoder;
14977                         connector->base.encoder = &encoder->base;
14978
14979                         if (encoder->base.crtc &&
14980                             encoder->base.crtc->state->active) {
14981                                 /*
14982                                  * This has to be done during hardware readout
14983                                  * because anything calling .crtc_disable may
14984                                  * rely on the connector_mask being accurate.
14985                                  */
14986                                 encoder->base.crtc->state->connector_mask |=
14987                                         1 << drm_connector_index(&connector->base);
14988                                 encoder->base.crtc->state->encoder_mask |=
14989                                         1 << drm_encoder_index(&encoder->base);
14990                         }
14991
14992                 } else {
14993                         connector->base.dpms = DRM_MODE_DPMS_OFF;
14994                         connector->base.encoder = NULL;
14995                 }
14996                 DRM_DEBUG_KMS("[CONNECTOR:%d:%s] hw state readout: %s\n",
14997                               connector->base.base.id, connector->base.name,
14998                               enableddisabled(connector->base.encoder));
14999         }
15000         drm_connector_list_iter_end(&conn_iter);
15001
15002         for_each_intel_crtc(dev, crtc) {
15003                 struct intel_crtc_state *crtc_state =
15004                         to_intel_crtc_state(crtc->base.state);
15005                 int min_cdclk = 0;
15006
15007                 memset(&crtc->base.mode, 0, sizeof(crtc->base.mode));
15008                 if (crtc_state->base.active) {
15009                         intel_mode_from_pipe_config(&crtc->base.mode, crtc_state);
15010                         intel_mode_from_pipe_config(&crtc_state->base.adjusted_mode, crtc_state);
15011                         WARN_ON(drm_atomic_set_mode_for_crtc(crtc->base.state, &crtc->base.mode));
15012
15013                         /*
15014                          * The initial mode needs to be set in order to keep
15015                          * the atomic core happy. It wants a valid mode if the
15016                          * crtc's enabled, so we do the above call.
15017                          *
15018                          * But we don't set all the derived state fully, hence
15019                          * set a flag to indicate that a full recalculation is
15020                          * needed on the next commit.
15021                          */
15022                         crtc_state->base.mode.private_flags = I915_MODE_FLAG_INHERITED;
15023
15024                         intel_crtc_compute_pixel_rate(crtc_state);
15025
15026                         if (dev_priv->display.modeset_calc_cdclk) {
15027                                 min_cdclk = intel_crtc_compute_min_cdclk(crtc_state);
15028                                 if (WARN_ON(min_cdclk < 0))
15029                                         min_cdclk = 0;
15030                         }
15031
15032                         drm_calc_timestamping_constants(&crtc->base,
15033                                                         &crtc_state->base.adjusted_mode);
15034                         update_scanline_offset(crtc);
15035                 }
15036
15037                 dev_priv->min_cdclk[crtc->pipe] = min_cdclk;
15038                 dev_priv->min_voltage_level[crtc->pipe] =
15039                         crtc_state->min_voltage_level;
15040
15041                 intel_pipe_config_sanity_check(dev_priv, crtc_state);
15042         }
15043 }
15044
15045 static void
15046 get_encoder_power_domains(struct drm_i915_private *dev_priv)
15047 {
15048         struct intel_encoder *encoder;
15049
15050         for_each_intel_encoder(&dev_priv->drm, encoder) {
15051                 u64 get_domains;
15052                 enum intel_display_power_domain domain;
15053
15054                 if (!encoder->get_power_domains)
15055                         continue;
15056
15057                 get_domains = encoder->get_power_domains(encoder);
15058                 for_each_power_domain(domain, get_domains)
15059                         intel_display_power_get(dev_priv, domain);
15060         }
15061 }
15062
15063 static void intel_early_display_was(struct drm_i915_private *dev_priv)
15064 {
15065         /* Display WA #1185 WaDisableDARBFClkGating:cnl,glk */
15066         if (IS_CANNONLAKE(dev_priv) || IS_GEMINILAKE(dev_priv))
15067                 I915_WRITE(GEN9_CLKGATE_DIS_0, I915_READ(GEN9_CLKGATE_DIS_0) |
15068                            DARBF_GATING_DIS);
15069
15070         if (IS_HASWELL(dev_priv)) {
15071                 /*
15072                  * WaRsPkgCStateDisplayPMReq:hsw
15073                  * System hang if this isn't done before disabling all planes!
15074                  */
15075                 I915_WRITE(CHICKEN_PAR1_1,
15076                            I915_READ(CHICKEN_PAR1_1) | FORCE_ARB_IDLE_PLANES);
15077         }
15078 }
15079
15080 /* Scan out the current hw modeset state,
15081  * and sanitizes it to the current state
15082  */
15083 static void
15084 intel_modeset_setup_hw_state(struct drm_device *dev,
15085                              struct drm_modeset_acquire_ctx *ctx)
15086 {
15087         struct drm_i915_private *dev_priv = to_i915(dev);
15088         enum pipe pipe;
15089         struct intel_crtc *crtc;
15090         struct intel_encoder *encoder;
15091         int i;
15092
15093         intel_early_display_was(dev_priv);
15094         intel_modeset_readout_hw_state(dev);
15095
15096         /* HW state is read out, now we need to sanitize this mess. */
15097         get_encoder_power_domains(dev_priv);
15098
15099         intel_sanitize_plane_mapping(dev_priv);
15100
15101         for_each_intel_encoder(dev, encoder) {
15102                 intel_sanitize_encoder(encoder);
15103         }
15104
15105         for_each_pipe(dev_priv, pipe) {
15106                 crtc = intel_get_crtc_for_pipe(dev_priv, pipe);
15107
15108                 intel_sanitize_crtc(crtc, ctx);
15109                 intel_dump_pipe_config(crtc, crtc->config,
15110                                        "[setup_hw_state]");
15111         }
15112
15113         intel_modeset_update_connector_atomic_state(dev);
15114
15115         for (i = 0; i < dev_priv->num_shared_dpll; i++) {
15116                 struct intel_shared_dpll *pll = &dev_priv->shared_dplls[i];
15117
15118                 if (!pll->on || pll->active_mask)
15119                         continue;
15120
15121                 DRM_DEBUG_KMS("%s enabled but not in use, disabling\n", pll->name);
15122
15123                 pll->funcs.disable(dev_priv, pll);
15124                 pll->on = false;
15125         }
15126
15127         if (IS_G4X(dev_priv)) {
15128                 g4x_wm_get_hw_state(dev);
15129                 g4x_wm_sanitize(dev_priv);
15130         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
15131                 vlv_wm_get_hw_state(dev);
15132                 vlv_wm_sanitize(dev_priv);
15133         } else if (INTEL_GEN(dev_priv) >= 9) {
15134                 skl_wm_get_hw_state(dev);
15135         } else if (HAS_PCH_SPLIT(dev_priv)) {
15136                 ilk_wm_get_hw_state(dev);
15137         }
15138
15139         for_each_intel_crtc(dev, crtc) {
15140                 u64 put_domains;
15141
15142                 put_domains = modeset_get_crtc_power_domains(&crtc->base, crtc->config);
15143                 if (WARN_ON(put_domains))
15144                         modeset_put_power_domains(dev_priv, put_domains);
15145         }
15146         intel_display_set_init_power(dev_priv, false);
15147
15148         intel_power_domains_verify_state(dev_priv);
15149
15150         intel_fbc_init_pipe_state(dev_priv);
15151 }
15152
15153 void intel_display_resume(struct drm_device *dev)
15154 {
15155         struct drm_i915_private *dev_priv = to_i915(dev);
15156         struct drm_atomic_state *state = dev_priv->modeset_restore_state;
15157         struct drm_modeset_acquire_ctx ctx;
15158         int ret;
15159
15160         dev_priv->modeset_restore_state = NULL;
15161         if (state)
15162                 state->acquire_ctx = &ctx;
15163
15164         drm_modeset_acquire_init(&ctx, 0);
15165
15166         while (1) {
15167                 ret = drm_modeset_lock_all_ctx(dev, &ctx);
15168                 if (ret != -EDEADLK)
15169                         break;
15170
15171                 drm_modeset_backoff(&ctx);
15172         }
15173
15174         if (!ret)
15175                 ret = __intel_display_resume(dev, state, &ctx);
15176
15177         intel_enable_ipc(dev_priv);
15178         drm_modeset_drop_locks(&ctx);
15179         drm_modeset_acquire_fini(&ctx);
15180
15181         if (ret)
15182                 DRM_ERROR("Restoring old state failed with %i\n", ret);
15183         if (state)
15184                 drm_atomic_state_put(state);
15185 }
15186
15187 int intel_connector_register(struct drm_connector *connector)
15188 {
15189         struct intel_connector *intel_connector = to_intel_connector(connector);
15190         int ret;
15191
15192         ret = intel_backlight_device_register(intel_connector);
15193         if (ret)
15194                 goto err;
15195
15196         return 0;
15197
15198 err:
15199         return ret;
15200 }
15201
15202 void intel_connector_unregister(struct drm_connector *connector)
15203 {
15204         struct intel_connector *intel_connector = to_intel_connector(connector);
15205
15206         intel_backlight_device_unregister(intel_connector);
15207         intel_panel_destroy_backlight(connector);
15208 }
15209
15210 static void intel_hpd_poll_fini(struct drm_device *dev)
15211 {
15212         struct intel_connector *connector;
15213         struct drm_connector_list_iter conn_iter;
15214
15215         /* Kill all the work that may have been queued by hpd. */
15216         drm_connector_list_iter_begin(dev, &conn_iter);
15217         for_each_intel_connector_iter(connector, &conn_iter) {
15218                 if (connector->modeset_retry_work.func)
15219                         cancel_work_sync(&connector->modeset_retry_work);
15220         }
15221         drm_connector_list_iter_end(&conn_iter);
15222 }
15223
15224 void intel_modeset_cleanup(struct drm_device *dev)
15225 {
15226         struct drm_i915_private *dev_priv = to_i915(dev);
15227
15228         flush_work(&dev_priv->atomic_helper.free_work);
15229         WARN_ON(!llist_empty(&dev_priv->atomic_helper.free_list));
15230
15231         intel_disable_gt_powersave(dev_priv);
15232
15233         /*
15234          * Interrupts and polling as the first thing to avoid creating havoc.
15235          * Too much stuff here (turning of connectors, ...) would
15236          * experience fancy races otherwise.
15237          */
15238         intel_irq_uninstall(dev_priv);
15239
15240         /*
15241          * Due to the hpd irq storm handling the hotplug work can re-arm the
15242          * poll handlers. Hence disable polling after hpd handling is shut down.
15243          */
15244         intel_hpd_poll_fini(dev);
15245
15246         /* poll work can call into fbdev, hence clean that up afterwards */
15247         intel_fbdev_fini(dev_priv);
15248
15249         intel_unregister_dsm_handler();
15250
15251         intel_fbc_global_disable(dev_priv);
15252
15253         /* flush any delayed tasks or pending work */
15254         flush_scheduled_work();
15255
15256         drm_mode_config_cleanup(dev);
15257
15258         intel_cleanup_overlay(dev_priv);
15259
15260         intel_cleanup_gt_powersave(dev_priv);
15261
15262         intel_teardown_gmbus(dev_priv);
15263
15264         destroy_workqueue(dev_priv->modeset_wq);
15265 }
15266
15267 void intel_connector_attach_encoder(struct intel_connector *connector,
15268                                     struct intel_encoder *encoder)
15269 {
15270         connector->encoder = encoder;
15271         drm_mode_connector_attach_encoder(&connector->base,
15272                                           &encoder->base);
15273 }
15274
15275 /*
15276  * set vga decode state - true == enable VGA decode
15277  */
15278 int intel_modeset_vga_set_state(struct drm_i915_private *dev_priv, bool state)
15279 {
15280         unsigned reg = INTEL_GEN(dev_priv) >= 6 ? SNB_GMCH_CTRL : INTEL_GMCH_CTRL;
15281         u16 gmch_ctrl;
15282
15283         if (pci_read_config_word(dev_priv->bridge_dev, reg, &gmch_ctrl)) {
15284                 DRM_ERROR("failed to read control word\n");
15285                 return -EIO;
15286         }
15287
15288         if (!!(gmch_ctrl & INTEL_GMCH_VGA_DISABLE) == !state)
15289                 return 0;
15290
15291         if (state)
15292                 gmch_ctrl &= ~INTEL_GMCH_VGA_DISABLE;
15293         else
15294                 gmch_ctrl |= INTEL_GMCH_VGA_DISABLE;
15295
15296         if (pci_write_config_word(dev_priv->bridge_dev, reg, gmch_ctrl)) {
15297                 DRM_ERROR("failed to write control word\n");
15298                 return -EIO;
15299         }
15300
15301         return 0;
15302 }
15303
15304 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
15305
15306 struct intel_display_error_state {
15307
15308         u32 power_well_driver;
15309
15310         int num_transcoders;
15311
15312         struct intel_cursor_error_state {
15313                 u32 control;
15314                 u32 position;
15315                 u32 base;
15316                 u32 size;
15317         } cursor[I915_MAX_PIPES];
15318
15319         struct intel_pipe_error_state {
15320                 bool power_domain_on;
15321                 u32 source;
15322                 u32 stat;
15323         } pipe[I915_MAX_PIPES];
15324
15325         struct intel_plane_error_state {
15326                 u32 control;
15327                 u32 stride;
15328                 u32 size;
15329                 u32 pos;
15330                 u32 addr;
15331                 u32 surface;
15332                 u32 tile_offset;
15333         } plane[I915_MAX_PIPES];
15334
15335         struct intel_transcoder_error_state {
15336                 bool power_domain_on;
15337                 enum transcoder cpu_transcoder;
15338
15339                 u32 conf;
15340
15341                 u32 htotal;
15342                 u32 hblank;
15343                 u32 hsync;
15344                 u32 vtotal;
15345                 u32 vblank;
15346                 u32 vsync;
15347         } transcoder[4];
15348 };
15349
15350 struct intel_display_error_state *
15351 intel_display_capture_error_state(struct drm_i915_private *dev_priv)
15352 {
15353         struct intel_display_error_state *error;
15354         int transcoders[] = {
15355                 TRANSCODER_A,
15356                 TRANSCODER_B,
15357                 TRANSCODER_C,
15358                 TRANSCODER_EDP,
15359         };
15360         int i;
15361
15362         if (INTEL_INFO(dev_priv)->num_pipes == 0)
15363                 return NULL;
15364
15365         error = kzalloc(sizeof(*error), GFP_ATOMIC);
15366         if (error == NULL)
15367                 return NULL;
15368
15369         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15370                 error->power_well_driver =
15371                         I915_READ(HSW_PWR_WELL_CTL_DRIVER(HSW_DISP_PW_GLOBAL));
15372
15373         for_each_pipe(dev_priv, i) {
15374                 error->pipe[i].power_domain_on =
15375                         __intel_display_power_is_enabled(dev_priv,
15376                                                          POWER_DOMAIN_PIPE(i));
15377                 if (!error->pipe[i].power_domain_on)
15378                         continue;
15379
15380                 error->cursor[i].control = I915_READ(CURCNTR(i));
15381                 error->cursor[i].position = I915_READ(CURPOS(i));
15382                 error->cursor[i].base = I915_READ(CURBASE(i));
15383
15384                 error->plane[i].control = I915_READ(DSPCNTR(i));
15385                 error->plane[i].stride = I915_READ(DSPSTRIDE(i));
15386                 if (INTEL_GEN(dev_priv) <= 3) {
15387                         error->plane[i].size = I915_READ(DSPSIZE(i));
15388                         error->plane[i].pos = I915_READ(DSPPOS(i));
15389                 }
15390                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15391                         error->plane[i].addr = I915_READ(DSPADDR(i));
15392                 if (INTEL_GEN(dev_priv) >= 4) {
15393                         error->plane[i].surface = I915_READ(DSPSURF(i));
15394                         error->plane[i].tile_offset = I915_READ(DSPTILEOFF(i));
15395                 }
15396
15397                 error->pipe[i].source = I915_READ(PIPESRC(i));
15398
15399                 if (HAS_GMCH_DISPLAY(dev_priv))
15400                         error->pipe[i].stat = I915_READ(PIPESTAT(i));
15401         }
15402
15403         /* Note: this does not include DSI transcoders. */
15404         error->num_transcoders = INTEL_INFO(dev_priv)->num_pipes;
15405         if (HAS_DDI(dev_priv))
15406                 error->num_transcoders++; /* Account for eDP. */
15407
15408         for (i = 0; i < error->num_transcoders; i++) {
15409                 enum transcoder cpu_transcoder = transcoders[i];
15410
15411                 error->transcoder[i].power_domain_on =
15412                         __intel_display_power_is_enabled(dev_priv,
15413                                 POWER_DOMAIN_TRANSCODER(cpu_transcoder));
15414                 if (!error->transcoder[i].power_domain_on)
15415                         continue;
15416
15417                 error->transcoder[i].cpu_transcoder = cpu_transcoder;
15418
15419                 error->transcoder[i].conf = I915_READ(PIPECONF(cpu_transcoder));
15420                 error->transcoder[i].htotal = I915_READ(HTOTAL(cpu_transcoder));
15421                 error->transcoder[i].hblank = I915_READ(HBLANK(cpu_transcoder));
15422                 error->transcoder[i].hsync = I915_READ(HSYNC(cpu_transcoder));
15423                 error->transcoder[i].vtotal = I915_READ(VTOTAL(cpu_transcoder));
15424                 error->transcoder[i].vblank = I915_READ(VBLANK(cpu_transcoder));
15425                 error->transcoder[i].vsync = I915_READ(VSYNC(cpu_transcoder));
15426         }
15427
15428         return error;
15429 }
15430
15431 #define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
15432
15433 void
15434 intel_display_print_error_state(struct drm_i915_error_state_buf *m,
15435                                 struct intel_display_error_state *error)
15436 {
15437         struct drm_i915_private *dev_priv = m->i915;
15438         int i;
15439
15440         if (!error)
15441                 return;
15442
15443         err_printf(m, "Num Pipes: %d\n", INTEL_INFO(dev_priv)->num_pipes);
15444         if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
15445                 err_printf(m, "PWR_WELL_CTL2: %08x\n",
15446                            error->power_well_driver);
15447         for_each_pipe(dev_priv, i) {
15448                 err_printf(m, "Pipe [%d]:\n", i);
15449                 err_printf(m, "  Power: %s\n",
15450                            onoff(error->pipe[i].power_domain_on));
15451                 err_printf(m, "  SRC: %08x\n", error->pipe[i].source);
15452                 err_printf(m, "  STAT: %08x\n", error->pipe[i].stat);
15453
15454                 err_printf(m, "Plane [%d]:\n", i);
15455                 err_printf(m, "  CNTR: %08x\n", error->plane[i].control);
15456                 err_printf(m, "  STRIDE: %08x\n", error->plane[i].stride);
15457                 if (INTEL_GEN(dev_priv) <= 3) {
15458                         err_printf(m, "  SIZE: %08x\n", error->plane[i].size);
15459                         err_printf(m, "  POS: %08x\n", error->plane[i].pos);
15460                 }
15461                 if (INTEL_GEN(dev_priv) <= 7 && !IS_HASWELL(dev_priv))
15462                         err_printf(m, "  ADDR: %08x\n", error->plane[i].addr);
15463                 if (INTEL_GEN(dev_priv) >= 4) {
15464                         err_printf(m, "  SURF: %08x\n", error->plane[i].surface);
15465                         err_printf(m, "  TILEOFF: %08x\n", error->plane[i].tile_offset);
15466                 }
15467
15468                 err_printf(m, "Cursor [%d]:\n", i);
15469                 err_printf(m, "  CNTR: %08x\n", error->cursor[i].control);
15470                 err_printf(m, "  POS: %08x\n", error->cursor[i].position);
15471                 err_printf(m, "  BASE: %08x\n", error->cursor[i].base);
15472         }
15473
15474         for (i = 0; i < error->num_transcoders; i++) {
15475                 err_printf(m, "CPU transcoder: %s\n",
15476                            transcoder_name(error->transcoder[i].cpu_transcoder));
15477                 err_printf(m, "  Power: %s\n",
15478                            onoff(error->transcoder[i].power_domain_on));
15479                 err_printf(m, "  CONF: %08x\n", error->transcoder[i].conf);
15480                 err_printf(m, "  HTOTAL: %08x\n", error->transcoder[i].htotal);
15481                 err_printf(m, "  HBLANK: %08x\n", error->transcoder[i].hblank);
15482                 err_printf(m, "  HSYNC: %08x\n", error->transcoder[i].hsync);
15483                 err_printf(m, "  VTOTAL: %08x\n", error->transcoder[i].vtotal);
15484                 err_printf(m, "  VBLANK: %08x\n", error->transcoder[i].vblank);
15485                 err_printf(m, "  VSYNC: %08x\n", error->transcoder[i].vsync);
15486         }
15487 }
15488
15489 #endif