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